You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@hugegraph.apache.org by ji...@apache.org on 2026/08/30 10:58:18 UTC
(hugegraph-toolchain) 03/24: fix(hubble): restore management operations UX
This is an automated email from the ASF dual-hosted git repository.
imbajin pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/hugegraph-toolchain.git
commit f97aa823447c39f9c8e48a908b9f25f83f3d1011
Author: dark <ji...@apache.org>
AuthorDate: Mon Aug 17 11:54:46 2026 +0800
fix(hubble): restore management operations UX
- refine account and node surfaces
- propagate deployment authentication mode
- stabilize PD, Store, and standalone operations discovery
---
.github/workflows/hubble-ci.yml | 15 +-
README.md | 6 -
.../org/apache/hugegraph/driver/HugeClient.java | 3 +-
.../hugegraph/driver/ServerCompatibility.java | 29 ++-
.../driver/HugeClientCompatibilityTest.java | 77 ++++++++
.../hugegraph/driver/ServerCompatibilityTest.java | 17 +-
.../org/apache/hugegraph/unit/UnitTestSuite.java | 4 +
hugegraph-hubble/README.md | 25 +--
.../docs/images/compat-1.5-standalone.png | Bin 82286 -> 0 bytes
.../docs/images/compat-1.7-standalone.png | Bin 81494 -> 0 bytes
.../docs/images/compat-1.8-auth-account.png | Bin 68710 -> 0 bytes
.../docs/images/compat-1.8-auth-dashboard.png | Bin 106470 -> 0 bytes
.../docs/images/compat-1.8-graphspace-access.png | Bin 62654 -> 0 bytes
hugegraph-hubble/docs/images/compat-1.8-pd.png | Bin 28788 -> 0 bytes
.../org/apache/hugegraph/config/HubbleConfig.java | 24 ++-
.../org/apache/hugegraph/config/WebMvcConfig.java | 3 +-
.../controller/op/OperationsController.java | 3 +
.../apache/hugegraph/options/HubbleOptions.java | 3 +-
.../hugegraph/service/auth/AuthContextService.java | 44 +++--
.../service/auth/GraphSpaceUserService.java | 68 +++----
.../apache/hugegraph/service/auth/UserService.java | 61 +++++--
.../service/op/DefaultOperationsDataService.java | 30 +++-
.../service/op/LiveOperationsCollector.java | 96 +++++++++-
.../service/op/OperationsPayloadParser.java | 72 ++++++++
.../hugegraph/service/space/GraphSpaceService.java | 11 +-
.../src/main/resources/i18n/messages.properties | 3 +
.../main/resources/i18n/messages_zh_CN.properties | 3 +
.../config/HubbleConfigEnvironmentTest.java | 68 +++++++
.../auth/GraphSpaceAuthOwnershipTest.java | 12 +-
.../service/auth/AuthContextServiceTest.java | 46 +++++
.../service/auth/GraphSpaceUserServiceTest.java | 196 +++++++++++++++++++++
.../op/DefaultOperationsDataServiceTest.java | 79 +++++++++
.../service/op/LiveOperationsCollectorTest.java | 96 +++++++++-
.../service/op/OperationsPayloadParserTest.java | 49 +++++-
.../service/space/GraphSpaceServiceTest.java | 80 +++++++++
.../apache/hugegraph/unit/AuthSecurityTest.java | 25 +++
.../hugegraph/unit/OperationsControllerTest.java | 30 ++++
.../org/apache/hugegraph/unit/UnitTestSuite.java | 2 +
.../unit/UserServiceCompatibilityTest.java | 147 +++++++++++++++-
.../static/conf/hugegraph-hubble.properties | 3 +
.../src/i18n/resources/en-US/modules/pages.json | 16 +-
.../src/i18n/resources/zh-CN/modules/pages.json | 18 +-
.../src/modules/navigation/ConsoleItem/index.js | 9 +-
.../modules/navigation/ConsoleItem/index.test.js | 21 +++
.../hubble-fe/src/pages/Account/EditLayer.js | 181 ++++++++++++++-----
.../hubble-fe/src/pages/Account/SpaceAccess.js | 11 +-
.../pages/Account/account-edit-recovery.test.js | 165 +++++++++++++++++
.../hubble-fe/src/pages/Account/accountError.js | 26 +++
.../hubble-fe/src/pages/Account/index.js | 7 +-
.../hubble-fe/src/pages/Operations/NodeDetail.js | 31 +---
.../src/pages/Operations/NodeDetail.test.js | 22 +--
.../hubble-fe/src/pages/Operations/Nodes.js | 10 +-
.../hubble-fe/src/pages/Operations/Nodes.test.js | 33 +++-
.../hubble-fe/src/pages/Operations/Overview.js | 29 +--
.../src/pages/Operations/Overview.test.js | 45 ++++-
.../hubble-fe/src/pages/Operations/components.js | 15 +-
.../src/pages/Operations/components.test.js | 26 +++
.../hubble-fe/src/pages/Operations/topology.js | 69 +++++++-
.../src/pages/Operations/topology.test.js | 50 ++++++
hugegraph-hubble/hubble-fe/src/setupProxy.js | 8 +-
hugegraph-hubble/hubble-fe/src/setupProxy.test.js | 90 ++++++++++
61 files changed, 2069 insertions(+), 243 deletions(-)
diff --git a/.github/workflows/hubble-ci.yml b/.github/workflows/hubble-ci.yml
index 5445dbb0b..d61370480 100644
--- a/.github/workflows/hubble-ci.yml
+++ b/.github/workflows/hubble-ci.yml
@@ -23,8 +23,9 @@ on:
env:
TRAVIS_DIR: hugegraph-hubble/hubble-dist/assembly/travis
- HUGEGRAPH_SERVER_COMMIT: 99936be5f41fccd193f120e01206e3cf3c73a050
- HUGEGRAPH_SERVER_FETCH_REF: refs/heads/master
+ # Server PR #3159 declares the GraphSpace default-role contract as API 0.72.
+ HUGEGRAPH_SERVER_COMMIT: 52035dad9ee8d6b666329ca0d03950c773d3e1eb
+ HUGEGRAPH_SERVER_FETCH_REF: refs/pull/3159/head
jobs:
hubble-ci:
@@ -138,6 +139,16 @@ jobs:
cd ../../../
pwd
$TRAVIS_DIR/install-hugegraph.sh $COMMIT_ID $COMMIT_REF
+ API_VERSION="$(curl --fail --silent http://127.0.0.1:8080/versions |
+ python -c 'import json,sys; print(json.load(sys.stdin)["versions"]["api"])')"
+ python - "$API_VERSION" <<'PY'
+ import sys
+ parts = tuple(int(value) for value in sys.argv[1].split(".")[:2])
+ if parts < (0, 72):
+ raise SystemExit(
+ f"Expected HugeGraph REST API >= 0.72, got {sys.argv[1]}"
+ )
+ PY
- name: Release package audit
env:
diff --git a/README.md b/README.md
index bff20dad7..3edc10958 100644
--- a/README.md
+++ b/README.md
@@ -19,12 +19,6 @@ four readable presets. A thin adapter keeps 1.7 usable and limits 1.5 to its
standalone core graph workflow; version checks are centralized rather than
spread across UI pages.
-
-
-
-
-
-
**Quick Navigation**: [Architecture](#architecture-overview) | [Quick Start](#quick-start) | [Modules](#module-overview) | [Build](#build--development) | [Docker](#docker) | [Related Projects](#related-projects)
## Related Projects
diff --git a/hugegraph-client/src/main/java/org/apache/hugegraph/driver/HugeClient.java b/hugegraph-client/src/main/java/org/apache/hugegraph/driver/HugeClient.java
index 578b9ce4b..41cf3e447 100644
--- a/hugegraph-client/src/main/java/org/apache/hugegraph/driver/HugeClient.java
+++ b/hugegraph-client/src/main/java/org/apache/hugegraph/driver/HugeClient.java
@@ -212,7 +212,8 @@ public class HugeClient implements Closeable {
// 0.81 equals to the {latest_api_version} +10
VersionUtil.check(apiVersion, "0.38", "0.81", "hugegraph-api in server");
this.client.apiVersion(apiVersion);
- this.compatibility = ServerCompatibility.profile(this.version.getCoreVersion());
+ this.compatibility = ServerCompatibility.profile(
+ this.version.getCoreVersion(), apiVersion.get());
this.client.setSupportGs(this.compatibility.supportsGraphSpace());
}
diff --git a/hugegraph-client/src/main/java/org/apache/hugegraph/driver/ServerCompatibility.java b/hugegraph-client/src/main/java/org/apache/hugegraph/driver/ServerCompatibility.java
index 18fb6bd2c..b695edfe8 100644
--- a/hugegraph-client/src/main/java/org/apache/hugegraph/driver/ServerCompatibility.java
+++ b/hugegraph-client/src/main/java/org/apache/hugegraph/driver/ServerCompatibility.java
@@ -29,32 +29,49 @@ import org.apache.hugegraph.util.VersionUtil;
public final class ServerCompatibility {
private static final String GRAPHSPACE_MIN_VERSION = "1.7.0";
- private static final String DEFAULT_ROLE_MIN_VERSION = "1.8.0";
+ private static final String DEFAULT_ROLE_MIN_API_VERSION = "0.72";
private ServerCompatibility() {
}
public static Profile profile(String coreVersion) {
+ return profile(coreVersion, null);
+ }
+
+ public static Profile profile(String coreVersion, String apiVersion) {
+ if (supportsDefaultRoleApi(apiVersion)) {
+ return Profile.MODERN;
+ }
if (coreVersion == null || coreVersion.trim().isEmpty()) {
return Profile.LEGACY;
}
try {
String normalized = coreVersion.trim();
- if (VersionUtil.gte(normalized, DEFAULT_ROLE_MIN_VERSION)) {
- return Profile.MODERN;
- }
return VersionUtil.gte(normalized, GRAPHSPACE_MIN_VERSION) ? Profile.GRAPHSPACE : Profile.LEGACY;
} catch (RuntimeException ignored) {
return Profile.LEGACY;
}
}
+ private static boolean supportsDefaultRoleApi(String apiVersion) {
+ if (apiVersion == null || apiVersion.trim().isEmpty()) {
+ return false;
+ }
+ try {
+ return VersionUtil.gte(apiVersion.trim(),
+ DEFAULT_ROLE_MIN_API_VERSION);
+ } catch (RuntimeException ignored) {
+ return false;
+ }
+ }
+
public static boolean supportsGraphSpace(String coreVersion) {
return profile(coreVersion).supportsGraphSpace();
}
- public static boolean supportsDefaultRole(String coreVersion) {
- return profile(coreVersion).supportsDefaultRole();
+ public static boolean supportsDefaultRole(String coreVersion,
+ String apiVersion) {
+ return profile(coreVersion, apiVersion).supportsDefaultRole();
}
public enum Profile {
diff --git a/hugegraph-client/src/test/java/org/apache/hugegraph/driver/HugeClientCompatibilityTest.java b/hugegraph-client/src/test/java/org/apache/hugegraph/driver/HugeClientCompatibilityTest.java
new file mode 100644
index 000000000..aed9bb494
--- /dev/null
+++ b/hugegraph-client/src/test/java/org/apache/hugegraph/driver/HugeClientCompatibilityTest.java
@@ -0,0 +1,77 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with this
+ * work for additional information regarding copyright ownership. The ASF
+ * licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.hugegraph.driver;
+
+import java.util.Arrays;
+
+import org.apache.hugegraph.structure.auth.User;
+import org.apache.hugegraph.testutil.Whitebox;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+public class HugeClientCompatibilityTest {
+
+ private HugeClient client;
+ private AuthManager auth;
+
+ @Before
+ public void setup() {
+ this.client = Mockito.mock(HugeClient.class,
+ Mockito.CALLS_REAL_METHODS);
+ this.auth = Mockito.mock(AuthManager.class);
+ Whitebox.setInternalState(this.client, "auth", this.auth);
+ }
+
+ @Test
+ public void shouldUseDirectLookupForModernServers() {
+ User alice = user("alice");
+ Whitebox.setInternalState(
+ this.client, "compatibility",
+ ServerCompatibility.Profile.MODERN);
+ Mockito.when(this.auth.getUserByName("alice")).thenReturn(alice);
+
+ Assert.assertTrue(this.client.supportsDefaultRole());
+ Assert.assertSame(alice, this.client.findUserByName("alice"));
+ Mockito.verify(this.auth, Mockito.never()).listUsers();
+ }
+
+ @Test
+ public void shouldSearchLegacyUserListsByName() {
+ User alice = user("alice");
+ User bob = user("bob");
+ Whitebox.setInternalState(
+ this.client, "compatibility",
+ ServerCompatibility.Profile.GRAPHSPACE);
+ Mockito.when(this.auth.listUsers())
+ .thenReturn(Arrays.asList(bob, alice));
+
+ Assert.assertFalse(this.client.supportsDefaultRole());
+ Assert.assertSame(alice, this.client.findUserByName("alice"));
+ Assert.assertNull(this.client.findUserByName("missing"));
+ Mockito.verify(this.auth, Mockito.never())
+ .getUserByName(Mockito.anyString());
+ }
+
+ private static User user(String name) {
+ User user = new User();
+ user.name(name);
+ return user;
+ }
+}
diff --git a/hugegraph-client/src/test/java/org/apache/hugegraph/driver/ServerCompatibilityTest.java b/hugegraph-client/src/test/java/org/apache/hugegraph/driver/ServerCompatibilityTest.java
index 96f98ad0c..05ebb41dd 100644
--- a/hugegraph-client/src/test/java/org/apache/hugegraph/driver/ServerCompatibilityTest.java
+++ b/hugegraph-client/src/test/java/org/apache/hugegraph/driver/ServerCompatibilityTest.java
@@ -35,9 +35,20 @@ public class ServerCompatibilityTest {
Assert.assertTrue(ServerCompatibility.supportsGraphSpace("1.7.0"));
Assert.assertTrue(ServerCompatibility.supportsGraphSpace(" 1.7.0 "));
Assert.assertTrue(ServerCompatibility.supportsGraphSpace("1.8.0"));
- Assert.assertFalse(ServerCompatibility.supportsDefaultRole("1.7.0"));
- Assert.assertTrue(ServerCompatibility.supportsDefaultRole("1.8.0"));
+ Assert.assertFalse(ServerCompatibility.supportsDefaultRole(
+ "1.7.0", "0.71.0.0"));
+ Assert.assertTrue(ServerCompatibility.supportsDefaultRole(
+ "1.7.0", "0.72.0.0"));
+ Assert.assertFalse(ServerCompatibility.supportsDefaultRole(
+ "1.8.0", "0.71.0.0"));
Assert.assertEquals(ServerCompatibility.Profile.GRAPHSPACE,
- ServerCompatibility.profile("1.7.1"));
+ ServerCompatibility.profile("1.7.1",
+ "0.71.0.0"));
+ Assert.assertEquals(ServerCompatibility.Profile.MODERN,
+ ServerCompatibility.profile("1.7.0",
+ "0.72.0.0"));
+ Assert.assertEquals(ServerCompatibility.Profile.GRAPHSPACE,
+ ServerCompatibility.profile("1.7.0",
+ "not-a-version"));
}
}
diff --git a/hugegraph-client/src/test/java/org/apache/hugegraph/unit/UnitTestSuite.java b/hugegraph-client/src/test/java/org/apache/hugegraph/unit/UnitTestSuite.java
index ab4c18de3..f48efbcec 100644
--- a/hugegraph-client/src/test/java/org/apache/hugegraph/unit/UnitTestSuite.java
+++ b/hugegraph-client/src/test/java/org/apache/hugegraph/unit/UnitTestSuite.java
@@ -17,6 +17,8 @@
package org.apache.hugegraph.unit;
+import org.apache.hugegraph.driver.HugeClientCompatibilityTest;
+import org.apache.hugegraph.driver.ServerCompatibilityTest;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@@ -33,6 +35,8 @@ import org.junit.runners.Suite;
ManagerAPITest.class,
GraphsAPITest.class,
PDHugeClientFactoryTest.class,
+ HugeClientCompatibilityTest.class,
+ ServerCompatibilityTest.class,
CommonUtilTest.class,
IdUtilTest.class,
SplicingIdGeneratorTest.class
diff --git a/hugegraph-hubble/README.md b/hugegraph-hubble/README.md
index 4062f4f9f..445b4ee20 100644
--- a/hugegraph-hubble/README.md
+++ b/hugegraph-hubble/README.md
@@ -17,6 +17,11 @@ always goes through the backend resolver. In PD mode, a valid server address
returned by discovery is sufficient; a manually configured server URL is not
required.
+Container and orchestrated deployments can set `HUBBLE_AUTH_ENABLED=true` or
+`false`. This explicit runtime value overrides `auth.enabled` from the
+properties file, and invalid values fail startup instead of silently selecting
+an authentication mode.
+
The UI presents four stable permission meanings: super administrator, GraphSpace
read-only, GraphSpace read-write, and GraphSpace administrator. The last one
means member management plus read/write within that GraphSpace; low-level
@@ -29,26 +34,6 @@ unsupported. Version checks stay in the client adapter/resolver rather than
being scattered through controllers or pages. See
[`AGENTS.md`](AGENTS.md) for the support matrix and verification rules.
-### UI reference captures
-
-The following captures are collected from Chrome against the running Hubble
-application and document the supported states:
-
-
-
-
-
-
-
-
-
-
-
-
-
-The 1.5 and 1.7 captures show standalone non-auth core workflows. The 1.8/master
-captures cover both PD/non-auth connection discovery and authenticated account / GraphSpace permission surfaces.
-
## Local development feedback loop
Run the frontend with third-party source-map noise disabled:
diff --git a/hugegraph-hubble/docs/images/compat-1.5-standalone.png b/hugegraph-hubble/docs/images/compat-1.5-standalone.png
deleted file mode 100644
index 34223b135..000000000
Binary files a/hugegraph-hubble/docs/images/compat-1.5-standalone.png and /dev/null differ
diff --git a/hugegraph-hubble/docs/images/compat-1.7-standalone.png b/hugegraph-hubble/docs/images/compat-1.7-standalone.png
deleted file mode 100644
index c656488e2..000000000
Binary files a/hugegraph-hubble/docs/images/compat-1.7-standalone.png and /dev/null differ
diff --git a/hugegraph-hubble/docs/images/compat-1.8-auth-account.png b/hugegraph-hubble/docs/images/compat-1.8-auth-account.png
deleted file mode 100644
index e86c1c2d7..000000000
Binary files a/hugegraph-hubble/docs/images/compat-1.8-auth-account.png and /dev/null differ
diff --git a/hugegraph-hubble/docs/images/compat-1.8-auth-dashboard.png b/hugegraph-hubble/docs/images/compat-1.8-auth-dashboard.png
deleted file mode 100644
index 9bbffb315..000000000
Binary files a/hugegraph-hubble/docs/images/compat-1.8-auth-dashboard.png and /dev/null differ
diff --git a/hugegraph-hubble/docs/images/compat-1.8-graphspace-access.png b/hugegraph-hubble/docs/images/compat-1.8-graphspace-access.png
deleted file mode 100644
index 537694b0d..000000000
Binary files a/hugegraph-hubble/docs/images/compat-1.8-graphspace-access.png and /dev/null differ
diff --git a/hugegraph-hubble/docs/images/compat-1.8-pd.png b/hugegraph-hubble/docs/images/compat-1.8-pd.png
deleted file mode 100644
index a72899a35..000000000
Binary files a/hugegraph-hubble/docs/images/compat-1.8-pd.png and /dev/null differ
diff --git a/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/config/HubbleConfig.java b/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/config/HubbleConfig.java
index 8caad2787..ea40f8668 100644
--- a/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/config/HubbleConfig.java
+++ b/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/config/HubbleConfig.java
@@ -28,10 +28,14 @@ import org.springframework.context.annotation.Configuration;
import java.io.File;
import java.net.URL;
+import java.util.Locale;
+import java.util.Map;
@Configuration
public class HubbleConfig {
+ static final String AUTH_ENABLED_ENV = "HUBBLE_AUTH_ENABLED";
+
@Autowired
private ApplicationArguments arguments;
@@ -56,6 +60,24 @@ public class HubbleConfig {
conf = path;
}
}
- return new HugeConfig(conf);
+ HugeConfig config = new HugeConfig(conf);
+ applyEnvironmentOverrides(config, System.getenv());
+ return config;
+ }
+
+ static void applyEnvironmentOverrides(HugeConfig config,
+ Map<String, String> environment) {
+ String authEnabled = environment.get(AUTH_ENABLED_ENV);
+ if (authEnabled == null) {
+ return;
+ }
+
+ String normalized = authEnabled.trim().toLowerCase(Locale.ROOT);
+ if (!normalized.equals("true") && !normalized.equals("false")) {
+ throw new ExternalException(
+ AUTH_ENABLED_ENV + " must be true or false");
+ }
+ config.setProperty(HubbleOptions.AUTH_ENABLED.name(),
+ Boolean.valueOf(normalized));
}
}
diff --git a/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/config/WebMvcConfig.java b/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/config/WebMvcConfig.java
index 27c96f601..f0a2950b7 100644
--- a/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/config/WebMvcConfig.java
+++ b/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/config/WebMvcConfig.java
@@ -18,6 +18,7 @@
package org.apache.hugegraph.config;
+import org.apache.hugegraph.common.Constant;
import org.apache.hugegraph.handler.LoginInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@@ -66,7 +67,7 @@ public class WebMvcConfig implements WebMvcConfigurer {
registry.addInterceptor(this.loginInterceptor())
.addPathPatterns("/api/**")
.excludePathPatterns("/api/**/auth/login")
- .excludePathPatterns("/api/**/config")
+ .excludePathPatterns(Constant.API_VERSION + "config")
.excludePathPatterns("/logout")
.excludePathPatterns("/api/**/auth/logout");
}
diff --git a/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/controller/op/OperationsController.java b/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/controller/op/OperationsController.java
index a8eb01420..ab8371bea 100644
--- a/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/controller/op/OperationsController.java
+++ b/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/controller/op/OperationsController.java
@@ -100,6 +100,9 @@ public class OperationsController extends BaseController {
}
private Set<String> currentCapabilities(HugeClient client) {
+ if (this.authMode != null && this.authMode.anonymous()) {
+ return OperationsCapabilityService.forLevel("ADMIN");
+ }
String level = this.userService.userLevel(client, this.getUser());
return OperationsCapabilityService.forLevel(level);
}
diff --git a/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/options/HubbleOptions.java b/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/options/HubbleOptions.java
index 3ae56c344..56b544dc3 100644
--- a/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/options/HubbleOptions.java
+++ b/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/options/HubbleOptions.java
@@ -281,7 +281,8 @@ public class HubbleOptions extends OptionHolder {
public static final ConfigOption<Boolean> AUTH_ENABLED =
new ConfigOption<>("auth.enabled",
- "Whether Hubble requires a user session. Set false when " + "the connected HugeGraph Server runs in anonymous mode.",
+ "Whether Hubble requires a user session. Set false when " +
+ "the connected HugeGraph Server runs in anonymous mode.",
null,
true
);
diff --git a/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/service/auth/AuthContextService.java b/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/service/auth/AuthContextService.java
index 11cd95d8e..e5bcb701c 100644
--- a/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/service/auth/AuthContextService.java
+++ b/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/service/auth/AuthContextService.java
@@ -51,6 +51,8 @@ public class AuthContextService {
public static final String ACCOUNT_SELF_MANAGE = "account_self_manage";
public static final String ACCOUNTS_MANAGE = "accounts_manage";
+ public static final String ACCOUNT_PERMISSION_PRESETS =
+ "account_permission_presets";
public static final String GRAPHSPACES_READ = "graphspaces_read";
public static final String GRAPHSPACES_MANAGE = "graphspaces_manage";
public static final String GRAPHSPACE_MEMBERS_MANAGE =
@@ -110,8 +112,12 @@ public class AuthContextService {
role = "ADMIN".equals(serverRole) ? SUPERADMIN : USER;
}
- Set<String> capabilities = this.capabilities(pdEnabled, role);
- Map<String, Set<String>> actions = this.actions(pdEnabled, role);
+ boolean permissionPresets = pdEnabled &&
+ client.supportsDefaultRole();
+ Set<String> capabilities = this.capabilities(pdEnabled, role,
+ permissionPresets);
+ Map<String, Set<String>> actions = this.actions(pdEnabled, role,
+ permissionPresets);
Map<String, Object> scopes = this.scopes(pdEnabled, role,
adminGraphSpaces);
String version = version(mode, username, role, capabilities,
@@ -130,16 +136,26 @@ public class AuthContextService {
}
private static Map<String, Object> anonymousContext(boolean pdEnabled) {
+ Set<String> capabilities = new LinkedHashSet<>();
+ capabilities.add(GRAPH_RESOURCES_ACCESS);
+ if (pdEnabled) {
+ capabilities.add(GRAPHSPACES_READ);
+ }
+ capabilities.addAll(OperationsCapabilityService.forLevel("ADMIN"));
+
Map<String, Object> context = new LinkedHashMap<>();
context.put("schema_version", SCHEMA_VERSION);
- context.put("context_version", "anonymous-v1");
+ context.put("context_version",
+ pdEnabled ? "anonymous-v2-pd" : "anonymous-v2-non-pd");
context.put("mode", "NON_AUTH");
context.put("username", null);
context.put("role", "ANONYMOUS");
Map<String, Set<String>> actions = new LinkedHashMap<>();
- actions.put("graphspaces", pdEnabled ? Collections.singleton("read") : Collections.emptySet());
- context.put("capabilities", pdEnabled ? set(GRAPH_RESOURCES_ACCESS, GRAPHSPACES_READ) :
- Collections.singleton(GRAPH_RESOURCES_ACCESS));
+ actions.put("graphspaces", pdEnabled ?
+ Collections.singleton("read") : Collections.emptySet());
+ actions.put("operations", OPERATIONS_ACTIONS);
+ context.put("capabilities",
+ Collections.unmodifiableSet(capabilities));
context.put("actions", actions);
Map<String, Object> scopes = new LinkedHashMap<>();
scopes.put("all_graphspaces", pdEnabled);
@@ -149,13 +165,17 @@ public class AuthContextService {
return Collections.unmodifiableMap(context);
}
- private Set<String> capabilities(boolean pdEnabled, String role) {
+ private Set<String> capabilities(boolean pdEnabled, String role,
+ boolean permissionPresets) {
Set<String> capabilities = new LinkedHashSet<>();
capabilities.add(ACCOUNT_SELF_MANAGE);
capabilities.add(GRAPH_RESOURCES_ACCESS);
if (pdEnabled) {
capabilities.add(GRAPHSPACES_READ);
}
+ if (permissionPresets) {
+ capabilities.add(ACCOUNT_PERMISSION_PRESETS);
+ }
if (SUPERADMIN.equals(role)) {
capabilities.add(ACCOUNTS_MANAGE);
if (pdEnabled) {
@@ -176,18 +196,20 @@ public class AuthContextService {
return Collections.unmodifiableSet(capabilities);
}
- private Map<String, Set<String>> actions(boolean pdEnabled, String role) {
+ private Map<String, Set<String>> actions(boolean pdEnabled, String role,
+ boolean permissionPresets) {
Map<String, Set<String>> actions = new LinkedHashMap<>();
boolean superAdmin = SUPERADMIN.equals(role);
- boolean spaceManager = pdEnabled &&
+ boolean spaceManager = pdEnabled && permissionPresets &&
(superAdmin || SPACEADMIN.equals(role));
actions.put("account", SELF_ACTIONS);
actions.put("accounts", superAdmin ? CRUD_ACTIONS : emptySet());
actions.put("graphspaces", pdEnabled ?
(superAdmin ? CRUD_ACTIONS : set("read")) : emptySet());
actions.put("members", spaceManager ? MEMBER_ACTIONS : emptySet());
- actions.put("roles", superAdmin ? CRUD_ACTIONS : emptySet());
- actions.put("authorizations", superAdmin ?
+ actions.put("roles", permissionPresets && superAdmin ?
+ CRUD_ACTIONS : emptySet());
+ actions.put("authorizations", permissionPresets && superAdmin ?
AUTHORIZATION_ACTIONS : emptySet());
actions.put("operations", superAdmin ?
OPERATIONS_ACTIONS : emptySet());
diff --git a/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/service/auth/GraphSpaceUserService.java b/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/service/auth/GraphSpaceUserService.java
index 225a1b535..c320bdd31 100644
--- a/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/service/auth/GraphSpaceUserService.java
+++ b/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/service/auth/GraphSpaceUserService.java
@@ -33,6 +33,7 @@ import org.apache.hugegraph.driver.HugeClient;
import org.apache.hugegraph.entity.auth.BelongEntity;
import org.apache.hugegraph.entity.auth.RoleEntity;
import org.apache.hugegraph.entity.auth.UserView;
+import org.apache.hugegraph.exception.ParameterizedException;
import org.apache.hugegraph.structure.auth.User;
import org.apache.hugegraph.util.E;
import org.apache.hugegraph.util.PageUtil;
@@ -168,7 +169,7 @@ public class GraphSpaceUserService extends AuthService {
if (preset == null || "SUPER_ADMIN".equals(preset)) {
return;
}
- E.checkArgument(client.supportsDefaultRole(), "Permission presets require HugeGraph Server 1.8+");
+ requirePermissionPresets(client);
User account = client.findUserByName(username);
if (account == null) {
return;
@@ -201,28 +202,26 @@ public class GraphSpaceUserService extends AuthService {
if (preset == null || "SUPER_ADMIN".equals(preset)) {
return;
}
- E.checkArgument(client.supportsDefaultRole(), "Permission presets require HugeGraph Server 1.8+");
+ requirePermissionPresets(client);
Set<String> graphSpaces =
new java.util.HashSet<>(client.graphSpace().listGraphSpace());
for (Map<String, String> permission :
permissions == null ? new ArrayList<Map<String, String>>() : permissions) {
String graphSpace = permission.get("graphspace");
String permissionPreset = permission.get("permission_preset");
- E.checkArgument(graphSpace != null && graphSpaces.contains(graphSpace),
- "The graphspace does not exist: %s", graphSpace);
- E.checkArgument("GS_READ_ONLY".equals(permissionPreset) ||
- "GS_READ_WRITE".equals(permissionPreset) || "GS_ADMIN".equals(permissionPreset),
- "Unsupported permission preset: %s",
- permissionPreset);
+ if (graphSpace == null || !graphSpaces.contains(graphSpace)) {
+ throw new ParameterizedException(
+ "auth.permission-preset.graphspace-not-found",
+ graphSpace);
+ }
+ requirePermissionPreset(permissionPreset);
}
}
public void applySpacePreset(HugeClient client, String graphSpace,
String userId, String preset) {
- E.checkArgument("GS_READ_ONLY".equals(preset) || "GS_READ_WRITE".equals(preset) || "GS_ADMIN".equals(preset),
- "Unsupported permission preset: %s", preset);
- E.checkArgument(client.supportsDefaultRole(),
- "Permission presets require HugeGraph Server 1.8+");
+ requirePermissionPreset(preset);
+ requirePermissionPresets(client);
User account = client.auth().getUser(userId);
E.checkNotNull(account, "User");
this.clearCustomRoles(client, graphSpace, userId);
@@ -251,6 +250,22 @@ public class GraphSpaceUserService extends AuthService {
this.unauthUser(client, graphSpace, userId);
}
+ private static void requirePermissionPresets(HugeClient client) {
+ if (!client.supportsDefaultRole()) {
+ throw new ParameterizedException(
+ "auth.permission-preset.unsupported");
+ }
+ }
+
+ private static void requirePermissionPreset(String preset) {
+ if (!"GS_READ_ONLY".equals(preset) &&
+ !"GS_READ_WRITE".equals(preset) &&
+ !"GS_ADMIN".equals(preset)) {
+ throw new ParameterizedException(
+ "auth.permission-preset.invalid", preset);
+ }
+ }
+
public boolean hasCustomRoles(HugeClient client, String graphSpace,
String userId) {
return !this.belongService.list(client, graphSpace, null, userId).isEmpty();
@@ -265,8 +280,8 @@ public class GraphSpaceUserService extends AuthService {
graphSpace, username, "analyst")) {
return true;
}
- return this.graphs(client, graphSpace).stream().anyMatch(
- graph -> client.graphSpace().checkDefaultRole(graphSpace, username, "observer", graph));
+ return client.graphSpace().checkDefaultRole(
+ graphSpace, username, "observer");
}
private void clearDefaultRoles(HugeClient client, String graphSpace,
@@ -275,11 +290,10 @@ public class GraphSpaceUserService extends AuthService {
graphSpace, username, "analyst")) {
client.graphSpace().deleteDefaultRole(graphSpace, username, "analyst");
}
- for (String graph : this.graphs(client, graphSpace)) {
- if (client.graphSpace().checkDefaultRole(
- graphSpace, username, "observer", graph)) {
- client.graphSpace().deleteDefaultRole(graphSpace, username, "observer", graph);
- }
+ if (client.graphSpace().checkDefaultRole(
+ graphSpace, username, "observer")) {
+ client.graphSpace().deleteDefaultRole(
+ graphSpace, username, "observer");
}
}
@@ -291,30 +305,18 @@ public class GraphSpaceUserService extends AuthService {
private void setDefaultRole(HugeClient client, String graphSpace,
String username, String role) {
- if ("observer".equals(role)) {
- for (String graph : this.graphs(client, graphSpace)) {
- client.graphSpace().setDefaultRole(graphSpace, username, role, graph);
- }
- return;
- }
client.graphSpace().setDefaultRole(graphSpace, username, role);
}
private void addDefaultRole(HugeClient client, String graphSpace,
UserView user, String username, String role) {
- boolean assigned = "observer".equals(role) ? this.graphs(client, graphSpace).stream().anyMatch(
- graph -> client.graphSpace().checkDefaultRole(graphSpace, username, role, graph)) :
- client.graphSpace().checkDefaultRole(graphSpace, username, role);
+ boolean assigned = client.graphSpace().checkDefaultRole(
+ graphSpace, username, role);
if (assigned) {
user.addRole(new RoleEntity(role, role));
}
}
- private List<String> graphs(HugeClient client, String graphSpace) {
- client.assignGraph(graphSpace, "");
- return client.graphs().listGraph();
- }
-
public void unauthUser(HugeClient client, String graphSpace,
String userId) {
User account = client.auth().getUser(userId);
diff --git a/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/service/auth/UserService.java b/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/service/auth/UserService.java
index 4e8153a4d..938cf5cd4 100644
--- a/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/service/auth/UserService.java
+++ b/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/service/auth/UserService.java
@@ -42,6 +42,7 @@ import org.apache.hugegraph.driver.AuthManager;
import org.apache.hugegraph.driver.HugeClient;
import org.apache.hugegraph.entity.auth.UserEntity;
import org.apache.hugegraph.exception.InternalException;
+import org.apache.hugegraph.exception.ServerException;
import org.apache.hugegraph.structure.auth.User;
import org.apache.hugegraph.util.E;
import org.apache.hugegraph.util.HubbleUtil;
@@ -156,7 +157,7 @@ public class UserService extends AuthService {
List<Object> listMap = getSpaceAndSpacenum(hugeClient);
Map<String, List<String>> spaceMap =
HubbleUtil.uncheckedCast(listMap.get(0));
- List<String> adminSpaces = spaceMap.get(userId);
+ List<String> adminSpaces = spaceMap.get(user.name());
if (adminSpaces == null) {
adminSpaces = new ArrayList<>();
}
@@ -205,7 +206,7 @@ public class UserService extends AuthService {
userEntity.setAdminSpaces(adminSpaces);
userEntity.setSpacenum(adminSpaces.size());
userEntity.setResSpaces(resSpaces);
- this.populatePermissionPresets(hugeClient, userEntity);
+ this.populateCurrentUserPermissionPresets(hugeClient, userEntity);
} else {
userEntity.setSuperadmin(isStandaloneAdmin(username));
userEntity.setAdminSpaces(new ArrayList<>());
@@ -216,7 +217,7 @@ public class UserService extends AuthService {
}
public void add(HugeClient client, UserEntity ue) {
- if (isPdEnabled()) {
+ if (isPdEnabled() && client.supportsDefaultRole()) {
this.graphSpaceUserService.validatePermissionPresets(client, ue.getGraphspacePermissions(),
ue.getPermissionPreset());
}
@@ -237,7 +238,7 @@ public class UserService extends AuthService {
client.auth().addSpaceAdmin(ue.getName(), graphspace);
}
}
- if (isPdEnabled()) {
+ if (isPdEnabled() && client.supportsDefaultRole()) {
this.graphSpaceUserService.applyPermissionPresets(client, ue.getName(), ue.getGraphspacePermissions(),
ue.getPermissionPreset());
}
@@ -400,6 +401,33 @@ public class UserService extends AuthService {
}
}
+ private void populateCurrentUserPermissionPresets(
+ HugeClient client, UserEntity userEntity) {
+ List<Map<String, String>> permissions = new ArrayList<>();
+ if (userEntity.isSuperadmin()) {
+ userEntity.setGraphspacePermissions(permissions);
+ userEntity.setPermissionPreset("SUPER_ADMIN");
+ return;
+ }
+ if (!client.supportsDefaultRole()) {
+ userEntity.setGraphspacePermissions(permissions);
+ userEntity.setPermissionPreset("LEGACY_CUSTOM");
+ return;
+ }
+ for (String graphSpace : client.graphSpace().listGraphSpace()) {
+ if (userEntity.getAdminSpaces() != null &&
+ userEntity.getAdminSpaces().contains(graphSpace)) {
+ permissions.add(permission(graphSpace, "GS_ADMIN"));
+ } else if (client.auth().checkDefaultRole(
+ graphSpace, "analyst")) {
+ permissions.add(permission(graphSpace, "GS_READ_WRITE"));
+ } else if (hasCurrentUserObserverRole(client, graphSpace)) {
+ permissions.add(permission(graphSpace, "GS_READ_ONLY"));
+ }
+ }
+ userEntity.setGraphspacePermissions(permissions);
+ }
+
private void populatePermissionPresets(HugeClient client,
Collection<UserEntity> users) {
if (!client.supportsDefaultRole()) {
@@ -454,9 +482,8 @@ public class UserService extends AuthService {
private static boolean hasObserverRole(HugeClient client,
String graphSpace,
String username) {
- client.assignGraph(graphSpace, "");
- return client.graphs().listGraph().stream().anyMatch(
- graph -> client.graphSpace().checkDefaultRole(graphSpace, username, "observer", graph));
+ return client.graphSpace().checkDefaultRole(
+ graphSpace, username, "observer");
}
private static boolean hasCurrentUserAccess(HugeClient client,
@@ -467,9 +494,19 @@ public class UserService extends AuthService {
if (client.auth().checkDefaultRole(graphSpace, "analyst")) {
return true;
}
- client.assignGraph(graphSpace, "");
- return client.graphs().listGraph().stream().anyMatch(
- graph -> client.auth().checkDefaultRole(graphSpace, "observer", graph));
+ return hasCurrentUserObserverRole(client, graphSpace);
+ }
+
+ private static boolean hasCurrentUserObserverRole(HugeClient client,
+ String graphSpace) {
+ try {
+ return client.auth().checkDefaultRole(graphSpace, "observer");
+ } catch (ServerException e) {
+ if (e.status() == 403) {
+ return false;
+ }
+ throw e;
+ }
}
protected List<Object> getSpaceAndSpacenum(HugeClient hugeClient) {
@@ -505,7 +542,7 @@ public class UserService extends AuthService {
}
public void update(HugeClient hugeClient, UserEntity userEntity) {
- if (isPdEnabled()) {
+ if (isPdEnabled() && hugeClient.supportsDefaultRole()) {
this.graphSpaceUserService.validatePermissionPresets(hugeClient, userEntity.getGraphspacePermissions(),
userEntity.getPermissionPreset());
}
@@ -531,7 +568,7 @@ public class UserService extends AuthService {
}
hugeClient.auth().updateUser(user);
- if (isPdEnabled()) {
+ if (isPdEnabled() && hugeClient.supportsDefaultRole()) {
this.graphSpaceUserService.applyPermissionPresets(hugeClient, userEntity.getName(),
userEntity.getGraphspacePermissions(),
userEntity.getPermissionPreset());
diff --git a/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/service/op/DefaultOperationsDataService.java b/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/service/op/DefaultOperationsDataService.java
index ba81f484b..b95fca4db 100644
--- a/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/service/op/DefaultOperationsDataService.java
+++ b/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/service/op/DefaultOperationsDataService.java
@@ -50,6 +50,12 @@ import org.apache.hugegraph.service.op.OperationsModels.SourceStatus;
@Service
public class DefaultOperationsDataService implements OperationsDataService {
+ private static final Set<String> PD_FACTS = Set.of(
+ "graphs", "partitions", "replicas", "stores", "stores_up",
+ "data_size_bytes");
+ private static final Set<String> STORE_FACTS = Set.of(
+ "capacity_total_bytes", "capacity_used_bytes");
+
private final OperationsCollector collector;
private final long ttlMillis;
private final Clock clock;
@@ -265,10 +271,7 @@ public class DefaultOperationsDataService implements OperationsDataService {
.map(node -> staleNode(node, source))
.forEach(nodes::add);
}
- if ("pd".equals(sourceName)) {
- facts.clear();
- facts.putAll(previous.getFacts());
- }
+ this.mergeFailedFacts(facts, previous.getFacts(), sourceName);
}
if (!stale) {
return current;
@@ -279,6 +282,25 @@ public class DefaultOperationsDataService implements OperationsDataService {
"partial_refresh_failed", sources, nodes, facts);
}
+ private void mergeFailedFacts(Map<String, Long> current,
+ Map<String, Long> previous,
+ String source) {
+ Set<String> owned;
+ if ("pd".equals(source)) {
+ owned = PD_FACTS;
+ } else if ("stores".equals(source)) {
+ owned = STORE_FACTS;
+ } else {
+ return;
+ }
+ for (String fact : owned) {
+ current.remove(fact);
+ if (previous.containsKey(fact)) {
+ current.put(fact, previous.get(fact));
+ }
+ }
+ }
+
private boolean mergeFailedMetricGroups(List<Node> current,
List<Node> previous,
String nodeType) {
diff --git a/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/service/op/LiveOperationsCollector.java b/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/service/op/LiveOperationsCollector.java
index 74c8c1bf4..d0e57fd42 100644
--- a/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/service/op/LiveOperationsCollector.java
+++ b/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/service/op/LiveOperationsCollector.java
@@ -30,6 +30,7 @@ import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
+import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CancellationException;
@@ -78,6 +79,7 @@ public class LiveOperationsCollector implements OperationsCollector {
private final ExecutorService storeExecutor;
private final int storeDeadlineMillis;
private final Set<String> storeAllowedTargets;
+ private final Set<String> pdAllowedHosts;
@Autowired
public LiveOperationsCollector(HugeConfig config, ObjectMapper mapper) {
@@ -98,7 +100,10 @@ public class LiveOperationsCollector implements OperationsCollector {
config.get(HubbleOptions.OPERATIONS_STORE_THREADS),
config.get(HubbleOptions.OPERATIONS_STORE_DEADLINE),
new java.util.LinkedHashSet<>(config.get(
- HubbleOptions.OPERATIONS_STORE_ALLOWED_TARGETS)));
+ HubbleOptions.OPERATIONS_STORE_ALLOWED_TARGETS)),
+ pdAllowedHosts(config.get(HubbleOptions.PD_PEERS),
+ pdBase(config.get(HubbleOptions.SERVER_PROTOCOL),
+ config.get(HubbleOptions.PD_SERVER))));
}
LiveOperationsCollector(boolean pdEnabled, String pdBase,
@@ -108,7 +113,7 @@ public class LiveOperationsCollector implements OperationsCollector {
OperationsPayloadParser parser, Clock clock) {
this(pdEnabled, pdBase, pdUsername, pdPassword, storeUsername,
storePassword, serverIdentity, http, parser, clock, 16, 5000,
- defaultStoreAllowedTargets());
+ defaultStoreAllowedTargets(), pdAllowedHosts(null, pdBase));
}
LiveOperationsCollector(boolean pdEnabled, String pdBase,
@@ -119,7 +124,8 @@ public class LiveOperationsCollector implements OperationsCollector {
int storeThreads, int storeDeadlineMillis) {
this(pdEnabled, pdBase, pdUsername, pdPassword, storeUsername,
storePassword, serverIdentity, http, parser, clock, storeThreads,
- storeDeadlineMillis, defaultStoreAllowedTargets());
+ storeDeadlineMillis, defaultStoreAllowedTargets(),
+ pdAllowedHosts(null, pdBase));
}
LiveOperationsCollector(boolean pdEnabled, String pdBase,
@@ -129,6 +135,20 @@ public class LiveOperationsCollector implements OperationsCollector {
OperationsPayloadParser parser, Clock clock,
int storeThreads, int storeDeadlineMillis,
Set<String> storeAllowedTargets) {
+ this(pdEnabled, pdBase, pdUsername, pdPassword, storeUsername,
+ storePassword, serverIdentity, http, parser, clock, storeThreads,
+ storeDeadlineMillis, storeAllowedTargets,
+ pdAllowedHosts(null, pdBase));
+ }
+
+ LiveOperationsCollector(boolean pdEnabled, String pdBase,
+ String pdUsername, String pdPassword,
+ String storeUsername, String storePassword,
+ String serverIdentity, OperationsHttpClient http,
+ OperationsPayloadParser parser, Clock clock,
+ int storeThreads, int storeDeadlineMillis,
+ Set<String> storeAllowedTargets,
+ Set<String> pdAllowedHosts) {
if (storeThreads <= 0 || storeDeadlineMillis <= 0) {
throw new IllegalArgumentException(
"Store metric collection limits must be positive");
@@ -152,6 +172,15 @@ public class LiveOperationsCollector implements OperationsCollector {
.map(URI::create)
.map(OperationsHttpClient::origin)
.collect(Collectors.toCollection(java.util.LinkedHashSet::new));
+ if (pdEnabled && (pdAllowedHosts == null || pdAllowedHosts.isEmpty())) {
+ throw new IllegalArgumentException(
+ "PD allowed hosts must not be empty");
+ }
+ this.pdAllowedHosts = pdAllowedHosts == null ?
+ Collections.emptySet() :
+ Collections.unmodifiableSet(
+ new java.util.LinkedHashSet<>(
+ pdAllowedHosts));
this.storeExecutor = Executors.newFixedThreadPool(
storeThreads, runnable -> {
Thread thread = new Thread(
@@ -240,6 +269,7 @@ public class LiveOperationsCollector implements OperationsCollector {
SourceStatus storesStatus;
try {
cluster = this.get("/v1/cluster");
+ cluster = this.authoritativePdCluster(cluster);
pdStatus = available("UP", now);
} catch (RuntimeException e) {
pdStatus = unavailable(reason(e), now);
@@ -270,6 +300,7 @@ public class LiveOperationsCollector implements OperationsCollector {
Topology topology = this.parser.parseTopology(EMPTY_CLUSTER,
stores, now);
this.mergeNodes(nodes, topology.getNodes());
+ facts.putAll(topology.getFacts());
storesParsed = true;
} catch (MalformedUpstreamException e) {
storesStatus = malformed(now);
@@ -636,6 +667,30 @@ public class LiveOperationsCollector implements OperationsCollector {
return this.http.get(target, this.pdUsername, this.pdPassword);
}
+ private String authoritativePdCluster(String candidate) {
+ try {
+ URI base = URI.create(this.pdBase);
+ URI leader = this.parser.parsePdLeaderRestTarget(
+ candidate, base.getScheme());
+ if (leader == null ||
+ !base.getScheme().equalsIgnoreCase(leader.getScheme()) ||
+ effectivePort(base) != effectivePort(leader) ||
+ !this.pdAllowedHosts.contains(
+ leader.getHost().toLowerCase(Locale.ROOT))) {
+ return candidate;
+ }
+ String leaderOrigin = OperationsHttpClient.origin(leader);
+ if (leaderOrigin.equals(OperationsHttpClient.origin(base))) {
+ return candidate;
+ }
+ URI target = URI.create(leaderOrigin + "/v1/cluster");
+ return this.http.get(target, this.pdUsername, this.pdPassword,
+ Collections.singleton(leaderOrigin));
+ } catch (RuntimeException e) {
+ return candidate;
+ }
+ }
+
private Map<String, Object> safeSystemMetrics(
Map<String, Map<String, Object>> upstream) {
Map<String, Object> result = new LinkedHashMap<>();
@@ -861,6 +916,41 @@ public class LiveOperationsCollector implements OperationsCollector {
normalized.substring(0, normalized.length() - 1) : normalized;
}
+ private static Set<String> pdAllowedHosts(String peers, String pdBase) {
+ Set<String> hosts = new java.util.LinkedHashSet<>();
+ if (pdBase != null) {
+ URI base = URI.create(pdBase);
+ if (base.getHost() != null) {
+ hosts.add(base.getHost().toLowerCase(Locale.ROOT));
+ }
+ }
+ if (peers != null) {
+ for (String peer : peers.split(",")) {
+ String value = peer.trim();
+ if (value.isEmpty()) {
+ continue;
+ }
+ try {
+ URI target = URI.create(value.contains("://") ?
+ value : "dummy://" + value);
+ if (target.getHost() != null) {
+ hosts.add(target.getHost().toLowerCase(Locale.ROOT));
+ }
+ } catch (IllegalArgumentException ignored) {
+ // Invalid peers are rejected by the owning PD client.
+ }
+ }
+ }
+ return Collections.unmodifiableSet(hosts);
+ }
+
+ private static int effectivePort(URI target) {
+ if (target.getPort() >= 0) {
+ return target.getPort();
+ }
+ return "https".equalsIgnoreCase(target.getScheme()) ? 443 : 80;
+ }
+
private static String stableId(String type, String identity) {
try {
byte[] digest = MessageDigest.getInstance("SHA-256").digest(
diff --git a/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/service/op/OperationsPayloadParser.java b/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/service/op/OperationsPayloadParser.java
index 231244c11..c35333000 100644
--- a/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/service/op/OperationsPayloadParser.java
+++ b/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/service/op/OperationsPayloadParser.java
@@ -90,10 +90,41 @@ public class OperationsPayloadParser {
this.putLong(facts, "replicas", cluster.get("shardCount"));
this.putLong(facts, "stores", cluster.get("storeSize"));
this.putLong(facts, "stores_up", cluster.get("onlineStoreSize"));
+ this.putKilobytesAsBytes(facts, "data_size_bytes",
+ cluster.get("dataSize"));
+ this.putCapacityFacts(facts, storeNodes.values());
return new Topology(this.clusterStatus(this.text(cluster, "state")),
nodes, facts);
}
+ public URI parsePdLeaderRestTarget(String clusterPayload, String scheme) {
+ try {
+ JsonNode cluster = this.data(clusterPayload, "pd_cluster");
+ JsonNode leader = cluster.get("pdLeader");
+ if (leader == null || leader.isNull()) {
+ return null;
+ }
+ this.requireObject(leader, "pd_cluster");
+ String restUrl = this.text(leader, "restUrl");
+ if (restUrl == null) {
+ return null;
+ }
+ URI target = URI.create(restUrl.contains("://") ?
+ restUrl : scheme + "://" + restUrl);
+ String path = target.getPath();
+ if (target.getHost() == null || target.getUserInfo() != null ||
+ target.getQuery() != null || target.getFragment() != null ||
+ path != null && !path.isEmpty() && !"/".equals(path)) {
+ throw new MalformedUpstreamException("pd_leader_rest_address");
+ }
+ return target;
+ } catch (MalformedUpstreamException e) {
+ throw e;
+ } catch (RuntimeException e) {
+ throw new MalformedUpstreamException("pd_leader_rest_address", e);
+ }
+ }
+
public Map<String, String> parseStoreHosts(String storesPayload) {
JsonNode stores = this.data(storesPayload, "pd_stores");
Map<String, String> result = new LinkedHashMap<>();
@@ -452,6 +483,47 @@ public class OperationsPayloadParser {
}
}
+ private void putKilobytesAsBytes(Map<String, Long> target, String key,
+ JsonNode value) {
+ Long kilobytes = this.longValue(value);
+ if (kilobytes == null || kilobytes < 0L) {
+ return;
+ }
+ try {
+ target.put(key, Math.multiplyExact(kilobytes, 1024L));
+ } catch (ArithmeticException ignored) {
+ // An overflowing upstream value is unavailable, never a fake size.
+ }
+ }
+
+ private void putCapacityFacts(Map<String, Long> target,
+ Iterable<JsonNode> stores) {
+ long total = 0L;
+ long available = 0L;
+ boolean found = false;
+ try {
+ for (JsonNode store : stores) {
+ Long storeTotal = this.longValue(store.get("capacity"));
+ Long storeAvailable = this.longValue(store.get("available"));
+ if (storeTotal == null || storeAvailable == null ||
+ storeTotal < 0L || storeAvailable < 0L ||
+ storeAvailable > storeTotal) {
+ return;
+ }
+ total = Math.addExact(total, storeTotal);
+ available = Math.addExact(available, storeAvailable);
+ found = true;
+ }
+ if (found) {
+ target.put("capacity_total_bytes", total);
+ target.put("capacity_used_bytes",
+ Math.subtractExact(total, available));
+ }
+ } catch (ArithmeticException ignored) {
+ // Partial or overflowing capacity is less useful than unavailable.
+ }
+ }
+
private void putMetric(Map<String, Object> target, String key,
JsonNode value) {
Long number = this.longValue(value);
diff --git a/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/service/space/GraphSpaceService.java b/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/service/space/GraphSpaceService.java
index ebd45a05b..4a14f4eb0 100644
--- a/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/service/space/GraphSpaceService.java
+++ b/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/service/space/GraphSpaceService.java
@@ -184,9 +184,7 @@ public class GraphSpaceService {
if (client.auth().checkDefaultRole(graphSpace, "analyst")) {
return true;
}
- client.assignGraph(graphSpace, "");
- return client.graphs().listGraph().stream().anyMatch(
- graph -> client.auth().checkDefaultRole(graphSpace, "observer", graph));
+ return client.auth().checkDefaultRole(graphSpace, "observer");
}
public List<Map<String, Object>> queryAnonymousGs(HugeClient client,
@@ -196,8 +194,11 @@ public class GraphSpaceService {
String after = createTime == null ? "" : createTime;
List<Map<String, Object>> results = client.graphSpace()
.listGraphSpace().stream()
- .map(client.graphSpace()::getGraphSpace).filter(space -> space != null && (space.getName().contains(prefix) ||
- space.getNickname() != null && space.getNickname().contains(prefix)))
+ .map(client.graphSpace()::getGraphSpace)
+ .filter(space -> space != null &&
+ (space.getName().contains(prefix) ||
+ space.getNickname() != null &&
+ space.getNickname().contains(prefix)))
.filter(space -> space.getCreateTime() == null || space.getCreateTime().compareTo(after) > 0)
.map(space -> {
GraphSpaceEntity entity =
diff --git a/hugegraph-hubble/hubble-be/src/main/resources/i18n/messages.properties b/hugegraph-hubble/hubble-be/src/main/resources/i18n/messages.properties
index 82c9a750b..365c5c546 100644
--- a/hugegraph-hubble/hubble-be/src/main/resources/i18n/messages.properties
+++ b/hugegraph-hubble/hubble-be/src/main/resources/i18n/messages.properties
@@ -31,6 +31,9 @@ server.capability.vermeer-compute-token-auth.unavailable=Vermeer compute is unav
auth.user.batch-create.failed=Failed to create users: {0}
auth.user.import-file.failed=Failed to prepare the uploaded user import file
auth.user.import-csv.failed=Failed to parse the uploaded user CSV file
+auth.permission-preset.unsupported=This server cannot apply GraphSpace permission presets. Connect Hubble to a distributed Server that supports GraphSpace permission presets.
+auth.permission-preset.graphspace-not-found=GraphSpace ''{0}'' is unavailable. Refresh the GraphSpace list and select an existing one.
+auth.permission-preset.invalid=Permission preset ''{0}'' is unsupported. Choose a preset shown in the account form.
common.name-time-order.conflict=The param name_order and time_order cannot set at same time
common.param.path-id-should-same-as-body=The id in path({0}) must be same as request body({1}) if it exists
diff --git a/hugegraph-hubble/hubble-be/src/main/resources/i18n/messages_zh_CN.properties b/hugegraph-hubble/hubble-be/src/main/resources/i18n/messages_zh_CN.properties
index 7b1f28aef..3de65f0b0 100644
--- a/hugegraph-hubble/hubble-be/src/main/resources/i18n/messages_zh_CN.properties
+++ b/hugegraph-hubble/hubble-be/src/main/resources/i18n/messages_zh_CN.properties
@@ -31,6 +31,9 @@ server.capability.vermeer-compute-token-auth.unavailable=Vermeer 计算需上游
auth.user.batch-create.failed=以下用户创建失败:{0}
auth.user.import-file.failed=无法准备上传的用户导入文件
auth.user.import-csv.failed=无法解析上传的用户 CSV 文件
+auth.permission-preset.unsupported=当前 Server 无法应用 GraphSpace 权限预设。请将 Hubble 连接到支持 GraphSpace 权限预设的分布式 Server。
+auth.permission-preset.graphspace-not-found=GraphSpace“{0}”不可用。请刷新 GraphSpace 列表后选择一个现有空间。
+auth.permission-preset.invalid=不支持权限预设“{0}”。请选择账号表单中提供的预设。
common.name-time-order.conflict=参数 name_order 和 time_order 不能同时设置
common.param.path-id-should-same-as-body=当请求体中的 id({1}) 存在时,必须与路径中的 ({0}) 相同
diff --git a/hugegraph-hubble/hubble-be/src/test/java/org/apache/hugegraph/config/HubbleConfigEnvironmentTest.java b/hugegraph-hubble/hubble-be/src/test/java/org/apache/hugegraph/config/HubbleConfigEnvironmentTest.java
new file mode 100644
index 000000000..e15649fce
--- /dev/null
+++ b/hugegraph-hubble/hubble-be/src/test/java/org/apache/hugegraph/config/HubbleConfigEnvironmentTest.java
@@ -0,0 +1,68 @@
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with this
+ * work for additional information regarding copyright ownership. The ASF
+ * licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.hugegraph.config;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.hugegraph.exception.ExternalException;
+import org.apache.hugegraph.options.HubbleOptions;
+import org.junit.Assert;
+import org.junit.Test;
+
+public class HubbleConfigEnvironmentTest {
+
+ @Test
+ public void testAuthModeCanBeOverriddenByEnvironment() {
+ HugeConfig config = config(true);
+
+ HubbleConfig.applyEnvironmentOverrides(
+ config, Map.of("HUBBLE_AUTH_ENABLED", "false"));
+
+ Assert.assertFalse(config.get(HubbleOptions.AUTH_ENABLED));
+ }
+
+ @Test
+ public void testMissingEnvironmentKeepsFileValue() {
+ HugeConfig config = config(false);
+
+ HubbleConfig.applyEnvironmentOverrides(config, Collections.emptyMap());
+
+ Assert.assertFalse(config.get(HubbleOptions.AUTH_ENABLED));
+ }
+
+ @Test(expected = ExternalException.class)
+ public void testAuthModeRejectsInvalidEnvironmentValue() {
+ HugeConfig config = config(true);
+
+ HubbleConfig.applyEnvironmentOverrides(
+ config, Map.of("HUBBLE_AUTH_ENABLED", "disabled"));
+ }
+
+ private static HugeConfig config(boolean authEnabled) {
+ if (!OptionSpace.containKey(HubbleOptions.AUTH_ENABLED.name())) {
+ OptionSpace.register("hubble-environment-test",
+ HubbleOptions.instance());
+ }
+ Map<String, Object> properties = new HashMap<>();
+ properties.put(HubbleOptions.AUTH_ENABLED.name(), authEnabled);
+ return new HugeConfig(properties);
+ }
+}
diff --git a/hugegraph-hubble/hubble-be/src/test/java/org/apache/hugegraph/controller/auth/GraphSpaceAuthOwnershipTest.java b/hugegraph-hubble/hubble-be/src/test/java/org/apache/hugegraph/controller/auth/GraphSpaceAuthOwnershipTest.java
index c8aa3634f..067263965 100644
--- a/hugegraph-hubble/hubble-be/src/test/java/org/apache/hugegraph/controller/auth/GraphSpaceAuthOwnershipTest.java
+++ b/hugegraph-hubble/hubble-be/src/test/java/org/apache/hugegraph/controller/auth/GraphSpaceAuthOwnershipTest.java
@@ -487,13 +487,11 @@ public class GraphSpaceAuthOwnershipTest {
}
@Test
- public void testReadOnlyPresetAppliesObserverToEveryGraph() {
+ public void testReadOnlyPresetAppliesSpaceWideObserver() {
User account = new User();
account.setId("user-id");
account.name("graph-user");
Mockito.when(this.auth.getUser("user-id")).thenReturn(account);
- Mockito.when(this.graphs.listGraph())
- .thenReturn(Arrays.asList("graph-1", "graph-2"));
BelongService belongs = Mockito.mock(BelongService.class);
Mockito.when(belongs.list(this.client, "SPACE_A", null, "user-id")).thenReturn(Collections.emptyList());
GraphSpaceUserService service = new GraphSpaceUserService();
@@ -502,9 +500,11 @@ public class GraphSpaceAuthOwnershipTest {
service.applySpacePreset(this.client, "SPACE_A", "user-id", "GS_READ_ONLY");
Mockito.verify(this.auth).addSpaceMember("graph-user", "SPACE_A");
- Mockito.verify(this.graphSpace).setDefaultRole("SPACE_A", "graph-user", "observer", "graph-1");
- Mockito.verify(this.graphSpace).setDefaultRole("SPACE_A", "graph-user", "observer", "graph-2");
- Mockito.verify(this.graphSpace, Mockito.never()).setDefaultRole("SPACE_A", "graph-user", "observer");
+ Mockito.verify(this.graphSpace).setDefaultRole(
+ "SPACE_A", "graph-user", "observer");
+ Mockito.verify(this.graphSpace, Mockito.never()).setDefaultRole(
+ Mockito.anyString(), Mockito.anyString(),
+ Mockito.anyString(), Mockito.anyString());
}
@Test
diff --git a/hugegraph-hubble/hubble-be/src/test/java/org/apache/hugegraph/service/auth/AuthContextServiceTest.java b/hugegraph-hubble/hubble-be/src/test/java/org/apache/hugegraph/service/auth/AuthContextServiceTest.java
index cc4ba00df..1ddda794f 100644
--- a/hugegraph-hubble/hubble-be/src/test/java/org/apache/hugegraph/service/auth/AuthContextServiceTest.java
+++ b/hugegraph-hubble/hubble-be/src/test/java/org/apache/hugegraph/service/auth/AuthContextServiceTest.java
@@ -42,6 +42,7 @@ public class AuthContextServiceTest {
Fixture fixture = new Fixture(true);
UserEntity user = user(true, Arrays.asList("space-b", "space-a"));
user.setPassword("password-canary");
+ Mockito.when(fixture.client.supportsDefaultRole()).thenReturn(true);
Mockito.when(fixture.users.getpersonal(fixture.client, "alice"))
.thenReturn(user);
@@ -53,6 +54,8 @@ public class AuthContextServiceTest {
Assert.assertEquals("SUPERADMIN", context.get("role"));
Assert.assertEquals("alice", context.get("username"));
Assert.assertTrue(capabilities(context).contains("accounts_manage"));
+ Assert.assertTrue(capabilities(context).contains(
+ "account_permission_presets"));
Assert.assertTrue(capabilities(context).contains("graphspaces_manage"));
Assert.assertTrue(capabilities(context).contains(
"operations_metrics_read"));
@@ -72,6 +75,7 @@ public class AuthContextServiceTest {
@Test
public void testPdSpaceAdminOnlyGetsScopedManagementActions() {
Fixture fixture = new Fixture(true);
+ Mockito.when(fixture.client.supportsDefaultRole()).thenReturn(true);
Mockito.when(fixture.users.getpersonal(fixture.client, "alice"))
.thenReturn(user(false,
Arrays.asList("space-b", "space-a", "space-a")));
@@ -95,6 +99,23 @@ public class AuthContextServiceTest {
Assert.assertFalse((Boolean) scopes(context).get("all_graphspaces"));
}
+ @Test
+ public void testPdServerWithoutPresetApiHidesScopedMutations() {
+ Fixture fixture = new Fixture(true);
+ Mockito.when(fixture.client.supportsDefaultRole()).thenReturn(false);
+ Mockito.when(fixture.users.getpersonal(fixture.client, "alice"))
+ .thenReturn(user(true, Collections.singletonList("space-a")));
+
+ Map<String, Object> context = fixture.service.context(fixture.client,
+ "alice");
+
+ Assert.assertFalse(capabilities(context).contains(
+ "account_permission_presets"));
+ Assert.assertTrue(actions(context, "members").isEmpty());
+ Assert.assertTrue(actions(context, "roles").isEmpty());
+ Assert.assertTrue(actions(context, "authorizations").isEmpty());
+ }
+
@Test
public void testPdUserOnlyGetsSelfActions() {
Fixture fixture = new Fixture(true);
@@ -137,6 +158,31 @@ public class AuthContextServiceTest {
.getpersonal(Mockito.any(), Mockito.anyString());
}
+ @Test
+ public void testAnonymousModeGetsReadOnlyOperationsCapabilities() {
+ Fixture fixture = new Fixture(true);
+ Mockito.when(fixture.config.get(HubbleOptions.AUTH_ENABLED))
+ .thenReturn(false);
+
+ Map<String, Object> context = fixture.service.context(fixture.client,
+ null);
+
+ Assert.assertEquals("NON_AUTH", context.get("mode"));
+ Assert.assertEquals("ANONYMOUS", context.get("role"));
+ Assert.assertEquals("anonymous-v2-pd",
+ context.get("context_version"));
+ Assert.assertTrue(capabilities(context).contains(
+ "operations_health_read"));
+ Assert.assertTrue(capabilities(context).contains(
+ "operations_topology_read"));
+ Assert.assertTrue(capabilities(context).contains(
+ "operations_metrics_read"));
+ Assert.assertEquals(Set.of("read_health", "read_topology",
+ "read_metrics"),
+ actions(context, "operations"));
+ Mockito.verifyZeroInteractions(fixture.users);
+ }
+
@Test
public void testContextVersionIsStableButChangesWithScope() {
Fixture fixture = new Fixture(true);
diff --git a/hugegraph-hubble/hubble-be/src/test/java/org/apache/hugegraph/service/auth/GraphSpaceUserServiceTest.java b/hugegraph-hubble/hubble-be/src/test/java/org/apache/hugegraph/service/auth/GraphSpaceUserServiceTest.java
new file mode 100644
index 000000000..97b20192b
--- /dev/null
+++ b/hugegraph-hubble/hubble-be/src/test/java/org/apache/hugegraph/service/auth/GraphSpaceUserServiceTest.java
@@ -0,0 +1,196 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hugegraph.service.auth;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.springframework.test.util.ReflectionTestUtils;
+
+import org.apache.hugegraph.driver.AuthManager;
+import org.apache.hugegraph.driver.GraphSpaceManager;
+import org.apache.hugegraph.driver.HugeClient;
+import org.apache.hugegraph.entity.auth.BelongEntity;
+import org.apache.hugegraph.exception.ParameterizedException;
+import org.apache.hugegraph.structure.auth.User;
+import org.apache.hugegraph.testutil.Assert;
+
+public class GraphSpaceUserServiceTest {
+
+ private HugeClient client;
+ private AuthManager auth;
+ private GraphSpaceManager graphSpace;
+ private BelongService belongService;
+ private GraphSpaceUserService service;
+
+ @Before
+ public void setup() {
+ this.client = Mockito.mock(HugeClient.class);
+ this.auth = Mockito.mock(AuthManager.class);
+ this.graphSpace = Mockito.mock(GraphSpaceManager.class);
+ this.belongService = Mockito.mock(BelongService.class);
+ this.service = new GraphSpaceUserService();
+ ReflectionTestUtils.setField(this.service, "belongService",
+ this.belongService);
+ Mockito.when(this.client.auth()).thenReturn(this.auth);
+ Mockito.when(this.client.graphSpace()).thenReturn(this.graphSpace);
+ Mockito.when(this.client.supportsDefaultRole()).thenReturn(true);
+ }
+
+ @Test
+ public void testPermissionPresetFailureHasActionableErrorKey() {
+ Mockito.when(this.client.supportsDefaultRole()).thenReturn(false);
+
+ ParameterizedException error = null;
+ try {
+ this.service.validatePermissionPresets(
+ this.client, Collections.emptyList(), "GS_READ_ONLY");
+ } catch (ParameterizedException e) {
+ error = e;
+ }
+
+ Assert.assertNotNull(error);
+ Assert.assertEquals("auth.permission-preset.unsupported",
+ error.getMessage());
+ }
+
+ @Test
+ public void testApplyReadOnlyPresetAndRemoveUnrequestedSpace() {
+ User user = user("u-1", "alice");
+ Mockito.when(this.client.findUserByName("alice")).thenReturn(user);
+ Mockito.when(this.auth.getUser("u-1")).thenReturn(user);
+ Mockito.when(this.graphSpace.listGraphSpace())
+ .thenReturn(java.util.Arrays.asList("team", "old"));
+ Mockito.when(this.belongService.list(
+ Mockito.eq(this.client), Mockito.anyString(),
+ Mockito.isNull(), Mockito.eq("u-1")))
+ .thenReturn(Collections.emptyList());
+ Mockito.when(this.auth.listSpaceMember("team"))
+ .thenReturn(Collections.emptyList());
+ Mockito.when(this.auth.listSpaceMember("old"))
+ .thenReturn(Collections.singletonList("alice"));
+ Mockito.when(this.auth.listSpaceAdmin(Mockito.anyString()))
+ .thenReturn(Collections.emptyList());
+
+ this.service.applyPermissionPresets(
+ this.client, "alice",
+ Collections.singletonList(permission("team", "GS_READ_ONLY")),
+ "GS_READ_ONLY");
+
+ Mockito.verify(this.auth).addSpaceMember("alice", "team");
+ Mockito.verify(this.graphSpace)
+ .setDefaultRole("team", "alice", "observer");
+ Mockito.verify(this.auth).delSpaceMember("alice", "old");
+ }
+
+ @Test
+ public void testApplyAdminPresetAddsManagementAndWriteAccess() {
+ User user = user("u-1", "alice");
+ Mockito.when(this.auth.getUser("u-1")).thenReturn(user);
+ Mockito.when(this.belongService.list(
+ this.client, "team", null, "u-1"))
+ .thenReturn(Collections.emptyList());
+ Mockito.when(this.auth.listSpaceMember("team"))
+ .thenReturn(Collections.emptyList());
+ Mockito.when(this.auth.listSpaceAdmin("team"))
+ .thenReturn(Collections.emptyList());
+
+ this.service.applySpacePreset(this.client, "team", "u-1",
+ "GS_ADMIN");
+
+ Mockito.verify(this.auth).addSpaceMember("alice", "team");
+ Mockito.verify(this.auth).addSpaceAdmin("alice", "team");
+ Mockito.verify(this.graphSpace)
+ .setDefaultRole("team", "alice", "analyst");
+ }
+
+ @Test
+ public void testApplyReadWritePresetRemovesAdminAccess() {
+ User user = user("u-1", "alice");
+ Mockito.when(this.auth.getUser("u-1")).thenReturn(user);
+ Mockito.when(this.belongService.list(
+ this.client, "team", null, "u-1"))
+ .thenReturn(Collections.emptyList());
+ Mockito.when(this.auth.listSpaceMember("team"))
+ .thenReturn(Collections.singletonList("alice"));
+ Mockito.when(this.auth.listSpaceAdmin("team"))
+ .thenReturn(Collections.singletonList("alice"));
+
+ this.service.applySpacePreset(this.client, "team", "u-1",
+ "GS_READ_WRITE");
+
+ Mockito.verify(this.auth).delSpaceAdmin("alice", "team");
+ Mockito.verify(this.graphSpace)
+ .setDefaultRole("team", "alice", "analyst");
+ Mockito.verify(this.auth, Mockito.never())
+ .addSpaceMember(Mockito.anyString(), Mockito.anyString());
+ }
+
+ @Test
+ public void testRemovePresetCleansEveryGrantType() {
+ User user = user("u-1", "alice");
+ BelongEntity belong = BelongEntity.builder()
+ .id("belong-1")
+ .userId("u-1")
+ .build();
+ Mockito.when(this.auth.getUser("u-1")).thenReturn(user);
+ Mockito.when(this.belongService.list(
+ this.client, "team", null, "u-1"))
+ .thenReturn(Collections.singletonList(belong));
+ Mockito.when(this.graphSpace.checkDefaultRole(
+ "team", "alice", "analyst"))
+ .thenReturn(true);
+ Mockito.when(this.graphSpace.checkDefaultRole(
+ "team", "alice", "observer"))
+ .thenReturn(true);
+ Mockito.when(this.auth.listSpaceAdmin("team"))
+ .thenReturn(Collections.singletonList("alice"));
+ Mockito.when(this.auth.listSpaceMember("team"))
+ .thenReturn(Collections.singletonList("alice"));
+
+ this.service.removeSpacePreset(this.client, "team", "u-1");
+
+ Mockito.verify(this.belongService)
+ .deleteById(this.client, "team", "belong-1");
+ Mockito.verify(this.graphSpace)
+ .deleteDefaultRole("team", "alice", "analyst");
+ Mockito.verify(this.graphSpace)
+ .deleteDefaultRole("team", "alice", "observer");
+ Mockito.verify(this.auth).delSpaceAdmin("alice", "team");
+ Mockito.verify(this.auth).delSpaceMember("alice", "team");
+ }
+
+ private static User user(String id, String name) {
+ User user = new User();
+ user.setId(id);
+ user.name(name);
+ return user;
+ }
+
+ private static Map<String, String> permission(String graphSpace,
+ String preset) {
+ Map<String, String> permission = new HashMap<>();
+ permission.put("graphspace", graphSpace);
+ permission.put("permission_preset", preset);
+ return permission;
+ }
+}
diff --git a/hugegraph-hubble/hubble-be/src/test/java/org/apache/hugegraph/service/op/DefaultOperationsDataServiceTest.java b/hugegraph-hubble/hubble-be/src/test/java/org/apache/hugegraph/service/op/DefaultOperationsDataServiceTest.java
index 393b6c27b..1b7825418 100644
--- a/hugegraph-hubble/hubble-be/src/test/java/org/apache/hugegraph/service/op/DefaultOperationsDataServiceTest.java
+++ b/hugegraph-hubble/hubble-be/src/test/java/org/apache/hugegraph/service/op/DefaultOperationsDataServiceTest.java
@@ -248,6 +248,56 @@ public class DefaultOperationsDataServiceTest {
Assert.assertTrue(backend.isStale());
}
+ @SuppressWarnings("unchecked")
+ @Test
+ public void testPdFailureKeepsFreshStoreCapacityFacts() {
+ AtomicInteger calls = new AtomicInteger();
+ OperationsCollector collector = (client, metrics) ->
+ calls.getAndIncrement() == 0 ?
+ factSnapshot("AVAILABLE", "AVAILABLE", 100L, 1000L) :
+ factSnapshot("UNAVAILABLE", "AVAILABLE", null, 2000L);
+ DefaultOperationsDataService service = new DefaultOperationsDataService(
+ collector, 5, CLOCK);
+ Set<String> capabilities = Set.of(
+ OperationsCapabilityService.HEALTH_READ,
+ OperationsCapabilityService.TOPOLOGY_READ);
+
+ service.overview(client("token-a"), capabilities, false);
+ Map<String, Object> result = service.overview(client("token-a"),
+ capabilities, true);
+
+ Map<String, Long> facts = (Map<String, Long>) result.get("facts");
+ Assert.assertEquals(Long.valueOf(100L),
+ facts.get("data_size_bytes"));
+ Assert.assertEquals(Long.valueOf(2000L),
+ facts.get("capacity_total_bytes"));
+ }
+
+ @SuppressWarnings("unchecked")
+ @Test
+ public void testStoreFailureKeepsFreshPdFacts() {
+ AtomicInteger calls = new AtomicInteger();
+ OperationsCollector collector = (client, metrics) ->
+ calls.getAndIncrement() == 0 ?
+ factSnapshot("AVAILABLE", "AVAILABLE", 100L, 1000L) :
+ factSnapshot("AVAILABLE", "UNAVAILABLE", 200L, null);
+ DefaultOperationsDataService service = new DefaultOperationsDataService(
+ collector, 5, CLOCK);
+ Set<String> capabilities = Set.of(
+ OperationsCapabilityService.HEALTH_READ,
+ OperationsCapabilityService.TOPOLOGY_READ);
+
+ service.overview(client("token-a"), capabilities, false);
+ Map<String, Object> result = service.overview(client("token-a"),
+ capabilities, true);
+
+ Map<String, Long> facts = (Map<String, Long>) result.get("facts");
+ Assert.assertEquals(Long.valueOf(200L),
+ facts.get("data_size_bytes"));
+ Assert.assertEquals(Long.valueOf(1000L),
+ facts.get("capacity_total_bytes"));
+ }
+
@Test
public void testPartialRefreshReusesOnlyFailedMetricGroup() {
AtomicInteger calls = new AtomicInteger();
@@ -499,6 +549,35 @@ public class DefaultOperationsDataServiceTest {
Collections.emptyMap());
}
+ private static Snapshot factSnapshot(String pdAvailability,
+ String storesAvailability,
+ Long dataSize, Long capacity) {
+ Map<String, SourceStatus> sources = new LinkedHashMap<>();
+ sources.put("pd", factSource(pdAvailability));
+ sources.put("stores", factSource(storesAvailability));
+ Map<String, Long> facts = new LinkedHashMap<>();
+ if (dataSize != null) {
+ facts.put("data_size_bytes", dataSize);
+ }
+ if (capacity != null) {
+ facts.put("capacity_total_bytes", capacity);
+ facts.put("capacity_used_bytes", capacity / 2L);
+ }
+ String status = "AVAILABLE".equals(pdAvailability) &&
+ "AVAILABLE".equals(storesAvailability) ?
+ "UP" : "DEGRADED";
+ return new Snapshot(status, 2000L, false, null, sources,
+ Collections.emptyList(), facts);
+ }
+
+ private static SourceStatus factSource(String availability) {
+ boolean available = "AVAILABLE".equals(availability);
+ return new SourceStatus(availability, available ? "UP" : "UNKNOWN",
+ 2000L, available ? 2000L : null, available,
+ false, available ? null :
+ "upstream_unavailable");
+ }
+
private static SourceStatus available() {
return new SourceStatus("AVAILABLE", "UP", 1000L, 1000L, true,
false, null);
diff --git a/hugegraph-hubble/hubble-be/src/test/java/org/apache/hugegraph/service/op/LiveOperationsCollectorTest.java b/hugegraph-hubble/hubble-be/src/test/java/org/apache/hugegraph/service/op/LiveOperationsCollectorTest.java
index 9640678af..f651b0f33 100644
--- a/hugegraph-hubble/hubble-be/src/test/java/org/apache/hugegraph/service/op/LiveOperationsCollectorTest.java
+++ b/hugegraph-hubble/hubble-be/src/test/java/org/apache/hugegraph/service/op/LiveOperationsCollectorTest.java
@@ -195,6 +195,32 @@ public class LiveOperationsCollectorTest {
snapshot.getSources().get("pd").getStatus());
}
+ @Test
+ public void testUsesConfiguredPdLeaderForAuthoritativeClusterState() {
+ LeaderAwareHttpClient http = new LeaderAwareHttpClient("pd-1");
+ LiveOperationsCollector collector = leaderAwareCollector(
+ http, Set.of("pd-service", "pd-1"));
+
+ Snapshot snapshot = collector.collect(serverClient(), false);
+
+ Assert.assertEquals("UP", snapshot.getSources().get("pd").getStatus());
+ Assert.assertEquals("UP", snapshot.getStatus());
+ Assert.assertEquals(1, http.leaderRequests());
+ }
+
+ @Test
+ public void testDoesNotFollowUnconfiguredPdLeader() {
+ LeaderAwareHttpClient http = new LeaderAwareHttpClient("untrusted");
+ LiveOperationsCollector collector = leaderAwareCollector(
+ http, Set.of("pd-service", "pd-1"));
+
+ Snapshot snapshot = collector.collect(serverClient(), false);
+
+ Assert.assertEquals("UNKNOWN",
+ snapshot.getSources().get("pd").getStatus());
+ Assert.assertEquals(0, http.leaderRequests());
+ }
+
@Test
public void testStoreMetricsUseOnlyPdDiscoveredTarget() throws IOException {
HttpServer pd = pdServer(200, cluster(), 200, stores());
@@ -228,6 +254,10 @@ public class LiveOperationsCollectorTest {
.get(group).getAvailability());
}
Assert.assertEquals(Long.valueOf(2000L), store.getObservedAt());
+ Assert.assertEquals(100L,
+ snapshot.getFacts().get("capacity_total_bytes"));
+ Assert.assertEquals(60L,
+ snapshot.getFacts().get("capacity_used_bytes"));
Assert.assertFalse(store.getMetrics().toString().contains("secret"));
OperationsModels.Node pdNode = snapshot.getNodes().stream()
.filter(node -> "PD".equals(node.getType()))
@@ -713,6 +743,16 @@ public class LiveOperationsCollectorTest {
"http://[::1]:8520")));
}
+ private static LiveOperationsCollector leaderAwareCollector(
+ LeaderAwareHttpClient http, Set<String> pdAllowedHosts) {
+ return new LiveOperationsCollector(
+ true, "http://pd-service:8620", "hubble", "secret",
+ "store-hubble", "store-secret", "server-under-test", http,
+ new OperationsPayloadParser(new ObjectMapper()), CLOCK,
+ 4, 1000, Collections.singleton("http://127.0.0.1:8520"),
+ pdAllowedHosts);
+ }
+
private static HugeClient serverClient() {
HugeClient client = Mockito.mock(HugeClient.class);
VersionManager version = Mockito.mock(VersionManager.class);
@@ -796,14 +836,14 @@ public class LiveOperationsCollectorTest {
"\"pdLeader\":{\"restUrl\":\"http://pd:8620\"," +
"\"state\":\"Up\",\"role\":\"Leader\"}," +
"\"stores\":[{\"storeId\":1,\"state\":\"Up\"," +
- "\"capacity\":100,\"available\":40}]}}";
+ "\"partitionCount\":12}]}}";
}
private static String stores() {
return "{\"status\":0,\"data\":{\"stores\":[{" +
"\"storeId\":\"1\",\"address\":\"127.0.0.1:8500\"," +
"\"restAddress\":\"127.0.0.1:PD_TEST_PORT\"," +
- "\"state\":\"Up\"}]}}";
+ "\"state\":\"Up\",\"capacity\":100,\"available\":40}]}}";
}
private static String storesWithoutRestAddress() {
@@ -958,4 +998,56 @@ public class LiveOperationsCollectorTest {
return this.metricAuthorities;
}
}
+
+ private static final class LeaderAwareHttpClient
+ extends OperationsHttpClient {
+
+ private final String leaderHost;
+ private final AtomicInteger leaderRequests;
+
+ private LeaderAwareHttpClient(String leaderHost) {
+ super(1000, 1000, 8192);
+ this.leaderHost = leaderHost;
+ this.leaderRequests = new AtomicInteger();
+ }
+
+ @Override
+ public String get(java.net.URI target, String username, String password,
+ Set<String> allowedTargets) {
+ return this.response(target);
+ }
+
+ @Override
+ public String get(java.net.URI target, String username,
+ String password) {
+ return this.response(target);
+ }
+
+ private String response(java.net.URI target) {
+ if ("/v1/cluster".equals(target.getPath())) {
+ if (!"pd-service".equals(target.getHost())) {
+ this.leaderRequests.incrementAndGet();
+ return leaderCluster("Cluster_OK", this.leaderHost);
+ }
+ return leaderCluster("Cluster_Not_Ready", this.leaderHost);
+ }
+ if ("/v1/stores".equals(target.getPath())) {
+ return stores();
+ }
+ throw new AssertionError("Unexpected operations target " + target);
+ }
+
+ private int leaderRequests() {
+ return this.leaderRequests.get();
+ }
+ }
+
+ private static String leaderCluster(String state, String leaderHost) {
+ return "{\"status\":0,\"data\":{\"state\":\"" + state + "\"," +
+ "\"graphSize\":2,\"pdList\":[{\"restUrl\":\"" +
+ leaderHost + ":8620\",\"state\":\"Up\"," +
+ "\"role\":\"Leader\"}],\"pdLeader\":{\"restUrl\":\"" +
+ leaderHost + ":8620\",\"state\":\"Up\"," +
+ "\"role\":\"Leader\"},\"stores\":[]}}";
+ }
}
diff --git a/hugegraph-hubble/hubble-be/src/test/java/org/apache/hugegraph/service/op/OperationsPayloadParserTest.java b/hugegraph-hubble/hubble-be/src/test/java/org/apache/hugegraph/service/op/OperationsPayloadParserTest.java
index 94ae333c0..f9216da42 100644
--- a/hugegraph-hubble/hubble-be/src/test/java/org/apache/hugegraph/service/op/OperationsPayloadParserTest.java
+++ b/hugegraph-hubble/hubble-be/src/test/java/org/apache/hugegraph/service/op/OperationsPayloadParserTest.java
@@ -44,7 +44,7 @@ public class OperationsPayloadParserTest {
"\"dataPath\":\"/secret/leader\",\"role\":\"Leader\"," +
"\"serviceVersion\":\"1.7.0\"}," +
"\"graphSize\":2,\"partitionSize\":12," +
- "\"shardCount\":3}}";
+ "\"shardCount\":3,\"dataSize\":5}}";
String stores = "{\"status\":0,\"data\":{\"stores\":[{" +
"\"storeId\":\"7\",\"address\":\"store-a:8500\"," +
"\"deployPath\":\"/secret/bin\"," +
@@ -60,6 +60,12 @@ public class OperationsPayloadParserTest {
Assert.assertEquals(2L, topology.getFacts().get("graphs"));
Assert.assertEquals(12L, topology.getFacts().get("partitions"));
Assert.assertEquals(3L, topology.getFacts().get("replicas"));
+ Assert.assertEquals(5120L,
+ topology.getFacts().get("data_size_bytes"));
+ Assert.assertEquals(1000L,
+ topology.getFacts().get("capacity_total_bytes"));
+ Assert.assertEquals(600L,
+ topology.getFacts().get("capacity_used_bytes"));
List<Node> nodes = topology.getNodes();
Assert.assertEquals(3, nodes.size());
Assert.assertEquals("LEADER", nodes.get(1).getRole());
@@ -75,6 +81,25 @@ public class OperationsPayloadParserTest {
Assert.assertFalse(serialized.contains("/secret"));
}
+ @Test
+ public void testOmitsIncompleteOrOverflowingSizeFacts() {
+ String cluster = "{\"status\":0,\"data\":{" +
+ "\"pdList\":[],\"dataSize\":9223372036854775807}}";
+ String stores = "{\"status\":0,\"data\":{\"stores\":[{" +
+ "\"storeId\":\"1\",\"capacity\":1000},{" +
+ "\"storeId\":\"2\",\"capacity\":1000," +
+ "\"available\":2000}]}}";
+
+ Topology topology = new OperationsPayloadParser(MAPPER)
+ .parseTopology(cluster, stores);
+
+ Assert.assertFalse(topology.getFacts().containsKey("data_size_bytes"));
+ Assert.assertFalse(topology.getFacts().containsKey(
+ "capacity_total_bytes"));
+ Assert.assertFalse(topology.getFacts().containsKey(
+ "capacity_used_bytes"));
+ }
+
@Test
public void testParsesOnlyStoreMetricTargetsAndInternalHostMap() {
OperationsPayloadParser parser = new OperationsPayloadParser(MAPPER);
@@ -100,6 +125,28 @@ public class OperationsPayloadParserTest {
metricTargets.get("store-a:8520"));
}
+ @Test
+ public void testParsesPdLeaderRestTargetWithConfiguredScheme() {
+ String cluster = "{\"status\":0,\"data\":{" +
+ "\"pdList\":[],\"pdLeader\":{" +
+ "\"restUrl\":\"pd-1:8620\"}}}";
+
+ URI target = new OperationsPayloadParser(MAPPER)
+ .parsePdLeaderRestTarget(cluster, "http");
+
+ Assert.assertEquals(URI.create("http://pd-1:8620"), target);
+ }
+
+ @Test(expected = MalformedUpstreamException.class)
+ public void testRejectsPdLeaderRestTargetWithPath() {
+ String cluster = "{\"status\":0,\"data\":{" +
+ "\"pdList\":[],\"pdLeader\":{" +
+ "\"restUrl\":\"http://pd-1:8620/private\"}}}";
+
+ new OperationsPayloadParser(MAPPER)
+ .parsePdLeaderRestTarget(cluster, "http");
+ }
+
@Test
public void testKeepsSameHostStoreTargetsDistinctByAuthority() {
OperationsPayloadParser parser = new OperationsPayloadParser(MAPPER);
diff --git a/hugegraph-hubble/hubble-be/src/test/java/org/apache/hugegraph/service/space/GraphSpaceServiceTest.java b/hugegraph-hubble/hubble-be/src/test/java/org/apache/hugegraph/service/space/GraphSpaceServiceTest.java
index 2f5958124..b64567571 100644
--- a/hugegraph-hubble/hubble-be/src/test/java/org/apache/hugegraph/service/space/GraphSpaceServiceTest.java
+++ b/hugegraph-hubble/hubble-be/src/test/java/org/apache/hugegraph/service/space/GraphSpaceServiceTest.java
@@ -22,11 +22,13 @@ import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
+import org.apache.hugegraph.driver.AuthManager;
import org.apache.hugegraph.driver.GraphSpaceManager;
import org.apache.hugegraph.driver.HugeClient;
import org.apache.hugegraph.entity.space.GraphSpaceEntity;
import org.apache.hugegraph.service.auth.UserService;
import org.apache.hugegraph.service.graphs.GraphsService;
+import org.apache.hugegraph.structure.space.GraphSpace;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
@@ -103,6 +105,76 @@ public class GraphSpaceServiceTest {
Assert.assertFalse(response.get(0).containsKey("configs"));
}
+ @Test
+ public void testAccessibleGraphSpacesHonorAuthorization() {
+ GraphSpaceManager manager = Mockito.mock(GraphSpaceManager.class);
+ AuthManager auth = Mockito.mock(AuthManager.class);
+ Map<String, GraphSpace> spaces = new HashMap<>();
+ spaces.put("public", graphSpace("public", false, "20260712"));
+ spaces.put("admin", graphSpace("admin", true, "20260712"));
+ spaces.put("analyst", graphSpace("analyst", true, "20260712"));
+ spaces.put("observer", graphSpace("observer", true, "20260712"));
+ spaces.put("denied", graphSpace("denied", true, "20260712"));
+
+ Mockito.when(this.client.graphSpace()).thenReturn(manager);
+ Mockito.when(this.client.auth()).thenReturn(auth);
+ Mockito.when(this.client.supportsDefaultRole()).thenReturn(true);
+ Mockito.when(manager.listGraphSpace())
+ .thenReturn(java.util.Arrays.asList("public", "admin",
+ "analyst", "observer",
+ "denied"));
+ Mockito.when(manager.getGraphSpace(Mockito.anyString()))
+ .thenAnswer(invocation -> spaces.get(invocation.getArgument(0)));
+ Mockito.when(auth.isSpaceAdmin("admin")).thenReturn(true);
+ Mockito.when(auth.checkDefaultRole("analyst", "analyst"))
+ .thenReturn(true);
+ Mockito.when(auth.checkDefaultRole("observer", "observer"))
+ .thenReturn(true);
+ Mockito.when(this.graphsService.listGraphNames(
+ Mockito.eq(this.client), Mockito.anyString(),
+ Mockito.eq("")))
+ .thenReturn(java.util.Collections.emptySet());
+
+ List<Map<String, Object>> response =
+ this.service.queryAccessibleGs(this.client, "", "");
+
+ Assert.assertEquals(java.util.Arrays.asList("admin", "analyst",
+ "observer", "public"),
+ response.stream().map(item -> item.get("name"))
+ .collect(java.util.stream.Collectors
+ .toList()));
+ Assert.assertTrue((Boolean) response.get(0).get("authed"));
+ Assert.assertFalse((Boolean) response.get(0).get("default"));
+ Mockito.verify(auth, Mockito.never())
+ .checkDefaultRole(Mockito.anyString(), Mockito.eq("observer"),
+ Mockito.anyString());
+ }
+
+ @Test
+ public void testAnonymousGraphSpacesApplyQueryAndTimeFilters() {
+ GraphSpaceManager manager = Mockito.mock(GraphSpaceManager.class);
+ GraphSpace visible = graphSpace("public", false, "20260712");
+ visible.setNickname("visible space");
+ GraphSpace old = graphSpace("visible-old", true, "20260701");
+ Mockito.when(this.client.graphSpace()).thenReturn(manager);
+ Mockito.when(manager.listGraphSpace())
+ .thenReturn(java.util.Arrays.asList("public", "visible-old"));
+ Mockito.when(manager.getGraphSpace("public")).thenReturn(visible);
+ Mockito.when(manager.getGraphSpace("visible-old")).thenReturn(old);
+ Mockito.when(this.graphsService.listGraphNames(
+ Mockito.eq(this.client), Mockito.anyString(),
+ Mockito.eq("")))
+ .thenReturn(java.util.Collections.emptySet());
+
+ List<Map<String, Object>> response =
+ this.service.queryAnonymousGs(this.client, "visible",
+ "20260702");
+
+ Assert.assertEquals(1, response.size());
+ Assert.assertEquals("public", response.get(0).get("name"));
+ Assert.assertTrue((Boolean) response.get(0).get("authed"));
+ }
+
@Test
public void testStatisticUsesActualFallbackDate() {
Mockito.when(this.graphsService.listGraphNames(this.client, "space", ""))
@@ -265,4 +337,12 @@ public class GraphSpaceServiceTest {
statistic.put("edge", edge);
return statistic;
}
+
+ private static GraphSpace graphSpace(String name, boolean auth,
+ String createTime) {
+ GraphSpace graphSpace = new GraphSpace(name);
+ graphSpace.setAuth(auth);
+ graphSpace.setCreateTime(createTime);
+ return graphSpace;
+ }
}
diff --git a/hugegraph-hubble/hubble-be/src/test/java/org/apache/hugegraph/unit/AuthSecurityTest.java b/hugegraph-hubble/hubble-be/src/test/java/org/apache/hugegraph/unit/AuthSecurityTest.java
index 64df7fce9..44916017a 100644
--- a/hugegraph-hubble/hubble-be/src/test/java/org/apache/hugegraph/unit/AuthSecurityTest.java
+++ b/hugegraph-hubble/hubble-be/src/test/java/org/apache/hugegraph/unit/AuthSecurityTest.java
@@ -28,6 +28,7 @@ import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.URL;
import java.nio.charset.StandardCharsets;
+import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
@@ -46,6 +47,9 @@ import org.springframework.http.ResponseEntity;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.util.ReflectionTestUtils;
+import org.springframework.util.AntPathMatcher;
+import org.springframework.web.servlet.handler.MappedInterceptor;
+import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.context.request.RequestContextHolder;
@@ -55,6 +59,7 @@ import org.apache.hugegraph.common.Constant;
import org.apache.hugegraph.common.Response;
import org.apache.hugegraph.config.HugeConfig;
import org.apache.hugegraph.config.IngestionProxyServlet;
+import org.apache.hugegraph.config.WebMvcConfig;
import org.apache.hugegraph.controller.BaseController;
import org.apache.hugegraph.controller.auth.LoginController;
import org.apache.hugegraph.driver.AuthManager;
@@ -212,6 +217,26 @@ public class AuthSecurityTest {
Assert.assertNull(request.getAttribute("hugeClient"));
}
+ @Test
+ public void testOnlyBootstrapConfigBypassesLoginInterceptor() {
+ InterceptorRegistry registry = new InterceptorRegistry();
+ new WebMvcConfig().addInterceptors(registry);
+ List<Object> interceptors = ReflectionTestUtils.invokeMethod(
+ registry, "getInterceptors");
+ MappedInterceptor login = interceptors.stream()
+ .map(MappedInterceptor.class::cast)
+ .filter(interceptor -> interceptor.getInterceptor()
+ instanceof LoginInterceptor)
+ .findFirst()
+ .orElseThrow(AssertionError::new);
+ AntPathMatcher matcher = new AntPathMatcher();
+
+ Assert.assertFalse(login.matches(
+ Constant.API_VERSION + "config", matcher));
+ Assert.assertTrue(login.matches(
+ Constant.API_VERSION + "setting/config", matcher));
+ }
+
@Test
public void testCustomInterceptorDoesNotCreateClientForMissingSession()
throws Exception {
diff --git a/hugegraph-hubble/hubble-be/src/test/java/org/apache/hugegraph/unit/OperationsControllerTest.java b/hugegraph-hubble/hubble-be/src/test/java/org/apache/hugegraph/unit/OperationsControllerTest.java
index ed89bdf1a..6f483ab48 100644
--- a/hugegraph-hubble/hubble-be/src/test/java/org/apache/hugegraph/unit/OperationsControllerTest.java
+++ b/hugegraph-hubble/hubble-be/src/test/java/org/apache/hugegraph/unit/OperationsControllerTest.java
@@ -23,6 +23,7 @@ import java.util.Map;
import org.apache.hugegraph.driver.HugeClient;
import org.apache.hugegraph.exception.ForbiddenException;
+import org.apache.hugegraph.service.auth.AuthModeService;
import org.apache.hugegraph.service.auth.UserService;
import org.apache.hugegraph.service.op.OperationsDataService;
import org.apache.hugegraph.testutil.Assert;
@@ -35,7 +36,9 @@ import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.apache.hugegraph.common.Constant;
+import org.apache.hugegraph.config.HugeConfig;
import org.apache.hugegraph.controller.op.OperationsController;
+import org.apache.hugegraph.options.HubbleOptions;
public class OperationsControllerTest {
@@ -82,7 +85,29 @@ public class OperationsControllerTest {
Assert.assertEquals(0, response.get("total"));
}
+ @Test
+ public void testAnonymousModeCanReadOperations() {
+ Fixture fixture = fixture("USER", true);
+ Mockito.when(fixture.dataService.overview(Mockito.any(),
+ Mockito.anySet(),
+ Mockito.eq(false)))
+ .thenReturn(Collections.singletonMap("status", "UP"));
+
+ Map<String, Object> capabilities =
+ fixture.controller.capabilities();
+ Map<String, Object> overview = fixture.controller.overview(false);
+
+ Assert.assertEquals(3,
+ ((java.util.Set<?>) capabilities.get(
+ "capabilities")).size());
+ Assert.assertEquals("UP", overview.get("status"));
+ }
+
private static Fixture fixture(String level) {
+ return fixture(level, false);
+ }
+
+ private static Fixture fixture(String level, boolean anonymous) {
MockHttpServletRequest request = new MockHttpServletRequest();
request.getSession().setAttribute(Constant.USERNAME_KEY, "operator");
request.getSession().setAttribute(Constant.TOKEN_KEY, "token");
@@ -96,6 +121,11 @@ public class OperationsControllerTest {
OperationsDataService dataService = Mockito.mock(
OperationsDataService.class);
OperationsController controller = new OperationsController();
+ HugeConfig config = Mockito.mock(HugeConfig.class);
+ Mockito.when(config.get(HubbleOptions.AUTH_ENABLED))
+ .thenReturn(!anonymous);
+ AuthModeService authMode = new AuthModeService(config);
+ ReflectionTestUtils.setField(controller, "authMode", authMode);
ReflectionTestUtils.setField(controller, "userService", userService);
ReflectionTestUtils.setField(controller, "dataService", dataService);
return new Fixture(controller, dataService);
diff --git a/hugegraph-hubble/hubble-be/src/test/java/org/apache/hugegraph/unit/UnitTestSuite.java b/hugegraph-hubble/hubble-be/src/test/java/org/apache/hugegraph/unit/UnitTestSuite.java
index a6b487b09..953ec23bc 100644
--- a/hugegraph-hubble/hubble-be/src/test/java/org/apache/hugegraph/unit/UnitTestSuite.java
+++ b/hugegraph-hubble/hubble-be/src/test/java/org/apache/hugegraph/unit/UnitTestSuite.java
@@ -25,6 +25,7 @@ import org.apache.hugegraph.controller.ingest.IngestControllerTest;
import org.apache.hugegraph.controller.langchain.LangChainControllerSecurityTest;
import org.apache.hugegraph.controller.schema.SchemaControllerSecurityTest;
import org.apache.hugegraph.controller.space.GraphSpaceControllerTest;
+import org.apache.hugegraph.config.HubbleConfigEnvironmentTest;
import org.apache.hugegraph.handler.ResponseAdvisorStatusTest;
import org.apache.hugegraph.service.load.IngestTransactionIntegrationTest;
import org.apache.hugegraph.service.auth.AuthContextServiceTest;
@@ -62,6 +63,7 @@ import org.junit.runners.Suite;
GraphsControllerCanonicalTest.class,
GremlinUtilTest.class,
GremlinHistoryFailureTest.class,
+ HubbleConfigEnvironmentTest.class,
HubbleOptionsTest.class,
IngestControllerTest.class,
IngestTransactionIntegrationTest.class,
diff --git a/hugegraph-hubble/hubble-be/src/test/java/org/apache/hugegraph/unit/UserServiceCompatibilityTest.java b/hugegraph-hubble/hubble-be/src/test/java/org/apache/hugegraph/unit/UserServiceCompatibilityTest.java
index 62570641a..c4b086468 100644
--- a/hugegraph-hubble/hubble-be/src/test/java/org/apache/hugegraph/unit/UserServiceCompatibilityTest.java
+++ b/hugegraph-hubble/hubble-be/src/test/java/org/apache/hugegraph/unit/UserServiceCompatibilityTest.java
@@ -18,6 +18,7 @@
package org.apache.hugegraph.unit;
import java.util.Arrays;
+import java.util.Collections;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.junit.Assert;
@@ -29,8 +30,11 @@ import org.springframework.test.util.ReflectionTestUtils;
import org.apache.hugegraph.config.HugeConfig;
import org.apache.hugegraph.driver.AuthManager;
+import org.apache.hugegraph.driver.GraphSpaceManager;
+import org.apache.hugegraph.driver.GraphsManager;
import org.apache.hugegraph.driver.HugeClient;
import org.apache.hugegraph.entity.auth.UserEntity;
+import org.apache.hugegraph.exception.ServerException;
import org.apache.hugegraph.options.HubbleOptions;
import org.apache.hugegraph.service.auth.GraphSpaceUserService;
import org.apache.hugegraph.service.auth.UserService;
@@ -41,6 +45,9 @@ public class UserServiceCompatibilityTest {
private HugeConfig config;
private HugeClient client;
private AuthManager auth;
+ private GraphSpaceManager graphSpace;
+ private GraphsManager graphs;
+ private GraphSpaceUserService graphSpaceUsers;
private UserService service;
@Before
@@ -48,13 +55,20 @@ public class UserServiceCompatibilityTest {
this.config = Mockito.mock(HugeConfig.class);
this.client = Mockito.mock(HugeClient.class);
this.auth = Mockito.mock(AuthManager.class);
+ this.graphSpace = Mockito.mock(GraphSpaceManager.class);
+ this.graphs = Mockito.mock(GraphsManager.class);
+ this.graphSpaceUsers = Mockito.mock(GraphSpaceUserService.class);
Mockito.when(this.client.auth()).thenReturn(this.auth);
+ Mockito.when(this.client.graphSpace()).thenReturn(this.graphSpace);
+ Mockito.when(this.client.graphs()).thenReturn(this.graphs);
Mockito.when(this.auth.createUser(Mockito.any(User.class)))
.thenReturn(new User());
+ Mockito.when(this.auth.listSuperAdmin())
+ .thenReturn(java.util.Collections.emptyList());
this.service = new UserService();
ReflectionTestUtils.setField(this.service, "config", this.config);
ReflectionTestUtils.setField(this.service, "graphSpaceUserService",
- Mockito.mock(GraphSpaceUserService.class));
+ this.graphSpaceUsers);
}
@Test
@@ -125,6 +139,137 @@ public class UserServiceCompatibilityTest {
Assert.assertEquals("description", request.getValue().description());
}
+ @Test
+ public void testCurrentUserPresetUsesSelfPermissionApi() {
+ Mockito.when(this.config.get(HubbleOptions.PD_ENABLED)).thenReturn(true);
+ Mockito.when(this.client.supportsDefaultRole()).thenReturn(true);
+ Mockito.when(this.client.findUserByName("user"))
+ .thenReturn(user("user"));
+ Mockito.when(this.graphSpace.listGraphSpace())
+ .thenReturn(java.util.Collections.singletonList("SPACE"));
+ Mockito.when(this.auth.checkDefaultRole("SPACE", "analyst"))
+ .thenReturn(true);
+
+ UserEntity result = this.service.getpersonal(this.client, "user");
+
+ Assert.assertEquals("GS_READ_WRITE",
+ result.getGraphspacePermissions().get(0)
+ .get("permission_preset"));
+ Mockito.verify(this.graphSpace, Mockito.never())
+ .checkDefaultRole(Mockito.anyString(), Mockito.anyString(),
+ Mockito.anyString());
+ }
+
+ @Test
+ public void testUserDetailFindsAdminSpacesByUsername() {
+ Mockito.when(this.config.get(HubbleOptions.PD_ENABLED)).thenReturn(true);
+ User account = user("alice");
+ account.setId("user-id");
+ Mockito.when(this.auth.getUser("user-id")).thenReturn(account);
+ Mockito.when(this.auth.listUsers())
+ .thenReturn(Collections.singletonList(account));
+ Mockito.when(this.graphSpace.listGraphSpace())
+ .thenReturn(Collections.singletonList("SPACE"));
+ Mockito.when(this.auth.listSpaceAdmin("SPACE"))
+ .thenReturn(Collections.singletonList("alice"));
+
+ UserEntity result = this.service.get(this.client, "user-id");
+
+ Assert.assertEquals(Collections.singletonList("SPACE"),
+ result.getAdminSpaces());
+ Assert.assertEquals(Integer.valueOf(1), result.getSpacenum());
+ }
+
+ @Test
+ public void testCurrentUserIgnoresOnlyForbiddenGraphSpaces() {
+ Mockito.when(this.config.get(HubbleOptions.PD_ENABLED)).thenReturn(true);
+ Mockito.when(this.client.supportsDefaultRole()).thenReturn(true);
+ Mockito.when(this.client.findUserByName("user"))
+ .thenReturn(user("user"));
+ Mockito.when(this.graphSpace.listGraphSpace())
+ .thenReturn(Arrays.asList("OWNED", "DENIED"));
+ Mockito.when(this.auth.checkDefaultRole("OWNED", "analyst"))
+ .thenReturn(true);
+ ServerException forbidden = new ServerException("forbidden");
+ forbidden.status(403);
+ Mockito.when(this.graphs.listGraph()).thenThrow(forbidden);
+
+ UserEntity result = this.service.getpersonal(this.client, "user");
+
+ Assert.assertEquals(Collections.singletonList("OWNED"),
+ result.getResSpaces());
+ Assert.assertEquals(1, result.getGraphspacePermissions().size());
+ }
+
+ @Test
+ public void testLegacyProfileUpdatePreservesPermissionAssignments() {
+ Mockito.when(this.config.get(HubbleOptions.PD_ENABLED)).thenReturn(true);
+ Mockito.when(this.client.supportsDefaultRole()).thenReturn(false);
+ UserEntity user = UserEntity.builder()
+ .id("user-id")
+ .name("user")
+ .nickname("display-name")
+ .build();
+
+ this.service.update(this.client, user);
+
+ Mockito.verify(this.graphSpaceUsers, Mockito.never())
+ .validatePermissionPresets(Mockito.any(), Mockito.any(),
+ Mockito.any());
+ Mockito.verify(this.graphSpaceUsers, Mockito.never())
+ .applyPermissionPresets(Mockito.any(), Mockito.anyString(),
+ Mockito.any(), Mockito.any());
+ Mockito.verify(this.auth).updateUser(Mockito.any(User.class));
+ }
+
+ @Test
+ public void testModernProfileUpdatePreservesPermissionAssignments() {
+ Mockito.when(this.config.get(HubbleOptions.PD_ENABLED)).thenReturn(true);
+ Mockito.when(this.client.supportsDefaultRole()).thenReturn(true);
+ GraphSpaceUserService actualGraphSpaceUsers =
+ new GraphSpaceUserService();
+ ReflectionTestUtils.setField(this.service, "graphSpaceUserService",
+ actualGraphSpaceUsers);
+ UserEntity user = UserEntity.builder()
+ .id("user-id")
+ .name("user")
+ .nickname("display-name")
+ .build();
+
+ this.service.update(this.client, user);
+
+ Mockito.verify(this.auth).updateUser(Mockito.any(User.class));
+ Mockito.verify(this.graphSpace, Mockito.never()).setDefaultRole(
+ Mockito.anyString(), Mockito.anyString(), Mockito.anyString());
+ Mockito.verify(this.graphSpace, Mockito.never()).deleteDefaultRole(
+ Mockito.anyString(), Mockito.anyString(), Mockito.anyString());
+ Mockito.verify(this.auth, Mockito.never()).addSpaceAdmin(
+ Mockito.anyString(), Mockito.anyString());
+ Mockito.verify(this.auth, Mockito.never()).delSpaceAdmin(
+ Mockito.anyString(), Mockito.anyString());
+ }
+
+ @Test
+ public void testLegacyUserCreationSkipsPermissionPresetApis() {
+ Mockito.when(this.config.get(HubbleOptions.PD_ENABLED)).thenReturn(true);
+ Mockito.when(this.client.supportsDefaultRole()).thenReturn(false);
+ UserEntity user = userEntity("display-name");
+ user.setPermissionPreset("GS_READ_ONLY");
+ user.setGraphspacePermissions(java.util.Collections.singletonList(
+ java.util.Collections.singletonMap(
+ "permission_preset", "GS_READ_ONLY")));
+
+ this.service.add(this.client, user);
+
+ Mockito.verify(this.auth).createUser(Mockito.any(User.class));
+ Mockito.verify(this.graphSpaceUsers, Mockito.never())
+ .validatePermissionPresets(Mockito.any(), Mockito.any(),
+ Mockito.any());
+ Mockito.verify(this.graphSpaceUsers, Mockito.never())
+ .applyPermissionPresets(Mockito.any(), Mockito.anyString(),
+ Mockito.any(), Mockito.any());
+ }
+
private static UserEntity userEntity(String nickname) {
return UserEntity.builder()
.name("user")
diff --git a/hugegraph-hubble/hubble-dist/assembly/static/conf/hugegraph-hubble.properties b/hugegraph-hubble/hubble-dist/assembly/static/conf/hugegraph-hubble.properties
index 8dfce484c..442560763 100644
--- a/hugegraph-hubble/hubble-dist/assembly/static/conf/hugegraph-hubble.properties
+++ b/hugegraph-hubble/hubble-dist/assembly/static/conf/hugegraph-hubble.properties
@@ -28,6 +28,9 @@ idc=bddwd
client.url_cache_max_entries=1024
# ===== Deployment Mode =====
+# Require an authenticated Hubble session. HUBBLE_AUTH_ENABLED can explicitly
+# override this value for container and orchestrated deployments.
+auth.enabled=true
# Set to false for standalone RocksDB mode (no PD dependency)
pd.enabled=false
# Direct server URL, only used when pd.enabled=false
diff --git a/hugegraph-hubble/hubble-fe/src/i18n/resources/en-US/modules/pages.json b/hugegraph-hubble/hubble-fe/src/i18n/resources/en-US/modules/pages.json
index eda395aec..688c9a933 100644
--- a/hugegraph-hubble/hubble-fe/src/i18n/resources/en-US/modules/pages.json
+++ b/hugegraph-hubble/hubble-fe/src/i18n/resources/en-US/modules/pages.json
@@ -392,9 +392,19 @@
"GS_READ_ONLY": "GraphSpace Read-only",
"GS_READ_WRITE": "GraphSpace Read-write",
"GS_ADMIN": "GraphSpace Administrator",
+ "preserve_mixed": "Keep existing mixed access",
"mixed": "Mixed GraphSpace access",
"legacy_custom": "Legacy/custom access"
},
+ "feedback": {
+ "save_failed": "Account was not saved",
+ "save_retry": "Check the account fields and server connection, then retry.",
+ "delete_retry": "The account could not be deleted. Refresh the list and retry.",
+ "presets_unavailable": "GraphSpace presets are unavailable",
+ "presets_unavailable_help": "This deployment does not provide the required permission API. The account will be created without elevated permissions",
+ "preset_edit_unavailable": "Permission editing is unavailable",
+ "preset_edit_unavailable_help": "Profile and password changes remain available; existing permissions are preserved until the connected HugeGraph REST API is upgraded to 0.72 or later"
+ },
"form": {
"title_detail": "View Account",
"title_edit": "Edit Account",
@@ -1229,6 +1239,8 @@
"node_id_copied": "Node ID copied",
"node_id_copy_failed": "Could not copy the node ID",
"leader_role": "Leader role",
+ "leader": "Leader",
+ "follower": "Follower",
"leader_shard": "{{count}} leader shard",
"leader_shards": "{{count}} leader shards",
"node_profile": "Node profile",
@@ -1318,8 +1330,8 @@
"metric_scope_backend": "Backend metrics are provided by Server and Store nodes, not {{nodeType}} nodes.",
"reason_upstream_timeout": "Upstream timed out",
"reason_upstream_unavailable": "Upstream unavailable",
- "reason_metrics_target_untrusted": "The metrics target failed the trust check. Review the PD/Prometheus target configuration.",
- "reason_metrics_target_missing": "No Store metrics target was discovered. Review the target configuration.",
+ "reason_metrics_target_untrusted": "The Store metrics origin is not trusted. Add its exact scheme, host, and port to operations.store.allowed_targets, restart Hubble, then refresh.",
+ "reason_metrics_target_missing": "PD did not report a Store metrics target. Check PD target discovery and the Store REST metrics port, then refresh.",
"reason_upstream_deadline": "Metrics collection timed out",
"reason_metrics_not_collected": "This metric is not collected from the current node",
"reason_topology_fields_unavailable": "The topology did not provide this field",
diff --git a/hugegraph-hubble/hubble-fe/src/i18n/resources/zh-CN/modules/pages.json b/hugegraph-hubble/hubble-fe/src/i18n/resources/zh-CN/modules/pages.json
index fa025bb7e..0a9870792 100644
--- a/hugegraph-hubble/hubble-fe/src/i18n/resources/zh-CN/modules/pages.json
+++ b/hugegraph-hubble/hubble-fe/src/i18n/resources/zh-CN/modules/pages.json
@@ -392,9 +392,19 @@
"GS_READ_ONLY": "GraphSpace 只读",
"GS_READ_WRITE": "GraphSpace 读写",
"GS_ADMIN": "GraphSpace 管理员",
+ "preserve_mixed": "保留现有混合权限",
"mixed": "混合 GraphSpace 权限",
"legacy_custom": "旧版/自定义权限"
},
+ "feedback": {
+ "save_failed": "账号未保存",
+ "save_retry": "请检查账号字段和 Server 连接后重试。",
+ "delete_retry": "账号删除失败,请刷新列表后重试。",
+ "presets_unavailable": "GraphSpace 权限预设不可用",
+ "presets_unavailable_help": "当前部署未提供所需权限 API,账号将以无提升权限的普通账号创建",
+ "preset_edit_unavailable": "当前无法编辑权限",
+ "preset_edit_unavailable_help": "仍可修改用户资料和密码,现有权限将保持不变;升级当前连接的 HugeGraph REST API 至 0.72 或更高版本后可编辑权限"
+ },
"form": {
"title_detail": "查看账号",
"title_edit": "编辑账号",
@@ -1229,6 +1239,8 @@
"node_id_copied": "节点 ID 已复制",
"node_id_copy_failed": "无法复制节点 ID",
"leader_role": "Leader 角色",
+ "leader": "Leader",
+ "follower": "Follower",
"leader_shard": "{{count}} 个 Leader 分区",
"leader_shards": "{{count}} 个 Leader 分区",
"node_profile": "节点概况",
@@ -1268,7 +1280,7 @@
"node_count": "{{count}} 个节点",
"node_count_plural": "{{count}} 个节点",
"more_nodes": "查看另外 {{count}} 个节点",
- "cluster_facts": "集群事实",
+ "cluster_facts": "集群信息",
"fact_stores_up": "在线 Store",
"fact_pd_leader": "PD Leader",
"fact_capacity": "容量",
@@ -1318,8 +1330,8 @@
"metric_scope_backend": "后端指标由 Server 和 Store 节点提供,不会在 {{nodeType}} 节点采集。",
"reason_upstream_timeout": "上游超时",
"reason_upstream_unavailable": "上游不可用",
- "reason_metrics_target_untrusted": "指标采集目标未通过信任校验,请检查 PD/Prometheus target 配置",
- "reason_metrics_target_missing": "未发现 Store 指标采集目标,请检查 target 配置",
+ "reason_metrics_target_untrusted": "Store 指标来源不在信任列表中。请将其完整协议、主机和端口加入 operations.store.allowed_targets,重启 Hubble 后刷新。",
+ "reason_metrics_target_missing": "PD 未返回 Store 指标目标。请检查 PD target 发现和 Store REST 指标端口后刷新。",
"reason_upstream_deadline": "指标采集超时",
"reason_metrics_not_collected": "当前节点未采集该指标",
"reason_topology_fields_unavailable": "拓扑未提供该字段",
diff --git a/hugegraph-hubble/hubble-fe/src/modules/navigation/ConsoleItem/index.js b/hugegraph-hubble/hubble-fe/src/modules/navigation/ConsoleItem/index.js
index a386045b3..11c5f3a54 100644
--- a/hugegraph-hubble/hubble-fe/src/modules/navigation/ConsoleItem/index.js
+++ b/hugegraph-hubble/hubble-fe/src/modules/navigation/ConsoleItem/index.js
@@ -25,6 +25,7 @@ import {useTranslation} from 'react-i18next';
import * as api from '../../../api';
import {useOperationsCapabilities} from '../../../pages/Operations/capabilities';
+import {isPdEnabled} from '../../../utils/config';
import Item from '../Item';
import {normalizeDashboardUrl} from './dashboard';
@@ -36,6 +37,7 @@ const ConsoleItem = ({embedded = false}) => {
capabilities,
error: capabilitiesError,
} = useOperationsCapabilities();
+ const pdMode = isPdEnabled();
const [dashboard, setDashboard] = useState({status: 'loading', url: ''});
useEffect(() => {
@@ -103,8 +105,8 @@ const ConsoleItem = ({embedded = false}) => {
? () => openDashboard(dashboard.url + path)
: undefined,
});
- const nativeItem = (titleKey, path, required) => {
- const available = capabilities.includes(required);
+ const nativeItem = (titleKey, path, required, modeAvailable = true) => {
+ const available = modeAvailable && capabilities.includes(required);
const disabled = capabilitiesLoading || Boolean(capabilitiesError) || !available;
return {
title: t(titleKey),
@@ -130,7 +132,8 @@ const ConsoleItem = ({embedded = false}) => {
nativeItem(
'navigation_page.cluster_overview',
'/operations/overview',
- 'operations_health_read'
+ 'operations_health_read',
+ pdMode
),
nativeItem(
'navigation_page.nodes',
diff --git a/hugegraph-hubble/hubble-fe/src/modules/navigation/ConsoleItem/index.test.js b/hugegraph-hubble/hubble-fe/src/modules/navigation/ConsoleItem/index.test.js
index 20e8df8b0..c69f169e3 100644
--- a/hugegraph-hubble/hubble-fe/src/modules/navigation/ConsoleItem/index.test.js
+++ b/hugegraph-hubble/hubble-fe/src/modules/navigation/ConsoleItem/index.test.js
@@ -22,6 +22,7 @@ import * as api from '../../../api';
import ConsoleItem from './index';
import itemStyle from '../Item/index.module.scss';
import {useOperationsCapabilities} from '../../../pages/Operations/capabilities';
+import {isPdEnabled} from '../../../utils/config';
const mockMessageError = jest.fn();
@@ -33,6 +34,9 @@ jest.mock('../../../api', () => ({
jest.mock('../../../pages/Operations/capabilities', () => ({
useOperationsCapabilities: jest.fn(),
}));
+jest.mock('../../../utils/config', () => ({
+ isPdEnabled: jest.fn(),
+}));
jest.mock('antd', () => ({
...jest.requireActual('antd'),
message: {error: (...args) => mockMessageError(...args)},
@@ -66,6 +70,7 @@ beforeEach(() => {
],
error: null,
});
+ isPdEnabled.mockReturnValue(true);
});
const renderConsole = () => render(
@@ -116,6 +121,22 @@ test('links native operations independently of the optional Dashboard', async ()
})).toHaveAttribute('tabindex', '0');
});
+test('disables Cluster Overview outside PD mode while keeping Nodes available', async () => {
+ isPdEnabled.mockReturnValue(false);
+ api.auth.getDashboard.mockResolvedValue({
+ status: 200,
+ data: {configured: false},
+ });
+ renderConsole();
+
+ expect(await screen.findByRole('button', {
+ name: 'navigation_page.cluster_overview',
+ })).toBeDisabled();
+ expect(screen.getByRole('button', {
+ name: 'navigation_page.nodes',
+ })).toHaveAttribute('data-url', '/operations/nodes');
+});
+
test('labels an unconfigured Dashboard instead of Coming Soon', async () => {
api.auth.getDashboard.mockResolvedValue({
status: 200,
diff --git a/hugegraph-hubble/hubble-fe/src/pages/Account/EditLayer.js b/hugegraph-hubble/hubble-fe/src/pages/Account/EditLayer.js
index 775f23587..85caa1852 100644
--- a/hugegraph-hubble/hubble-fe/src/pages/Account/EditLayer.js
+++ b/hugegraph-hubble/hubble-fe/src/pages/Account/EditLayer.js
@@ -16,13 +16,15 @@
* under the License.
*/
-import {Modal, Input, Form, Select, message, Spin} from 'antd';
+import {Alert, Modal, Input, Form, Select, message, Spin} from 'antd';
import {useCallback, useEffect, useRef, useState} from 'react';
import {useTranslation} from 'react-i18next';
import * as api from '../../api';
import * as rules from '../../utils/rules';
import style from './index.module.scss';
import FormHelpLabel from '../../components/FormHelpLabel';
+import {accountErrorMessage} from './accountError';
+import {useAuthContext} from '../../auth/AuthContext';
import {
getAccountPreset,
getPresetSpaces,
@@ -32,8 +34,15 @@ import {
const PAGE_ERROR_CONFIG = {suppressBusinessErrorToast: true};
const DEFAULT_ALLOWED_OPERATIONS = {create: true, edit: true, auth: true};
+const PRESERVE_PERMISSIONS = 'PRESERVE_PERMISSIONS';
const permissionPresetChanged = (prev, next) => (prev.permission_preset !== next.permission_preset
);
+const toProfilePayload = values => ({
+ user_name: values.user_name,
+ user_nickname: values.user_nickname,
+ user_password: values.user_password,
+ user_description: values.user_description,
+});
const HelpLabel = ({t, labelKey}) => (
<FormHelpLabel
@@ -51,13 +60,25 @@ const EditLayer = ({
allowedOperations = DEFAULT_ALLOWED_OPERATIONS,
}) => {
const {t} = useTranslation();
+ const {context} = useAuthContext();
const [form] = Form.useForm();
const [graphspaceList, setGraphspaceList] = useState([]);
const [detail, setDetail] = useState({});
const [loading, setLoading] = useState(false);
const [submitting, setSubmitting] = useState(false);
+ const [mutationError, setMutationError] = useState(null);
const submitPending = useRef(false);
const detailRequest = useRef(0);
+ const permissionPresetsSupported = !context
+ || context.capabilities?.includes('account_permission_presets');
+ const permissionFieldsVisible = permissionPresetsSupported
+ && ['create', 'edit'].includes(op);
+ const preservesMixedPermissions = op === 'edit'
+ && getAccountPreset(detail) === null;
+ const presetOptions = [
+ ...(preservesMixedPermissions ? [PRESERVE_PERMISSIONS] : []),
+ ...Object.values(PERMISSION_PRESETS),
+ ];
const title = {
'detail': t('account.form.title_detail'),
@@ -67,18 +88,25 @@ const EditLayer = ({
};
const createUser = useCallback(values => {
- return api.auth.addUser(toPermissionPayload(values), PAGE_ERROR_CONFIG).then(res => {
+ const payload = permissionPresetsSupported
+ ? toPermissionPayload(values)
+ : toProfilePayload(values);
+ return api.auth.addUser(payload, PAGE_ERROR_CONFIG).then(res => {
if (res.status === 200) {
message.success(t('common.msg.create_success'));
onCancel();
refresh();
return;
}
- message.error(t('common.msg.operation_failed'));
- }).catch(() => message.error(t('common.msg.operation_failed')));
- }, [onCancel, refresh, t]);
+ throw res;
+ });
+ }, [onCancel, permissionPresetsSupported, refresh, t]);
const updateUser = useCallback(values => {
- return api.auth.updateUser(data.id, toPermissionPayload(values), PAGE_ERROR_CONFIG
+ const payload = permissionPresetsSupported
+ && values.permission_preset !== PRESERVE_PERMISSIONS
+ ? toPermissionPayload(values)
+ : toProfilePayload(values);
+ return api.auth.updateUser(data.id, payload, PAGE_ERROR_CONFIG
).then(res => {
if (res.status === 200) {
message.success(t('common.msg.update_success'));
@@ -88,9 +116,9 @@ const EditLayer = ({
return;
}
- message.error(t('common.msg.operation_failed'));
- }).catch(() => message.error(t('common.msg.operation_failed')));
- }, [onCancel, refresh, data.id, t]);
+ throw res;
+ });
+ }, [onCancel, refresh, data.id, permissionPresetsSupported, t]);
const updateUserAuth = useCallback(values => {
const payload = toPermissionPayload({
@@ -107,8 +135,8 @@ const EditLayer = ({
return;
}
- message.error(t('common.msg.operation_failed'));
- }).catch(() => message.error(t('common.msg.operation_failed')));
+ throw res;
+ });
}, [data.id, onCancel, refresh, t]);
const onFinish = useCallback(async () => {
@@ -118,6 +146,7 @@ const EditLayer = ({
submitPending.current = true;
setSubmitting(true);
+ setMutationError(null);
try {
const values = await form.validateFields();
if (op === 'create') {
@@ -134,7 +163,11 @@ const EditLayer = ({
}
catch (error) {
if (!error || !error.errorFields) {
- message.error(t('common.msg.operation_failed'));
+ const detail = accountErrorMessage(
+ error, t('account.feedback.save_retry')
+ );
+ setMutationError(detail);
+ message.error(detail);
}
}
finally {
@@ -148,6 +181,7 @@ const EditLayer = ({
detailRequest.current += 1;
setDetail({});
setGraphspaceList([]);
+ setMutationError(null);
form.resetFields();
setLoading(false);
return;
@@ -156,7 +190,7 @@ const EditLayer = ({
const request = detailRequest.current + 1;
detailRequest.current = request;
setGraphspaceList([]);
- if (op !== 'detail') {
+ if (op !== 'detail' && (permissionPresetsSupported || op === 'auth')) {
api.manage.getGraphSpaceList(undefined, PAGE_ERROR_CONFIG).then(res => {
if (detailRequest.current !== request) {
return;
@@ -191,7 +225,8 @@ const EditLayer = ({
if (op !== 'detail') {
form.setFieldsValue({
...res.data,
- permission_preset: getAccountPreset(res.data),
+ permission_preset: getAccountPreset(res.data)
+ ?? PRESERVE_PERMISSIONS,
graphspaces: op === 'auth'
? (res.data?.adminSpaces ?? [])
: getPresetSpaces(res.data),
@@ -223,7 +258,7 @@ const EditLayer = ({
form.resetFields();
setLoading(false);
}
- }, [visible, data.id, form, op, t]);
+ }, [visible, data.id, form, op, permissionPresetsSupported, t]);
if (op !== 'detail' && !allowedOperations[op]) {
return null;
@@ -252,12 +287,22 @@ const EditLayer = ({
<Form.Item label={t('account.form.name')} className={style.item}>
{detail.user_nickname}
</Form.Item>
- <Form.Item label={t('account.form.permission_preset')} className={style.item}> {t(`account.permission_preset.${getAccountPreset(detail) ?? 'mixed'}`)}
+ <Form.Item
+ label={t('account.form.permission_preset')}
+ className={style.item}
+ >
+ {t(
+ `account.permission_preset.${getAccountPreset(detail) ?? 'mixed'}`
+ )}
</Form.Item>
<Form.Item label={t('account.form.remark')} className={style.item}>
{detail.user_description}
</Form.Item>
- <Form.Item label={t('account.form.graphspaces')} className={style.item}> {getPresetSpaces(detail).join(', ')}
+ <Form.Item
+ label={t('account.form.graphspaces')}
+ className={style.item}
+ >
+ {getPresetSpaces(detail).join(', ')}
</Form.Item>
<Form.Item label={t('account.col.create_time')} className={style.item}>
{detail.user_create}
@@ -277,6 +322,30 @@ const EditLayer = ({
width={600}
>
<Spin spinning={loading}>
+ {!permissionPresetsSupported && ['create', 'edit'].includes(op) && (
+ <Alert
+ type='info'
+ showIcon
+ message={t(
+ op === 'create'
+ ? 'account.feedback.presets_unavailable'
+ : 'account.feedback.preset_edit_unavailable'
+ )}
+ description={t(
+ op === 'create'
+ ? 'account.feedback.presets_unavailable_help'
+ : 'account.feedback.preset_edit_unavailable_help'
+ )}
+ />
+ )}
+ {mutationError && (
+ <Alert
+ type='error'
+ showIcon
+ message={t('account.feedback.save_failed')}
+ description={mutationError}
+ />
+ )}
<Form
labelCol={{span: 6}}
// initialValues={data}
@@ -299,29 +368,11 @@ const EditLayer = ({
<Form.Item
label={<HelpLabel t={t} labelKey='account.form.name' />}
name="user_nickname"
- rules={[rules.required(), rules.isAccountName]}
+ rules={[rules.isAccountName]}
validateFirst
>
<Input placeholder={t('account.form.name_placeholder')} />
</Form.Item>
- <Form.Item
- label={<HelpLabel t={t} labelKey='account.form.permission_preset' />}
- name="permission_preset"
- rules={[rules.required()]}
- >
- <Select
- options={Object.values(PERMISSION_PRESETS).map(value => ({
- value,
- label: t(`account.permission_preset.${value}`),
- }))}
- />
- </Form.Item>
- <Form.Item
- label={<HelpLabel t={t} labelKey='account.form.remark' />}
- name="user_description"
- >
- <Input placeholder={t('account.form.remark_placeholder')} />
- </Form.Item>
<Form.Item
label={<HelpLabel t={t} labelKey='account.form.default_password' />}
name="user_password"
@@ -334,19 +385,57 @@ const EditLayer = ({
autoComplete="new-password"
/>
</Form.Item>
+ {permissionFieldsVisible && (
+ <Form.Item
+ label={<HelpLabel t={t} labelKey='account.form.permission_preset' />}
+ name="permission_preset"
+ rules={[rules.required()]}
+ >
+ <Select
+ options={presetOptions.map(value => ({
+ value,
+ label: t(value === PRESERVE_PERMISSIONS
+ ? 'account.permission_preset.preserve_mixed'
+ : `account.permission_preset.${value}`),
+ }))}
+ />
+ </Form.Item>
+ )}
<Form.Item
- noStyle
- shouldUpdate={permissionPresetChanged}
+ label={<HelpLabel t={t} labelKey='account.form.remark' />}
+ name="user_description"
>
- {({getFieldValue}) => (getFieldValue('permission_preset') === PERMISSION_PRESETS.SUPER_ADMIN ? null : (
- <Form.Item
- label={<HelpLabel t={t} labelKey='account.form.graphspaces' />}
- name="graphspaces"
- >
- <Select options={graphspaceList} mode="multiple" />
- </Form.Item>
- ))}
+ <Input placeholder={t('account.form.remark_placeholder')} />
</Form.Item>
+ {permissionFieldsVisible && (
+ <Form.Item
+ noStyle
+ shouldUpdate={permissionPresetChanged}
+ >
+ {({getFieldValue}) => (
+ [
+ PERMISSION_PRESETS.SUPER_ADMIN,
+ PRESERVE_PERMISSIONS,
+ ].includes(
+ getFieldValue('permission_preset')
+ )
+ ? null
+ : (
+ <Form.Item
+ label={(
+ <HelpLabel
+ t={t}
+ labelKey='account.form.graphspaces'
+ />
+ )}
+ name="graphspaces"
+ >
+ <Select options={graphspaceList} mode="multiple" />
+ </Form.Item>
+ )
+ )}
+ </Form.Item>
+ )}
</>
)}
{op === 'auth' && (
diff --git a/hugegraph-hubble/hubble-fe/src/pages/Account/SpaceAccess.js b/hugegraph-hubble/hubble-fe/src/pages/Account/SpaceAccess.js
index d6eb374ee..de5a04414 100644
--- a/hugegraph-hubble/hubble-fe/src/pages/Account/SpaceAccess.js
+++ b/hugegraph-hubble/hubble-fe/src/pages/Account/SpaceAccess.js
@@ -40,6 +40,13 @@ import {PERMISSION_PRESETS} from './permissionPresets';
const PAGE_ERROR_CONFIG = {suppressBusinessErrorToast: true};
const PAGE_PARAMS = {query: '', page_no: 1, page_size: 200};
const responseRecords = response => response?.data?.records ?? [];
+const showMutationError = (error, t) => {
+ const response = error?.response ?? error;
+ const detail = response?.data?.message ?? response?.message;
+ message.error(detail
+ ? `${t('common.msg.operation_failed')} (${detail})`
+ : t('common.msg.operation_failed'));
+};
const adminRole = {
role_id: PERMISSION_PRESETS.GS_ADMIN,
permission_preset: PERMISSION_PRESETS.GS_ADMIN,
@@ -274,7 +281,7 @@ const SpaceAccess = () => {
try {
const response = await operation();
if (response?.status !== 200) {
- message.error(t('common.msg.operation_failed'));
+ showMutationError(response, t);
return;
}
message.success(t('common.msg.success'));
@@ -282,7 +289,7 @@ const SpaceAccess = () => {
refreshAll();
}
catch (error) {
- message.error(t('common.msg.operation_failed'));
+ showMutationError(error, t);
}
finally {
setSubmitting(false);
diff --git a/hugegraph-hubble/hubble-fe/src/pages/Account/account-edit-recovery.test.js b/hugegraph-hubble/hubble-fe/src/pages/Account/account-edit-recovery.test.js
index c08a3407c..4521c33c5 100644
--- a/hugegraph-hubble/hubble-fe/src/pages/Account/account-edit-recovery.test.js
+++ b/hugegraph-hubble/hubble-fe/src/pages/Account/account-edit-recovery.test.js
@@ -20,6 +20,8 @@ import {act, fireEvent, render, screen, waitFor} from '@testing-library/react';
import EditLayer from './EditLayer';
import * as api from '../../api';
+let mockAuthContext = null;
+
jest.mock('../../api', () => ({
auth: {
addUser: jest.fn(),
@@ -32,6 +34,10 @@ jest.mock('../../api', () => ({
},
}));
+jest.mock('../../auth/AuthContext', () => ({
+ useAuthContext: () => ({context: mockAuthContext}),
+}));
+
jest.mock('../../utils/rules', () => ({
isName: {},
isAccountName: {},
@@ -62,6 +68,7 @@ const props = {
beforeEach(() => {
jest.clearAllMocks();
+ mockAuthContext = null;
window.matchMedia = jest.fn().mockImplementation(query => ({
matches: false,
media: query,
@@ -75,6 +82,134 @@ beforeEach(() => {
});
});
+test('creates a non-elevated account when preset API is unavailable',
+ async () => {
+ mockAuthContext = {capabilities: ['accounts_manage']};
+ api.auth.addUser.mockResolvedValue({status: 200});
+ render(<EditLayer {...props} data={{}} op='create' />);
+ await act(async () => undefined);
+
+ expect(screen.getByRole('alert')).toHaveTextContent(
+ 'account.feedback.presets_unavailable'
+ );
+ expect(screen.queryByText('account.form.permission_preset'))
+ .not.toBeInTheDocument();
+ expect(api.manage.getGraphSpaceList).not.toHaveBeenCalled();
+
+ fireEvent.change(screen.getByPlaceholderText(
+ 'account.form.id_placeholder'
+ ), {target: {value: 'alice'}});
+ fireEvent.change(screen.getByPlaceholderText(
+ 'account.form.default_password_placeholder'
+ ), {target: {value: 'alice-password'}});
+ await act(async () => {
+ fireEvent.click(document.querySelector(
+ '.ant-modal-footer .ant-btn-primary'
+ ));
+ });
+
+ await waitFor(() => expect(api.auth.addUser).toHaveBeenCalled());
+ const payload = api.auth.addUser.mock.calls[0][0];
+ expect(payload).not.toHaveProperty('permission_preset');
+ expect(payload).not.toHaveProperty('graphspace_permissions');
+ expect(payload).not.toHaveProperty('adminSpaces');
+ expect(payload).not.toHaveProperty('is_superadmin');
+ });
+
+test('preserves permissions when editing a legacy account profile', async () => {
+ mockAuthContext = {capabilities: ['accounts_manage']};
+ api.auth.getUserInfo.mockResolvedValue({
+ status: 200,
+ data: {
+ user_name: 'alice',
+ user_nickname: 'Alice',
+ permission_preset: 'LEGACY_CUSTOM',
+ graphspace_permissions: [{
+ graphspace: 'analytics',
+ permission_preset: 'GS_READ_ONLY',
+ }],
+ },
+ });
+ api.auth.updateUser.mockResolvedValue({status: 200});
+
+ render(<EditLayer {...props} data={{id: 'alice'}} op='edit' />);
+
+ expect(await screen.findByDisplayValue('Alice')).toBeInTheDocument();
+ expect(screen.getByRole('alert')).toHaveTextContent(
+ 'account.feedback.preset_edit_unavailable'
+ );
+ expect(screen.queryByText('account.form.permission_preset'))
+ .not.toBeInTheDocument();
+ expect(api.manage.getGraphSpaceList).not.toHaveBeenCalled();
+
+ fireEvent.change(screen.getByDisplayValue('Alice'), {
+ target: {value: 'Alice Updated'},
+ });
+ await act(async () => {
+ fireEvent.click(document.querySelector(
+ '.ant-modal-footer .ant-btn-primary'
+ ));
+ });
+
+ await waitFor(() => expect(api.auth.updateUser).toHaveBeenCalledWith(
+ 'alice',
+ expect.objectContaining({
+ user_name: 'alice',
+ user_nickname: 'Alice Updated',
+ }),
+ expect.anything()
+ ));
+ await waitFor(() => expect(props.onCancel).toHaveBeenCalled());
+ const payload = api.auth.updateUser.mock.calls[0][1];
+ expect(payload).not.toHaveProperty('permission_preset');
+ expect(payload).not.toHaveProperty('graphspace_permissions');
+ expect(payload).not.toHaveProperty('adminSpaces');
+ expect(payload).not.toHaveProperty('is_superadmin');
+});
+
+test('preserves mixed GraphSpace permissions on profile edit', async () => {
+ mockAuthContext = {
+ capabilities: ['accounts_manage', 'account_permission_presets'],
+ };
+ api.auth.getUserInfo.mockResolvedValue({
+ status: 200,
+ data: {
+ user_name: 'alice',
+ user_nickname: 'Alice',
+ graphspace_permissions: [{
+ graphspace: 'read',
+ permission_preset: 'GS_READ_ONLY',
+ }, {
+ graphspace: 'write',
+ permission_preset: 'GS_READ_WRITE',
+ }],
+ },
+ });
+ api.auth.updateUser.mockResolvedValue({status: 200});
+
+ render(<EditLayer {...props} data={{id: 'alice'}} op='edit' />);
+
+ expect(await screen.findByDisplayValue('Alice')).toBeInTheDocument();
+ expect(screen.getByText('account.permission_preset.preserve_mixed'))
+ .toBeInTheDocument();
+ fireEvent.change(screen.getByDisplayValue('Alice'), {
+ target: {value: 'Alice Updated'},
+ });
+ await act(async () => {
+ fireEvent.click(document.querySelector(
+ '.ant-modal-footer .ant-btn-primary'
+ ));
+ });
+
+ await waitFor(() => expect(api.auth.updateUser).toHaveBeenCalled());
+ const payload = api.auth.updateUser.mock.calls[0][1];
+ expect(payload.user_nickname).toBe('Alice Updated');
+ expect(payload).not.toHaveProperty('permission_preset');
+ expect(payload).not.toHaveProperty('graphspace_permissions');
+ expect(payload).not.toHaveProperty('adminSpaces');
+ expect(payload).not.toHaveProperty('is_superadmin');
+});
+
test('ignores a second account mutation while the first submit is pending', async () => {
const detailRequest = deferred();
const mutation = deferred();
@@ -160,6 +295,36 @@ test('requires an explicit password when creating an account', async () => {
)).toBeRequired();
});
+test('keeps a specific account creation error visible in the form', async () => {
+ api.auth.addUser.mockResolvedValue({
+ status: 400,
+ message: 'Refresh the GraphSpace list and select an existing one.',
+ });
+ render(<EditLayer {...props} data={{}} op='create' />);
+ await act(async () => undefined);
+
+ fireEvent.change(screen.getByPlaceholderText(
+ 'account.form.id_placeholder'
+ ), {target: {value: 'alice'}});
+ fireEvent.change(screen.getByPlaceholderText(
+ 'account.form.default_password_placeholder'
+ ), {target: {value: 'secret'}});
+ fireEvent.mouseDown(screen.getAllByRole('combobox')[0]);
+ fireEvent.click(screen.getByText(
+ 'account.permission_preset.SUPER_ADMIN'
+ ));
+ fireEvent.click(document.querySelector(
+ '.ant-modal-footer .ant-btn-primary'
+ ));
+
+ const alert = await screen.findByRole('alert');
+ expect(alert).toHaveTextContent('account.feedback.save_failed');
+ expect(alert).toHaveTextContent(
+ 'Refresh the GraphSpace list and select an existing one.'
+ );
+ expect(props.onCancel).not.toHaveBeenCalled();
+});
+
test('shows the derived space administrator level in account details', async () => {
api.auth.getUserInfo.mockResolvedValue({
status: 200,
diff --git a/hugegraph-hubble/hubble-fe/src/pages/Account/accountError.js b/hugegraph-hubble/hubble-fe/src/pages/Account/accountError.js
new file mode 100644
index 000000000..c84f6562a
--- /dev/null
+++ b/hugegraph-hubble/hubble-fe/src/pages/Account/accountError.js
@@ -0,0 +1,26 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import {sanitizePublicError} from '../../utils/publicError';
+
+const accountErrorMessage = (error, fallback) => {
+ const response = error?.response ?? error;
+ const detail = response?.data?.message ?? response?.message;
+ return sanitizePublicError(detail, fallback);
+};
+
+export {accountErrorMessage};
diff --git a/hugegraph-hubble/hubble-fe/src/pages/Account/index.js b/hugegraph-hubble/hubble-fe/src/pages/Account/index.js
index 572795bc4..f1323041f 100644
--- a/hugegraph-hubble/hubble-fe/src/pages/Account/index.js
+++ b/hugegraph-hubble/hubble-fe/src/pages/Account/index.js
@@ -36,6 +36,7 @@ import * as api from '../../api';
import {useAuthContext} from '../../auth/AuthContext';
import {getAccountPreset, PERMISSION_PRESETS} from './permissionPresets';
import SpaceAccess from './SpaceAccess';
+import {accountErrorMessage} from './accountError';
const PAGE_ERROR_CONFIG = {suppressBusinessErrorToast: true};
@@ -107,8 +108,10 @@ const GlobalAccounts = () => {
setRefresh(value => !value);
return;
}
- message.error(t('common.msg.operation_failed'));
- }).catch(() => message.error(t('common.msg.operation_failed')));
+ throw res;
+ }).catch(error => message.error(accountErrorMessage(
+ error, t('account.feedback.delete_retry')
+ )));
},
});
}, [t]);
diff --git a/hugegraph-hubble/hubble-fe/src/pages/Operations/NodeDetail.js b/hugegraph-hubble/hubble-fe/src/pages/Operations/NodeDetail.js
index bfd05d91b..8269d5699 100644
--- a/hugegraph-hubble/hubble-fe/src/pages/Operations/NodeDetail.js
+++ b/hugegraph-hubble/hubble-fe/src/pages/Operations/NodeDetail.js
@@ -26,6 +26,7 @@ import {isPdEnabled} from '../../utils/config';
import {
displayNodeType,
HealthStatus,
+ nodeRoleLabel,
RefreshButton,
SourceStrip,
TierIcon,
@@ -502,23 +503,6 @@ const NodeDetail = () => {
}
return {availability: node.metrics?.[group] ? 'AVAILABLE' : 'UNSUPPORTED'};
};
- const metricScopeMessage = (group, status) => {
- if (status.availability !== 'NOT_APPLICABLE') {
- return null;
- }
- if (['drive', 'raft'].includes(group)) {
- return t('operations.metric_scope_store_only', {
- metric: t(`operations.metric_${group}`),
- nodeType: displayNodeType(node.type),
- });
- }
- if (group === 'backend' && node.type === 'PD') {
- return t('operations.metric_scope_backend', {
- nodeType: displayNodeType(node.type),
- });
- }
- return null;
- };
return (
<main className='operations-page operations-node-detail'>
<header className='operations-page-header'>
@@ -538,8 +522,11 @@ const NodeDetail = () => {
<div>
<h2>{node.name ?? t('operations.unavailable')}</h2>
<span>
- {displayNodeType(node.type)} · {node.role ?? node.version
- ?? t('operations.unavailable')}
+ {displayNodeType(node.type)} · {
+ node.role
+ ? nodeRoleLabel(node, t)
+ : (node.version ?? t('operations.unavailable'))
+ }
</span>
</div>
<HealthStatus status={node.status} size='large' />
@@ -572,7 +559,7 @@ const NodeDetail = () => {
</Descriptions.Item>
{node.role && (
<Descriptions.Item label={t('operations.role')}>
- {node.role}
+ {nodeRoleLabel(node, t)}
</Descriptions.Item>
)}
<Descriptions.Item label={t('operations.version')}>
@@ -585,8 +572,7 @@ const NodeDetail = () => {
className='operations-metric-grid'
aria-label={t('operations.node_metrics')}
>
- {(pdMode ? ['system', 'drive', 'raft', 'backend']
- : applicableMetricGroups).map(group => {
+ {applicableMetricGroups.map(group => {
const status = metricStatus(group);
return (
<MetricGroup
@@ -595,7 +581,6 @@ const NodeDetail = () => {
name={t(`operations.metric_${group}`)}
values={node.metrics?.[group]}
status={status}
- emptyMessage={metricScopeMessage(group, status)}
/>
);
})}
diff --git a/hugegraph-hubble/hubble-fe/src/pages/Operations/NodeDetail.test.js b/hugegraph-hubble/hubble-fe/src/pages/Operations/NodeDetail.test.js
index ab0f63b9c..f3796c8eb 100644
--- a/hugegraph-hubble/hubble-fe/src/pages/Operations/NodeDetail.test.js
+++ b/hugegraph-hubble/hubble-fe/src/pages/Operations/NodeDetail.test.js
@@ -353,7 +353,7 @@ test('renders each metric group from its own metric status', async () => {
}
});
-test('explains metric groups that do not apply to a PD node', async () => {
+test('hides metric groups that do not apply to a PD node', async () => {
getNode.mockResolvedValue({
...response,
node: {
@@ -376,22 +376,12 @@ test('explains metric groups that do not apply to a PD node', async () => {
const sources = screen.getByRole('region', {name: 'Source freshness'});
expect(within(sources).getByText('PD')).toBeInTheDocument();
expect(within(sources).getByText('Store')).toBeInTheDocument();
+ expect(screen.getByRole('heading', {name: 'System'}))
+ .toBeInTheDocument();
- const drive = screen.getByRole('heading', {name: 'Drive'}).closest('section');
- expect(within(drive).getByText('Not applicable')).toBeInTheDocument();
- expect(within(drive).getByText(
- 'Drive metrics are collected from Store nodes, not PD nodes.'
- )).toBeInTheDocument();
-
- const raft = screen.getByRole('heading', {name: 'Raft'}).closest('section');
- expect(within(raft).getByText(
- 'Raft metrics are collected from Store nodes, not PD nodes.'
- )).toBeInTheDocument();
-
- const backend = screen.getByRole('heading', {name: 'Backend'}).closest('section');
- expect(within(backend).getByText(
- 'Backend metrics are provided by Server and Store nodes, not PD nodes.'
- )).toBeInTheDocument();
+ expect(screen.queryByRole('heading', {name: 'Drive'})).not.toBeInTheDocument();
+ expect(screen.queryByRole('heading', {name: 'Raft'})).not.toBeInTheDocument();
+ expect(screen.queryByRole('heading', {name: 'Backend'})).not.toBeInTheDocument();
expect(screen.queryByText('Unsupported by this service version')).not.toBeInTheDocument();
});
diff --git a/hugegraph-hubble/hubble-fe/src/pages/Operations/Nodes.js b/hugegraph-hubble/hubble-fe/src/pages/Operations/Nodes.js
index b57b7a40d..692baa3b9 100644
--- a/hugegraph-hubble/hubble-fe/src/pages/Operations/Nodes.js
+++ b/hugegraph-hubble/hubble-fe/src/pages/Operations/Nodes.js
@@ -31,7 +31,7 @@ import {
RefreshButton,
TierIcon,
} from './components';
-import {formatObservedAt, hasStaleMetrics} from './topology';
+import {formatObservedAt, hasStaleMetrics, metricIssueReason} from './topology';
import {operationsReturnState} from './navigation';
import './operations.scss';
@@ -83,7 +83,7 @@ const NodeIdentityCell = ({record, returnState, unavailable, t}) => {
aria-label={leader
? t('operations.leader_role') : nodeRoleLabel(record, t)}
>
- {record.role ?? nodeRoleLabel(record, t)}
+ {nodeRoleLabel(record, t)}
</Tag>
)}
<Tooltip title={record.id}>
@@ -250,7 +250,11 @@ const Nodes = () => {
{title: t('operations.status'), dataIndex: 'status', key: 'status', width: 140,
sorter: true, sortOrder: sortOrder('status'),
render: (value, record) => (
- <HealthStatus status={value} stale={hasStaleMetrics(record)} />
+ <HealthStatus
+ status={value}
+ reason={metricIssueReason(record)}
+ stale={hasStaleMetrics(record)}
+ />
)},
{title: t('operations.last_observed'), key: 'observed_at', width: 208,
sorter: true, sortOrder: sortOrder('observed_at'), render: () => observed},
diff --git a/hugegraph-hubble/hubble-fe/src/pages/Operations/Nodes.test.js b/hugegraph-hubble/hubble-fe/src/pages/Operations/Nodes.test.js
index 86f44e105..1970c9ca7 100644
--- a/hugegraph-hubble/hubble-fe/src/pages/Operations/Nodes.test.js
+++ b/hugegraph-hubble/hubble-fe/src/pages/Operations/Nodes.test.js
@@ -240,6 +240,37 @@ test('shows stale observation metadata and exposes real detail links', async ()
.not.toHaveClass('ant-btn-loading'));
});
+test('explains unavailable Store metrics in the node list', async () => {
+ getNodes.mockResolvedValue({
+ items: [{
+ id: 'store-unavailable',
+ name: 'Store unavailable',
+ type: 'STORE',
+ status: 'UP',
+ metric_statuses: {
+ system: {
+ availability: 'UNAVAILABLE',
+ stale: false,
+ reason: 'metrics_target_untrusted',
+ },
+ },
+ }],
+ total: 1,
+ observed_at: 1000,
+ stale: false,
+ });
+
+ render(
+ <MemoryRouter future={{v7_startTransition: true, v7_relativeSplatPath: true}}>
+ <Nodes />
+ </MemoryRouter>
+ );
+
+ expect(await screen.findByRole('img', {name: /Store metrics origin is not trusted/}))
+ .toBeInTheDocument();
+ expect(screen.queryByText('Stale')).not.toBeInTheDocument();
+});
+
test('keeps the search input synchronized with URL history and clear actions', async () => {
getNodes.mockResolvedValue({items: [], total: 0, observed_at: 1000, stale: false});
@@ -376,7 +407,7 @@ test('merges role into node identity and keeps the full ID explainable and copya
expect(identity).toHaveAccessibleName(
/service-reported node name.*store-c410c1adb107-full-id/i
);
- expect(identity).toHaveTextContent('LEADER');
+ expect(identity).toHaveTextContent('Leader');
expect(within(identity).getByLabelText('Leader role')).toBeInTheDocument();
expect(screen.queryByRole('columnheader', {name: 'Role'})).not.toBeInTheDocument();
diff --git a/hugegraph-hubble/hubble-fe/src/pages/Operations/Overview.js b/hugegraph-hubble/hubble-fe/src/pages/Operations/Overview.js
index 2fbfc9e56..be24f6164 100644
--- a/hugegraph-hubble/hubble-fe/src/pages/Operations/Overview.js
+++ b/hugegraph-hubble/hubble-fe/src/pages/Operations/Overview.js
@@ -41,10 +41,13 @@ import {
SourceStrip,
} from './components';
import {
+ formatBytes,
formatMetricValue,
formatObservedAge,
formatObservedAt,
hasStaleMetrics,
+ metricIssueReason,
+ ratioPercent,
selectAttentionNodes,
} from './topology';
import {TopbarPageContextSlot} from '../../components/Topbar/PageContextSlot';
@@ -189,10 +192,9 @@ const Overview = () => {
const pdLeader = facts.pd_leader ?? nodes.find(node => (
node.type === 'PD' && node.role === 'LEADER'
))?.name;
- const capacityPercent = Number.isFinite(facts.capacity_used)
- && Number.isFinite(facts.capacity_total) && facts.capacity_total > 0
- ? Math.round(facts.capacity_used / facts.capacity_total * 100)
- : null;
+ const capacityPercent = ratioPercent(
+ facts.capacity_used_bytes, facts.capacity_total_bytes
+ );
const dashboardStatusReason = dashboard.status === 'checking'
? t('navigation_page.dashboard_checking')
: dashboard.status === 'unconfigured'
@@ -223,7 +225,11 @@ const Overview = () => {
title: t('operations.status'),
dataIndex: 'status',
render: (status, node) => (
- <HealthStatus status={status} stale={hasStaleMetrics(node)} />
+ <HealthStatus
+ status={status}
+ reason={metricIssueReason(node)}
+ stale={hasStaleMetrics(node)}
+ />
),
},
];
@@ -240,7 +246,11 @@ const Overview = () => {
title: t('operations.status'),
dataIndex: 'status',
render: (status, node) => (
- <HealthStatus status={status} stale={hasStaleMetrics(node)} />
+ <HealthStatus
+ status={status}
+ reason={metricIssueReason(node)}
+ stale={hasStaleMetrics(node)}
+ />
),
},
{
@@ -294,8 +304,7 @@ const Overview = () => {
key: 'data_size',
icon: HddOutlined,
label: t('operations.fact_data_size'),
- value: facts.data_size === null || facts.data_size === undefined
- ? null : `${facts.data_size} ${facts.data_size_unit ?? ''}`.trim(),
+ value: formatBytes(facts.data_size_bytes),
},
];
@@ -440,8 +449,8 @@ const Overview = () => {
<span>{t('operations.fact_capacity')}</span>
<strong>
{capacityPercent === null ? unavailable : (
- `${facts.capacity_used} / ${facts.capacity_total} `
- + `${facts.capacity_unit ?? ''} `
+ `${formatBytes(facts.capacity_used_bytes)} / `
+ + `${formatBytes(facts.capacity_total_bytes)} `
+ `(${capacityPercent}%)`
)}
</strong>
diff --git a/hugegraph-hubble/hubble-fe/src/pages/Operations/Overview.test.js b/hugegraph-hubble/hubble-fe/src/pages/Operations/Overview.test.js
index d3e0b74d7..29a7878e8 100644
--- a/hugegraph-hubble/hubble-fe/src/pages/Operations/Overview.test.js
+++ b/hugegraph-hubble/hubble-fe/src/pages/Operations/Overview.test.js
@@ -394,6 +394,39 @@ test('shows a bounded, failure-first list of nodes needing attention', async ()
]);
});
+test('shows the recovery reason for unavailable Store metrics without stale copy',
+ async () => {
+ getOverview.mockResolvedValue({
+ status: 'DEGRADED',
+ observed_at: 1000,
+ sources: {},
+ facts: {},
+ nodes: [{
+ id: 'store-untrusted',
+ name: 'store-untrusted',
+ type: 'STORE',
+ status: 'UP',
+ metric_statuses: {
+ system: {
+ availability: 'UNAVAILABLE',
+ stale: false,
+ reason: 'metrics_target_untrusted',
+ },
+ },
+ }],
+ });
+
+ renderOverview();
+
+ const attention = await screen.findByRole('region', {
+ name: 'Nodes needing attention',
+ });
+ expect(within(attention).getByRole('img', {
+ name: /operations\.store\.allowed_targets/,
+ })).toBeInTheDocument();
+ expect(within(attention).queryByText('Stale')).not.toBeInTheDocument();
+ });
+
test('keeps every failed source visible when the whole cluster is down', async () => {
getOverview.mockResolvedValue({
status: 'DOWN',
@@ -495,11 +528,9 @@ test('renders leader, capacity and attention facts in the visual hierarchy', asy
pd_leader: 'pd-1',
stores_up: 22,
stores: 24,
- capacity_used: 38.2,
- capacity_total: 60,
- capacity_unit: 'TB',
- data_size: 14.6,
- data_size_unit: 'TB',
+ capacity_used_bytes: 40_802_189_312,
+ capacity_total_bytes: 64_424_509_440,
+ data_size_bytes: 15_676_565_504,
},
nodes: [
{id: 'store-3', name: 'store-3', type: 'STORE', status: 'DOWN'},
@@ -515,8 +546,10 @@ test('renders leader, capacity and attention facts in the visual hierarchy', asy
expect(screen.getByText('1 Store is down')).toBeInTheDocument();
expect(screen.getByText('PD Leader')).toBeInTheDocument();
expect(screen.getByText('pd-1')).toBeInTheDocument();
+ expect(screen.getByText('14.6 GiB')).toBeInTheDocument();
+ expect(screen.getByText('38 GiB / 60 GiB (63%)')).toBeInTheDocument();
expect(screen.getByRole('progressbar', {name: 'Capacity'})).toHaveAttribute(
- 'aria-valuenow', '64'
+ 'aria-valuenow', '63'
);
const attention = screen.getByRole('region', {name: 'Nodes needing attention'});
expect(within(attention).getByRole('table')).toBeInTheDocument();
diff --git a/hugegraph-hubble/hubble-fe/src/pages/Operations/components.js b/hugegraph-hubble/hubble-fe/src/pages/Operations/components.js
index df586871a..213151785 100644
--- a/hugegraph-hubble/hubble-fe/src/pages/Operations/components.js
+++ b/hugegraph-hubble/hubble-fe/src/pages/Operations/components.js
@@ -35,6 +35,7 @@ import {
formatObservedAge,
formatObservedAt,
hasStaleMetrics,
+ metricIssueReason,
selectTierNodes,
storeLeaderCount,
} from './topology';
@@ -194,6 +195,12 @@ const RefreshButton = ({loading = false, onClick}) => {
const nodeRoleLabel = (node, t) => {
if (node?.role) {
+ if (node.role === 'LEADER') {
+ return t('operations.leader');
+ }
+ if (node.role === 'FOLLOWER') {
+ return t('operations.follower');
+ }
return node.role;
}
const leaders = storeLeaderCount(node);
@@ -215,7 +222,7 @@ const TierNode = ({node, returnState}) => {
].filter(Boolean).join(' ')}
to={`/operations/nodes/${node.id}`}
state={returnState}
- aria-label={`${node.type} ${node.name} ${node.role ?? ''} ${
+ aria-label={`${node.type} ${node.name} ${nodeRoleLabel(node, t)} ${
displayHealthStatus(node.status, t)}`}
>
<TierIcon type={node.type} />
@@ -232,7 +239,11 @@ const TierNode = ({node, returnState}) => {
? (node.version ?? '—') : nodeRoleLabel(node, t)}
</span>
</span>
- <HealthStatus status={node.status} stale={hasStaleMetrics(node)} />
+ <HealthStatus
+ status={node.status}
+ reason={metricIssueReason(node)}
+ stale={hasStaleMetrics(node)}
+ />
</Link>
);
};
diff --git a/hugegraph-hubble/hubble-fe/src/pages/Operations/components.test.js b/hugegraph-hubble/hubble-fe/src/pages/Operations/components.test.js
index 3d79cc5fe..432f8e368 100644
--- a/hugegraph-hubble/hubble-fe/src/pages/Operations/components.test.js
+++ b/hugegraph-hubble/hubble-fe/src/pages/Operations/components.test.js
@@ -113,3 +113,29 @@ test('shows stale metrics beside an up topology status', () => {
expect(within(card).getByText('UP')).toBeInTheDocument();
expect(within(card).getByText('Stale')).toBeInTheDocument();
});
+
+test('explains unavailable Store metrics on the topology card', () => {
+ render(
+ <MemoryRouter future={{v7_startTransition: true, v7_relativeSplatPath: true}}>
+ <ClusterTopology nodes={[{
+ id: 'store-unavailable',
+ name: 'store-unavailable',
+ type: 'STORE',
+ status: 'UP',
+ metric_statuses: {
+ system: {
+ availability: 'UNAVAILABLE',
+ stale: false,
+ reason: 'metrics_target_untrusted',
+ },
+ },
+ }]}
+ />
+ </MemoryRouter>
+ );
+
+ const card = screen.getByText('store-unavailable').closest('a');
+ expect(within(card).getByRole('img', {name: /Store metrics origin is not trusted/}))
+ .toBeInTheDocument();
+ expect(within(card).queryByText('Stale')).not.toBeInTheDocument();
+});
diff --git a/hugegraph-hubble/hubble-fe/src/pages/Operations/topology.js b/hugegraph-hubble/hubble-fe/src/pages/Operations/topology.js
index d89fe5ed1..5a1accd00 100644
--- a/hugegraph-hubble/hubble-fe/src/pages/Operations/topology.js
+++ b/hugegraph-hubble/hubble-fe/src/pages/Operations/topology.js
@@ -24,8 +24,15 @@ const STATUS_PRIORITY = {
};
const hasStaleMetrics = node => Object.values(node?.metric_statuses ?? {})
- .some(status => status?.stale || status?.availability === 'UNAVAILABLE'
- || status?.availability === 'MALFORMED');
+ .some(status => status?.stale === true);
+
+const hasMetricIssues = node => Object.values(node?.metric_statuses ?? {})
+ .some(status => ['UNAVAILABLE', 'MALFORMED'].includes(status?.availability));
+
+const metricIssueReason = node => Object.values(node?.metric_statuses ?? {})
+ .find(status => ['UNAVAILABLE', 'MALFORMED'].includes(
+ status?.availability
+ ))?.reason ?? null;
const storeLeaderCount = node => {
if (node?.type !== 'STORE') {
@@ -39,7 +46,8 @@ const selectAttentionNodes = (nodes = [], limit = 5) => {
if (!Array.isArray(nodes)) {
return [];
}
- return nodes.filter(node => node.status !== 'UP' || hasStaleMetrics(node))
+ return nodes.filter(node => node.status !== 'UP' || hasStaleMetrics(node)
+ || hasMetricIssues(node))
.sort((left, right) => {
const status = (STATUS_PRIORITY[left.status] ?? 4)
- (STATUS_PRIORITY[right.status] ?? 4);
@@ -82,6 +90,57 @@ const formatMetricValue = (value, unit = '', unavailable = 'Unavailable') => {
return `${value}${unit ? ` ${unit}` : ''}`;
};
+const isBigNumber = value => value !== null
+ && typeof value === 'object'
+ && typeof value.constructor?.isBigNumber === 'function'
+ && value.constructor.isBigNumber(value)
+ && typeof value.comparedTo === 'function'
+ && typeof value.dividedBy === 'function'
+ && typeof value.times === 'function'
+ && typeof value.toNumber === 'function';
+
+const formatBytes = value => {
+ const units = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB'];
+ if (value === null || value === undefined || value === '') {
+ return null;
+ }
+ const big = isBigNumber(value);
+ let size = big ? value : Number(value);
+ const invalid = big ? size.comparedTo(0) < 0
+ : !Number.isFinite(size) || size < 0;
+ if (invalid) {
+ return null;
+ }
+ let unit = 0;
+ while ((big ? size.comparedTo(1024) >= 0 : size >= 1024)
+ && unit < units.length - 1) {
+ size = big ? size.dividedBy(1024) : size / 1024;
+ unit += 1;
+ }
+ const display = big ? size.toNumber() : size;
+ return `${new Intl.NumberFormat(undefined, {maximumFractionDigits: 1})
+ .format(display)} ${units[unit]}`;
+};
+
+const ratioPercent = (used, total) => {
+ const usedBig = isBigNumber(used);
+ const totalBig = isBigNumber(total);
+ if (!usedBig && (!Number.isFinite(used) || used < 0)
+ || !totalBig && (!Number.isFinite(total) || total <= 0)) {
+ return null;
+ }
+ if (!usedBig && !totalBig) {
+ return Math.round(used / total * 100);
+ }
+ const BigNumber = (usedBig ? used : total).constructor;
+ const safeUsed = usedBig ? used : new BigNumber(String(used));
+ const safeTotal = totalBig ? total : new BigNumber(String(total));
+ if (safeUsed.comparedTo(0) < 0 || safeTotal.comparedTo(0) <= 0) {
+ return null;
+ }
+ return Math.round(safeUsed.dividedBy(safeTotal).times(100).toNumber());
+};
+
const formatObservedAt = (value, locale, unavailable) => {
const timestamp = Number(value);
if (!Number.isFinite(timestamp) || timestamp <= 0) {
@@ -119,6 +178,10 @@ export {
selectTierNodes,
selectAttentionNodes,
hasStaleMetrics,
+ hasMetricIssues,
+ metricIssueReason,
+ formatBytes,
+ ratioPercent,
formatMetricValue,
formatObservedAge,
formatObservedAt,
diff --git a/hugegraph-hubble/hubble-fe/src/pages/Operations/topology.test.js b/hugegraph-hubble/hubble-fe/src/pages/Operations/topology.test.js
index 24b496004..214586a19 100644
--- a/hugegraph-hubble/hubble-fe/src/pages/Operations/topology.test.js
+++ b/hugegraph-hubble/hubble-fe/src/pages/Operations/topology.test.js
@@ -16,9 +16,15 @@
* under the License.
*/
+import JSONbig from 'json-bigint';
import {
selectTierNodes,
selectAttentionNodes,
+ hasStaleMetrics,
+ hasMetricIssues,
+ metricIssueReason,
+ formatBytes,
+ ratioPercent,
formatMetricValue,
formatObservedAge,
formatObservedAt,
@@ -88,6 +94,38 @@ test('treats stale metric snapshots as attention even while topology is up', ()
expect(selectAttentionNodes([staleStore])).toEqual([staleStore]);
});
+test('keeps metric availability separate from snapshot freshness', () => {
+ const unavailableStore = {
+ ...node('store-1', 'STORE'),
+ metric_statuses: {
+ system: {availability: 'UNAVAILABLE', stale: false},
+ },
+ };
+
+ expect(hasStaleMetrics(unavailableStore)).toBe(false);
+ expect(hasMetricIssues(unavailableStore)).toBe(true);
+ expect(metricIssueReason(unavailableStore)).toBe(null);
+ expect(selectAttentionNodes([unavailableStore])).toEqual([unavailableStore]);
+});
+
+test('exposes an unavailable metric recovery reason without marking it stale', () => {
+ const unavailableStore = {
+ ...node('store-1', 'STORE'),
+ metric_statuses: {
+ system: {
+ availability: 'UNAVAILABLE',
+ stale: false,
+ reason: 'metrics_target_untrusted',
+ },
+ },
+ };
+
+ expect(metricIssueReason(unavailableStore)).toBe(
+ 'metrics_target_untrusted'
+ );
+ expect(hasStaleMetrics(unavailableStore)).toBe(false);
+});
+
test('never renders unknown values as zero or NaN', () => {
expect(formatMetricValue(null)).toBe('Unavailable');
expect(formatMetricValue(undefined)).toBe('Unavailable');
@@ -96,6 +134,18 @@ test('never renders unknown values as zero or NaN', () => {
expect(formatMetricValue(null, '', '不可用')).toBe('不可用');
});
+test('formats byte facts without inventing values', () => {
+ expect(formatBytes(0)).toBe('0 B');
+ expect(formatBytes(1536)).toBe('1.5 KiB');
+ expect(formatBytes(null)).toBe(null);
+ expect(formatBytes(-1)).toBe(null);
+ const facts = JSONbig.parse(
+ '{"used":9007199254740993,"total":18014398509481986}'
+ );
+ expect(formatBytes(facts.used)).toBe('8 PiB');
+ expect(ratioPercent(facts.used, facts.total)).toBe(50);
+});
+
test('safely formats malformed observed timestamps', () => {
expect(formatObservedAt('invalid', 'en-US', 'Unavailable')).toBe('Unavailable');
expect(formatObservedAt(0, 'en-US', 'Unavailable')).toBe('Unavailable');
diff --git a/hugegraph-hubble/hubble-fe/src/setupProxy.js b/hugegraph-hubble/hubble-fe/src/setupProxy.js
index 9daecff8f..5ad7bb81e 100644
--- a/hugegraph-hubble/hubble-fe/src/setupProxy.js
+++ b/hugegraph-hubble/hubble-fe/src/setupProxy.js
@@ -19,7 +19,11 @@
const {createProxyMiddleware} = require('http-proxy-middleware');
module.exports = app => {
- const target = process.env.HUBBLE_API_PROXY || 'http://127.0.0.1:8088';
+ const target = [
+ process.env.HUBBLE_API_TARGET,
+ process.env.HUBBLE_API_PROXY,
+ 'http://127.0.0.1:8088',
+ ].find(Boolean);
app.use(
'/api/v1.3',
createProxyMiddleware({
@@ -28,7 +32,7 @@ module.exports = app => {
pathRewrite: {
'^/api': '/api',
},
- // Override Origin so Java backend CORS check passes (dev server runs on different port)
+ // Override Origin so Java backend CORS check passes.
headers: {
origin: target,
},
diff --git a/hugegraph-hubble/hubble-fe/src/setupProxy.test.js b/hugegraph-hubble/hubble-fe/src/setupProxy.test.js
new file mode 100644
index 000000000..a5bf8cd72
--- /dev/null
+++ b/hugegraph-hubble/hubble-fe/src/setupProxy.test.js
@@ -0,0 +1,90 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+const {createProxyMiddleware} = require('http-proxy-middleware');
+const setupProxy = require('./setupProxy');
+
+jest.mock('http-proxy-middleware', () => ({
+ createProxyMiddleware: jest.fn(options => options),
+}));
+
+const originalTarget = process.env.HUBBLE_API_TARGET;
+const originalProxy = process.env.HUBBLE_API_PROXY;
+
+afterEach(() => {
+ if (originalTarget === undefined) {
+ delete process.env.HUBBLE_API_TARGET;
+ }
+ else {
+ process.env.HUBBLE_API_TARGET = originalTarget;
+ }
+ if (originalProxy === undefined) {
+ delete process.env.HUBBLE_API_PROXY;
+ }
+ else {
+ process.env.HUBBLE_API_PROXY = originalProxy;
+ }
+ jest.clearAllMocks();
+});
+
+test('uses the backend default port for local development', () => {
+ delete process.env.HUBBLE_API_TARGET;
+ delete process.env.HUBBLE_API_PROXY;
+ const app = {use: jest.fn()};
+
+ setupProxy(app);
+
+ expect(createProxyMiddleware).toHaveBeenCalledWith(expect.objectContaining({
+ target: 'http://127.0.0.1:8088',
+ }));
+});
+
+test('keeps the legacy proxy environment variable compatible', () => {
+ delete process.env.HUBBLE_API_TARGET;
+ process.env.HUBBLE_API_PROXY = 'http://127.0.0.1:19000';
+
+ setupProxy({use: jest.fn()});
+
+ expect(createProxyMiddleware).toHaveBeenCalledWith(expect.objectContaining({
+ target: 'http://127.0.0.1:19000',
+ headers: {origin: 'http://127.0.0.1:19000'},
+ }));
+});
+
+test('uses HUBBLE_API_TARGET as the preferred backend origin', () => {
+ process.env.HUBBLE_API_TARGET = 'http://127.0.0.1:18080';
+ delete process.env.HUBBLE_API_PROXY;
+
+ setupProxy({use: jest.fn()});
+
+ expect(createProxyMiddleware).toHaveBeenCalledWith(expect.objectContaining({
+ target: 'http://127.0.0.1:18080',
+ headers: {origin: 'http://127.0.0.1:18080'},
+ }));
+});
+
+test('prefers HUBBLE_API_TARGET over the legacy proxy setting', () => {
+ process.env.HUBBLE_API_TARGET = 'http://127.0.0.1:18080';
+ process.env.HUBBLE_API_PROXY = 'http://127.0.0.1:19000';
+
+ setupProxy({use: jest.fn()});
+
+ expect(createProxyMiddleware).toHaveBeenCalledWith(expect.objectContaining({
+ target: 'http://127.0.0.1:18080',
+ headers: {origin: 'http://127.0.0.1:18080'},
+ }));
+});