feat(nacos): add access control support
This commit is contained in:
67 files changed
+9062
-135
No files matched your search
@@ -2933,6 +2933,11 @@ impl AppState {
|
||||
|
||||
let (host, port) = self.connection_host_port(connection_id, config).await?;
|
||||
let nacos_config = nacos_config.with_server_endpoint(&host, port)?;
|
||||
let transport_layers = self.resolved_transport_layers(config).await?;
|
||||
if transport_layers.is_empty() {
|
||||
return Ok(nacos_config);
|
||||
}
|
||||
|
||||
if nacos_config.rnacos_console_addr.is_empty() {
|
||||
return Ok(nacos_config);
|
||||
}
|
||||
@@ -2946,10 +2951,6 @@ impl AppState {
|
||||
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,
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,4 +1,5 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
use crate::models::connection::ConnectionConfig;
|
||||
|
||||
@@ -66,6 +67,12 @@ pub struct NacosAdminConfig {
|
||||
pub namespace: String,
|
||||
#[serde(default)]
|
||||
pub context_path: String,
|
||||
/// Namespace IDs supplied for an official Nacos ordinary user that cannot
|
||||
/// call the namespace or authorization management APIs. They define the
|
||||
/// discoverable scope; Nacos still authorizes every configuration and
|
||||
/// naming request.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub managed_namespaces: Vec<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 plus config type and description metadata) on
|
||||
@@ -104,6 +111,13 @@ pub fn default_page_size() -> u32 {
|
||||
}
|
||||
|
||||
impl NacosAdminConfig {
|
||||
/// Binds short-lived, destructive workflows to the exact Nacos target and
|
||||
/// credentials that created them. The digest is never exposed or persisted.
|
||||
pub fn operation_fingerprint(&self) -> String {
|
||||
let encoded = serde_json::to_vec(self).expect("NacosAdminConfig serialization must succeed");
|
||||
format!("{:x}", Sha256::digest(encoded))
|
||||
}
|
||||
|
||||
pub fn from_connection(cfg: &ConnectionConfig) -> Result<Self, String> {
|
||||
let parsed = if let Some(raw) = cfg.external_config.as_ref() {
|
||||
serde_json::from_value::<NacosAdminConfig>(raw.clone())
|
||||
@@ -117,6 +131,7 @@ impl NacosAdminConfig {
|
||||
display_server_addr: String::new(),
|
||||
namespace: cfg.database.clone().unwrap_or_default(),
|
||||
context_path: String::new(),
|
||||
managed_namespaces: Vec::new(),
|
||||
rnacos_console_addr: String::new(),
|
||||
rnacos_history_enabled: None,
|
||||
rnacos_console_auth: NacosRNacosConsoleAuth::Inherit,
|
||||
@@ -157,6 +172,14 @@ impl NacosAdminConfig {
|
||||
{
|
||||
self.context_path = "/nacos".to_string();
|
||||
}
|
||||
let mut managed_namespaces = Vec::new();
|
||||
for namespace in std::mem::take(&mut self.managed_namespaces) {
|
||||
let namespace = namespace.trim().to_string();
|
||||
if !namespace.is_empty() && !managed_namespaces.contains(&namespace) {
|
||||
managed_namespaces.push(namespace);
|
||||
}
|
||||
}
|
||||
self.managed_namespaces = managed_namespaces;
|
||||
self.rnacos_console_addr = if self.rnacos_console_addr.trim().is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
@@ -369,6 +392,19 @@ mod tests {
|
||||
assert_eq!(parsed.rnacos_console_addr, "http://127.0.0.1:10848");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalizes_managed_namespaces() {
|
||||
let cfg = connection_with_external(serde_json::json!({
|
||||
"implementation": "nacos",
|
||||
"versionMode": "v3",
|
||||
"serverAddr": "http://127.0.0.1:8818",
|
||||
"managedNamespaces": [" public ", "team-a", "team-a", ""],
|
||||
}));
|
||||
|
||||
let parsed = NacosAdminConfig::from_connection(&cfg).unwrap();
|
||||
assert_eq!(parsed.managed_namespaces, vec!["public", "team-a"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepts_optional_profile_fields_and_rejects_endpoint_userinfo() {
|
||||
let parsed = NacosAdminConfig::from_connection(&connection_with_external(serde_json::json!({
|
||||
|
||||
+2005
-23
File diff suppressed because it is too large.
Load diff
@@ -6,10 +6,12 @@
|
||||
//! still supports an older Rust toolchain. A future SDK adapter can implement
|
||||
//! the same port without changing commands, routes, or frontend contracts.
|
||||
|
||||
pub mod access_control;
|
||||
pub mod archive;
|
||||
pub mod batch;
|
||||
pub mod config;
|
||||
pub mod http;
|
||||
pub mod namespace_access;
|
||||
pub mod port;
|
||||
mod prometheus;
|
||||
pub mod search;
|
||||
@@ -116,6 +118,8 @@ impl NacosAdminRegistry {
|
||||
pub async fn drop_connection(&self, connection_id: &str) {
|
||||
self.instances.write().await.remove(connection_id);
|
||||
self.build_locks.write().await.remove(connection_id);
|
||||
access_control::invalidate_operations(connection_id);
|
||||
namespace_access::invalidate(connection_id);
|
||||
}
|
||||
|
||||
async fn rnacos_console_session(&self, cfg: &NacosAdminConfig) -> RNacosConsoleSessionHandle {
|
||||
@@ -176,6 +180,7 @@ mod tests {
|
||||
display_server_addr: "http://127.0.0.1:8848".to_string(),
|
||||
namespace: "public".to_string(),
|
||||
context_path: "/nacos".to_string(),
|
||||
managed_namespaces: Vec::new(),
|
||||
rnacos_console_addr: "http://127.0.0.1:10848".to_string(),
|
||||
rnacos_history_enabled: Some(true),
|
||||
rnacos_console_auth: NacosRNacosConsoleAuth::UsernamePassword {
|
||||
|
||||
@@ -0,0 +1,835 @@
|
||||
use std::collections::{BTreeSet, HashMap};
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
use crate::nacos::port::{NacosAdmin, NacosNamespaceAuthorizationSnapshot};
|
||||
use crate::nacos::types::*;
|
||||
|
||||
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";
|
||||
|
||||
#[derive(Clone)]
|
||||
struct NamespaceAccessCacheEntry {
|
||||
connection_fingerprint: String,
|
||||
namespace_signature: [u8; 32],
|
||||
readable_ids: BTreeSet<String>,
|
||||
access_control: NacosAccessControlCapabilities,
|
||||
expires_at: Instant,
|
||||
}
|
||||
|
||||
struct ReadableNamespaces {
|
||||
namespaces: Vec<NacosNamespaceInfo>,
|
||||
access_control: NacosAccessControlCapabilities,
|
||||
}
|
||||
|
||||
fn cache() -> &'static Mutex<HashMap<String, NamespaceAccessCacheEntry>> {
|
||||
static CACHE: OnceLock<Mutex<HashMap<String, NamespaceAccessCacheEntry>>> = OnceLock::new();
|
||||
CACHE.get_or_init(|| Mutex::new(HashMap::new()))
|
||||
}
|
||||
|
||||
pub fn invalidate(connection_id: &str) {
|
||||
cache().lock().unwrap_or_else(|error| error.into_inner()).remove(connection_id);
|
||||
}
|
||||
|
||||
/// Access-control changes can affect a different DBX connection that targets
|
||||
/// the same server with the edited account, so invalidate every cached account.
|
||||
pub fn invalidate_all() {
|
||||
cache().lock().unwrap_or_else(|error| error.into_inner()).clear();
|
||||
}
|
||||
|
||||
pub async fn list_readable_namespaces(
|
||||
connection_id: &str,
|
||||
connection_fingerprint: String,
|
||||
admin: Arc<dyn NacosAdmin>,
|
||||
) -> Result<Vec<NacosNamespaceInfo>, String> {
|
||||
Ok(load_readable_namespaces(connection_id, connection_fingerprint, admin).await?.namespaces)
|
||||
}
|
||||
|
||||
pub async fn sidebar_snapshot(
|
||||
connection_id: &str,
|
||||
connection_fingerprint: String,
|
||||
admin: Arc<dyn NacosAdmin>,
|
||||
) -> Result<NacosNamespaceSidebarSnapshot, String> {
|
||||
match load_readable_namespaces(connection_id, connection_fingerprint, admin.clone()).await {
|
||||
Ok(result) => {
|
||||
Ok(NacosNamespaceSidebarSnapshot { namespaces: result.namespaces, access_control: result.access_control })
|
||||
}
|
||||
Err(error) if is_namespace_authorization_error(&error) => {
|
||||
let access_control = admin.access_control_capabilities();
|
||||
let has_access_control_reads = access_control.list_users.supported
|
||||
|| access_control.list_role_bindings.supported
|
||||
|| access_control.list_permissions.supported;
|
||||
if has_access_control_reads {
|
||||
// Namespace visibility remains fail-closed, while an account
|
||||
// that can inspect access control can still open that workspace.
|
||||
Ok(NacosNamespaceSidebarSnapshot { namespaces: Vec::new(), access_control })
|
||||
} else {
|
||||
Err(error)
|
||||
}
|
||||
}
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
}
|
||||
|
||||
fn is_namespace_authorization_error(error: &str) -> bool {
|
||||
error.contains("NACOS_ERROR[managedNamespacesRequired]")
|
||||
|| error.contains("NACOS_ERROR[namespaceAuthorizationUnavailable]")
|
||||
}
|
||||
|
||||
async fn load_readable_namespaces(
|
||||
connection_id: &str,
|
||||
connection_fingerprint: String,
|
||||
admin: Arc<dyn NacosAdmin>,
|
||||
) -> Result<ReadableNamespaces, String> {
|
||||
let namespaces = admin.list_namespaces().await?;
|
||||
let Some(username) =
|
||||
admin.current_username().map(|value| value.trim().to_string()).filter(|value| !value.is_empty())
|
||||
else {
|
||||
return Ok(ReadableNamespaces { namespaces, access_control: admin.access_control_capabilities() });
|
||||
};
|
||||
if let Some(explicit_scope) = admin.explicitly_scoped_namespace_ids() {
|
||||
let readable = explicit_scope.iter().map(|namespace| namespace_identity(namespace)).collect();
|
||||
return Ok(ReadableNamespaces {
|
||||
namespaces: filter_namespaces(namespaces, &readable),
|
||||
access_control: NacosAccessControlCapabilities::unavailable(NacosCapabilityReason::PermissionDenied),
|
||||
});
|
||||
}
|
||||
let signature = namespace_signature(&namespaces);
|
||||
if let Some((readable, cached_access_control)) =
|
||||
cached_readable_ids(connection_id, &connection_fingerprint, signature)
|
||||
{
|
||||
return Ok(ReadableNamespaces {
|
||||
namespaces: filter_namespaces(namespaces, &readable),
|
||||
access_control: cached_access_control,
|
||||
});
|
||||
}
|
||||
|
||||
let (access_control, readable) = match admin.refresh_namespace_authorization(&username).await {
|
||||
Ok(Some(authorization)) => {
|
||||
let access_control = authorization.access_control.clone();
|
||||
let readable = readable_ids_from_authorization_snapshot(authorization, &namespaces)?;
|
||||
(access_control, readable)
|
||||
}
|
||||
Ok(None) => {
|
||||
let access_control = admin.access_control_capabilities();
|
||||
let readable = readable_ids_from_authorization(admin, &username, &namespaces).await?;
|
||||
(access_control, readable)
|
||||
}
|
||||
Err(error) => return Err(namespace_authorization_unavailable(&error)),
|
||||
};
|
||||
cache_readable_ids(connection_id, connection_fingerprint, signature, readable.clone(), access_control.clone());
|
||||
Ok(ReadableNamespaces { namespaces: filter_namespaces(namespaces, &readable), access_control })
|
||||
}
|
||||
|
||||
fn readable_ids_from_authorization_snapshot(
|
||||
authorization: NacosNamespaceAuthorizationSnapshot,
|
||||
namespaces: &[NacosNamespaceInfo],
|
||||
) -> Result<BTreeSet<String>, String> {
|
||||
if authorization.global_admin {
|
||||
return Ok(all_namespace_ids(namespaces));
|
||||
}
|
||||
let roles = authorization.roles.into_iter().collect::<BTreeSet<_>>();
|
||||
if roles.is_empty() {
|
||||
return Ok(BTreeSet::new());
|
||||
}
|
||||
readable_ids_from_permissions(&roles, &authorization.permissions, namespaces)
|
||||
.ok_or_else(|| namespace_authorization_unavailable("the server returned an unsupported permission resource"))
|
||||
}
|
||||
|
||||
async fn readable_ids_from_authorization(
|
||||
admin: Arc<dyn NacosAdmin>,
|
||||
username: &str,
|
||||
namespaces: &[NacosNamespaceInfo],
|
||||
) -> Result<BTreeSet<String>, String> {
|
||||
match admin.access_control_capabilities().mode {
|
||||
NacosAccessControlMode::EmbeddedRoles => readable_ids_from_embedded_user(admin, username, namespaces).await,
|
||||
NacosAccessControlMode::RoleBindings => readable_ids_from_role_bindings(admin, username, namespaces).await,
|
||||
NacosAccessControlMode::Unavailable => {
|
||||
Err(namespace_authorization_unavailable("this connection does not expose account authorization data"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn readable_ids_from_embedded_user(
|
||||
admin: Arc<dyn NacosAdmin>,
|
||||
username: &str,
|
||||
namespaces: &[NacosNamespaceInfo],
|
||||
) -> Result<BTreeSet<String>, String> {
|
||||
let users = admin
|
||||
.list_users(NacosUserQuery { username: Some(username.to_string()), page_no: Some(1), page_size: Some(2) })
|
||||
.await
|
||||
.map_err(|error| namespace_authorization_unavailable(&error))?;
|
||||
let user = users.items.into_iter().find(|user| user.username == username).ok_or_else(|| {
|
||||
namespace_authorization_unavailable("the current r-nacos account was absent from the authorization response")
|
||||
})?;
|
||||
Ok(readable_ids_from_namespace_privilege(user.enabled, user.namespace_privilege.as_ref(), namespaces))
|
||||
}
|
||||
|
||||
async fn readable_ids_from_role_bindings(
|
||||
admin: Arc<dyn NacosAdmin>,
|
||||
username: &str,
|
||||
namespaces: &[NacosNamespaceInfo],
|
||||
) -> Result<BTreeSet<String>, String> {
|
||||
let roles = list_current_roles(admin.clone(), username)
|
||||
.await
|
||||
.map_err(|error| namespace_authorization_unavailable(&error))?;
|
||||
if roles.contains(ADMIN_ROLE) {
|
||||
return Ok(all_namespace_ids(namespaces));
|
||||
}
|
||||
if roles.is_empty() {
|
||||
return Ok(BTreeSet::new());
|
||||
}
|
||||
|
||||
let permissions = list_all_permissions(admin).await.map_err(|error| namespace_authorization_unavailable(&error))?;
|
||||
readable_ids_from_permissions(&roles, &permissions, namespaces)
|
||||
.ok_or_else(|| namespace_authorization_unavailable("the server returned an unsupported permission resource"))
|
||||
}
|
||||
|
||||
fn namespace_authorization_unavailable(detail: &str) -> String {
|
||||
let detail_lowercase = detail.to_ascii_lowercase();
|
||||
let error_code = if detail_lowercase.contains("403")
|
||||
|| detail_lowercase.contains("forbidden")
|
||||
|| detail_lowercase.contains("access denied")
|
||||
|| detail_lowercase.contains("authorization failed")
|
||||
{
|
||||
"managedNamespacesRequired"
|
||||
} else {
|
||||
"namespaceAuthorizationUnavailable"
|
||||
};
|
||||
format!(
|
||||
"NACOS_ERROR[{error_code}]: DBX cannot safely determine readable namespaces without per-namespace probes: {detail}"
|
||||
)
|
||||
}
|
||||
|
||||
async fn list_current_roles(admin: Arc<dyn NacosAdmin>, username: &str) -> Result<BTreeSet<String>, String> {
|
||||
let mut roles = BTreeSet::new();
|
||||
let mut page_no = 1;
|
||||
loop {
|
||||
let page = admin
|
||||
.list_role_bindings(NacosRoleQuery {
|
||||
username: Some(username.to_string()),
|
||||
role: None,
|
||||
page_no: Some(page_no),
|
||||
page_size: Some(AUTH_PAGE_SIZE),
|
||||
})
|
||||
.await?;
|
||||
let count = page.items.len();
|
||||
roles.extend(page.items.into_iter().filter(|binding| binding.username == username).map(|binding| binding.role));
|
||||
if count < AUTH_PAGE_SIZE as usize || roles.len() as u64 >= page.total_count {
|
||||
break;
|
||||
}
|
||||
page_no += 1;
|
||||
}
|
||||
Ok(roles)
|
||||
}
|
||||
|
||||
async fn list_all_permissions(admin: Arc<dyn NacosAdmin>) -> Result<Vec<NacosPermissionInfo>, String> {
|
||||
let mut permissions = Vec::new();
|
||||
let mut page_no = 1;
|
||||
loop {
|
||||
let page = admin
|
||||
.list_permissions(NacosPermissionQuery {
|
||||
role: None,
|
||||
resource: None,
|
||||
page_no: Some(page_no),
|
||||
page_size: Some(AUTH_PAGE_SIZE),
|
||||
})
|
||||
.await?;
|
||||
let count = page.items.len();
|
||||
permissions.extend(page.items);
|
||||
if count < AUTH_PAGE_SIZE as usize || permissions.len() as u64 >= page.total_count {
|
||||
break;
|
||||
}
|
||||
page_no += 1;
|
||||
}
|
||||
Ok(permissions)
|
||||
}
|
||||
|
||||
fn readable_ids_from_namespace_privilege(
|
||||
enabled: Option<bool>,
|
||||
privilege: Option<&NacosNamespacePrivilege>,
|
||||
namespaces: &[NacosNamespaceInfo],
|
||||
) -> BTreeSet<String> {
|
||||
let Some(privilege) = privilege.filter(|_| enabled != Some(false)) else {
|
||||
return if enabled == Some(false) { BTreeSet::new() } else { all_namespace_ids(namespaces) };
|
||||
};
|
||||
if !privilege.enabled {
|
||||
return all_namespace_ids(namespaces);
|
||||
}
|
||||
let mut readable = if privilege.whitelist_is_all {
|
||||
all_namespace_ids(namespaces)
|
||||
} else {
|
||||
privilege.whitelist.iter().map(|namespace| namespace_identity(namespace)).collect()
|
||||
};
|
||||
if privilege.blacklist_is_all {
|
||||
readable.clear();
|
||||
} else {
|
||||
for namespace in &privilege.blacklist {
|
||||
readable.remove(&namespace_identity(namespace));
|
||||
}
|
||||
}
|
||||
readable
|
||||
}
|
||||
|
||||
fn readable_ids_from_permissions(
|
||||
roles: &BTreeSet<String>,
|
||||
permissions: &[NacosPermissionInfo],
|
||||
namespaces: &[NacosNamespaceInfo],
|
||||
) -> Option<BTreeSet<String>> {
|
||||
let mut readable = BTreeSet::new();
|
||||
for permission in permissions.iter().filter(|permission| roles.contains(&permission.role)) {
|
||||
if !matches!(permission.action_raw.trim().to_ascii_lowercase().as_str(), "r" | "rw") {
|
||||
continue;
|
||||
}
|
||||
match permission.parsed_scope.as_ref().map(|scope| scope.kind) {
|
||||
Some(NacosPermissionScopeKind::Global) => return Some(all_namespace_ids(namespaces)),
|
||||
Some(NacosPermissionScopeKind::Namespace) => {
|
||||
if let Some(namespace) =
|
||||
permission.parsed_scope.as_ref().and_then(|scope| scope.namespace_id.as_deref())
|
||||
{
|
||||
readable.insert(namespace_identity(namespace));
|
||||
}
|
||||
}
|
||||
// A custom resource can grant access to an individual group or
|
||||
// data ID, but it cannot prove namespace-wide read access. Ignore
|
||||
// it rather than widening the sidebar's visible namespace scope.
|
||||
Some(NacosPermissionScopeKind::Custom | NacosPermissionScopeKind::Unknown) => {}
|
||||
None => return None,
|
||||
}
|
||||
}
|
||||
Some(readable)
|
||||
}
|
||||
|
||||
fn namespace_identity(namespace: &str) -> String {
|
||||
if namespace.is_empty() || namespace == "public" {
|
||||
"public".to_string()
|
||||
} else {
|
||||
namespace.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
fn all_namespace_ids(namespaces: &[NacosNamespaceInfo]) -> BTreeSet<String> {
|
||||
namespaces.iter().map(|namespace| namespace_identity(&namespace.namespace)).collect()
|
||||
}
|
||||
|
||||
fn filter_namespaces(namespaces: Vec<NacosNamespaceInfo>, readable: &BTreeSet<String>) -> Vec<NacosNamespaceInfo> {
|
||||
namespaces.into_iter().filter(|namespace| readable.contains(&namespace_identity(&namespace.namespace))).collect()
|
||||
}
|
||||
|
||||
fn namespace_signature(namespaces: &[NacosNamespaceInfo]) -> [u8; 32] {
|
||||
let mut identities =
|
||||
namespaces.iter().map(|namespace| namespace_identity(&namespace.namespace)).collect::<Vec<_>>();
|
||||
identities.sort();
|
||||
identities.dedup();
|
||||
let mut hasher = Sha256::new();
|
||||
for identity in identities {
|
||||
hasher.update((identity.len() as u64).to_le_bytes());
|
||||
hasher.update(identity.as_bytes());
|
||||
}
|
||||
hasher.finalize().into()
|
||||
}
|
||||
|
||||
fn cached_readable_ids(
|
||||
connection_id: &str,
|
||||
connection_fingerprint: &str,
|
||||
namespace_signature: [u8; 32],
|
||||
) -> Option<(BTreeSet<String>, NacosAccessControlCapabilities)> {
|
||||
let mut entries = cache().lock().unwrap_or_else(|error| error.into_inner());
|
||||
let now = Instant::now();
|
||||
entries.retain(|_, entry| entry.expires_at > now);
|
||||
entries.get(connection_id).and_then(|entry| {
|
||||
(entry.connection_fingerprint == connection_fingerprint && entry.namespace_signature == namespace_signature)
|
||||
.then(|| (entry.readable_ids.clone(), entry.access_control.clone()))
|
||||
})
|
||||
}
|
||||
|
||||
fn cache_readable_ids(
|
||||
connection_id: &str,
|
||||
connection_fingerprint: String,
|
||||
namespace_signature: [u8; 32],
|
||||
readable_ids: BTreeSet<String>,
|
||||
access_control: NacosAccessControlCapabilities,
|
||||
) {
|
||||
let mut entries = cache().lock().unwrap_or_else(|error| error.into_inner());
|
||||
let now = Instant::now();
|
||||
entries.retain(|_, entry| entry.expires_at > now);
|
||||
if !entries.contains_key(connection_id) && entries.len() >= CACHE_MAX_CONNECTIONS {
|
||||
if let Some(oldest) = entries.iter().min_by_key(|(_, entry)| entry.expires_at).map(|(id, _)| id.clone()) {
|
||||
entries.remove(&oldest);
|
||||
}
|
||||
}
|
||||
entries.insert(
|
||||
connection_id.to_string(),
|
||||
NamespaceAccessCacheEntry {
|
||||
connection_fingerprint,
|
||||
namespace_signature,
|
||||
readable_ids,
|
||||
access_control,
|
||||
expires_at: now + CACHE_TTL,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use async_trait::async_trait;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
fn namespace(id: &str) -> NacosNamespaceInfo {
|
||||
NacosNamespaceInfo {
|
||||
namespace: id.to_string(),
|
||||
namespace_show_name: id.to_string(),
|
||||
namespace_desc: None,
|
||||
config_count: None,
|
||||
quota: None,
|
||||
namespace_type: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn role_binding_capabilities() -> NacosAccessControlCapabilities {
|
||||
NacosAccessControlCapabilities {
|
||||
mode: NacosAccessControlMode::RoleBindings,
|
||||
list_users: NacosOperationCapability::supported(),
|
||||
create_user: NacosOperationCapability::supported(),
|
||||
update_user: NacosOperationCapability::supported(),
|
||||
delete_user: NacosOperationCapability::supported(),
|
||||
list_role_bindings: NacosOperationCapability::supported(),
|
||||
assign_role: NacosOperationCapability::supported(),
|
||||
remove_role: NacosOperationCapability::supported(),
|
||||
list_permissions: NacosOperationCapability::supported(),
|
||||
grant_permission: NacosOperationCapability::supported(),
|
||||
revoke_permission: NacosOperationCapability::supported(),
|
||||
enhanced_workspace: true,
|
||||
supports_namespace_privileges: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn roles_only_capabilities() -> NacosAccessControlCapabilities {
|
||||
let mut capabilities = NacosAccessControlCapabilities::unavailable(NacosCapabilityReason::PermissionDenied);
|
||||
capabilities.mode = NacosAccessControlMode::RoleBindings;
|
||||
capabilities.list_users = NacosOperationCapability::supported();
|
||||
capabilities.list_role_bindings = NacosOperationCapability::supported();
|
||||
capabilities
|
||||
}
|
||||
|
||||
struct CountingAdmin {
|
||||
namespaces: Vec<NacosNamespaceInfo>,
|
||||
readable_ids: BTreeSet<String>,
|
||||
permission_error: bool,
|
||||
explicitly_scoped_ids: Option<Vec<String>>,
|
||||
namespace_calls: AtomicUsize,
|
||||
capability_calls: AtomicUsize,
|
||||
role_calls: AtomicUsize,
|
||||
permission_calls: AtomicUsize,
|
||||
config_calls: AtomicUsize,
|
||||
}
|
||||
|
||||
impl CountingAdmin {
|
||||
fn restricted(namespace_count: usize) -> Self {
|
||||
let namespaces = (0..namespace_count).map(|index| namespace(&format!("team-{index}"))).collect::<Vec<_>>();
|
||||
let readable_ids = namespaces
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(index, _)| index % 2 == 0)
|
||||
.map(|(_, namespace)| namespace.namespace.clone())
|
||||
.collect();
|
||||
Self {
|
||||
namespaces,
|
||||
readable_ids,
|
||||
permission_error: false,
|
||||
explicitly_scoped_ids: None,
|
||||
namespace_calls: AtomicUsize::new(0),
|
||||
capability_calls: AtomicUsize::new(0),
|
||||
role_calls: AtomicUsize::new(0),
|
||||
permission_calls: AtomicUsize::new(0),
|
||||
config_calls: AtomicUsize::new(0),
|
||||
}
|
||||
}
|
||||
|
||||
fn total_authorization_calls(&self) -> usize {
|
||||
self.namespace_calls.load(Ordering::SeqCst)
|
||||
+ self.capability_calls.load(Ordering::SeqCst)
|
||||
+ self.role_calls.load(Ordering::SeqCst)
|
||||
+ self.permission_calls.load(Ordering::SeqCst)
|
||||
+ self.config_calls.load(Ordering::SeqCst)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl NacosAdmin for CountingAdmin {
|
||||
fn access_control_capabilities(&self) -> NacosAccessControlCapabilities {
|
||||
if self.permission_error {
|
||||
roles_only_capabilities()
|
||||
} else {
|
||||
role_binding_capabilities()
|
||||
}
|
||||
}
|
||||
|
||||
fn current_username(&self) -> Option<String> {
|
||||
Some("reader".to_string())
|
||||
}
|
||||
|
||||
fn explicitly_scoped_namespace_ids(&self) -> Option<Vec<String>> {
|
||||
self.explicitly_scoped_ids.clone()
|
||||
}
|
||||
|
||||
async fn refresh_namespace_authorization(
|
||||
&self,
|
||||
username: &str,
|
||||
) -> Result<Option<NacosNamespaceAuthorizationSnapshot>, String> {
|
||||
self.capability_calls.fetch_add(1, Ordering::SeqCst);
|
||||
let role_bindings = self
|
||||
.list_role_bindings(NacosRoleQuery {
|
||||
username: Some(username.to_string()),
|
||||
role: None,
|
||||
page_no: Some(1),
|
||||
page_size: Some(AUTH_PAGE_SIZE),
|
||||
})
|
||||
.await?;
|
||||
let permissions = self
|
||||
.list_permissions(NacosPermissionQuery {
|
||||
role: None,
|
||||
resource: None,
|
||||
page_no: Some(1),
|
||||
page_size: Some(AUTH_PAGE_SIZE),
|
||||
})
|
||||
.await?;
|
||||
Ok(Some(NacosNamespaceAuthorizationSnapshot {
|
||||
access_control: role_binding_capabilities(),
|
||||
roles: role_bindings.items.into_iter().map(|binding| binding.role).collect(),
|
||||
permissions: permissions.items,
|
||||
global_admin: false,
|
||||
}))
|
||||
}
|
||||
|
||||
async fn test_connection(&self) -> Result<NacosConnectionInfo, String> {
|
||||
Err("unused".to_string())
|
||||
}
|
||||
|
||||
async fn list_namespaces(&self) -> Result<Vec<NacosNamespaceInfo>, String> {
|
||||
self.namespace_calls.fetch_add(1, Ordering::SeqCst);
|
||||
Ok(self.namespaces.clone())
|
||||
}
|
||||
|
||||
async fn create_namespace(&self, _: NacosNamespaceCreate) -> Result<(), String> {
|
||||
Err("unused".to_string())
|
||||
}
|
||||
|
||||
async fn update_namespace(&self, _: NacosNamespaceUpdate) -> Result<(), String> {
|
||||
Err("unused".to_string())
|
||||
}
|
||||
|
||||
async fn list_configs(&self, _: NacosConfigQuery) -> Result<NacosConfigList, String> {
|
||||
self.config_calls.fetch_add(1, Ordering::SeqCst);
|
||||
Err("per-namespace probes are forbidden in the sidebar path".to_string())
|
||||
}
|
||||
|
||||
async fn search_config_content_page(
|
||||
&self,
|
||||
_: &str,
|
||||
_: &str,
|
||||
_: u32,
|
||||
_: u32,
|
||||
) -> Result<Option<NacosConfigList>, String> {
|
||||
Err("unused".to_string())
|
||||
}
|
||||
|
||||
async fn get_config(&self, _: NacosConfigKey) -> Result<NacosConfigItem, String> {
|
||||
Err("unused".to_string())
|
||||
}
|
||||
|
||||
async fn publish_config(&self, _: NacosConfigUpsert) -> Result<(), String> {
|
||||
Err("unused".to_string())
|
||||
}
|
||||
|
||||
async fn delete_config(&self, _: NacosConfigKey) -> Result<(), String> {
|
||||
Err("unused".to_string())
|
||||
}
|
||||
|
||||
async fn list_config_history(&self, _: NacosConfigHistoryQuery) -> Result<NacosConfigHistoryList, String> {
|
||||
Err("unused".to_string())
|
||||
}
|
||||
|
||||
async fn get_config_history(&self, _: NacosConfigHistoryKey) -> Result<NacosConfigItem, String> {
|
||||
Err("unused".to_string())
|
||||
}
|
||||
|
||||
async fn rollback_config(&self, _: NacosConfigRollbackRequest) -> Result<(), String> {
|
||||
Err("unused".to_string())
|
||||
}
|
||||
|
||||
async fn get_rnacos_console_captcha(&self) -> Result<NacosRNacosConsoleCaptcha, String> {
|
||||
Err("unused".to_string())
|
||||
}
|
||||
|
||||
async fn login_rnacos_console(&self, _: Option<String>) -> Result<(), String> {
|
||||
Err("unused".to_string())
|
||||
}
|
||||
|
||||
async fn list_role_bindings(&self, _: NacosRoleQuery) -> Result<NacosRoleList, String> {
|
||||
self.role_calls.fetch_add(1, Ordering::SeqCst);
|
||||
Ok(NacosRoleList {
|
||||
page_no: 1,
|
||||
page_size: AUTH_PAGE_SIZE,
|
||||
total_count: 1,
|
||||
items: vec![NacosRoleBinding { username: "reader".to_string(), role: "reader-role".to_string() }],
|
||||
})
|
||||
}
|
||||
|
||||
async fn list_permissions(&self, _: NacosPermissionQuery) -> Result<NacosPermissionList, String> {
|
||||
self.permission_calls.fetch_add(1, Ordering::SeqCst);
|
||||
if self.permission_error {
|
||||
return Err("403 Forbidden".to_string());
|
||||
}
|
||||
let items = self
|
||||
.readable_ids
|
||||
.iter()
|
||||
.map(|namespace| NacosPermissionInfo {
|
||||
role: "reader-role".to_string(),
|
||||
resource_raw: format!("{namespace}:*:*"),
|
||||
action_raw: "r".to_string(),
|
||||
parsed_scope: Some(NacosPermissionScope {
|
||||
kind: NacosPermissionScopeKind::Namespace,
|
||||
namespace_id: Some(namespace.clone()),
|
||||
}),
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
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 get_service(&self, _: NacosServiceQuery) -> Result<NacosServiceDetail, String> {
|
||||
Err("unused".to_string())
|
||||
}
|
||||
|
||||
async fn create_service(&self, _: NacosServiceUpsert) -> Result<(), String> {
|
||||
Err("unused".to_string())
|
||||
}
|
||||
|
||||
async fn update_service(&self, _: NacosServiceUpsert) -> Result<(), String> {
|
||||
Err("unused".to_string())
|
||||
}
|
||||
|
||||
async fn delete_service(&self, _: NacosServiceQuery) -> Result<(), String> {
|
||||
Err("unused".to_string())
|
||||
}
|
||||
|
||||
async fn list_instances(&self, _: NacosInstanceQuery) -> Result<Vec<NacosInstanceInfo>, String> {
|
||||
Err("unused".to_string())
|
||||
}
|
||||
|
||||
async fn update_instance(&self, _: NacosInstanceUpdateRequest) -> Result<(), String> {
|
||||
Err("unused".to_string())
|
||||
}
|
||||
|
||||
async fn register_instance(&self, _: NacosInstanceRegistration) -> Result<(), String> {
|
||||
Err("unused".to_string())
|
||||
}
|
||||
|
||||
async fn deregister_instance(&self, _: NacosInstanceRef) -> Result<(), String> {
|
||||
Err("unused".to_string())
|
||||
}
|
||||
|
||||
async fn get_dashboard(&self, _: NacosDashboardQuery) -> Result<NacosDashboardSnapshot, String> {
|
||||
Err("unused".to_string())
|
||||
}
|
||||
|
||||
async fn raw_request(&self, _: NacosRawRequest) -> Result<NacosRawResponse, String> {
|
||||
Err("unused".to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn role_permissions_keep_only_readable_namespaces() {
|
||||
let namespaces = vec![namespace("public"), namespace("team-a"), namespace("team-b")];
|
||||
let roles = BTreeSet::from(["reader".to_string()]);
|
||||
let permissions = vec![
|
||||
NacosPermissionInfo {
|
||||
role: "reader".to_string(),
|
||||
resource_raw: "team-a:*:*".to_string(),
|
||||
action_raw: "r".to_string(),
|
||||
parsed_scope: Some(NacosPermissionScope {
|
||||
kind: NacosPermissionScopeKind::Namespace,
|
||||
namespace_id: Some("team-a".to_string()),
|
||||
}),
|
||||
},
|
||||
NacosPermissionInfo {
|
||||
role: "reader".to_string(),
|
||||
resource_raw: "team-b:*:*".to_string(),
|
||||
action_raw: "w".to_string(),
|
||||
parsed_scope: Some(NacosPermissionScope {
|
||||
kind: NacosPermissionScopeKind::Namespace,
|
||||
namespace_id: Some("team-b".to_string()),
|
||||
}),
|
||||
},
|
||||
];
|
||||
|
||||
assert_eq!(
|
||||
readable_ids_from_permissions(&roles, &permissions, &namespaces),
|
||||
Some(BTreeSet::from(["team-a".to_string()]))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_permissions_do_not_grant_namespace_wide_visibility() {
|
||||
let namespaces = vec![namespace("public"), namespace("team-a"), namespace("team-b")];
|
||||
let roles = BTreeSet::from(["reader".to_string()]);
|
||||
let permissions = vec![NacosPermissionInfo {
|
||||
role: "reader".to_string(),
|
||||
resource_raw: "team-a:GROUP_A:*".to_string(),
|
||||
action_raw: "r".to_string(),
|
||||
parsed_scope: Some(NacosPermissionScope {
|
||||
kind: NacosPermissionScopeKind::Custom,
|
||||
namespace_id: Some("team-a".to_string()),
|
||||
}),
|
||||
}];
|
||||
|
||||
assert_eq!(readable_ids_from_permissions(&roles, &permissions, &namespaces), Some(BTreeSet::new()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn embedded_privileges_apply_whitelist_and_blacklist() {
|
||||
let namespaces = vec![namespace("public"), namespace("team-a"), namespace("team-b")];
|
||||
let privilege = NacosNamespacePrivilege {
|
||||
enabled: true,
|
||||
whitelist_is_all: false,
|
||||
whitelist: vec!["team-a".to_string(), "team-b".to_string()],
|
||||
blacklist_is_all: false,
|
||||
blacklist: vec!["team-b".to_string()],
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
readable_ids_from_namespace_privilege(Some(true), Some(&privilege), &namespaces),
|
||||
BTreeSet::from(["team-a".to_string()])
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn restricted_sidebar_filtering_has_constant_request_count() {
|
||||
let mut request_counts = Vec::new();
|
||||
for namespace_count in [1, 100] {
|
||||
let connection_id = format!("constant-sidebar-requests-{namespace_count}");
|
||||
invalidate(&connection_id);
|
||||
let admin = Arc::new(CountingAdmin::restricted(namespace_count));
|
||||
|
||||
let snapshot = sidebar_snapshot(&connection_id, "server-a".to_string(), admin.clone()).await.unwrap();
|
||||
|
||||
assert_eq!(snapshot.namespaces.len(), namespace_count.div_ceil(2));
|
||||
assert!(snapshot.namespaces.iter().all(|namespace| namespace
|
||||
.namespace
|
||||
.trim_start_matches("team-")
|
||||
.parse::<usize>()
|
||||
.unwrap()
|
||||
% 2
|
||||
== 0));
|
||||
assert_eq!(admin.config_calls.load(Ordering::SeqCst), 0);
|
||||
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), 1);
|
||||
request_counts.push(admin.total_authorization_calls());
|
||||
}
|
||||
|
||||
assert_eq!(request_counts, vec![4, 4]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unavailable_authorization_fails_closed_without_namespace_probes() {
|
||||
let connection_id = "unavailable-sidebar-authorization";
|
||||
invalidate(connection_id);
|
||||
let mut admin = CountingAdmin::restricted(100);
|
||||
admin.permission_error = true;
|
||||
let admin = Arc::new(admin);
|
||||
|
||||
let error = list_readable_namespaces(connection_id, "server-a".to_string(), admin.clone()).await.unwrap_err();
|
||||
|
||||
assert!(error.contains("NACOS_ERROR[managedNamespacesRequired]"));
|
||||
assert_eq!(admin.config_calls.load(Ordering::SeqCst), 0);
|
||||
assert_eq!(admin.total_authorization_calls(), 4);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn roles_only_sidebar_keeps_access_control_entry_without_widening_namespaces() {
|
||||
let connection_id = "roles-only-sidebar-authorization";
|
||||
invalidate(connection_id);
|
||||
let mut admin = CountingAdmin::restricted(100);
|
||||
admin.permission_error = true;
|
||||
let admin = Arc::new(admin);
|
||||
|
||||
let snapshot = sidebar_snapshot(connection_id, "server-a".to_string(), admin.clone()).await.unwrap();
|
||||
|
||||
assert!(snapshot.namespaces.is_empty());
|
||||
assert!(snapshot.access_control.list_role_bindings.supported);
|
||||
assert!(!snapshot.access_control.list_permissions.supported);
|
||||
assert_eq!(admin.config_calls.load(Ordering::SeqCst), 0);
|
||||
assert_eq!(admin.total_authorization_calls(), 4);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn explicitly_scoped_namespace_list_skips_authorization_queries() {
|
||||
let connection_id = "explicit-sidebar-scope";
|
||||
invalidate(connection_id);
|
||||
let mut admin = CountingAdmin::restricted(100);
|
||||
admin.permission_error = true;
|
||||
admin.explicitly_scoped_ids = Some(vec!["team-2".to_string(), "team-78".to_string()]);
|
||||
let admin = Arc::new(admin);
|
||||
|
||||
let snapshot = sidebar_snapshot(connection_id, "server-a".to_string(), admin.clone()).await.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
snapshot.namespaces.iter().map(|namespace| namespace.namespace.as_str()).collect::<Vec<_>>(),
|
||||
vec!["team-2", "team-78"]
|
||||
);
|
||||
assert_eq!(admin.total_authorization_calls(), 1);
|
||||
assert!(!snapshot.access_control.list_users.supported);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cache_is_bound_to_connection_fingerprint_and_namespace_set() {
|
||||
let connection_id = "namespace-cache-test";
|
||||
invalidate(connection_id);
|
||||
let first_namespaces = vec![namespace("public"), namespace("team-a")];
|
||||
let first_signature = namespace_signature(&first_namespaces);
|
||||
cache_readable_ids(
|
||||
connection_id,
|
||||
"server-a".to_string(),
|
||||
first_signature,
|
||||
BTreeSet::from(["team-a".to_string()]),
|
||||
role_binding_capabilities(),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
cached_readable_ids(connection_id, "server-a", first_signature).map(|(ids, _)| ids),
|
||||
Some(BTreeSet::from(["team-a".to_string()]))
|
||||
);
|
||||
assert_eq!(cached_readable_ids(connection_id, "server-b", first_signature), None);
|
||||
assert_eq!(cached_readable_ids(connection_id, "server-a", namespace_signature(&[namespace("team-b")])), None);
|
||||
invalidate(connection_id);
|
||||
assert_eq!(cached_readable_ids(connection_id, "server-a", first_signature), None);
|
||||
|
||||
cache_readable_ids(
|
||||
connection_id,
|
||||
"server-a".to_string(),
|
||||
first_signature,
|
||||
BTreeSet::new(),
|
||||
role_binding_capabilities(),
|
||||
);
|
||||
cache_readable_ids(
|
||||
"other-connection",
|
||||
"server-a".to_string(),
|
||||
first_signature,
|
||||
BTreeSet::new(),
|
||||
role_binding_capabilities(),
|
||||
);
|
||||
invalidate_all();
|
||||
assert_eq!(cached_readable_ids(connection_id, "server-a", first_signature), None);
|
||||
assert_eq!(cached_readable_ids("other-connection", "server-a", first_signature), None);
|
||||
}
|
||||
}
|
||||
@@ -2,13 +2,65 @@ use async_trait::async_trait;
|
||||
|
||||
use crate::nacos::types::*;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct NacosNamespaceAuthorizationSnapshot {
|
||||
pub access_control: NacosAccessControlCapabilities,
|
||||
pub roles: Vec<String>,
|
||||
pub permissions: Vec<NacosPermissionInfo>,
|
||||
pub global_admin: bool,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait NacosAdmin: Send + Sync {
|
||||
fn service_capabilities(&self) -> NacosServiceCapabilities {
|
||||
NacosServiceCapabilities::default()
|
||||
}
|
||||
|
||||
fn access_control_capabilities(&self) -> NacosAccessControlCapabilities {
|
||||
NacosAccessControlCapabilities::default()
|
||||
}
|
||||
|
||||
fn invalidate_access_control_capabilities(&self) {}
|
||||
|
||||
fn current_username(&self) -> Option<String> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Returns the user-configured namespace scope for accounts that cannot
|
||||
/// safely rely on server-wide namespace discovery.
|
||||
fn explicitly_scoped_namespace_ids(&self) -> Option<Vec<String>> {
|
||||
None
|
||||
}
|
||||
|
||||
async fn test_connection(&self) -> Result<NacosConnectionInfo, String>;
|
||||
/// Runs the user-initiated connection check, including validation of every
|
||||
/// explicitly configured namespace. Normal connection establishment must
|
||||
/// remain bounded and should call `test_connection` instead.
|
||||
async fn test_connection_with_scope_validation(&self) -> Result<NacosConnectionInfo, String> {
|
||||
self.test_connection().await
|
||||
}
|
||||
/// Refreshes account capabilities from non-mutating authorization reads.
|
||||
/// Implementations that cannot inspect permissions keep their conservative
|
||||
/// configured capabilities.
|
||||
async fn refresh_access_control_capabilities(&self) -> NacosAccessControlCapabilities {
|
||||
self.access_control_capabilities()
|
||||
}
|
||||
/// Refreshes access-control capabilities and, when the adapter can do so
|
||||
/// without another round trip, returns the authorization rows needed to
|
||||
/// derive namespace visibility.
|
||||
async fn refresh_namespace_authorization(
|
||||
&self,
|
||||
_username: &str,
|
||||
) -> Result<Option<NacosNamespaceAuthorizationSnapshot>, String> {
|
||||
let _ = self.refresh_access_control_capabilities().await;
|
||||
Ok(None)
|
||||
}
|
||||
/// Returns connection information for the Nacos management UI after
|
||||
/// refreshing account capabilities, without re-running full namespace
|
||||
/// scope validation on every tree or console refresh.
|
||||
async fn inspect_connection(&self) -> Result<NacosConnectionInfo, String> {
|
||||
self.test_connection().await
|
||||
}
|
||||
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>;
|
||||
@@ -32,6 +84,36 @@ pub trait NacosAdmin: Send + Sync {
|
||||
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_users(&self, _: NacosUserQuery) -> Result<NacosUserList, String> {
|
||||
Err("Nacos user management is unavailable for this connection".to_string())
|
||||
}
|
||||
async fn create_user(&self, _: NacosUserCreate) -> Result<(), String> {
|
||||
Err("Nacos user management is unavailable for this connection".to_string())
|
||||
}
|
||||
async fn update_user(&self, _: NacosUserUpdate) -> Result<(), String> {
|
||||
Err("Nacos user management is unavailable for this connection".to_string())
|
||||
}
|
||||
async fn delete_user(&self, _: String) -> Result<(), String> {
|
||||
Err("Nacos user management is unavailable for this connection".to_string())
|
||||
}
|
||||
async fn list_role_bindings(&self, _: NacosRoleQuery) -> Result<NacosRoleList, String> {
|
||||
Err("Nacos role management is unavailable for this connection".to_string())
|
||||
}
|
||||
async fn assign_role(&self, _: NacosRoleBinding) -> Result<(), String> {
|
||||
Err("Nacos role management is unavailable for this connection".to_string())
|
||||
}
|
||||
async fn remove_role(&self, _: NacosRoleBinding) -> Result<(), String> {
|
||||
Err("Nacos role management is unavailable for this connection".to_string())
|
||||
}
|
||||
async fn list_permissions(&self, _: NacosPermissionQuery) -> Result<NacosPermissionList, String> {
|
||||
Err("Nacos permission management is unavailable for this connection".to_string())
|
||||
}
|
||||
async fn grant_permission(&self, _: NacosPermissionInfo) -> Result<(), String> {
|
||||
Err("Nacos permission management is unavailable for this connection".to_string())
|
||||
}
|
||||
async fn revoke_permission(&self, _: NacosPermissionInfo) -> Result<(), String> {
|
||||
Err("Nacos permission management is unavailable for this connection".to_string())
|
||||
}
|
||||
async fn list_services(&self, query: NacosServiceQuery) -> Result<NacosServiceList, String>;
|
||||
async fn get_service(&self, query: NacosServiceQuery) -> Result<NacosServiceDetail, String>;
|
||||
async fn create_service(&self, req: NacosServiceUpsert) -> Result<(), String>;
|
||||
|
||||
@@ -806,6 +806,7 @@ app_memory_usage 1
|
||||
display_server_addr: server_addr.to_string(),
|
||||
namespace: String::new(),
|
||||
context_path: context_path.to_string(),
|
||||
managed_namespaces: Vec::new(),
|
||||
rnacos_console_addr: String::new(),
|
||||
rnacos_history_enabled: None,
|
||||
rnacos_console_auth: Default::default(),
|
||||
|
||||
@@ -4,6 +4,42 @@ use crate::connection::AppState;
|
||||
use crate::models::connection::DatabaseType;
|
||||
use crate::nacos::types::*;
|
||||
|
||||
async fn refresh_access_control_after_mutation(admin: &std::sync::Arc<dyn crate::nacos::port::NacosAdmin>) {
|
||||
admin.invalidate_access_control_capabilities();
|
||||
let _ = admin.refresh_access_control_capabilities().await;
|
||||
}
|
||||
|
||||
async fn current_access_control_capabilities(
|
||||
admin: &std::sync::Arc<dyn crate::nacos::port::NacosAdmin>,
|
||||
) -> NacosAccessControlCapabilities {
|
||||
// A synchronous read intentionally treats an expired entry as absent. All
|
||||
// feature and safety gates therefore go through the refreshing path so a
|
||||
// stale cache cannot disable the workspace or reopen legacy mutations.
|
||||
admin.refresh_access_control_capabilities().await
|
||||
}
|
||||
|
||||
fn ensure_access_control_operation(
|
||||
capabilities: &NacosAccessControlCapabilities,
|
||||
operation: NacosAccessControlOperation,
|
||||
) -> Result<(), String> {
|
||||
let capability = capabilities.operation(operation);
|
||||
if capability.supported {
|
||||
return Ok(());
|
||||
}
|
||||
let reason = match capability.reason {
|
||||
Some(NacosCapabilityReason::ImplementationReadOnly) => "implementationReadOnly",
|
||||
Some(NacosCapabilityReason::VersionUnsupported) => "versionUnsupported",
|
||||
Some(NacosCapabilityReason::EndpointUnavailable) => "endpointUnavailable",
|
||||
Some(NacosCapabilityReason::NotVerified) => "notVerified",
|
||||
Some(NacosCapabilityReason::ConnectionReadOnly) => "connectionReadOnly",
|
||||
Some(NacosCapabilityReason::PermissionDenied) => "permissionDenied",
|
||||
None => "notVerified",
|
||||
};
|
||||
Err(format!(
|
||||
"NACOS_ERROR[unsupportedOperation]: Nacos access-control operation {operation:?} is unavailable ({reason})"
|
||||
))
|
||||
}
|
||||
|
||||
pub async fn nacos_test_connection_core(state: &AppState, conn_id: &str) -> Result<NacosConnectionInfo, String> {
|
||||
let cfg = state.configs.read().await.get(conn_id).cloned().ok_or("Connection not found")?;
|
||||
if cfg.db_type != DatabaseType::Nacos {
|
||||
@@ -13,12 +49,20 @@ 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?;
|
||||
admin.test_connection().await
|
||||
admin.inspect_connection().await
|
||||
}
|
||||
|
||||
pub async fn nacos_list_namespaces_core(state: &AppState, conn_id: &str) -> Result<Vec<NacosNamespaceInfo>, String> {
|
||||
let admin = get_admin(state, conn_id).await?;
|
||||
admin.list_namespaces().await
|
||||
let (admin, fingerprint) = get_admin_with_operation_fingerprint(state, conn_id).await?;
|
||||
crate::nacos::namespace_access::list_readable_namespaces(conn_id, fingerprint, admin).await
|
||||
}
|
||||
|
||||
pub async fn nacos_sidebar_snapshot_core(
|
||||
state: &AppState,
|
||||
conn_id: &str,
|
||||
) -> Result<NacosNamespaceSidebarSnapshot, String> {
|
||||
let (admin, fingerprint) = get_admin_with_operation_fingerprint(state, conn_id).await?;
|
||||
crate::nacos::namespace_access::sidebar_snapshot(conn_id, fingerprint, admin).await
|
||||
}
|
||||
|
||||
pub async fn nacos_create_namespace_core(
|
||||
@@ -131,7 +175,181 @@ pub async fn nacos_login_rnacos_console_core(
|
||||
captcha: Option<String>,
|
||||
) -> Result<(), String> {
|
||||
let admin = get_admin(state, conn_id).await?;
|
||||
admin.login_rnacos_console(captcha).await
|
||||
let result = admin.login_rnacos_console(captcha).await;
|
||||
if result.is_ok() {
|
||||
refresh_access_control_after_mutation(&admin).await;
|
||||
crate::nacos::namespace_access::invalidate(conn_id);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
pub async fn nacos_list_users_core(
|
||||
state: &AppState,
|
||||
conn_id: &str,
|
||||
query: NacosUserQuery,
|
||||
) -> Result<NacosUserList, String> {
|
||||
let admin = get_admin(state, conn_id).await?;
|
||||
admin.list_users(query).await
|
||||
}
|
||||
|
||||
pub async fn nacos_create_user_core(state: &AppState, conn_id: &str, req: NacosUserCreate) -> Result<(), String> {
|
||||
ensure_connection_writable(state, conn_id, "Create Nacos user").await?;
|
||||
let admin = get_admin(state, conn_id).await?;
|
||||
let capabilities = current_access_control_capabilities(&admin).await;
|
||||
ensure_access_control_operation(&capabilities, NacosAccessControlOperation::CreateUser)?;
|
||||
let result = admin.create_user(req).await;
|
||||
if result.is_ok() {
|
||||
refresh_access_control_after_mutation(&admin).await;
|
||||
crate::nacos::namespace_access::invalidate_all();
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
pub async fn nacos_update_user_core(state: &AppState, conn_id: &str, req: NacosUserUpdate) -> Result<(), String> {
|
||||
ensure_connection_writable(state, conn_id, "Update Nacos user").await?;
|
||||
let admin = get_admin(state, conn_id).await?;
|
||||
let capabilities = current_access_control_capabilities(&admin).await;
|
||||
ensure_access_control_operation(&capabilities, NacosAccessControlOperation::UpdateUser)?;
|
||||
let result = admin.update_user(req).await;
|
||||
if result.is_ok() {
|
||||
refresh_access_control_after_mutation(&admin).await;
|
||||
crate::nacos::namespace_access::invalidate_all();
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
pub async fn nacos_delete_user_core(state: &AppState, conn_id: &str, username: String) -> Result<(), String> {
|
||||
ensure_connection_writable(state, conn_id, "Delete Nacos user").await?;
|
||||
let admin = get_admin(state, conn_id).await?;
|
||||
let capabilities = current_access_control_capabilities(&admin).await;
|
||||
if capabilities.enhanced_workspace {
|
||||
return Err(
|
||||
"Nacos users in the enhanced workspace must be deleted through the access-control workflow".to_string()
|
||||
);
|
||||
}
|
||||
ensure_access_control_operation(&capabilities, NacosAccessControlOperation::DeleteUser)?;
|
||||
let result = admin.delete_user(username).await;
|
||||
if result.is_ok() {
|
||||
refresh_access_control_after_mutation(&admin).await;
|
||||
crate::nacos::namespace_access::invalidate_all();
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
pub async fn nacos_list_role_bindings_core(
|
||||
state: &AppState,
|
||||
conn_id: &str,
|
||||
query: NacosRoleQuery,
|
||||
) -> Result<NacosRoleList, String> {
|
||||
let admin = get_admin(state, conn_id).await?;
|
||||
admin.list_role_bindings(query).await
|
||||
}
|
||||
|
||||
pub async fn nacos_assign_role_core(state: &AppState, conn_id: &str, binding: NacosRoleBinding) -> Result<(), String> {
|
||||
ensure_connection_writable(state, conn_id, "Assign Nacos role").await?;
|
||||
let admin = get_admin(state, conn_id).await?;
|
||||
let capabilities = current_access_control_capabilities(&admin).await;
|
||||
if capabilities.enhanced_workspace {
|
||||
return Err(
|
||||
"Nacos roles in the enhanced workspace must be changed through the access-control workflow".to_string()
|
||||
);
|
||||
}
|
||||
ensure_access_control_operation(&capabilities, NacosAccessControlOperation::AssignRole)?;
|
||||
let result = admin.assign_role(binding).await;
|
||||
if result.is_ok() {
|
||||
refresh_access_control_after_mutation(&admin).await;
|
||||
crate::nacos::namespace_access::invalidate_all();
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
pub async fn nacos_remove_role_core(state: &AppState, conn_id: &str, binding: NacosRoleBinding) -> Result<(), String> {
|
||||
ensure_connection_writable(state, conn_id, "Remove Nacos role").await?;
|
||||
let admin = get_admin(state, conn_id).await?;
|
||||
let capabilities = current_access_control_capabilities(&admin).await;
|
||||
if capabilities.enhanced_workspace {
|
||||
return Err(
|
||||
"Nacos roles in the enhanced workspace must be changed through the access-control workflow".to_string()
|
||||
);
|
||||
}
|
||||
ensure_access_control_operation(&capabilities, NacosAccessControlOperation::RemoveRole)?;
|
||||
if binding.role == "ROLE_ADMIN" {
|
||||
return Err("The Nacos administrator role cannot be removed through the legacy endpoint".to_string());
|
||||
}
|
||||
let result = admin.remove_role(binding).await;
|
||||
if result.is_ok() {
|
||||
refresh_access_control_after_mutation(&admin).await;
|
||||
crate::nacos::namespace_access::invalidate_all();
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
pub async fn nacos_access_snapshot_core(state: &AppState, conn_id: &str) -> Result<NacosAccessControlSnapshot, String> {
|
||||
let admin = get_admin(state, conn_id).await?;
|
||||
if !current_access_control_capabilities(&admin).await.enhanced_workspace {
|
||||
return Err("The enhanced access-control workspace is unavailable for this Nacos connection".to_string());
|
||||
}
|
||||
crate::nacos::access_control::load_snapshot(admin).await
|
||||
}
|
||||
|
||||
pub async fn nacos_start_access_operation_core(
|
||||
state: &AppState,
|
||||
conn_id: &str,
|
||||
req: NacosAccessOperationRequest,
|
||||
) -> Result<NacosAccessOperationResult, String> {
|
||||
ensure_connection_writable(state, conn_id, "Manage Nacos access control").await?;
|
||||
let (admin, fingerprint) = get_admin_with_operation_fingerprint(state, conn_id).await?;
|
||||
if !current_access_control_capabilities(&admin).await.enhanced_workspace {
|
||||
return Err("The enhanced access-control workspace is unavailable for this Nacos connection".to_string());
|
||||
}
|
||||
let (result, state_changed) =
|
||||
crate::nacos::access_control::start_operation(conn_id, fingerprint, admin.clone(), req).await?;
|
||||
if state_changed {
|
||||
refresh_access_control_after_mutation(&admin).await;
|
||||
crate::nacos::namespace_access::invalidate_all();
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
pub async fn nacos_get_access_operation_core(
|
||||
state: &AppState,
|
||||
conn_id: &str,
|
||||
operation_id: &str,
|
||||
) -> Result<NacosAccessOperationResult, String> {
|
||||
let (_, fingerprint) = get_admin_with_operation_fingerprint(state, conn_id).await?;
|
||||
crate::nacos::access_control::get_operation(conn_id, &fingerprint, operation_id)
|
||||
}
|
||||
|
||||
pub async fn nacos_retry_access_operation_core(
|
||||
state: &AppState,
|
||||
conn_id: &str,
|
||||
retry: NacosAccessOperationRetry,
|
||||
) -> Result<NacosAccessOperationResult, String> {
|
||||
ensure_connection_writable(state, conn_id, "Retry Nacos access-control operation").await?;
|
||||
let (admin, fingerprint) = get_admin_with_operation_fingerprint(state, conn_id).await?;
|
||||
let (result, state_changed) =
|
||||
crate::nacos::access_control::retry_operation(conn_id, fingerprint, admin.clone(), retry).await?;
|
||||
if state_changed {
|
||||
refresh_access_control_after_mutation(&admin).await;
|
||||
crate::nacos::namespace_access::invalidate_all();
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
pub async fn nacos_undo_access_operation_core(
|
||||
state: &AppState,
|
||||
conn_id: &str,
|
||||
operation_id: &str,
|
||||
) -> Result<NacosAccessOperationResult, String> {
|
||||
ensure_connection_writable(state, conn_id, "Undo Nacos access-control operation").await?;
|
||||
let (admin, fingerprint) = get_admin_with_operation_fingerprint(state, conn_id).await?;
|
||||
let (result, state_changed) =
|
||||
crate::nacos::access_control::undo_operation(conn_id, fingerprint, admin.clone(), operation_id).await?;
|
||||
if state_changed {
|
||||
refresh_access_control_after_mutation(&admin).await;
|
||||
crate::nacos::namespace_access::invalidate_all();
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
pub async fn nacos_list_services_core(
|
||||
@@ -278,6 +496,20 @@ pub(crate) async fn get_admin(
|
||||
state.nacos_registry.get_or_build_config(conn_id, admin_config).await
|
||||
}
|
||||
|
||||
async fn get_admin_with_operation_fingerprint(
|
||||
state: &AppState,
|
||||
conn_id: &str,
|
||||
) -> Result<(std::sync::Arc<dyn crate::nacos::port::NacosAdmin>, String), 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());
|
||||
}
|
||||
let admin_config = state.nacos_admin_config_for_connection(conn_id, &cfg).await?;
|
||||
let fingerprint = admin_config.operation_fingerprint();
|
||||
let admin = state.nacos_registry.get_or_build_config(conn_id, admin_config).await?;
|
||||
Ok((admin, fingerprint))
|
||||
}
|
||||
|
||||
pub(crate) async fn ensure_connection_writable(state: &AppState, conn_id: &str, action: &str) -> Result<(), String> {
|
||||
let cfg = state.configs.read().await.get(conn_id).cloned().ok_or("Connection not found")?;
|
||||
if cfg.read_only {
|
||||
@@ -302,6 +534,7 @@ fn ensure_service_operation(
|
||||
Some(NacosCapabilityReason::EndpointUnavailable) => "endpointUnavailable",
|
||||
Some(NacosCapabilityReason::NotVerified) => "notVerified",
|
||||
Some(NacosCapabilityReason::ConnectionReadOnly) => "connectionReadOnly",
|
||||
Some(NacosCapabilityReason::PermissionDenied) => "permissionDenied",
|
||||
None => "notVerified",
|
||||
};
|
||||
Err(format!("NACOS_ERROR[unsupportedOperation]: Nacos service operation {operation:?} is unavailable ({reason})"))
|
||||
@@ -311,6 +544,18 @@ fn ensure_service_operation(
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn access_control_operation_guard_uses_individual_capabilities() {
|
||||
let mut capabilities = NacosAccessControlCapabilities::unavailable(NacosCapabilityReason::PermissionDenied);
|
||||
capabilities.update_user = NacosOperationCapability::supported();
|
||||
|
||||
assert!(ensure_access_control_operation(&capabilities, NacosAccessControlOperation::UpdateUser).is_ok());
|
||||
let error =
|
||||
ensure_access_control_operation(&capabilities, NacosAccessControlOperation::CreateUser).unwrap_err();
|
||||
assert!(error.contains("CreateUser"));
|
||||
assert!(error.contains("permissionDenied"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn core_service_operation_guard_allows_documented_rnacos_v1_writes() {
|
||||
use crate::nacos::config::{
|
||||
@@ -327,6 +572,7 @@ mod tests {
|
||||
namespace: "public".to_string(),
|
||||
version_mode: Some(NacosVersionMode::Auto),
|
||||
context_path: "/nacos".to_string(),
|
||||
managed_namespaces: Vec::new(),
|
||||
rnacos_console_addr: String::new(),
|
||||
rnacos_history_enabled: Some(false),
|
||||
rnacos_console_auth: NacosRNacosConsoleAuth::Inherit,
|
||||
|
||||
@@ -12,6 +12,8 @@ pub struct NacosCapabilities {
|
||||
pub supports_raw_api: bool,
|
||||
#[serde(default)]
|
||||
pub service_management: NacosServiceCapabilities,
|
||||
#[serde(default)]
|
||||
pub access_control: NacosAccessControlCapabilities,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
@@ -46,6 +48,7 @@ pub enum NacosCapabilityReason {
|
||||
EndpointUnavailable,
|
||||
NotVerified,
|
||||
ConnectionReadOnly,
|
||||
PermissionDenied,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
@@ -61,6 +64,93 @@ pub enum NacosServiceOperation {
|
||||
DeregisterInstance,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum NacosAccessControlMode {
|
||||
#[default]
|
||||
Unavailable,
|
||||
RoleBindings,
|
||||
EmbeddedRoles,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum NacosAccessControlOperation {
|
||||
ListUsers,
|
||||
CreateUser,
|
||||
UpdateUser,
|
||||
DeleteUser,
|
||||
ListRoleBindings,
|
||||
AssignRole,
|
||||
RemoveRole,
|
||||
ListPermissions,
|
||||
GrantPermission,
|
||||
RevokePermission,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NacosAccessControlCapabilities {
|
||||
#[serde(default)]
|
||||
pub mode: NacosAccessControlMode,
|
||||
pub list_users: NacosOperationCapability,
|
||||
pub create_user: NacosOperationCapability,
|
||||
pub update_user: NacosOperationCapability,
|
||||
pub delete_user: NacosOperationCapability,
|
||||
pub list_role_bindings: NacosOperationCapability,
|
||||
pub assign_role: NacosOperationCapability,
|
||||
pub remove_role: NacosOperationCapability,
|
||||
pub list_permissions: NacosOperationCapability,
|
||||
pub grant_permission: NacosOperationCapability,
|
||||
pub revoke_permission: NacosOperationCapability,
|
||||
/// Whether all read endpoints required by the directory-detail workspace
|
||||
/// are available. Write operations remain independently capability-gated.
|
||||
#[serde(default)]
|
||||
pub enhanced_workspace: bool,
|
||||
#[serde(default)]
|
||||
pub supports_namespace_privileges: bool,
|
||||
}
|
||||
|
||||
impl NacosAccessControlCapabilities {
|
||||
pub fn unavailable(reason: NacosCapabilityReason) -> Self {
|
||||
Self {
|
||||
mode: NacosAccessControlMode::Unavailable,
|
||||
list_users: NacosOperationCapability::unsupported(reason),
|
||||
create_user: NacosOperationCapability::unsupported(reason),
|
||||
update_user: NacosOperationCapability::unsupported(reason),
|
||||
delete_user: NacosOperationCapability::unsupported(reason),
|
||||
list_role_bindings: NacosOperationCapability::unsupported(reason),
|
||||
assign_role: NacosOperationCapability::unsupported(reason),
|
||||
remove_role: NacosOperationCapability::unsupported(reason),
|
||||
list_permissions: NacosOperationCapability::unsupported(reason),
|
||||
grant_permission: NacosOperationCapability::unsupported(reason),
|
||||
revoke_permission: NacosOperationCapability::unsupported(reason),
|
||||
enhanced_workspace: false,
|
||||
supports_namespace_privileges: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn operation(&self, operation: NacosAccessControlOperation) -> &NacosOperationCapability {
|
||||
match operation {
|
||||
NacosAccessControlOperation::ListUsers => &self.list_users,
|
||||
NacosAccessControlOperation::CreateUser => &self.create_user,
|
||||
NacosAccessControlOperation::UpdateUser => &self.update_user,
|
||||
NacosAccessControlOperation::DeleteUser => &self.delete_user,
|
||||
NacosAccessControlOperation::ListRoleBindings => &self.list_role_bindings,
|
||||
NacosAccessControlOperation::AssignRole => &self.assign_role,
|
||||
NacosAccessControlOperation::RemoveRole => &self.remove_role,
|
||||
NacosAccessControlOperation::ListPermissions => &self.list_permissions,
|
||||
NacosAccessControlOperation::GrantPermission => &self.grant_permission,
|
||||
NacosAccessControlOperation::RevokePermission => &self.revoke_permission,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for NacosAccessControlCapabilities {
|
||||
fn default() -> Self {
|
||||
Self::unavailable(NacosCapabilityReason::NotVerified)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NacosServiceCapabilities {
|
||||
@@ -115,10 +205,341 @@ impl Default for NacosCapabilities {
|
||||
supports_instance_update: true,
|
||||
supports_raw_api: true,
|
||||
service_management: NacosServiceCapabilities::default(),
|
||||
access_control: NacosAccessControlCapabilities::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NacosNamespacePrivilege {
|
||||
#[serde(default = "default_true")]
|
||||
pub enabled: bool,
|
||||
#[serde(default = "default_true")]
|
||||
pub whitelist_is_all: bool,
|
||||
#[serde(default)]
|
||||
pub whitelist: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub blacklist_is_all: bool,
|
||||
#[serde(default)]
|
||||
pub blacklist: Vec<String>,
|
||||
}
|
||||
|
||||
fn default_true() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
impl Default for NacosNamespacePrivilege {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
enabled: true,
|
||||
whitelist_is_all: true,
|
||||
whitelist: Vec::new(),
|
||||
blacklist_is_all: false,
|
||||
blacklist: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NacosUserQuery {
|
||||
#[serde(default)]
|
||||
pub username: Option<String>,
|
||||
#[serde(default)]
|
||||
pub page_no: Option<u32>,
|
||||
#[serde(default)]
|
||||
pub page_size: Option<u32>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NacosUserInfo {
|
||||
pub username: String,
|
||||
#[serde(default)]
|
||||
pub nickname: Option<String>,
|
||||
#[serde(default)]
|
||||
pub enabled: Option<bool>,
|
||||
#[serde(default)]
|
||||
pub roles: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub namespace_privilege: Option<NacosNamespacePrivilege>,
|
||||
#[serde(default)]
|
||||
pub source: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NacosUserList {
|
||||
pub page_no: u32,
|
||||
pub page_size: u32,
|
||||
pub total_count: u64,
|
||||
pub items: Vec<NacosUserInfo>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NacosUserCreate {
|
||||
pub username: String,
|
||||
pub password: String,
|
||||
#[serde(default)]
|
||||
pub nickname: Option<String>,
|
||||
#[serde(default)]
|
||||
pub enabled: Option<bool>,
|
||||
#[serde(default)]
|
||||
pub roles: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub namespace_privilege: Option<NacosNamespacePrivilege>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NacosUserUpdate {
|
||||
pub username: String,
|
||||
#[serde(default)]
|
||||
pub password: Option<String>,
|
||||
#[serde(default)]
|
||||
pub nickname: Option<String>,
|
||||
#[serde(default)]
|
||||
pub enabled: Option<bool>,
|
||||
#[serde(default)]
|
||||
pub roles: Option<Vec<String>>,
|
||||
#[serde(default)]
|
||||
pub namespace_privilege: Option<NacosNamespacePrivilege>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NacosRoleQuery {
|
||||
#[serde(default)]
|
||||
pub username: Option<String>,
|
||||
#[serde(default)]
|
||||
pub role: Option<String>,
|
||||
#[serde(default)]
|
||||
pub page_no: Option<u32>,
|
||||
#[serde(default)]
|
||||
pub page_size: Option<u32>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NacosRoleBinding {
|
||||
pub username: String,
|
||||
pub role: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NacosRoleList {
|
||||
pub page_no: u32,
|
||||
pub page_size: u32,
|
||||
pub total_count: u64,
|
||||
pub items: Vec<NacosRoleBinding>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NacosPermissionQuery {
|
||||
#[serde(default)]
|
||||
pub role: Option<String>,
|
||||
#[serde(default)]
|
||||
pub resource: Option<String>,
|
||||
#[serde(default)]
|
||||
pub page_no: Option<u32>,
|
||||
#[serde(default)]
|
||||
pub page_size: Option<u32>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NacosPermissionInfo {
|
||||
pub role: String,
|
||||
pub resource_raw: String,
|
||||
pub action_raw: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub parsed_scope: Option<NacosPermissionScope>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NacosPermissionScope {
|
||||
pub kind: NacosPermissionScopeKind,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub namespace_id: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum NacosPermissionScopeKind {
|
||||
Namespace,
|
||||
Global,
|
||||
Custom,
|
||||
Unknown,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NacosPermissionList {
|
||||
pub page_no: u32,
|
||||
pub page_size: u32,
|
||||
pub total_count: u64,
|
||||
pub items: Vec<NacosPermissionInfo>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NacosRoleSummary {
|
||||
pub role: String,
|
||||
pub member_count: u64,
|
||||
pub permission_count: u64,
|
||||
pub complete: bool,
|
||||
pub administrator: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NacosEffectivePermission {
|
||||
pub resource_raw: String,
|
||||
pub action: String,
|
||||
pub parsed_scope: Option<NacosPermissionScope>,
|
||||
pub source_roles: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NacosAccessControlSnapshot {
|
||||
pub users: Vec<NacosUserInfo>,
|
||||
pub role_bindings: Vec<NacosRoleBinding>,
|
||||
pub permissions: Vec<NacosPermissionInfo>,
|
||||
pub roles: Vec<NacosRoleSummary>,
|
||||
pub namespaces: Vec<NacosNamespaceInfo>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub current_username: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NacosNewUserDraft {
|
||||
pub username: String,
|
||||
pub password: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NacosPermissionDraft {
|
||||
pub namespace_ids: Vec<String>,
|
||||
pub action: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(tag = "kind", rename_all = "camelCase")]
|
||||
pub enum NacosAccessOperationRequest {
|
||||
CreateUser {
|
||||
username: String,
|
||||
password: String,
|
||||
#[serde(default)]
|
||||
roles: Vec<String>,
|
||||
#[serde(default)]
|
||||
confirmation: Option<String>,
|
||||
},
|
||||
CreateRole {
|
||||
role: String,
|
||||
#[serde(default)]
|
||||
members: Vec<String>,
|
||||
#[serde(default, rename = "newUsers")]
|
||||
new_users: Vec<NacosNewUserDraft>,
|
||||
permissions: Vec<NacosPermissionDraft>,
|
||||
#[serde(default)]
|
||||
confirmation: Option<String>,
|
||||
},
|
||||
UpdateUserRoles {
|
||||
username: String,
|
||||
roles: Vec<String>,
|
||||
#[serde(default)]
|
||||
confirmation: Option<String>,
|
||||
},
|
||||
UpdateRole {
|
||||
role: String,
|
||||
members: Vec<String>,
|
||||
#[serde(default, rename = "newUsers")]
|
||||
new_users: Vec<NacosNewUserDraft>,
|
||||
permissions: Vec<NacosPermissionDraft>,
|
||||
#[serde(default)]
|
||||
confirmation: Option<String>,
|
||||
},
|
||||
DeleteUser {
|
||||
username: String,
|
||||
#[serde(default)]
|
||||
confirmation: Option<String>,
|
||||
},
|
||||
DeleteRole {
|
||||
role: String,
|
||||
#[serde(default)]
|
||||
confirmation: Option<String>,
|
||||
},
|
||||
RevokePermission {
|
||||
permission: NacosPermissionInfo,
|
||||
#[serde(default)]
|
||||
confirmation: Option<String>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum NacosAccessOperationStatus {
|
||||
Running,
|
||||
Partial,
|
||||
Succeeded,
|
||||
Failed,
|
||||
Undoing,
|
||||
Undone,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum NacosAccessOperationStepStatus {
|
||||
Pending,
|
||||
Running,
|
||||
Succeeded,
|
||||
Failed,
|
||||
Skipped,
|
||||
Compensated,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NacosAccessOperationStep {
|
||||
pub id: String,
|
||||
pub action: String,
|
||||
pub target: String,
|
||||
pub status: NacosAccessOperationStepStatus,
|
||||
pub retryable: bool,
|
||||
#[serde(default)]
|
||||
pub needs_password: bool,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub message: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NacosAccessOperationResult {
|
||||
pub operation_id: String,
|
||||
pub status: NacosAccessOperationStatus,
|
||||
pub steps: Vec<NacosAccessOperationStep>,
|
||||
#[serde(default)]
|
||||
pub can_retry: bool,
|
||||
#[serde(default)]
|
||||
pub can_undo: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NacosAccessOperationRetry {
|
||||
pub operation_id: String,
|
||||
#[serde(default)]
|
||||
pub credentials: Vec<NacosNewUserDraft>,
|
||||
}
|
||||
|
||||
/// 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.
|
||||
@@ -158,6 +579,13 @@ pub struct NacosNamespaceInfo {
|
||||
pub namespace_type: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NacosNamespaceSidebarSnapshot {
|
||||
pub namespaces: Vec<NacosNamespaceInfo>,
|
||||
pub access_control: NacosAccessControlCapabilities,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NacosNamespaceCreate {
|
||||
|
||||
Reference in new issue
Block a user