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:19 UTC
(hugegraph-toolchain) 04/24: fix(hubble): enforce GraphSpace permission presets
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 b3b2f05348bb343c1aeb9cf7ffba5b364da63b47
Author: dark <ji...@apache.org>
AuthorDate: Tue Aug 18 06:26:38 2026 +0800
fix(hubble): enforce GraphSpace permission presets
- preserve analyst and administrator preset semantics
- scope graph and template operations
- align write controls and graph listing
---
.../hugegraph/controller/BaseController.java | 11 +
.../controller/auth/GraphSpaceUserController.java | 40 +++-
.../controller/space/SchemaTemplateController.java | 6 +-
.../apache/hugegraph/entity/auth/RoleEntity.java | 15 +-
.../hugegraph/handler/CustomInterceptor.java | 9 +-
.../hugegraph/service/auth/AuthContextService.java | 72 ++++++-
.../service/auth/GraphSpaceUserService.java | 38 ++--
.../apache/hugegraph/service/auth/UserService.java | 6 +-
.../hugegraph/service/graphs/GraphsService.java | 5 +-
.../service/op/LiveOperationsCollector.java | 95 +--------
.../service/op/OperationsPayloadParser.java | 28 ---
.../hugegraph/service/space/GraphSpaceService.java | 6 +-
.../src/main/resources/i18n/messages.properties | 1 +
.../main/resources/i18n/messages_zh_CN.properties | 1 +
.../auth/AccountMutationAuthorizationTest.java | 13 +-
.../auth/GraphSpaceAuthOwnershipTest.java | 25 ++-
.../SchemaTemplateControllerSecurityTest.java | 74 +++++++
.../service/auth/AuthContextServiceTest.java | 102 ++++++++-
.../service/auth/GraphSpaceUserServiceTest.java | 80 +++++++
.../service/op/LiveOperationsCollectorTest.java | 23 +-
.../service/op/OperationsPayloadParserTest.java | 22 --
.../service/space/GraphSpaceServiceTest.java | 26 +++
.../apache/hugegraph/unit/AuthSecurityTest.java | 34 +++
.../hugegraph/unit/GraphsServiceDefaultTest.java | 29 +++
.../org/apache/hugegraph/unit/UnitTestSuite.java | 2 +
.../unit/UserServiceCompatibilityTest.java | 20 ++
.../hubble-fe/src/auth/graphspaceAccess.js | 47 +++++
.../hubble-fe/src/auth/graphspaceAccess.test.js | 43 ++++
.../i18n/resources/en-US/components/common.json | 2 +-
.../src/i18n/resources/en-US/modules/pages.json | 13 +-
.../i18n/resources/zh-CN/components/common.json | 2 +-
.../src/i18n/resources/zh-CN/modules/pages.json | 13 +-
.../src/modules/navigation/ConsoleItem/index.js | 10 +-
.../modules/navigation/ConsoleItem/index.test.js | 18 ++
.../hubble-fe/src/pages/Account/EditLayer.js | 7 +-
.../hubble-fe/src/pages/Account/SpaceAccess.js | 51 ++---
.../src/pages/Account/SpaceAccess.test.js | 71 ++++++-
.../src/pages/Account/account-recovery.test.js | 19 ++
.../hubble-fe/src/pages/Account/index.js | 36 +++-
.../src/pages/Account/permissionPresets.js | 17 +-
.../src/pages/Account/permissionPresets.test.js | 10 +
hugegraph-hubble/hubble-fe/src/pages/Graph/Card.js | 12 +-
.../hubble-fe/src/pages/Graph/Card.test.js | 22 ++
.../src/pages/Graph/default-card-actions.test.js | 73 ++++++-
.../hubble-fe/src/pages/Graph/index.js | 59 +++---
.../src/pages/Graph/inline-nickname-edit.test.js | 20 ++
.../hubble-fe/src/pages/Meta/Edge/index.js | 26 ++-
.../hubble-fe/src/pages/Meta/ImageView.js | 231 ++++++++++++---------
.../hubble-fe/src/pages/Meta/ImageView.test.js | 40 ++++
.../hubble-fe/src/pages/Meta/ListView.js | 10 +-
.../hubble-fe/src/pages/Meta/Property/index.js | 22 +-
.../hubble-fe/src/pages/Meta/Vertex/index.js | 26 ++-
.../src/pages/Meta/meta-read-only.test.js | 141 +++++++++++++
.../hubble-fe/src/pages/Schema/index.js | 53 +++--
.../src/pages/Schema/schema-list-recovery.test.js | 74 +++++++
hugegraph-hubble/hubble-fe/src/utils/rules.test.js | 31 ++-
56 files changed, 1519 insertions(+), 463 deletions(-)
diff --git a/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/controller/BaseController.java b/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/controller/BaseController.java
index faf93d6ba..82446d910 100644
--- a/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/controller/BaseController.java
+++ b/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/controller/BaseController.java
@@ -27,6 +27,7 @@ import org.apache.hugegraph.driver.factory.PDHugeClientFactory;
import org.apache.hugegraph.options.HubbleOptions;
import org.apache.hugegraph.service.auth.UserService;
import org.apache.hugegraph.service.auth.AuthModeService;
+import org.apache.hugegraph.service.auth.AuthContextService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.hugegraph.config.HugeConfig;
import org.springframework.beans.factory.annotation.Autowired;
@@ -62,6 +63,8 @@ public abstract class BaseController {
protected UserService userService;
@Autowired
protected AuthModeService authMode;
+ @Autowired
+ protected AuthContextService authContextService;
public static final String ORDER_ASC = "asc";
public static final String ORDER_DESC = "desc";
@@ -176,6 +179,14 @@ public abstract class BaseController {
return client;
}
+ protected HugeClient requireGraphSpaceWrite(String graphSpace) {
+ HugeClient client = this.authClient(null, null);
+ this.authContextService.requireGraphSpaceWrite(
+ client, this.getUser(), graphSpace);
+ client.assignGraph(graphSpace, null);
+ return client;
+ }
+
protected HugeClient requireGraphSpaceAuthorizationAdmin(
String graphSpace) {
HugeClient client = this.authClient(null, null);
diff --git a/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/controller/auth/GraphSpaceUserController.java b/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/controller/auth/GraphSpaceUserController.java
index a4a9832f0..692c385d0 100644
--- a/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/controller/auth/GraphSpaceUserController.java
+++ b/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/controller/auth/GraphSpaceUserController.java
@@ -84,7 +84,8 @@ public class GraphSpaceUserController extends AuthController {
public UserManager setGraphSpaceAdmin(
@PathVariable("graphspace") String graphSpace,
@PathVariable("id") String userId) {
- HugeClient client = this.requireGraphSpaceManager(graphSpace);
+ HugeClient client =
+ this.requireGraphSpaceAuthorizationAdmin(graphSpace);
return client.auth().addSpaceAdmin(userId, graphSpace);
}
@@ -93,22 +94,26 @@ public class GraphSpaceUserController extends AuthController {
@PathVariable("graphspace") String graphSpace,
@PathVariable("id") String userId,
@RequestBody Map<String, String> body) {
- HugeClient client = this.requireGraphSpaceManager(graphSpace);
- this.userService.applySpacePreset(client, graphSpace, userId, body.get("permission_preset"));
+ String preset = body.get("permission_preset");
+ HugeClient client = this.requirePresetManager(graphSpace, userId,
+ preset);
+ this.userService.applySpacePreset(client, graphSpace, userId, preset);
}
@DeleteMapping("spaceadmin/{id}")
public void removeGraphSpaceAdmin(
@PathVariable("graphspace") String graphSpace,
@PathVariable("id") String userId) {
- HugeClient client = this.requireGraphSpaceManager(graphSpace);
+ HugeClient client =
+ this.requireGraphSpaceAuthorizationAdmin(graphSpace);
client.auth().delSpaceAdmin(userId, graphSpace);
}
@PostMapping
public UserView create(@PathVariable("graphspace") String graphSpace,
@RequestBody UserView userView) {
- HugeClient client = this.requireGraphSpaceManager(graphSpace);
+ HugeClient client =
+ this.requireGraphSpaceAuthorizationAdmin(graphSpace);
return this.userService.createOrUpdate(client, graphSpace, userView);
}
@@ -116,7 +121,8 @@ public class GraphSpaceUserController extends AuthController {
public UserView createOrUpdate(@PathVariable("graphspace") String graphSpace,
@PathVariable("id") String userId,
@RequestBody UserView userView) {
- HugeClient client = this.requireGraphSpaceManager(graphSpace);
+ HugeClient client =
+ this.requireGraphSpaceAuthorizationAdmin(graphSpace);
userView.setId(userId);
return this.userService.createOrUpdate(client, graphSpace, userView);
}
@@ -124,7 +130,27 @@ public class GraphSpaceUserController extends AuthController {
@DeleteMapping("{id}")
public void delete(@PathVariable("graphspace") String graphSpace,
@PathVariable("id") String userId) {
- HugeClient client = this.requireGraphSpaceManager(graphSpace);
+ HugeClient client = this.requireMemberManager(graphSpace, userId);
this.userService.unauthUser(client, graphSpace, userId);
}
+
+ private HugeClient requirePresetManager(String graphSpace, String userId,
+ String preset) {
+ if ("GS_ADMIN".equals(preset)) {
+ return this.requireGraphSpaceAuthorizationAdmin(graphSpace);
+ }
+ return this.requireMemberManager(graphSpace, userId);
+ }
+
+ private HugeClient requireMemberManager(String graphSpace,
+ String userId) {
+ HugeClient client = this.requireGraphSpaceManager(graphSpace);
+ User account = client.auth().getUser(userId);
+ if (account != null &&
+ client.auth().listSpaceAdmin(graphSpace)
+ .contains(account.name())) {
+ return this.requireGraphSpaceAuthorizationAdmin(graphSpace);
+ }
+ return client;
+ }
}
diff --git a/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/controller/space/SchemaTemplateController.java b/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/controller/space/SchemaTemplateController.java
index 2e887a342..7526183b5 100644
--- a/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/controller/space/SchemaTemplateController.java
+++ b/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/controller/space/SchemaTemplateController.java
@@ -94,7 +94,7 @@ public class SchemaTemplateController extends BaseController {
@RequestBody SchemaTemplate schemaTemplate) {
E.checkArgument(isPdEnabled(),
"Schema template is not supported in standalone mode");
- HugeClient client = this.authClient(graphSpace, null);
+ HugeClient client = this.requireGraphSpaceWrite(graphSpace);
return schemaTemplateService.create(client, schemaTemplate);
}
@@ -102,7 +102,7 @@ public class SchemaTemplateController extends BaseController {
@DeleteMapping("{name}")
public void delete(@PathVariable("graphspace") String graphSpace,
@PathVariable("name") String name) {
- HugeClient client = this.authClient(graphSpace, null);
+ HugeClient client = this.requireGraphSpaceWrite(graphSpace);
schemaTemplateService.delete(client, name);
}
@@ -110,7 +110,7 @@ public class SchemaTemplateController extends BaseController {
public Object update(@PathVariable("graphspace") String graphSpace,
@PathVariable("name") String name,
@RequestBody SchemaTemplate schemaTemplate) {
- HugeClient client = this.authClient(graphSpace, null);
+ HugeClient client = this.requireGraphSpaceWrite(graphSpace);
schemaTemplate.name(name);
return schemaTemplateService.update(client, schemaTemplate);
}
diff --git a/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/entity/auth/RoleEntity.java b/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/entity/auth/RoleEntity.java
index 5da056121..89c6b4e2f 100644
--- a/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/entity/auth/RoleEntity.java
+++ b/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/entity/auth/RoleEntity.java
@@ -19,7 +19,6 @@
package org.apache.hugegraph.entity.auth;
import com.fasterxml.jackson.annotation.JsonProperty;
-import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@@ -28,7 +27,6 @@ import org.apache.hugegraph.common.Identifiable;
@Data
@NoArgsConstructor
-@AllArgsConstructor
@Builder
public class RoleEntity implements Identifiable {
@@ -37,4 +35,17 @@ public class RoleEntity implements Identifiable {
@JsonProperty("role_name")
private String name;
+
+ @JsonProperty("permission_preset")
+ private String permissionPreset;
+
+ public RoleEntity(String id, String name) {
+ this(id, name, null);
+ }
+
+ public RoleEntity(String id, String name, String permissionPreset) {
+ this.id = id;
+ this.name = name;
+ this.permissionPreset = permissionPreset;
+ }
}
diff --git a/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/handler/CustomInterceptor.java b/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/handler/CustomInterceptor.java
index 9db4a23a4..09e88c3ec 100644
--- a/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/handler/CustomInterceptor.java
+++ b/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/handler/CustomInterceptor.java
@@ -196,8 +196,13 @@ public class CustomInterceptor extends HandlerInterceptorAdapter {
graphSpace = decodeSegment(graphSpace);
}
if ("graphs".equals(parts[i]) && i < parts.length - 1) {
- graph = parts[i + 1];
- graph = decodeSegment(graph);
+ String candidate = parts[i + 1];
+ boolean collectionAction = i + 1 == parts.length - 1 &&
+ ("list".equals(candidate) ||
+ "default".equals(candidate));
+ if (!collectionAction) {
+ graph = decodeSegment(candidate);
+ }
}
}
return new String[]{graphSpace, graph};
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 e5bcb701c..8e0c19105 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
@@ -38,6 +38,7 @@ import org.springframework.stereotype.Service;
import org.apache.hugegraph.config.HugeConfig;
import org.apache.hugegraph.driver.HugeClient;
import org.apache.hugegraph.entity.auth.UserEntity;
+import org.apache.hugegraph.exception.ForbiddenException;
import org.apache.hugegraph.exception.InternalException;
import org.apache.hugegraph.options.HubbleOptions;
import org.apache.hugegraph.service.op.OperationsCapabilityService;
@@ -96,9 +97,10 @@ public class AuthContextService {
boolean pdEnabled = this.config.get(HubbleOptions.PD_ENABLED);
String mode = pdEnabled ? "PD" : "NON_PD";
String role;
+ UserEntity user = null;
List<String> adminGraphSpaces = Collections.emptyList();
if (pdEnabled) {
- UserEntity user = this.users.getpersonal(client, username);
+ user = this.users.getpersonal(client, username);
adminGraphSpaces = sorted(user.getAdminSpaces());
if (user.isSuperadmin()) {
role = SUPERADMIN;
@@ -114,12 +116,17 @@ public class AuthContextService {
boolean permissionPresets = pdEnabled &&
client.supportsDefaultRole();
+ List<String> writeGraphSpaces = pdEnabled ?
+ writeGraphSpaces(user,
+ permissionPresets) :
+ Collections.emptyList();
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);
+ adminGraphSpaces,
+ writeGraphSpaces);
String version = version(mode, username, role, capabilities,
actions, scopes);
@@ -135,6 +142,25 @@ public class AuthContextService {
return Collections.unmodifiableMap(context);
}
+ public void requireGraphSpaceWrite(HugeClient client, String username,
+ String graphSpace) {
+ if (Boolean.FALSE.equals(
+ this.config.get(HubbleOptions.AUTH_ENABLED)) ||
+ !this.config.get(HubbleOptions.PD_ENABLED) ||
+ !client.supportsDefaultRole()) {
+ return;
+ }
+
+ UserEntity user = this.users.getpersonal(client, username);
+ if (user.isSuperadmin() ||
+ contains(user.getAdminSpaces(), graphSpace) ||
+ writeGraphSpaces(user, true).contains(graphSpace)) {
+ return;
+ }
+ throw new ForbiddenException(
+ "Permission denied: write graphspace resources");
+ }
+
private static Map<String, Object> anonymousContext(boolean pdEnabled) {
Set<String> capabilities = new LinkedHashSet<>();
capabilities.add(GRAPH_RESOURCES_ACCESS);
@@ -160,6 +186,7 @@ public class AuthContextService {
Map<String, Object> scopes = new LinkedHashMap<>();
scopes.put("all_graphspaces", pdEnabled);
scopes.put("admin_graphspaces", Collections.emptyList());
+ scopes.put("write_graphspaces", Collections.emptyList());
scopes.put("graph_resources", "SERVER_ANONYMOUS");
context.put("scopes", scopes);
return Collections.unmodifiableMap(context);
@@ -218,15 +245,50 @@ public class AuthContextService {
}
private Map<String, Object> scopes(boolean pdEnabled, String role,
- List<String> adminGraphSpaces) {
+ List<String> adminGraphSpaces,
+ List<String> writeGraphSpaces) {
Map<String, Object> scopes = new LinkedHashMap<>();
scopes.put("all_graphspaces",
pdEnabled && SUPERADMIN.equals(role));
scopes.put("admin_graphspaces", adminGraphSpaces);
+ scopes.put("write_graphspaces", writeGraphSpaces);
scopes.put("graph_resources", "SERVER_AUTHORIZED");
return Collections.unmodifiableMap(scopes);
}
+ private static List<String> writeGraphSpaces(UserEntity user,
+ boolean permissionPresets) {
+ if (user.isSuperadmin()) {
+ return Collections.emptyList();
+ }
+ if (!permissionPresets) {
+ return sorted(user.getResSpaces());
+ }
+
+ Set<String> values = new TreeSet<>();
+ if (user.getGraphspacePermissions() != null) {
+ for (Map<String, String> permission :
+ user.getGraphspacePermissions()) {
+ String preset = permission.get("permission_preset");
+ if ("GS_READ_WRITE".equals(preset) ||
+ "GS_ADMIN".equals(preset)) {
+ String graphSpace = permission.get("graphspace");
+ if (graphSpace != null) {
+ values.add(graphSpace);
+ }
+ }
+ }
+ }
+ if (user.getAdminSpaces() != null) {
+ for (String graphSpace : user.getAdminSpaces()) {
+ if (graphSpace != null) {
+ values.add(graphSpace);
+ }
+ }
+ }
+ return Collections.unmodifiableList(new ArrayList<>(values));
+ }
+
private static List<String> sorted(Collection<String> values) {
if (values == null || values.isEmpty()) {
return Collections.emptyList();
@@ -235,6 +297,10 @@ public class AuthContextService {
new TreeSet<>(values)));
}
+ private static boolean contains(Collection<String> values, String value) {
+ return values != null && values.contains(value);
+ }
+
private static Set<String> set(String... values) {
return Collections.unmodifiableSet(new LinkedHashSet<>(
Arrays.asList(values)));
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 c320bdd31..d02ea3538 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
@@ -95,17 +95,17 @@ public class GraphSpaceUserService extends AuthService {
user.addRole(new RoleEntity(belong.getRoleId(),
belong.getRoleName()));
});
- if (user.getId() == null) {
- User account = client.auth().getUser(userId);
- if (account != null) {
+ User account = client.auth().getUser(userId);
+ if (account != null) {
+ if (user.getId() == null) {
user.setId(account.id().toString());
user.setName(account.name());
- if (client.supportsDefaultRole()) {
- this.addDefaultRole(client, graphSpace, user,
- account.name(), "observer");
- this.addDefaultRole(client, graphSpace, user,
- account.name(), "analyst");
- }
+ }
+ if (client.supportsDefaultRole()) {
+ this.addDefaultRole(client, graphSpace, user,
+ account.name(), "observer");
+ this.addDefaultRole(client, graphSpace, user,
+ account.name(), "analyst");
}
}
return user;
@@ -123,6 +123,7 @@ public class GraphSpaceUserService extends AuthService {
public UserView createOrUpdate(HugeClient client, String graphSpace,
UserView userView) {
+ requireLegacyRoleAssignments(client);
E.checkNotNull(userView.getId(), "User Id Not Null");
E.checkArgument(userView.getRoles() != null &&
!userView.getRoles().isEmpty(),
@@ -257,6 +258,13 @@ public class GraphSpaceUserService extends AuthService {
}
}
+ private static void requireLegacyRoleAssignments(HugeClient client) {
+ if (client.supportsDefaultRole()) {
+ throw new ParameterizedException(
+ "auth.permission-preset.required");
+ }
+ }
+
private static void requirePermissionPreset(String preset) {
if (!"GS_READ_ONLY".equals(preset) &&
!"GS_READ_WRITE".equals(preset) &&
@@ -276,12 +284,10 @@ public class GraphSpaceUserService extends AuthService {
if (!client.supportsDefaultRole()) {
return false;
}
- if (client.graphSpace().checkDefaultRole(
- graphSpace, username, "analyst")) {
- return true;
- }
return client.graphSpace().checkDefaultRole(
- graphSpace, username, "observer");
+ graphSpace, username, "analyst") ||
+ client.graphSpace().checkDefaultRole(
+ graphSpace, username, "observer");
}
private void clearDefaultRoles(HugeClient client, String graphSpace,
@@ -313,7 +319,9 @@ public class GraphSpaceUserService extends AuthService {
boolean assigned = client.graphSpace().checkDefaultRole(
graphSpace, username, role);
if (assigned) {
- user.addRole(new RoleEntity(role, role));
+ String preset = "observer".equals(role) ?
+ "GS_READ_ONLY" : "GS_READ_WRITE";
+ user.addRole(new RoleEntity(role, role, preset));
}
}
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 938cf5cd4..003647598 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
@@ -488,13 +488,11 @@ public class UserService extends AuthService {
private static boolean hasCurrentUserAccess(HugeClient client,
String graphSpace) {
- if (!client.supportsDefaultRole()) {
- return false;
- }
if (client.auth().checkDefaultRole(graphSpace, "analyst")) {
return true;
}
- return hasCurrentUserObserverRole(client, graphSpace);
+ return client.supportsDefaultRole() &&
+ hasCurrentUserObserverRole(client, graphSpace);
}
private static boolean hasCurrentUserObserverRole(HugeClient client,
diff --git a/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/service/graphs/GraphsService.java b/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/service/graphs/GraphsService.java
index d2eb78e8d..059146209 100644
--- a/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/service/graphs/GraphsService.java
+++ b/hugegraph-hubble/hubble-be/src/main/java/org/apache/hugegraph/service/graphs/GraphsService.java
@@ -234,7 +234,10 @@ public class GraphsService {
private List<Map<String, Object>> listGraphProfiles(GraphsManager graphs,
String query) {
try {
- return graphs.listProfile(query);
+ List<Map<String, Object>> profiles = graphs.listProfile(query);
+ if (!profiles.isEmpty()) {
+ return profiles;
+ }
} catch (RuntimeException e) {
if (e instanceof ServerException) {
int status = ((ServerException) e).status();
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 d0e57fd42..7b59bd8dc 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,7 +30,6 @@ 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;
@@ -79,7 +78,6 @@ 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) {
@@ -100,10 +98,7 @@ 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)),
- pdAllowedHosts(config.get(HubbleOptions.PD_PEERS),
- pdBase(config.get(HubbleOptions.SERVER_PROTOCOL),
- config.get(HubbleOptions.PD_SERVER))));
+ HubbleOptions.OPERATIONS_STORE_ALLOWED_TARGETS)));
}
LiveOperationsCollector(boolean pdEnabled, String pdBase,
@@ -113,7 +108,7 @@ public class LiveOperationsCollector implements OperationsCollector {
OperationsPayloadParser parser, Clock clock) {
this(pdEnabled, pdBase, pdUsername, pdPassword, storeUsername,
storePassword, serverIdentity, http, parser, clock, 16, 5000,
- defaultStoreAllowedTargets(), pdAllowedHosts(null, pdBase));
+ defaultStoreAllowedTargets());
}
LiveOperationsCollector(boolean pdEnabled, String pdBase,
@@ -124,8 +119,7 @@ public class LiveOperationsCollector implements OperationsCollector {
int storeThreads, int storeDeadlineMillis) {
this(pdEnabled, pdBase, pdUsername, pdPassword, storeUsername,
storePassword, serverIdentity, http, parser, clock, storeThreads,
- storeDeadlineMillis, defaultStoreAllowedTargets(),
- pdAllowedHosts(null, pdBase));
+ storeDeadlineMillis, defaultStoreAllowedTargets());
}
LiveOperationsCollector(boolean pdEnabled, String pdBase,
@@ -135,20 +129,6 @@ 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");
@@ -172,15 +152,6 @@ 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(
@@ -269,7 +240,6 @@ 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);
@@ -667,30 +637,6 @@ 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<>();
@@ -916,41 +862,6 @@ 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 c35333000..f36e946c8 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
@@ -97,34 +97,6 @@ public class OperationsPayloadParser {
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<>();
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 4a14f4eb0..10e5d6a58 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
@@ -178,13 +178,11 @@ public class GraphSpaceService {
private static boolean hasCurrentUserAccess(HugeClient client,
String graphSpace) {
- if (!client.supportsDefaultRole()) {
- return false;
- }
if (client.auth().checkDefaultRole(graphSpace, "analyst")) {
return true;
}
- return client.auth().checkDefaultRole(graphSpace, "observer");
+ return client.supportsDefaultRole() &&
+ client.auth().checkDefaultRole(graphSpace, "observer");
}
public List<Map<String, Object>> queryAnonymousGs(HugeClient client,
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 365c5c546..8b9cfa5e7 100644
--- a/hugegraph-hubble/hubble-be/src/main/resources/i18n/messages.properties
+++ b/hugegraph-hubble/hubble-be/src/main/resources/i18n/messages.properties
@@ -32,6 +32,7 @@ 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.required=Custom GraphSpace role assignments are disabled on this Server. Use one of the permission presets shown in Hubble.
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
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 3de65f0b0..7b92c919a 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
@@ -32,6 +32,7 @@ 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.required=当前 Server 已禁用 GraphSpace 自定义角色分配。请使用 Hubble 提供的权限预设。
auth.permission-preset.graphspace-not-found=GraphSpace“{0}”不可用。请刷新 GraphSpace 列表后选择一个现有空间。
auth.permission-preset.invalid=不支持权限预设“{0}”。请选择账号表单中提供的预设。
common.name-time-order.conflict=参数 name_order 和 time_order 不能同时设置
diff --git a/hugegraph-hubble/hubble-be/src/test/java/org/apache/hugegraph/controller/auth/AccountMutationAuthorizationTest.java b/hugegraph-hubble/hubble-be/src/test/java/org/apache/hugegraph/controller/auth/AccountMutationAuthorizationTest.java
index 2225fcfdb..3eabedb0a 100644
--- a/hugegraph-hubble/hubble-be/src/test/java/org/apache/hugegraph/controller/auth/AccountMutationAuthorizationTest.java
+++ b/hugegraph-hubble/hubble-be/src/test/java/org/apache/hugegraph/controller/auth/AccountMutationAuthorizationTest.java
@@ -491,12 +491,12 @@ public class AccountMutationAuthorizationTest {
() -> controller.create("SPACE", member));
org.junit.Assert.assertTrue(failure.getMessage()
- .contains("graphspace members"));
+ .contains("authorization objects"));
Mockito.verifyZeroInteractions(memberService);
}
@Test
- public void testCurrentSpaceAdminCanAssignGraphSpaceMembership() {
+ public void testCurrentSpaceAdminCannotUseLegacyRoleMembershipRoute() {
TestGraphSpaceUserController controller =
new TestGraphSpaceUserController(this.client, "manager");
GraphSpaceUserService memberService =
@@ -510,12 +510,11 @@ public class AccountMutationAuthorizationTest {
.thenReturn(true);
UserView member = new UserView("bob", "bob",
Collections.emptyList());
- Mockito.when(memberService.createOrUpdate(this.client, "SPACE",
- member))
- .thenReturn(member);
- org.junit.Assert.assertSame(member,
- controller.create("SPACE", member));
+ assertForbidden(() -> controller.create("SPACE", member));
+ assertForbidden(() -> controller.createOrUpdate("SPACE", "bob",
+ member));
+ Mockito.verifyZeroInteractions(memberService);
}
@Test
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 067263965..bf8a7d083 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
@@ -44,6 +44,7 @@ import org.apache.hugegraph.entity.auth.RoleEntity;
import org.apache.hugegraph.entity.auth.UserEntity;
import org.apache.hugegraph.entity.auth.UserView;
import org.apache.hugegraph.exception.ForbiddenException;
+import org.apache.hugegraph.handler.ExceptionAdvisor;
import org.apache.hugegraph.service.auth.AccessService;
import org.apache.hugegraph.service.auth.BelongService;
import org.apache.hugegraph.service.auth.GraphSpaceUserService;
@@ -58,7 +59,7 @@ import org.apache.hugegraph.structure.auth.Role;
import org.apache.hugegraph.structure.auth.Target;
import org.apache.hugegraph.structure.auth.User;
-import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@@ -509,6 +510,7 @@ public class GraphSpaceAuthOwnershipTest {
@Test
public void testGraphSpaceUserRoleUpdatePreflightsAllRoles() {
+ Mockito.when(this.client.supportsDefaultRole()).thenReturn(false);
List<Group> groups = this.createScopedGroups("SPACE_A", "SPACE_B");
Mockito.when(this.auth.getGraphSpaceGroup("local-role"))
.thenReturn(groups.get(0));
@@ -532,6 +534,7 @@ public class GraphSpaceAuthOwnershipTest {
@Test
public void testGraphSpaceUserCreationAddsPdMemberBeforeBelong() {
+ Mockito.when(this.client.supportsDefaultRole()).thenReturn(false);
Group group = this.createScopedGroups("SPACE_A").get(0);
Mockito.when(this.auth.getGraphSpaceGroup("local-role"))
.thenReturn(group);
@@ -560,7 +563,7 @@ public class GraphSpaceAuthOwnershipTest {
}
@Test
- public void testSpaceAdminAssignmentUsesPostOnly() throws Exception {
+ public void testOnlySuperAdminCanMutateSpaceAdmins() throws Exception {
UserService authorization = Mockito.mock(UserService.class);
Mockito.when(authorization.isAssignSpaceAdmin(this.client, "SPACE"))
.thenReturn(true);
@@ -568,19 +571,21 @@ public class GraphSpaceAuthOwnershipTest {
new TestGraphSpaceUserController(this.client);
setBaseUserService(controller, authorization);
MockMvc mvc = MockMvcBuilders.standaloneSetup(controller)
+ .setControllerAdvice(
+ new ExceptionAdvisor())
.build();
- mvc.perform(get("/api/v1.3/graphspaces/SPACE/auth/users/" +
- "spaceadmin/user-id"))
- .andExpect(status().isMethodNotAllowed());
- mvc.perform(put("/api/v1.3/graphspaces/SPACE/auth/users/" +
- "spaceadmin/user-id")
- .contentType(MediaType.APPLICATION_JSON))
- .andExpect(status().isMethodNotAllowed());
mvc.perform(post("/api/v1.3/graphspaces/SPACE/auth/users/" +
"spaceadmin/user-id")
.contentType(MediaType.APPLICATION_JSON))
- .andExpect(status().isOk());
+ .andExpect(status().isForbidden());
+ mvc.perform(delete("/api/v1.3/graphspaces/SPACE/auth/users/" +
+ "spaceadmin/user-id"))
+ .andExpect(status().isForbidden());
+ mvc.perform(put("/api/v1.3/graphspaces/SPACE/auth/users/user-id/preset")
+ .contentType(MediaType.APPLICATION_JSON)
+ .content("{\"permission_preset\":\"GS_ADMIN\"}"))
+ .andExpect(status().isForbidden());
}
private static Target target(String id, String graphSpace) {
diff --git a/hugegraph-hubble/hubble-be/src/test/java/org/apache/hugegraph/controller/space/SchemaTemplateControllerSecurityTest.java b/hugegraph-hubble/hubble-be/src/test/java/org/apache/hugegraph/controller/space/SchemaTemplateControllerSecurityTest.java
new file mode 100644
index 000000000..c0151aca4
--- /dev/null
+++ b/hugegraph-hubble/hubble-be/src/test/java/org/apache/hugegraph/controller/space/SchemaTemplateControllerSecurityTest.java
@@ -0,0 +1,74 @@
+/*
+ *
+ * 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.controller.space;
+
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import org.apache.hugegraph.config.HugeConfig;
+import org.apache.hugegraph.driver.HugeClient;
+import org.apache.hugegraph.exception.ForbiddenException;
+import org.apache.hugegraph.options.HubbleOptions;
+import org.apache.hugegraph.structure.space.SchemaTemplate;
+import org.apache.hugegraph.testutil.Assert;
+
+public class SchemaTemplateControllerSecurityTest {
+
+ @Test
+ public void testCreateRequiresGraphSpaceWrite() {
+ TestController controller = controller();
+
+ Assert.assertThrows(ForbiddenException.class, () ->
+ controller.create("space", Mockito.mock(SchemaTemplate.class)));
+ }
+
+ @Test
+ public void testUpdateRequiresGraphSpaceWrite() {
+ TestController controller = controller();
+
+ Assert.assertThrows(ForbiddenException.class, () ->
+ controller.update("space", "template",
+ Mockito.mock(SchemaTemplate.class)));
+ }
+
+ @Test
+ public void testDeleteRequiresGraphSpaceWrite() {
+ TestController controller = controller();
+
+ Assert.assertThrows(ForbiddenException.class, () ->
+ controller.delete("space", "template"));
+ }
+
+ private static TestController controller() {
+ TestController controller = new TestController();
+ HugeConfig config = Mockito.mock(HugeConfig.class);
+ Mockito.when(config.get(HubbleOptions.PD_ENABLED)).thenReturn(true);
+ controller.config = config;
+ return controller;
+ }
+
+ private static class TestController extends SchemaTemplateController {
+
+ @Override
+ protected HugeClient requireGraphSpaceWrite(String graphSpace) {
+ throw new ForbiddenException(
+ "Permission denied: write graphspace resources");
+ }
+ }
+}
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 1ddda794f..3eb8eecc6 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
@@ -18,8 +18,10 @@
package org.apache.hugegraph.service.auth;
+import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
+import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -32,6 +34,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.hugegraph.config.HugeConfig;
import org.apache.hugegraph.driver.HugeClient;
import org.apache.hugegraph.entity.auth.UserEntity;
+import org.apache.hugegraph.exception.ForbiddenException;
import org.apache.hugegraph.options.HubbleOptions;
import org.apache.hugegraph.testutil.Assert;
@@ -96,6 +99,8 @@ public class AuthContextServiceTest {
Assert.assertFalse(capabilities(context).contains("graphspace_authorizations_manage"));
Assert.assertEquals(Arrays.asList("space-a", "space-b"),
scopes(context).get("admin_graphspaces"));
+ Assert.assertEquals(Arrays.asList("space-a", "space-b"),
+ scopes(context).get("write_graphspaces"));
Assert.assertFalse((Boolean) scopes(context).get("all_graphspaces"));
}
@@ -119,8 +124,14 @@ public class AuthContextServiceTest {
@Test
public void testPdUserOnlyGetsSelfActions() {
Fixture fixture = new Fixture(true);
+ UserEntity user = user(false, Collections.emptyList());
+ user.setGraphspacePermissions(Arrays.asList(
+ permission("space-c", "GS_READ_ONLY"),
+ permission("space-b", "GS_READ_WRITE"),
+ permission("space-a", "GS_READ_WRITE")));
+ Mockito.when(fixture.client.supportsDefaultRole()).thenReturn(true);
Mockito.when(fixture.users.getpersonal(fixture.client, "alice"))
- .thenReturn(user(false, Collections.emptyList()));
+ .thenReturn(user);
Map<String, Object> context = fixture.service.context(fixture.client,
"alice");
@@ -128,12 +139,90 @@ public class AuthContextServiceTest {
Assert.assertEquals("USER", context.get("role"));
Assert.assertEquals(Set.of("account_self_manage",
"graph_resources_access",
- "graphspaces_read"),
+ "graphspaces_read",
+ "account_permission_presets"),
capabilities(context));
Assert.assertEquals(Set.of("read", "update", "change_password"),
actions(context, "account"));
Assert.assertTrue(actions(context, "accounts").isEmpty());
Assert.assertTrue(actions(context, "members").isEmpty());
+ Assert.assertEquals(Arrays.asList("space-a", "space-b"),
+ scopes(context).get("write_graphspaces"));
+ }
+
+ @Test
+ public void testPdReadOnlyUserGetsNoWriteScope() {
+ Fixture fixture = new Fixture(true);
+ UserEntity user = user(false, Collections.emptyList());
+ user.setGraphspacePermissions(Collections.singletonList(
+ permission("space-a", "GS_READ_ONLY")));
+ Mockito.when(fixture.client.supportsDefaultRole()).thenReturn(true);
+ Mockito.when(fixture.users.getpersonal(fixture.client, "alice"))
+ .thenReturn(user);
+
+ Map<String, Object> context = fixture.service.context(fixture.client,
+ "alice");
+
+ Assert.assertEquals(Collections.emptyList(),
+ scopes(context).get("write_graphspaces"));
+ }
+
+ @Test
+ public void testPdReadOnlyUserCannotWriteGraphSpaceResources() {
+ Fixture fixture = new Fixture(true);
+ UserEntity user = user(false, Collections.emptyList());
+ user.setGraphspacePermissions(Collections.singletonList(
+ permission("space-a", "GS_READ_ONLY")));
+ Mockito.when(fixture.client.supportsDefaultRole()).thenReturn(true);
+ Mockito.when(fixture.users.getpersonal(fixture.client, "alice"))
+ .thenReturn(user);
+
+ Assert.assertThrows(
+ ForbiddenException.class,
+ () -> fixture.service.requireGraphSpaceWrite(
+ fixture.client, "alice", "space-a"));
+ }
+
+ @Test
+ public void testPdReadWriteUserCanWriteGraphSpaceResources() {
+ Fixture fixture = new Fixture(true);
+ UserEntity user = user(false, Collections.emptyList());
+ user.setGraphspacePermissions(Collections.singletonList(
+ permission("space-a", "GS_READ_WRITE")));
+ Mockito.when(fixture.client.supportsDefaultRole()).thenReturn(true);
+ Mockito.when(fixture.users.getpersonal(fixture.client, "alice"))
+ .thenReturn(user);
+
+ fixture.service.requireGraphSpaceWrite(fixture.client, "alice",
+ "space-a");
+ }
+
+ @Test
+ public void testLegacyPdDefersGraphSpaceWritesToServerAuthorization() {
+ Fixture fixture = new Fixture(true);
+ Mockito.when(fixture.client.supportsDefaultRole()).thenReturn(false);
+
+ fixture.service.requireGraphSpaceWrite(fixture.client, "alice",
+ "space-a");
+
+ Mockito.verify(fixture.users, Mockito.never())
+ .getpersonal(Mockito.any(), Mockito.anyString());
+ }
+
+ @Test
+ public void testLegacyPdAnalystKeepsWriteScope() {
+ Fixture fixture = new Fixture(true);
+ UserEntity user = user(false, Collections.emptyList());
+ user.setResSpaces(Arrays.asList("space-b", "space-a"));
+ Mockito.when(fixture.client.supportsDefaultRole()).thenReturn(false);
+ Mockito.when(fixture.users.getpersonal(fixture.client, "alice"))
+ .thenReturn(user);
+
+ Map<String, Object> context = fixture.service.context(fixture.client,
+ "alice");
+
+ Assert.assertEquals(Arrays.asList("space-a", "space-b"),
+ scopes(context).get("write_graphspaces"));
}
@Test
@@ -211,9 +300,18 @@ public class AuthContextServiceTest {
user.setName("alice");
user.setSuperadmin(superadmin);
user.setAdminSpaces(adminSpaces);
+ user.setResSpaces(new ArrayList<>());
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;
+ }
+
@SuppressWarnings("unchecked")
private static Set<String> capabilities(Map<String, Object> context) {
return (Set<String>) context.get("capabilities");
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
index 97b20192b..acace9f1d 100644
--- 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
@@ -30,6 +30,8 @@ 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.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.testutil.Assert;
@@ -73,6 +75,84 @@ public class GraphSpaceUserServiceTest {
error.getMessage());
}
+ @Test
+ public void testListUsersMarksOnlyServerDefaultRolesAsPresets() {
+ User user = user("u-1", "alice");
+ Mockito.when(this.belongService.list(
+ this.client, "team", null, null))
+ .thenReturn(Collections.emptyList());
+ Mockito.when(this.auth.listSpaceMember("team"))
+ .thenReturn(Collections.singletonList("alice"));
+ Mockito.when(this.client.findUserByName("alice")).thenReturn(user);
+ Mockito.when(this.graphSpace.checkDefaultRole(
+ "team", "alice", "observer"))
+ .thenReturn(true);
+
+ UserView view = this.service.listUsers(this.client, "team").get(0);
+
+ Assert.assertEquals(1, view.getRoles().size());
+ Assert.assertEquals("observer", view.getRoles().get(0).getName());
+ Assert.assertEquals("GS_READ_ONLY",
+ view.getRoles().get(0).getPermissionPreset());
+ }
+
+ @Test
+ public void testLegacyAccessDoesNotCallNewDefaultRoleApi() {
+ Mockito.when(this.client.supportsDefaultRole()).thenReturn(false);
+
+ Assert.assertFalse(this.service.hasGraphSpaceAccess(
+ this.client, "team", "alice"));
+ Mockito.verifyZeroInteractions(this.graphSpace);
+ Mockito.verifyZeroInteractions(this.auth);
+ }
+
+ @Test
+ public void testModernRolePayloadRequiresPresetApi() {
+ UserView user = new UserView(
+ "u-1", "alice",
+ Collections.singletonList(new RoleEntity("custom", "custom")));
+
+ ParameterizedException error = null;
+ try {
+ this.service.createOrUpdate(this.client, "team", user);
+ } catch (ParameterizedException e) {
+ error = e;
+ }
+
+ Assert.assertNotNull(error);
+ Assert.assertEquals("auth.permission-preset.required",
+ error.getMessage());
+ Mockito.verifyZeroInteractions(this.belongService);
+ Mockito.verifyZeroInteractions(this.auth);
+ }
+
+ @Test
+ public void testGetUserMergesCustomAndExplicitDefaultRoles() {
+ User user = user("u-1", "alice");
+ BelongEntity custom = BelongEntity.builder()
+ .userId("u-1")
+ .userName("alice")
+ .roleId("custom-id")
+ .roleName("analyst")
+ .build();
+ Mockito.when(this.belongService.list(
+ this.client, "team", null, "u-1"))
+ .thenReturn(Collections.singletonList(custom));
+ Mockito.when(this.auth.getUser("u-1")).thenReturn(user);
+ Mockito.when(this.graphSpace.checkDefaultRole(
+ "team", "alice", "observer"))
+ .thenReturn(true);
+
+ UserView view = this.service.getUser(this.client, "team", "u-1");
+
+ Assert.assertEquals(2, view.getRoles().size());
+ RoleEntity customRole = view.getRoles().get(0);
+ RoleEntity defaultRole = view.getRoles().get(1);
+ Assert.assertNull(customRole.getPermissionPreset());
+ Assert.assertEquals("GS_READ_ONLY",
+ defaultRole.getPermissionPreset());
+ }
+
@Test
public void testApplyReadOnlyPresetAndRemoveUnrequestedSpace() {
User user = user("u-1", "alice");
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 f651b0f33..bb5d4bf7b 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
@@ -196,23 +196,9 @@ public class LiveOperationsCollectorTest {
}
@Test
- public void testUsesConfiguredPdLeaderForAuthoritativeClusterState() {
+ public void testUsesOnlyConfiguredPdServiceForClusterState() {
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"));
+ LiveOperationsCollector collector = leaderAwareCollector(http);
Snapshot snapshot = collector.collect(serverClient(), false);
@@ -744,13 +730,12 @@ public class LiveOperationsCollectorTest {
}
private static LiveOperationsCollector leaderAwareCollector(
- LeaderAwareHttpClient http, Set<String> pdAllowedHosts) {
+ LeaderAwareHttpClient http) {
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);
+ 4, 1000, Collections.singleton("http://127.0.0.1:8520"));
}
private static HugeClient serverClient() {
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 f9216da42..805de2106 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
@@ -125,28 +125,6 @@ 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 b64567571..4a05ea346 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
@@ -150,6 +150,32 @@ public class GraphSpaceServiceTest {
Mockito.anyString());
}
+ @Test
+ public void testLegacyAnalystGraphSpaceRemainsVisible() {
+ GraphSpaceManager manager = Mockito.mock(GraphSpaceManager.class);
+ AuthManager auth = Mockito.mock(AuthManager.class);
+ GraphSpace space = graphSpace("legacy", true, "20260712");
+ Mockito.when(this.client.graphSpace()).thenReturn(manager);
+ Mockito.when(this.client.auth()).thenReturn(auth);
+ Mockito.when(this.client.supportsDefaultRole()).thenReturn(false);
+ Mockito.when(manager.listGraphSpace())
+ .thenReturn(java.util.Collections.singletonList("legacy"));
+ Mockito.when(manager.getGraphSpace("legacy")).thenReturn(space);
+ Mockito.when(auth.checkDefaultRole("legacy", "analyst"))
+ .thenReturn(true);
+ Mockito.when(this.graphsService.listGraphNames(this.client, "legacy",
+ ""))
+ .thenReturn(java.util.Collections.emptySet());
+
+ List<Map<String, Object>> response =
+ this.service.queryAccessibleGs(this.client, "", "");
+
+ Assert.assertEquals(1, response.size());
+ Assert.assertEquals("legacy", response.get(0).get("name"));
+ Mockito.verify(auth, Mockito.never())
+ .checkDefaultRole("legacy", "observer");
+ }
+
@Test
public void testAnonymousGraphSpacesApplyQueryAndTimeFilters() {
GraphSpaceManager manager = Mockito.mock(GraphSpaceManager.class);
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 44916017a..3c4e9b065 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
@@ -373,6 +373,40 @@ public class AuthSecurityTest {
Assert.assertEquals("token", interceptor.token);
}
+ @Test
+ public void testCustomInterceptorKeepsGraphCollectionActionsUnscoped()
+ throws Exception {
+ TestCustomInterceptor interceptor = new TestCustomInterceptor();
+
+ for (String action : new String[]{"list", "default"}) {
+ MockHttpServletRequest request = new MockHttpServletRequest(
+ "GET", "/api/v1.3/graphspaces/space1/graphs/" + action);
+ request.getSession().setAttribute(Constant.TOKEN_KEY, "token");
+ request.getSession().setAttribute(Constant.USERNAME_KEY, "user");
+
+ Assert.assertTrue(interceptor.preHandle(
+ request, new MockHttpServletResponse(), null));
+ Assert.assertEquals("space1", interceptor.graphSpace);
+ Assert.assertNull(interceptor.graph);
+ }
+ Assert.assertEquals(2, interceptor.authClients);
+ }
+
+ @Test
+ public void testCustomInterceptorAllowsGraphNamedLikeCollectionAction()
+ throws Exception {
+ TestCustomInterceptor interceptor = new TestCustomInterceptor();
+ MockHttpServletRequest request = new MockHttpServletRequest(
+ "GET", "/api/v1.3/graphspaces/space1/graphs/list/schema");
+ request.getSession().setAttribute(Constant.TOKEN_KEY, "token");
+ request.getSession().setAttribute(Constant.USERNAME_KEY, "user");
+
+ Assert.assertTrue(interceptor.preHandle(
+ request, new MockHttpServletResponse(), null));
+ Assert.assertEquals("space1", interceptor.graphSpace);
+ Assert.assertEquals("list", interceptor.graph);
+ }
+
@Test
public void testAnonymousClientUsesGraphSpaceScope() throws Exception {
TestCustomInterceptor interceptor = new TestCustomInterceptor();
diff --git a/hugegraph-hubble/hubble-be/src/test/java/org/apache/hugegraph/unit/GraphsServiceDefaultTest.java b/hugegraph-hubble/hubble-be/src/test/java/org/apache/hugegraph/unit/GraphsServiceDefaultTest.java
index 7cd14011a..e824dff54 100644
--- a/hugegraph-hubble/hubble-be/src/test/java/org/apache/hugegraph/unit/GraphsServiceDefaultTest.java
+++ b/hugegraph-hubble/hubble-be/src/test/java/org/apache/hugegraph/unit/GraphsServiceDefaultTest.java
@@ -401,6 +401,35 @@ public class GraphsServiceDefaultTest {
Mockito.verify(this.graphs, Mockito.never()).getGraph("other");
}
+ @Test
+ public void testGraphProfilesFallBackWhenProfileListIsEmpty() {
+ Mockito.when(this.graphs.listProfile(""))
+ .thenReturn(Collections.emptyList());
+ Mockito.when(this.graphs.listGraph())
+ .thenReturn(Collections.singletonList("hugegraph"));
+ Mockito.when(this.graphs.getGraph("hugegraph"))
+ .thenReturn(Collections.singletonMap("backend", "hstore"));
+ Mockito.when(this.client.assignGraph("DEFAULT", "hugegraph"))
+ .thenReturn(this.client);
+ GraphManager graph = Mockito.mock(GraphManager.class);
+ Mockito.when(this.client.graph()).thenReturn(graph);
+ GraphMetricsAPI.ElementCount snapshot = new GraphMetricsAPI.ElementCount();
+ snapshot.setVertices(0L);
+ snapshot.setEdges(0L);
+ Mockito.when(graph.getEVCount(Mockito.anyString())).thenReturn(snapshot);
+
+ List<Map<String, Object>> result =
+ this.service.sortedGraphsProfile(this.client, "DEFAULT", "", "",
+ false,
+ Collections.emptyMap());
+
+ Assert.assertEquals(1, result.size());
+ Assert.assertEquals("hugegraph", result.get(0).get("name"));
+ Assert.assertEquals("hstore", result.get(0).get("backend"));
+ Mockito.verify(this.graphs).listGraph();
+ Mockito.verify(this.graphs).getGraph("hugegraph");
+ }
+
@Test
public void testGraphProfilesDoNotMaskForbiddenResponse() {
ServerException forbidden = new ServerException("forbidden");
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 953ec23bc..f2aca19e4 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.controller.space.SchemaTemplateControllerSecurityTest;
import org.apache.hugegraph.config.HubbleConfigEnvironmentTest;
import org.apache.hugegraph.handler.ResponseAdvisorStatusTest;
import org.apache.hugegraph.service.load.IngestTransactionIntegrationTest;
@@ -71,6 +72,7 @@ import org.junit.runners.Suite;
LegacyFacadeRemovalTest.class,
MessageSourceHandlerTest.class,
SchemaControllerSecurityTest.class,
+ SchemaTemplateControllerSecurityTest.class,
GroovySchemaCompatibilityTest.class,
JobManagerServiceTest.class,
K8sTokenEndpointSecurityTest.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 c4b086468..2e60a2260 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
@@ -201,6 +201,26 @@ public class UserServiceCompatibilityTest {
Assert.assertEquals(1, result.getGraphspacePermissions().size());
}
+ @Test
+ public void testLegacyAnalystKeepsGraphSpaceAccess() {
+ Mockito.when(this.config.get(HubbleOptions.PD_ENABLED)).thenReturn(true);
+ Mockito.when(this.client.supportsDefaultRole()).thenReturn(false);
+ Mockito.when(this.client.findUserByName("user"))
+ .thenReturn(user("user"));
+ Mockito.when(this.graphSpace.listGraphSpace())
+ .thenReturn(Collections.singletonList("SPACE"));
+ Mockito.when(this.auth.checkDefaultRole("SPACE", "analyst"))
+ .thenReturn(true);
+
+ UserEntity result = this.service.getpersonal(this.client, "user");
+
+ Assert.assertEquals(Collections.singletonList("SPACE"),
+ result.getResSpaces());
+ Assert.assertEquals("LEGACY_CUSTOM", result.getPermissionPreset());
+ Mockito.verify(this.auth, Mockito.never())
+ .checkDefaultRole("SPACE", "observer");
+ }
+
@Test
public void testLegacyProfileUpdatePreservesPermissionAssignments() {
Mockito.when(this.config.get(HubbleOptions.PD_ENABLED)).thenReturn(true);
diff --git a/hugegraph-hubble/hubble-fe/src/auth/graphspaceAccess.js b/hugegraph-hubble/hubble-fe/src/auth/graphspaceAccess.js
new file mode 100644
index 000000000..deadbf473
--- /dev/null
+++ b/hugegraph-hubble/hubble-fe/src/auth/graphspaceAccess.js
@@ -0,0 +1,47 @@
+/*
+ *
+ * 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 {useAuthContext} from './AuthContext';
+import {isPdEnabled} from '../utils/config';
+
+const includes = (values, target) => Array.isArray(values)
+ && values.includes(target);
+
+const resolveGraphspaceAccess = (context, graphspace, pdEnabled) => {
+ if (!context) {
+ return {canManage: false, canWrite: false};
+ }
+
+ const scopes = context.scopes ?? {};
+ const anonymousStandalone = context.mode === 'NON_AUTH' && !pdEnabled;
+ const canManage = anonymousStandalone
+ || context.role === 'SUPERADMIN'
+ || scopes.all_graphspaces === true
+ || includes(scopes.admin_graphspaces, graphspace);
+ const canWrite = canManage
+ || context.mode === 'NON_PD'
+ || includes(scopes.write_graphspaces, graphspace);
+ return {canManage, canWrite};
+};
+
+const useGraphspaceAccess = graphspace => {
+ const {context} = useAuthContext();
+ return resolveGraphspaceAccess(context, graphspace, isPdEnabled());
+};
+
+export {resolveGraphspaceAccess, useGraphspaceAccess};
diff --git a/hugegraph-hubble/hubble-fe/src/auth/graphspaceAccess.test.js b/hugegraph-hubble/hubble-fe/src/auth/graphspaceAccess.test.js
new file mode 100644
index 000000000..bf2cff573
--- /dev/null
+++ b/hugegraph-hubble/hubble-fe/src/auth/graphspaceAccess.test.js
@@ -0,0 +1,43 @@
+/*
+ *
+ * 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 {resolveGraphspaceAccess} from './graphspaceAccess';
+
+test.each([
+ [null, true, false, false],
+ [{mode: 'PD', role: 'USER', scopes: {}}, true, false, false],
+ [{
+ mode: 'PD',
+ role: 'USER',
+ scopes: {write_graphspaces: ['space']},
+ }, true, false, true],
+ [{
+ mode: 'PD',
+ role: 'SPACEADMIN',
+ scopes: {admin_graphspaces: ['space']},
+ }, true, true, true],
+ [{mode: 'NON_PD', role: 'USER', scopes: {}}, false, false, true],
+ [{mode: 'NON_PD', role: 'SUPERADMIN', scopes: {}}, false, true, true],
+ [{mode: 'NON_AUTH', role: 'ANONYMOUS', scopes: {}}, false, true, true],
+])(
+ 'resolves graphspace access for %#',
+ (context, pdEnabled, canManage, canWrite) => {
+ expect(resolveGraphspaceAccess(context, 'space', pdEnabled))
+ .toEqual({canManage, canWrite});
+ }
+);
diff --git a/hugegraph-hubble/hubble-fe/src/i18n/resources/en-US/components/common.json b/hugegraph-hubble/hubble-fe/src/i18n/resources/en-US/components/common.json
index fa17a2657..8a1b8dd91 100644
--- a/hugegraph-hubble/hubble-fe/src/i18n/resources/en-US/components/common.json
+++ b/hugegraph-hubble/hubble-fe/src/i18n/resources/en-US/components/common.json
@@ -26,7 +26,7 @@
"property_name_rule": "Use Chinese characters, letters, numbers, or underscores only",
"normal_name_rule": "Use Chinese characters, letters, numbers, or underscores only, up to 48 characters",
"jdbc_rule": "Enter a valid JDBC URL, for example: jdbc:mysql://127.0.0.1:3306/db_name",
- "account_name_rule": "Account name must be within 16 characters and cannot start or end with an underscore",
+ "account_name_rule": "Use 1–16 characters without spaces; letters, numbers, Chinese/CJK forms, and underscores are supported; underscores cannot be first or last",
"favorite_name_rule": "Use Chinese characters, letters, numbers, or underscores only, up to 48 characters",
"invalid_data_format": "Invalid data format"
}
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 688c9a933..07838bafd 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
@@ -354,6 +354,7 @@
},
"empty": {
"description": "This GraphSpace is ready but has no graphs yet. Create the first graph to model, import, and query data",
+ "read_only_description": "This GraphSpace has no graphs available to this read-only account",
"create": "Create first graph",
"demo_prerequisite": "After creating a graph, select it and use Data Import to build a quick Demo dataset.",
"view_demo": "View Demo data entry",
@@ -377,7 +378,8 @@
"name": "Account Name",
"remark": "Remark",
"level": "Account Level",
- "resource": "Resource Permission",
+ "resource": "GraphSpaces",
+ "resource_all": "All",
"create_time": "Created At",
"is_superadmin": "Super Admin",
"permission": "Admin Permission"
@@ -394,6 +396,7 @@
"GS_ADMIN": "GraphSpace Administrator",
"preserve_mixed": "Keep existing mixed access",
"mixed": "Mixed GraphSpace access",
+ "unassigned": "No GraphSpace preset assigned",
"legacy_custom": "Legacy/custom access"
},
"feedback": {
@@ -414,7 +417,7 @@
"id_help": "The unique login identifier. It cannot be changed after creation",
"id_placeholder": "Login username",
"name": "Display Name",
- "name_help": "The name shown to administrators. It can be changed later",
+ "name_help": "Use 1–16 characters without spaces; Chinese/CJK forms, letters, numbers, and underscores are supported",
"name_placeholder": "Can be changed after creation",
"is_superadmin": "Super Admin",
"level": "Account Level",
@@ -509,7 +512,7 @@
"new_password_placeholder": "Enter new password",
"confirm_password_placeholder": "Enter new password again",
"password_mismatch": "Passwords do not match",
- "account_name_rule": "Account name must be 1-16 characters and cannot start or end with an underscore"
+ "account_name_rule": "Use 1–16 characters without spaces; letters, numbers, Chinese/CJK forms, and underscores are supported; underscores cannot be first or last"
}
},
"role": {
@@ -1101,6 +1104,7 @@
"empty_title": "Build your first graph schema",
"empty_description": "Define reusable properties first, then create vertex and edge types",
"create_from_template": "Create Schema from a Template",
+ "read_only_empty": "This graph has no Schema yet. A read-write or administrator account is required to create one.",
"template_description": "Choose a built-in example or a saved template from this GraphSpace and apply it to the current graph",
"manual_title": "Or create the Schema manually",
"builtin_templates": "Built-in Examples",
@@ -1151,7 +1155,7 @@
"read_only": {
"page_title": "{{name}} - Schema Template Library",
"title": "Read-only template library",
- "description": "You can browse built-in and saved templates here. Creating, saving, editing, and deleting templates requires PD mode",
+ "description": "You can browse built-in and saved templates here. Creating, saving, editing, and deleting templates are unavailable for this connection or account",
"apply_to_graph": "Apply templates to {{graph}}",
"choose_graph": "Choose a graph to apply a template",
"builtin": "Built in"
@@ -1400,6 +1404,7 @@
"datasource_manage": "Data Source Management",
"operation_manage": "Operations",
"cluster_overview": "Cluster Overview",
+ "cluster_overview_requires_pd": "Cluster Overview requires PD and is unavailable in standalone mode. Use Nodes to inspect server status.",
"nodes": "Nodes",
"advanced_monitoring": "External Advanced Dashboard",
"operations_unavailable": "Native operations capabilities are unavailable for this account.",
diff --git a/hugegraph-hubble/hubble-fe/src/i18n/resources/zh-CN/components/common.json b/hugegraph-hubble/hubble-fe/src/i18n/resources/zh-CN/components/common.json
index 877d473b4..d796010c1 100644
--- a/hugegraph-hubble/hubble-fe/src/i18n/resources/zh-CN/components/common.json
+++ b/hugegraph-hubble/hubble-fe/src/i18n/resources/zh-CN/components/common.json
@@ -26,7 +26,7 @@
"property_name_rule": "只能包含中文、字母、数字、_",
"normal_name_rule": "只能包含中文、字母、数字、_,最多 48 个字符",
"jdbc_rule": "请输入正确的jdbc url, 例如:jdbc:mysql://127.0.0.1:3306/db_name",
- "account_name_rule": "账号名不超过16个字符,且不能以下划线开始和结尾",
+ "account_name_rule": "使用 1–16 个不含空格的字符,支持中文/东亚兼容字符、字母、数字和下划线;下划线不能位于首尾",
"favorite_name_rule": "只能包含中文、字母、数字、_, 不能超过48个字符",
"invalid_data_format": "非法的数据格式"
}
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 0a9870792..1efe05188 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
@@ -354,6 +354,7 @@
},
"empty": {
"description": "这个 GraphSpace 已可用,但还没有图。创建第一张图后即可配置 Schema、导入和查询数据",
+ "read_only_description": "当前只读账号在此 GraphSpace 中暂无可访问的图",
"create": "创建第一张图",
"demo_prerequisite": "创建图后,选择该图并前往数据导入,即可快速构建 Demo 数据集。",
"view_demo": "查看 Demo 数据入口",
@@ -377,7 +378,8 @@
"name": "账号名",
"remark": "备注",
"level": "账号级别",
- "resource": "资源权限",
+ "resource": "图空间",
+ "resource_all": "全部",
"create_time": "创建时间",
"is_superadmin": "是否为超级管理员",
"permission": "管理权限"
@@ -394,6 +396,7 @@
"GS_ADMIN": "GraphSpace 管理员",
"preserve_mixed": "保留现有混合权限",
"mixed": "混合 GraphSpace 权限",
+ "unassigned": "未分配 GraphSpace 权限预设",
"legacy_custom": "旧版/自定义权限"
},
"feedback": {
@@ -414,7 +417,7 @@
"id_help": "用于登录的唯一账号标识,创建后不可修改",
"id_placeholder": "用户登录",
"name": "账号名",
- "name_help": "显示给其他管理员识别的账号名称,创建后仍可修改",
+ "name_help": "使用 1–16 个不含空格的字符,支持中文/东亚兼容字符、字母、数字和下划线",
"name_placeholder": "账号名设置后可更改",
"is_superadmin": "是否为超级管理员",
"level": "账号级别",
@@ -509,7 +512,7 @@
"new_password_placeholder": "请输入新密码",
"confirm_password_placeholder": "请再次输入密码",
"password_mismatch": "两次密码不一致",
- "account_name_rule": "账号名不超过16个字符,且不能以下划线开始和结尾"
+ "account_name_rule": "使用 1–16 个不含空格的字符,支持中文/东亚兼容字符、字母、数字和下划线;下划线不能位于首尾"
}
},
"role": {
@@ -1101,6 +1104,7 @@
"empty_title": "创建第一个图 Schema",
"empty_description": "建议先定义可复用属性,再创建顶点类型和边类型",
"create_from_template": "根据模板创建 Schema",
+ "read_only_empty": "当前图尚无 Schema,需要读写或管理员账号才能创建。",
"template_description": "选择内置示例或当前图空间已保存的模板,直接应用到当前图",
"manual_title": "或手动创建 Schema",
"builtin_templates": "内置示例",
@@ -1151,7 +1155,7 @@
"read_only": {
"page_title": "{{name}} - Schema 模板库",
"title": "只读模板库",
- "description": "可在此浏览内置模板与已保存模板;创建、保存、编辑和删除模板需要 PD 模式",
+ "description": "可在此浏览内置模板与已保存模板;当前连接或账号无法创建、保存、编辑和删除模板",
"apply_to_graph": "前往 {{graph}} 应用模板",
"choose_graph": "选择图并应用模板",
"builtin": "内置"
@@ -1400,6 +1404,7 @@
"datasource_manage": "数据源管理",
"operation_manage": "运维管理",
"cluster_overview": "集群概览",
+ "cluster_overview_requires_pd": "集群概览依赖 PD,单机模式不可用;可前往节点页面查看 Server 状态。",
"nodes": "节点",
"advanced_monitoring": "外部高级 Dashboard",
"operations_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 11c5f3a54..fc47de692 100644
--- a/hugegraph-hubble/hubble-fe/src/modules/navigation/ConsoleItem/index.js
+++ b/hugegraph-hubble/hubble-fe/src/modules/navigation/ConsoleItem/index.js
@@ -105,14 +105,17 @@ const ConsoleItem = ({embedded = false}) => {
? () => openDashboard(dashboard.url + path)
: undefined,
});
- const nativeItem = (titleKey, path, required, modeAvailable = true) => {
+ const nativeItem = (titleKey, path, required, modeAvailable = true,
+ modeReason = '') => {
const available = modeAvailable && capabilities.includes(required);
const disabled = capabilitiesLoading || Boolean(capabilitiesError) || !available;
return {
title: t(titleKey),
url: available ? path : '',
disabled,
- reason: disabled ? t('navigation_page.operations_unavailable') : '',
+ reason: disabled
+ ? (!modeAvailable && modeReason
+ ? modeReason : t('navigation_page.operations_unavailable')) : '',
badge: disabled ? t('navigation_page.unavailable') : '',
};
};
@@ -133,7 +136,8 @@ const ConsoleItem = ({embedded = false}) => {
'navigation_page.cluster_overview',
'/operations/overview',
'operations_health_read',
- pdMode
+ pdMode,
+ t('navigation_page.cluster_overview_requires_pd')
),
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 c69f169e3..f65d52371 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
@@ -132,11 +132,29 @@ test('disables Cluster Overview outside PD mode while keeping Nodes available',
expect(await screen.findByRole('button', {
name: 'navigation_page.cluster_overview',
})).toBeDisabled();
+ expect(screen.getByRole('group', {
+ name: /navigation_page\.cluster_overview_requires_pd/,
+ })).toBeInTheDocument();
expect(screen.getByRole('button', {
name: 'navigation_page.nodes',
})).toHaveAttribute('data-url', '/operations/nodes');
});
+test('keeps the capability reason when PD mode is available', async () => {
+ useOperationsCapabilities.mockReturnValue({
+ loading: false,
+ capabilities: ['operations_topology_read'],
+ error: null,
+ });
+ renderConsole();
+
+ expect(await screen.findByRole('group', {
+ name: /navigation_page\.operations_unavailable/,
+ })).toHaveAccessibleName(
+ expect.not.stringContaining('navigation_page.cluster_overview_requires_pd')
+ );
+});
+
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 85caa1852..9d957fe21 100644
--- a/hugegraph-hubble/hubble-fe/src/pages/Account/EditLayer.js
+++ b/hugegraph-hubble/hubble-fe/src/pages/Account/EditLayer.js
@@ -27,6 +27,7 @@ import {accountErrorMessage} from './accountError';
import {useAuthContext} from '../../auth/AuthContext';
import {
getAccountPreset,
+ getAccountPresetLabelKey,
getPresetSpaces,
PERMISSION_PRESETS,
toPermissionPayload,
@@ -291,9 +292,9 @@ const EditLayer = ({
label={t('account.form.permission_preset')}
className={style.item}
>
- {t(
- `account.permission_preset.${getAccountPreset(detail) ?? 'mixed'}`
- )}
+ {t(`account.permission_preset.${getAccountPresetLabelKey(
+ detail, permissionPresetsSupported
+ )}`)}
</Form.Item>
<Form.Item label={t('account.form.remark')} className={style.item}>
{detail.user_description}
diff --git a/hugegraph-hubble/hubble-fe/src/pages/Account/SpaceAccess.js b/hugegraph-hubble/hubble-fe/src/pages/Account/SpaceAccess.js
index de5a04414..be575f469 100644
--- a/hugegraph-hubble/hubble-fe/src/pages/Account/SpaceAccess.js
+++ b/hugegraph-hubble/hubble-fe/src/pages/Account/SpaceAccess.js
@@ -74,43 +74,32 @@ const mergeMembersAndAdmins = (members, admins) => {
const rolePreset = role => {
const explicit = role?.permission_preset ?? role?.permissionPreset;
- if (Object.values(PERMISSION_PRESETS).includes(explicit)) {
- return explicit;
- }
- const names = [role?.role_name, role?.role_nickname, role?.name,
- role?.nickname].filter(Boolean).map(name => name.toLowerCase());
- if (names.includes('observer')) {
- return PERMISSION_PRESETS.GS_READ_ONLY;
- }
- if (names.includes('analyst')) {
- return PERMISSION_PRESETS.GS_READ_WRITE;
- }
- const permissions = role?.permissions ?? role?.actions;
- if (Array.isArray(permissions)) {
- if (permissions.includes('delete') || permissions.includes('admin')) {
- return PERMISSION_PRESETS.GS_ADMIN;
- }
- if (permissions.includes('write') || permissions.includes('update')) {
- return PERMISSION_PRESETS.GS_READ_WRITE;
- }
- if (permissions.includes('read')) {
- return PERMISSION_PRESETS.GS_READ_ONLY;
- }
- }
- return null;
+ return Object.values(PERMISSION_PRESETS).includes(explicit)
+ ? explicit
+ : null;
};
const rolesPreset = roles => {
const values = roles ?? [];
const presets = values.map(rolePreset);
+ if (presets.some(preset => preset === null)) {
+ return null;
+ }
+ if (values.some(role => (role?.permission_preset ?? role?.permissionPreset)
+ === PERMISSION_PRESETS.GS_ADMIN)) {
+ return PERMISSION_PRESETS.GS_ADMIN;
+ }
return values.length > 0 && presets.every(Boolean) && new Set(presets).size === 1 ? presets[0] : null;
};
const roleLabel = (role, t) => {
const preset = rolePreset(role);
- return preset
- ? t(`account.permission_preset.${preset}`)
- : t('account.permission_preset.legacy_custom');
+ if (preset) {
+ return t(`account.permission_preset.${preset}`);
+ }
+ const name = role?.role_name ?? role?.name;
+ const legacy = t('account.permission_preset.legacy_custom');
+ return name ? `${name} · ${legacy}` : legacy;
};
const RowAction = ({row, onAction, children}) => {
@@ -331,6 +320,8 @@ const SpaceAccess = () => {
)
), [confirmDelete, graphSpace, t]);
const addMember = useCallback(() => openMember(), [openMember]);
+ const canManageMember = row => scopes.all_graphspaces
+ || !row.is_space_admin;
const retrySpaces = useCallback(
() => setSpacesRevision(value => value + 1), []
);
@@ -350,12 +341,12 @@ const SpaceAccess = () => {
title: t('common.operation'),
render: row => (
<Space>
- {canAddMember && (
+ {canAddMember && canManageMember(row) && (
<RowAction row={row} onAction={editMember}>
{t('common.action.edit')}
</RowAction>
)}
- {canRemoveMember && (
+ {canRemoveMember && canManageMember(row) && (
<RowAction row={row} onAction={deleteMember}>
{t('common.action.delete')}
</RowAction>
@@ -456,6 +447,8 @@ const SpaceAccess = () => {
<Select
options={Object.values(PERMISSION_PRESETS)
.filter(value => value !== PERMISSION_PRESETS.SUPER_ADMIN)
+ .filter(value => scopes.all_graphspaces
+ || value !== PERMISSION_PRESETS.GS_ADMIN)
.map(value => ({
value,
label: t(`account.permission_preset.${value}`),
diff --git a/hugegraph-hubble/hubble-fe/src/pages/Account/SpaceAccess.test.js b/hugegraph-hubble/hubble-fe/src/pages/Account/SpaceAccess.test.js
index 7367678f9..bcbcade6c 100644
--- a/hugegraph-hubble/hubble-fe/src/pages/Account/SpaceAccess.test.js
+++ b/hugegraph-hubble/hubble-fe/src/pages/Account/SpaceAccess.test.js
@@ -16,7 +16,14 @@
* limitations under the License.
*/
-import {act, fireEvent, render, screen, waitFor} from '@testing-library/react';
+import {
+ act,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+ within,
+} from '@testing-library/react';
import SpaceAccess, {rolesPreset} from './SpaceAccess';
import * as api from '../../api';
@@ -85,6 +92,43 @@ test('requires explicit preset for mixed or legacy member roles', () => {
{role_name: 'observer'},
{role_name: 'analyst'},
])).toBeNull();
+ expect(rolesPreset([
+ {role_name: 'observer', permission_preset: 'GS_READ_ONLY'},
+ ])).toBe('GS_READ_ONLY');
+});
+
+test('keeps graphspace administrator selected with member roles', () => {
+ expect(rolesPreset([
+ {role_name: 'analyst', permission_preset: 'GS_READ_WRITE'},
+ {permission_preset: 'GS_ADMIN'},
+ ])).toBe('GS_ADMIN');
+ expect(rolesPreset([
+ {role_name: 'analyst'},
+ {role_name: 'custom-role', permissions: ['delete']},
+ ])).toBeNull();
+ expect(rolesPreset([
+ {role_name: 'analyst', permissions: ['write', 'delete']},
+ ])).toBeNull();
+ expect(rolesPreset([
+ {role_name: 'custom-role'},
+ {permission_preset: 'GS_ADMIN'},
+ ])).toBeNull();
+});
+
+test('shows legacy role names without treating them as presets', async () => {
+ setResponses({
+ members: [{
+ user_id: 'alice',
+ user_name: 'alice',
+ roles: [{role_id: 'custom', role_name: 'analyst'}],
+ }],
+ });
+
+ render(<SpaceAccess />);
+
+ expect(await screen.findByText(
+ 'analyst · account.permission_preset.legacy_custom'
+ )).toBeInTheDocument();
});
beforeEach(() => {
@@ -209,6 +253,13 @@ test('submits only the selected preset when adding a member', async () => {
});
test('uses the preset API for GS admin', async () => {
+ mockAuthContext.context.scopes = {
+ all_graphspaces: true,
+ admin_graphspaces: [],
+ };
+ api.manage.getGraphSpaceList.mockResolvedValue(page([
+ {name: 'SPACE_A'},
+ ]));
api.auth.setSpacePreset.mockResolvedValue({status: 200});
render(<SpaceAccess />);
@@ -231,6 +282,24 @@ test('uses the preset API for GS admin', async () => {
expect(api.auth.addSpaceMember).not.toHaveBeenCalled();
});
+test('does not let a space administrator manage other space administrators',
+ async () => {
+ api.auth.getSpaceAdmins.mockResolvedValueOnce(page([{
+ id: 'admin-id',
+ name: 'space-admin',
+ }]));
+
+ render(<SpaceAccess />);
+
+ const row = (await screen.findByText('space-admin')).closest('tr');
+ expect(within(row).queryByRole('button', {
+ name: 'common.action.edit',
+ })).not.toBeInTheDocument();
+ expect(within(row).queryByRole('button', {
+ name: 'common.action.delete',
+ })).not.toBeInTheDocument();
+ });
+
test('shows GraphSpace administrators through the preset model', async () => {
api.auth.getSpaceAdmins.mockResolvedValueOnce(page([{
id: 'admin-id',
diff --git a/hugegraph-hubble/hubble-fe/src/pages/Account/account-recovery.test.js b/hugegraph-hubble/hubble-fe/src/pages/Account/account-recovery.test.js
index ad74bcc28..64e157f68 100644
--- a/hugegraph-hubble/hubble-fe/src/pages/Account/account-recovery.test.js
+++ b/hugegraph-hubble/hubble-fe/src/pages/Account/account-recovery.test.js
@@ -48,6 +48,7 @@ beforeEach(() => {
mockAuthContext = {
refresh: jest.fn(),
context: {
+ capabilities: ['account_permission_presets'],
actions: {
accounts: ['create', 'read', 'update', 'delete'],
authorizations: ['read', 'grant', 'revoke'],
@@ -119,6 +120,24 @@ test('labels administrators, space administrators, and regular users in the list
.toBeInTheDocument();
});
+test('does not label an unassigned legacy account as GraphSpace read-only', async () => {
+ mockAuthContext.context.capabilities = ['accounts_manage'];
+ api.auth.getAllUserList.mockResolvedValue({
+ status: 200,
+ data: {
+ records: [{user_name: 'analyst', adminSpaces: []}],
+ total: 1,
+ },
+ });
+
+ render(<Account />);
+
+ expect(await screen.findByText('account.permission_preset.unassigned'))
+ .toBeInTheDocument();
+ expect(screen.queryByText('account.permission_preset.GS_READ_ONLY'))
+ .not.toBeInTheDocument();
+});
+
test('space administrators use scoped management without loading global accounts', async () => {
mockCurrentUser = {
id: 'space-admin',
diff --git a/hugegraph-hubble/hubble-fe/src/pages/Account/index.js b/hugegraph-hubble/hubble-fe/src/pages/Account/index.js
index f1323041f..32fc903f3 100644
--- a/hugegraph-hubble/hubble-fe/src/pages/Account/index.js
+++ b/hugegraph-hubble/hubble-fe/src/pages/Account/index.js
@@ -34,7 +34,12 @@ import TableHeader from '../../components/TableHeader';
import EditLayer from './EditLayer';
import * as api from '../../api';
import {useAuthContext} from '../../auth/AuthContext';
-import {getAccountPreset, PERMISSION_PRESETS} from './permissionPresets';
+import {
+ getAccountPreset,
+ getAccountPresetLabelKey,
+ getPresetSpaces,
+ PERMISSION_PRESETS,
+} from './permissionPresets';
import SpaceAccess from './SpaceAccess';
import {accountErrorMessage} from './accountError';
@@ -55,6 +60,8 @@ const GlobalAccounts = () => {
const canUpdateAccount = accountActions.includes('update');
const canDeleteAccount = accountActions.includes('delete');
const canGrantAuthorization = authorizationActions.includes('grant');
+ const permissionPresetsSupported = !context
+ || context.capabilities?.includes('account_permission_presets');
const hasRowMutations = canUpdateAccount || canDeleteAccount || canGrantAuthorization;
const [editLayerVisible, setEditLayerVisible] = useState(false);
const [op, setOp] = useState('detail');
@@ -124,34 +131,45 @@ const GlobalAccounts = () => {
{
title: t('account.col.id'),
dataIndex: 'user_name',
+ width: 150,
},
{
title: t('account.col.name'),
dataIndex: 'user_nickname',
+ width: 150,
},
{
title: t('account.col.remark'),
dataIndex: 'user_description',
+ width: 180,
ellipsis: {showTitle: false},
render: val => <Tooltip title={val} placement='bottomLeft'>{val}</Tooltip>,
},
{
title: t('account.col.level'),
- width: 140,
+ width: 190,
render: row => {
const preset = getAccountPreset(row);
- if (!preset) {
- return <Tag>{t('account.permission_preset.mixed')}</Tag>;
- }
const color = preset === PERMISSION_PRESETS.SUPER_ADMIN ? 'red'
: preset === PERMISSION_PRESETS.GS_ADMIN ? 'blue' : 'default';
- return <Tag color={color}>{t(`account.permission_preset.${preset}`)}</Tag>;
+ const labelKey = getAccountPresetLabelKey(
+ row, permissionPresetsSupported
+ );
+ return (
+ <Tag color={color}>
+ {t(`account.permission_preset.${labelKey}`)}
+ </Tag>
+ );
},
},
{
title: t('account.col.resource'),
- dataIndex: 'spacenum',
width: 120,
+ render: row => (
+ getAccountPreset(row) === PERMISSION_PRESETS.SUPER_ADMIN
+ ? t('account.col.resource_all')
+ : getPresetSpaces(row).length
+ ),
},
{
title: t('account.col.create_time'),
@@ -161,7 +179,8 @@ const GlobalAccounts = () => {
},
{
title: t('common.operation'),
- width: hasRowMutations ? 300 : 100,
+ width: hasRowMutations ? 280 : 100,
+ fixed: 'right',
align: 'center',
render: row => (
<Space>
@@ -265,6 +284,7 @@ const GlobalAccounts = () => {
pagination={pagination}
onChange={handleTable}
loading={listLoading}
+ scroll={{x: 1270}}
/>
<EditLayer
diff --git a/hugegraph-hubble/hubble-fe/src/pages/Account/permissionPresets.js b/hugegraph-hubble/hubble-fe/src/pages/Account/permissionPresets.js
index 072d8a227..a70cb242e 100644
--- a/hugegraph-hubble/hubble-fe/src/pages/Account/permissionPresets.js
+++ b/hugegraph-hubble/hubble-fe/src/pages/Account/permissionPresets.js
@@ -81,6 +81,15 @@ const getPresetSpaces = account => {
: [];
};
+const getAccountPresetLabelKey = (account, permissionPresetsSupported) => {
+ if (!permissionPresetsSupported
+ && !account?.is_superadmin
+ && getPresetSpaces(account).length === 0) {
+ return 'unassigned';
+ }
+ return getAccountPreset(account) ?? 'mixed';
+};
+
// This is the only compatibility mapping used by account forms.
const toPermissionPayload = values => {
const preset = values.permission_preset ?? PERMISSION_PRESETS.GS_READ_ONLY;
@@ -100,4 +109,10 @@ const toPermissionPayload = values => {
};
};
-export {PERMISSION_PRESETS, getAccountPreset, getPresetSpaces, toPermissionPayload};
+export {
+ PERMISSION_PRESETS,
+ getAccountPreset,
+ getAccountPresetLabelKey,
+ getPresetSpaces,
+ toPermissionPayload,
+};
diff --git a/hugegraph-hubble/hubble-fe/src/pages/Account/permissionPresets.test.js b/hugegraph-hubble/hubble-fe/src/pages/Account/permissionPresets.test.js
index bed366348..71e6905bf 100644
--- a/hugegraph-hubble/hubble-fe/src/pages/Account/permissionPresets.test.js
+++ b/hugegraph-hubble/hubble-fe/src/pages/Account/permissionPresets.test.js
@@ -17,6 +17,7 @@
import {
getAccountPreset,
+ getAccountPresetLabelKey,
getPresetSpaces,
PERMISSION_PRESETS,
toPermissionPayload,
@@ -35,6 +36,15 @@ test.each([
expect(getAccountPreset(account)).toBe(expected);
});
+test('does not claim GraphSpace access without a supported preset or assignment', () => {
+ expect(getAccountPresetLabelKey({adminSpaces: []}, false))
+ .toBe('unassigned');
+ expect(getAccountPresetLabelKey({is_superadmin: true}, false))
+ .toBe(PERMISSION_PRESETS.SUPER_ADMIN);
+ expect(getAccountPresetLabelKey({adminSpaces: ['SPACE']}, false))
+ .toBe(PERMISSION_PRESETS.GS_ADMIN);
+});
+
test('normalizes GraphSpace objects and keeps legacy payload in one adapter', () => {
expect(getPresetSpaces({adminSpaces: [{name: 'team'}]})).toEqual(['team']);
expect(getPresetSpaces({
diff --git a/hugegraph-hubble/hubble-fe/src/pages/Graph/Card.js b/hugegraph-hubble/hubble-fe/src/pages/Graph/Card.js
index 07bfe2e18..9d2a0d2b8 100644
--- a/hugegraph-hubble/hubble-fe/src/pages/Graph/Card.js
+++ b/hugegraph-hubble/hubble-fe/src/pages/Graph/Card.js
@@ -72,7 +72,7 @@ const TitleField = ({item, onClick, onKeyDown, schemaTypeCounts}) => {
);
};
-const GraphCard = ({item, menus}) => {
+const GraphCard = ({item, menus, canMutate = true}) => {
const {t} = useTranslation();
const navigate = useNavigate();
const graphName = getResourceDisplayName(item.name, item.nickname);
@@ -156,8 +156,14 @@ const GraphCard = ({item, menus}) => {
<strong>{t('graph.card.empty_schema')}</strong>
<span>{t('graph.card.empty_schema_help')}</span>
<Space>
- <Button type='primary' size='small' onClick={handleGotoSchema}>
- {t('graph.card.open_schema')}
+ <Button
+ type={canMutate ? 'primary' : 'default'}
+ size='small'
+ onClick={handleGotoSchema}
+ >
+ {canMutate
+ ? t('graph.card.open_schema')
+ : t('graph.menu.view_schema')}
</Button>
<Button size='small' onClick={handleGotoAnalysis}>
{t('graph.card.query_graph')}
diff --git a/hugegraph-hubble/hubble-fe/src/pages/Graph/Card.test.js b/hugegraph-hubble/hubble-fe/src/pages/Graph/Card.test.js
index 02b095313..2b264b962 100644
--- a/hugegraph-hubble/hubble-fe/src/pages/Graph/Card.test.js
+++ b/hugegraph-hubble/hubble-fe/src/pages/Graph/Card.test.js
@@ -124,6 +124,28 @@ test('uses a compact actionable state when the graph has no schema', () => {
.not.toBeInTheDocument();
});
+test('labels an empty schema as view-only for a read-only account', () => {
+ render(
+ <MemoryRouter future={{v7_startTransition: true, v7_relativeSplatPath: true}}>
+ <GraphCard
+ item={{
+ name: 'hugegraph',
+ graphspace: 'space',
+ storage: 0,
+ schemaview: {vertices: [], edges: []},
+ }}
+ menus={[]}
+ canMutate={false}
+ />
+ </MemoryRouter>
+ );
+
+ expect(screen.getByRole('button', {name: 'graph.menu.view_schema'}))
+ .toBeInTheDocument();
+ expect(screen.queryByRole('button', {name: 'graph.card.open_schema'}))
+ .not.toBeInTheDocument();
+});
+
test('ships the requested graph creation and schema labels', () => {
const zh = require('../../i18n/resources/zh-CN/modules/pages.json');
const en = require('../../i18n/resources/en-US/modules/pages.json');
diff --git a/hugegraph-hubble/hubble-fe/src/pages/Graph/default-card-actions.test.js b/hugegraph-hubble/hubble-fe/src/pages/Graph/default-card-actions.test.js
index 33e1d4783..9507133e4 100644
--- a/hugegraph-hubble/hubble-fe/src/pages/Graph/default-card-actions.test.js
+++ b/hugegraph-hubble/hubble-fe/src/pages/Graph/default-card-actions.test.js
@@ -223,7 +223,11 @@ test('disables example dataset writes for the protected built-in graphspace', as
test('disables example dataset writes without graphspace update permission', async () => {
mockAuthContext = {
- context: {role: 'USER', scopes: {admin_graphspaces: []}},
+ context: {
+ mode: 'PD',
+ role: 'USER',
+ scopes: {admin_graphspaces: [], write_graphspaces: []},
+ },
};
render(<Graph />);
@@ -237,6 +241,50 @@ test('disables example dataset writes without graphspace update permission', asy
expect(within(menu).getByText(label).closest('[role="menuitem"]'))
.toHaveAttribute('aria-disabled', 'true');
});
+ [
+ 'graph.menu.clear_graph',
+ 'graph.menu.set_default',
+ 'common.action.edit',
+ 'common.action.delete',
+ ].forEach(label => {
+ expect(within(menu).getByText(label).closest('[role="menuitem"]'))
+ .toHaveAttribute('aria-disabled', 'true');
+ });
+ expect(screen.queryByRole('button', {name: 'graph.create'}))
+ .not.toBeInTheDocument();
+});
+
+test('separates read-write graph data from GraphSpace management', async () => {
+ mockAuthContext = {
+ context: {
+ mode: 'PD',
+ role: 'USER',
+ scopes: {admin_graphspaces: [], write_graphspaces: ['space']},
+ },
+ };
+ api.manage.getGraphList.mockResolvedValue({
+ status: 200,
+ data: {
+ records: [{
+ name: 'graph-a',
+ graphspace: 'space',
+ default: false,
+ }],
+ total: 1,
+ },
+ });
+
+ render(<Graph />);
+
+ const menu = await screen.findByTestId('graph-card-menu');
+ expect(within(menu).getByText('common.action.edit').closest('[role="menuitem"]'))
+ .toHaveAttribute('aria-disabled', 'true');
+ expect(within(menu).getByText('graph.menu.clear_graph').closest('[role="menuitem"]'))
+ .toHaveAttribute('aria-disabled', 'true');
+ expect(within(menu).getByText('graph.menu.load_hlm_sample')
+ .closest('[role="menuitem"]')).not.toHaveAttribute('aria-disabled');
+ expect(screen.queryByRole('button', {name: 'graph.create'}))
+ .not.toBeInTheDocument();
});
test('places the new-graph card after existing graphs', async () => {
@@ -300,6 +348,29 @@ test('explains an empty GraphSpace and distinguishes filtered results', async ()
expect(search).toHaveValue('');
});
+test('shows a read-only empty state without mutation links', async () => {
+ mockAuthContext = {
+ context: {
+ mode: 'PD',
+ role: 'USER',
+ scopes: {admin_graphspaces: [], write_graphspaces: []},
+ },
+ };
+ api.manage.getGraphList.mockResolvedValue({
+ status: 200,
+ data: {records: [], total: 0},
+ });
+
+ render(<Graph />);
+
+ expect(await screen.findByText('graph.empty.read_only_description'))
+ .toBeInTheDocument();
+ expect(screen.queryByRole('button', {name: 'graph.empty.create'}))
+ .not.toBeInTheDocument();
+ expect(screen.queryByRole('link', {name: 'graph.empty.view_demo'}))
+ .not.toBeInTheDocument();
+});
+
test('falls back to the real GraphSpace name in list mode when alias is empty', async () => {
api.manage.getGraphList.mockResolvedValue({
status: 200,
diff --git a/hugegraph-hubble/hubble-fe/src/pages/Graph/index.js b/hugegraph-hubble/hubble-fe/src/pages/Graph/index.js
index 770fdbca6..60d634f5b 100644
--- a/hugegraph-hubble/hubble-fe/src/pages/Graph/index.js
+++ b/hugegraph-hubble/hubble-fe/src/pages/Graph/index.js
@@ -53,10 +53,10 @@ import GraphCard from './Card';
import ClearGraphConfirmModal from './ClearGraphConfirmModal';
import KeyboardAction from '../../components/KeyboardAction';
import {getResourceDisplayName} from '../../utils/displayName';
-import {useAuthContext} from '../../auth/AuthContext';
import {sanitizePublicError} from '../../utils/publicError';
import EditableNicknameCell from './EditableNicknameCell';
import {TopbarPageContextSlot} from '../../components/Topbar/PageContextSlot';
+import {useGraphspaceAccess} from '../../auth/graphspaceAccess';
const GraphRowAction = ({onAction, graph, children}) => {
const handleClick = useCallback(() => onAction(graph), [graph, onAction]);
@@ -106,14 +106,10 @@ const Graph = () => {
const [sampleLoading, setSampleLoading] = useState('');
const {graphspace} = useParams();
const navigate = useNavigate();
- const {context: authContext} = useAuthContext();
const pdMode = isPdEnabled();
const graphCreateEnabled = isGraphCreateEnabled(pdMode);
const graphDefaultMutationEnabled = isGraphDefaultMutationEnabled(pdMode);
- const adminGraphspaces = authContext?.scopes?.admin_graphspaces ?? [];
- const canUpdateGraphspace = value => authContext?.role === 'SUPERADMIN'
- || authContext?.scopes?.all_graphspaces === true
- || adminGraphspaces.includes(value);
+ const {canManage, canWrite} = useGraphspaceAccess(graphspace);
const handlePagination = useCallback(current => {
setPagination({...pagination, current});
@@ -337,13 +333,15 @@ const Graph = () => {
<Empty
description={hasFilters
? t('graph.empty.filtered_description')
- : t('graph.empty.description')}
+ : canManage
+ ? t('graph.empty.description')
+ : t('graph.empty.read_only_description')}
>
{hasFilters ? (
<Button onClick={handleClearFilters}>
{t('graph.empty.clear_filters')}
</Button>
- ) : (
+ ) : canManage ? (
<Space direction='vertical' size={8}>
{graphCreateEnabled && (
<Button type='primary' onClick={showEditLayer}>
@@ -355,7 +353,7 @@ const Graph = () => {
</span>
<Link to='/task'>{t('graph.empty.view_demo')}</Link>
</Space>
- )}
+ ) : null}
</Empty>
);
@@ -364,7 +362,7 @@ const Graph = () => {
title: t('graph.col.name'),
render: row => (
<GraphNicknameColumn
- canEdit={canUpdateGraphspace(row.graphspace || graphspace)}
+ canEdit={canManage}
onSave={saveNickname}
row={row}
t={t}
@@ -411,14 +409,14 @@ const Graph = () => {
<Link to={`/graphspace/${graphspace}/graph/${row.name}/meta`}>
{t('graph.menu.meta_config')}
</Link>
- {(row.default)
+ {(row.default || !canManage)
? <span className={style.disable}>{t('graph.menu.clear_graph')}</span>
: (
<GraphRowAction onAction={clearGraph} graph={row.name}>
{t('graph.menu.clear_graph')}
</GraphRowAction>
)}
- {(row.graphspace === 'neizhianli')
+ {(row.graphspace === 'neizhianli' || !canManage)
? <span className={style.disable}>{t('common.action.delete')}</span>
: (
<GraphRowAction onAction={deleteGraph} graph={row.name}>
@@ -429,7 +427,7 @@ const Graph = () => {
{t('graph.menu.view_schema')}
</GraphRowAction>
{graphDefaultMutationEnabled && (
- row.default
+ row.default || !canManage
? <span className={style.disable}>{t('graph.menu.set_default')}</span>
: (
<GraphRowAction onAction={handleSetDefault} graph={row.name}>
@@ -459,33 +457,34 @@ const Graph = () => {
const getMenus = item => {
const itemGraphspace = item.graphspace || graphspace;
const immutable = itemGraphspace === 'neizhianli';
- const readOnly = !canUpdateGraphspace(itemGraphspace);
- const sampleDisabled = immutable || readOnly || Boolean(sampleLoading);
+ const sampleDisabled = immutable || !canWrite || Boolean(sampleLoading);
return [
{
key: 'clear',
danger: true,
- disabled: item.default,
- label: item.default
+ disabled: item.default || !canManage,
+ label: item.default || !canManage
? <span className={style.disable}>{t('graph.menu.clear_graph')}</span>
: t('graph.menu.clear_graph'),
- onClick: item.default ? undefined : () => clearGraph(item.name),
+ onClick: item.default || !canManage
+ ? undefined : () => clearGraph(item.name),
},
graphDefaultMutationEnabled && {
key: 'default',
- disabled: item.default,
- label: item.default
+ disabled: item.default || !canManage,
+ label: item.default || !canManage
? <span className={style.disable}>{t('graph.menu.set_default')}</span>
: t('graph.menu.set_default'),
- onClick: item.default ? undefined : () => handleSetDefault(item.name),
+ onClick: item.default || !canManage
+ ? undefined : () => handleSetDefault(item.name),
},
{
key: 'edit',
- disabled: immutable,
- label: immutable
+ disabled: immutable || !canManage,
+ label: immutable || !canManage
? <span className={style.disable}>{t('common.action.edit')}</span>
: t('common.action.edit'),
- onClick: immutable
+ onClick: immutable || !canManage
? undefined : () => editGraph(item.name),
},
{
@@ -512,11 +511,11 @@ const Graph = () => {
{
key: 'delete',
danger: true,
- disabled: immutable,
- label: immutable
+ disabled: immutable || !canManage,
+ label: immutable || !canManage
? <span className={style.disable}>{t('common.action.delete')}</span>
: t('common.action.delete'),
- onClick: immutable
+ onClick: immutable || !canManage
? undefined : () => deleteGraph(item.name),
},
graphCreateEnabled && {
@@ -628,11 +627,13 @@ const Graph = () => {
<GraphCard
item={item}
menus={menus}
+ canMutate={canWrite}
/>
</Col>
);
})}
- {graphCreateEnabled && data.length > 0 && (
+ {graphCreateEnabled && canManage
+ && data.length > 0 && (
<Col span={8} key='add'>
<KeyboardAction
onAction={showEditLayer}
@@ -661,7 +662,7 @@ const Graph = () => {
)
: (
<>
- {graphCreateEnabled && (
+ {graphCreateEnabled && canManage && (
<>
<Row>
<Col>
diff --git a/hugegraph-hubble/hubble-fe/src/pages/Graph/inline-nickname-edit.test.js b/hugegraph-hubble/hubble-fe/src/pages/Graph/inline-nickname-edit.test.js
index 47267ffe4..fde6b1ca5 100644
--- a/hugegraph-hubble/hubble-fe/src/pages/Graph/inline-nickname-edit.test.js
+++ b/hugegraph-hubble/hubble-fe/src/pages/Graph/inline-nickname-edit.test.js
@@ -161,6 +161,26 @@ test('does not expose inline editing outside the server-authorized GraphSpace sc
})).not.toBeInTheDocument();
});
+test('does not grant graph administration to a read-write GraphSpace scope', async () => {
+ mockAuthContext = {
+ context: {
+ mode: 'PD',
+ role: 'USER',
+ scopes: {
+ all_graphspaces: false,
+ admin_graphspaces: [],
+ write_graphspaces: ['space'],
+ },
+ },
+ };
+ await renderGraph();
+ await openListMode();
+
+ expect(screen.queryByRole('button', {
+ name: 'common.action.edit graph.form.nickname',
+ })).not.toBeInTheDocument();
+});
+
test('keeps a rejected PUT draft visible with an inline error', async () => {
api.manage.updateGraph.mockRejectedValue({
config: {suppressBusinessErrorToast: true},
diff --git a/hugegraph-hubble/hubble-fe/src/pages/Meta/Edge/index.js b/hugegraph-hubble/hubble-fe/src/pages/Meta/Edge/index.js
index 873817c85..86bf9af13 100644
--- a/hugegraph-hubble/hubble-fe/src/pages/Meta/Edge/index.js
+++ b/hugegraph-hubble/hubble-fe/src/pages/Meta/Edge/index.js
@@ -28,7 +28,7 @@ import * as api from '../../../api';
const DELETE_REQUEST_CONFIG = {suppressBusinessErrorToast: true};
-const EdgeTable = () => {
+const EdgeTable = ({canWrite = true}) => {
const [editLayerVisible, setEditLayerVisible] = useState(false);
const [refresh, setRefresh] = useState(false);
const [selectedItems, setSelectedItems] = useState([]);
@@ -152,7 +152,7 @@ const EdgeTable = () => {
ellipsis: true,
render: val => val.map(item => item.name).join(';'),
},
- {
+ canWrite && {
title: t('common.operation'),
align: 'center',
render: row => (
@@ -166,7 +166,7 @@ const EdgeTable = () => {
</Space>
),
},
- ];
+ ].filter(Boolean);
useEffect(() => {
api.manage.getMetaPropertyList(graphspace, graph, {page_size: -1}).then(res => {
@@ -192,9 +192,17 @@ const EdgeTable = () => {
<Row>
<Col>
<Space>
- <Button type='primary' onClick={handleCreate}>{t('common.create')}</Button>
+ {canWrite && (
+ <Button type='primary' onClick={handleCreate}>
+ {t('common.create')}
+ </Button>
+ )}
<Button onClick={handleRefresh}>{t('common.refresh')}</Button>
- <Button onClick={handleDeleteBatch}>{t('common.batch_delete')}</Button>
+ {canWrite && (
+ <Button onClick={handleDeleteBatch}>
+ {t('common.batch_delete')}
+ </Button>
+ )}
</Space>
</Col>
</Row>
@@ -204,12 +212,12 @@ const EdgeTable = () => {
<Table
columns={columns}
dataSource={data}
- rowSelection={{
+ rowSelection={canWrite ? {
type: 'checkbox',
onChange: selectedRowKeys => {
setSelectedItems(selectedRowKeys);
},
- }}
+ } : null}
pagination={pagination}
onChange={handleTable}
rowKey={rowKey}
@@ -218,7 +226,7 @@ const EdgeTable = () => {
scroll={{x: 'max-content'}}
/>
- <EditEdgeLayer
+ {canWrite && <EditEdgeLayer
visible={editLayerVisible}
graphspace={graphspace}
graph={graph}
@@ -227,7 +235,7 @@ const EdgeTable = () => {
name={edgeName}
propertyList={propertyList}
vertexList={vertexList}
- />
+ />}
</>
);
};
diff --git a/hugegraph-hubble/hubble-fe/src/pages/Meta/ImageView.js b/hugegraph-hubble/hubble-fe/src/pages/Meta/ImageView.js
index 233f23c4a..dbd708d8a 100644
--- a/hugegraph-hubble/hubble-fe/src/pages/Meta/ImageView.js
+++ b/hugegraph-hubble/hubble-fe/src/pages/Meta/ImageView.js
@@ -32,6 +32,7 @@ import {useTranslation} from 'react-i18next';
import styles from './ImageView.module.scss';
import {BUILTIN_SCHEMA_TEMPLATES} from '../Schema/builtinSchemaTemplates';
import {toGraphSchemaGroovy} from '../Schema/schemaGroovy';
+import {useGraphspaceAccess} from '../../auth/graphspaceAccess';
const SCHEMA_LABEL_DOCS_URL
= 'https://hugegraph.apache.org/docs/clients/hugegraph-client/';
@@ -77,7 +78,7 @@ const formatKeys = keys => {
return Array.isArray(keys) ? keys.join(', ') : '';
};
-const SchemaTooltip = ({model, type, t}) => {
+const SchemaTooltip = ({model, type, t, canWrite}) => {
const schema = model?.data || {};
const properties = formatProperties(schema.properties);
const isVertex = type === 'vertex';
@@ -104,9 +105,11 @@ const SchemaTooltip = ({model, type, t}) => {
</div>
))}
</dl>
- <span className={styles.tooltipHint}>
- {t('schema.image_view.hover.edit_hint')}
- </span>
+ {canWrite && (
+ <span className={styles.tooltipHint}>
+ {t('schema.image_view.hover.edit_hint')}
+ </span>
+ )}
</section>
);
};
@@ -115,6 +118,7 @@ const ImageView = () => {
const {t} = useTranslation();
// const graphRef = useRef(null);
const {graphspace, graph} = useParams();
+ const {canWrite} = useGraphspaceAccess(graphspace);
const [data, setData] = useState({vertices: [], edges: []});
const [propertyVisible, setPropertyVisible] = useState(false);
const [vertexVisible, setVertexVisible] = useState(false);
@@ -287,6 +291,9 @@ const ImageView = () => {
}, [graph, graphspace, handleRefresh, selectedTemplate, t]);
const handleDoubleClick = useCallback((id, type, data) => {
+ if (!canWrite) {
+ return;
+ }
if (type === 'node') {
setVertexVisible(true);
setEdgeVisible(false);
@@ -298,15 +305,15 @@ const ImageView = () => {
setEdgeVisible(true);
setEdgeName(data.label);
}
- }, []);
+ }, [canWrite]);
const renderVertexTooltip = useCallback(({model}) => (
- <SchemaTooltip model={model} type='vertex' t={t} />
- ), [t]);
+ <SchemaTooltip model={model} type='vertex' t={t} canWrite={canWrite} />
+ ), [canWrite, t]);
const renderEdgeTooltip = useCallback(({model}) => (
- <SchemaTooltip model={model} type='edge' t={t} />
- ), [t]);
+ <SchemaTooltip model={model} type='edge' t={t} canWrite={canWrite} />
+ ), [canWrite, t]);
const loadSchemaView = useCallback(() => {
const token = Symbol('schema-image');
@@ -398,21 +405,25 @@ const ImageView = () => {
const schemaActions = (
<Space wrap>
- <Button
- disabled={loading || loadError}
- onClick={createProperty}
- >
- {t('schema.property.create')}
- </Button>
- <Button disabled={loading || loadError} onClick={createVertex}>
- {t('schema.vertex.create')}
- </Button>
- <Button
- disabled={loading || loadError || vertexList.length === 0}
- onClick={createEdge}
- >
- {t('schema.edge.form.title_create')}
- </Button>
+ {canWrite && (
+ <>
+ <Button
+ disabled={loading || loadError}
+ onClick={createProperty}
+ >
+ {t('schema.property.create')}
+ </Button>
+ <Button disabled={loading || loadError} onClick={createVertex}>
+ {t('schema.vertex.create')}
+ </Button>
+ <Button
+ disabled={loading || loadError || vertexList.length === 0}
+ onClick={createEdge}
+ >
+ {t('schema.edge.form.title_create')}
+ </Button>
+ </>
+ )}
<Button disabled={loading || loadError} onClick={showPropertyList}>
{t('schema.image_view.view_properties')}
</Button>
@@ -450,33 +461,41 @@ const ImageView = () => {
</Row>
<Spin spinning={loading}>
{schemaIsEmpty ? (
- <section className={styles.empty} aria-labelledby='schema-empty-title'>
- <h2 id='schema-empty-title'>
- {t('schema.image_view.create_from_template')}
- </h2>
- <p>{t('schema.image_view.template_description')}</p>
- <Button type='primary' onClick={openTemplatePicker}>
- {t('schema.image_view.create_from_template')}
- </Button>
- <Typography.Title level={5} className={styles.manualTitle}>
- {t('schema.image_view.manual_title')}
- </Typography.Title>
- <ol className={styles.steps}>
- <li>{t('schema.image_view.step_property')}</li>
- <li>{t('schema.image_view.step_vertex')}</li>
- <li>{t('schema.image_view.step_edge')}</li>
- </ol>
- {schemaActions}
- <p className={styles.edgeHint}>
- {t('schema.image_view.edge_prerequisite')}
- </p>
- <div className={styles.startGuide}>
- <p>{t('schema.image_view.start_description')}</p>
- <Button type='link' onClick={createProperty}>
- {t('schema.image_view.start_with_property')}
+ canWrite ? (
+ <section className={styles.empty} aria-labelledby='schema-empty-title'>
+ <h2 id='schema-empty-title'>
+ {t('schema.image_view.create_from_template')}
+ </h2>
+ <p>{t('schema.image_view.template_description')}</p>
+ <Button type='primary' onClick={openTemplatePicker}>
+ {t('schema.image_view.create_from_template')}
</Button>
- </div>
- </section>
+ <Typography.Title level={5} className={styles.manualTitle}>
+ {t('schema.image_view.manual_title')}
+ </Typography.Title>
+ <ol className={styles.steps}>
+ <li>{t('schema.image_view.step_property')}</li>
+ <li>{t('schema.image_view.step_vertex')}</li>
+ <li>{t('schema.image_view.step_edge')}</li>
+ </ol>
+ {schemaActions}
+ <p className={styles.edgeHint}>
+ {t('schema.image_view.edge_prerequisite')}
+ </p>
+ <div className={styles.startGuide}>
+ <p>{t('schema.image_view.start_description')}</p>
+ <Button type='link' onClick={createProperty}>
+ {t('schema.image_view.start_with_property')}
+ </Button>
+ </div>
+ </section>
+ ) : (
+ <section className={styles.empty}>
+ <Typography.Text>
+ {t('schema.image_view.read_only_empty')}
+ </Typography.Text>
+ </section>
+ )
) : (
<GraphView
data={data}
@@ -490,7 +509,7 @@ const ImageView = () => {
gravity: 10,
linkDistance: smallSchema ? 240 : 150,
}}
- onDoubleClick={handleDoubleClick}
+ onDoubleClick={canWrite ? handleDoubleClick : undefined}
nodeTooltip={renderVertexTooltip}
edgeTooltip={renderEdgeTooltip}
height={600}
@@ -498,55 +517,57 @@ const ImageView = () => {
)}
</Spin>
- <Modal
- open={templateVisible}
- title={t('schema.image_view.create_from_template')}
- okText={t('schema.image_view.apply_template')}
- cancelText={t('common.action.cancel')}
- confirmLoading={templateApplying}
- okButtonProps={{
- disabled: templateLoading || templateLoadError || !selectedTemplate,
- }}
- onOk={applySchemaTemplate}
- onCancel={closeTemplatePicker}
- destroyOnClose
- >
- <Spin spinning={templateLoading}>
- {templateLoadError ? (
- <Alert
- type='error'
- showIcon
- message={t('schema.image_view.template_load_failed')}
- action={(
- <Button size='small' onClick={loadSchemaTemplates}>
- {t('schema.image_view.retry_templates')}
- </Button>
- )}
- />
- ) : (
- <Space direction='vertical' size='middle' style={{width: '100%'}}>
- <Typography.Text>
- {t('schema.image_view.template_picker_help')}
- </Typography.Text>
- <Select
- aria-label={t('schema.image_view.template_select')}
- placeholder={t('schema.image_view.template_placeholder')}
- value={selectedTemplate}
- options={templateOptions}
- onChange={setSelectedTemplate}
- style={{width: '100%'}}
+ {canWrite && (
+ <Modal
+ open={templateVisible}
+ title={t('schema.image_view.create_from_template')}
+ okText={t('schema.image_view.apply_template')}
+ cancelText={t('common.action.cancel')}
+ confirmLoading={templateApplying}
+ okButtonProps={{
+ disabled: templateLoading || templateLoadError || !selectedTemplate,
+ }}
+ onOk={applySchemaTemplate}
+ onCancel={closeTemplatePicker}
+ destroyOnClose
+ >
+ <Spin spinning={templateLoading}>
+ {templateLoadError ? (
+ <Alert
+ type='error'
+ showIcon
+ message={t('schema.image_view.template_load_failed')}
+ action={(
+ <Button size='small' onClick={loadSchemaTemplates}>
+ {t('schema.image_view.retry_templates')}
+ </Button>
+ )}
/>
- {!savedOptions.length && (
- <Typography.Text type='secondary'>
- {t('schema.image_view.no_saved_templates')}
+ ) : (
+ <Space direction='vertical' size='middle' style={{width: '100%'}}>
+ <Typography.Text>
+ {t('schema.image_view.template_picker_help')}
</Typography.Text>
- )}
- </Space>
- )}
- </Spin>
- </Modal>
+ <Select
+ aria-label={t('schema.image_view.template_select')}
+ placeholder={t('schema.image_view.template_placeholder')}
+ value={selectedTemplate}
+ options={templateOptions}
+ onChange={setSelectedTemplate}
+ style={{width: '100%'}}
+ />
+ {!savedOptions.length && (
+ <Typography.Text type='secondary'>
+ {t('schema.image_view.no_saved_templates')}
+ </Typography.Text>
+ )}
+ </Space>
+ )}
+ </Spin>
+ </Modal>
+ )}
- <EditVertexLayer
+ {canWrite && <EditVertexLayer
visible={vertexVisible}
onCancle={hideVertexLayer}
graph={graph}
@@ -554,9 +575,9 @@ const ImageView = () => {
refresh={handleRefresh}
name={vertexName}
propertyList={propertyList}
- />
+ />}
- <EditEdgeLayer
+ {canWrite && <EditEdgeLayer
visible={edgeVisible}
graphspace={graphspace}
graph={graph}
@@ -565,15 +586,15 @@ const ImageView = () => {
name={edgeName}
propertyList={propertyList}
vertexList={vertexList}
- />
+ />}
- <EditPropertyLayer
+ {canWrite && <EditPropertyLayer
visible={propertyVisible}
onCancle={hidePropertyLayer}
graphspace={graphspace}
graph={graph}
refresh={handleRefresh}
- />
+ />}
<Drawer
open={propertyListVisible}
@@ -582,7 +603,11 @@ const ImageView = () => {
mask={false}
title={t('schema.image_view.view_properties')}
>
- <PropertyTable noHeader forceRefresh={refresh} />
+ <PropertyTable
+ noHeader
+ forceRefresh={refresh}
+ canWrite={canWrite}
+ />
</Drawer>
</div>
);
diff --git a/hugegraph-hubble/hubble-fe/src/pages/Meta/ImageView.test.js b/hugegraph-hubble/hubble-fe/src/pages/Meta/ImageView.test.js
index a887eaee0..e1e2ca49c 100644
--- a/hugegraph-hubble/hubble-fe/src/pages/Meta/ImageView.test.js
+++ b/hugegraph-hubble/hubble-fe/src/pages/Meta/ImageView.test.js
@@ -22,6 +22,7 @@ import ImageView from './ImageView';
import * as api from '../../api';
let mockRouteParams = {graphspace: 'space-a', graph: 'graph-a'};
+let mockCanWrite = true;
jest.mock('antd', () => {
const actual = jest.requireActual('antd');
@@ -50,6 +51,9 @@ jest.mock('../../api', () => ({
addGraphSchema: jest.fn(),
},
}));
+jest.mock('../../auth/graphspaceAccess', () => ({
+ useGraphspaceAccess: () => ({canWrite: mockCanWrite}),
+}));
jest.mock('../../components/GraphinView', () => props => {
const node = props.data.nodes?.[0];
@@ -118,6 +122,7 @@ jest.mock('./Property', () => () => null);
beforeEach(() => {
jest.clearAllMocks();
mockRouteParams = {graphspace: 'space-a', graph: 'graph-a'};
+ mockCanWrite = true;
window.matchMedia = jest.fn().mockImplementation(query => ({
matches: false,
media: query,
@@ -526,6 +531,41 @@ test('opens schema editing on double click but not on single click', async () =>
.toHaveTextContent('person'));
});
+test('keeps Schema controls read-only without a write scope', async () => {
+ mockCanWrite = false;
+ loadSchema({vertices: [schemaVertex('person')]});
+
+ render(<ImageView />);
+
+ await waitForPresentation('person');
+ expect(screen.queryByRole('button', {name: 'schema.property.create'}))
+ .not.toBeInTheDocument();
+ expect(screen.queryByRole('button', {name: 'schema.vertex.create'}))
+ .not.toBeInTheDocument();
+ expect(screen.queryByRole('button', {name: 'schema.edge.form.title_create'}))
+ .not.toBeInTheDocument();
+ expect(screen.getByRole('button', {name: 'schema.image_view.view_properties'}))
+ .toBeInTheDocument();
+ expect(screen.queryByText('schema.image_view.hover.edit_hint'))
+ .not.toBeInTheDocument();
+ expect(screen.queryByTestId('vertex-edit-layer')).not.toBeInTheDocument();
+
+ fireEvent.doubleClick(screen.getByTestId('schema-node-double-click'));
+ expect(screen.queryByTestId('vertex-edit-layer')).not.toBeInTheDocument();
+});
+
+test('explains an empty Schema without offering mutations to a read-only account', async () => {
+ mockCanWrite = false;
+
+ render(<ImageView />);
+
+ expect(await screen.findByText('schema.image_view.read_only_empty'))
+ .toBeInTheDocument();
+ expect(screen.queryByRole('button', {
+ name: 'schema.image_view.create_from_template',
+ })).not.toBeInTheDocument();
+});
+
test('links safely to the official HugeGraph SchemaLabel documentation', async () => {
loadSchema({vertices: [schemaVertex('person')]});
diff --git a/hugegraph-hubble/hubble-fe/src/pages/Meta/ListView.js b/hugegraph-hubble/hubble-fe/src/pages/Meta/ListView.js
index a24c01f08..c5fb1d7cb 100644
--- a/hugegraph-hubble/hubble-fe/src/pages/Meta/ListView.js
+++ b/hugegraph-hubble/hubble-fe/src/pages/Meta/ListView.js
@@ -23,9 +23,13 @@ import EdgeTable from './Edge';
import VertexIndexTable from './VertexIndex';
import EdgeIndexTable from './EdgeIndex';
import {useTranslation} from 'react-i18next';
+import {useParams} from 'react-router-dom';
+import {useGraphspaceAccess} from '../../auth/graphspaceAccess';
const ListView = () => {
const {t} = useTranslation();
+ const {graphspace} = useParams();
+ const {canWrite} = useGraphspaceAccess(graphspace);
return (
<Tabs
defaultActiveKey='1'
@@ -34,17 +38,17 @@ const ListView = () => {
{
label: t('schema.tab.property'),
key: '1',
- children: <PropertyTable />,
+ children: <PropertyTable canWrite={canWrite} />,
},
{
label: t('schema.tab.vertex'),
key: '2',
- children: <VertexTable />,
+ children: <VertexTable canWrite={canWrite} />,
},
{
label: t('schema.tab.edge'),
key: '3',
- children: <EdgeTable />,
+ children: <EdgeTable canWrite={canWrite} />,
},
{
label: t('schema.tab.vertex_index'),
diff --git a/hugegraph-hubble/hubble-fe/src/pages/Meta/Property/index.js b/hugegraph-hubble/hubble-fe/src/pages/Meta/Property/index.js
index 6fb76612e..b1983725e 100644
--- a/hugegraph-hubble/hubble-fe/src/pages/Meta/Property/index.js
+++ b/hugegraph-hubble/hubble-fe/src/pages/Meta/Property/index.js
@@ -29,7 +29,7 @@ import MetaTableStatus from '../common/MetaTableStatus';
const PROPERTY_IN_USE_KEY = 'schema.property.in_use';
const DELETE_REQUEST_CONFIG = {suppressBusinessErrorToast: true};
-const PropertyTable = ({noHeader, forceRefresh}) => {
+const PropertyTable = ({noHeader, forceRefresh, canWrite = true}) => {
const [editLayerVisible, setEditLayerVisible] = useState(false);
const [refresh, setRefresh] = useState(false);
const [selectedItems, setSelectedItems] = useState([]);
@@ -134,7 +134,7 @@ const PropertyTable = ({noHeader, forceRefresh}) => {
align: 'center',
render: val => val.toLocaleLowerCase(),
},
- {
+ canWrite && {
title: t('schema.property.col.operation'),
width: 120,
align: 'center',
@@ -144,7 +144,7 @@ const PropertyTable = ({noHeader, forceRefresh}) => {
</RowActionButton>
),
},
- ];
+ ].filter(Boolean);
return (
<>
@@ -153,9 +153,17 @@ const PropertyTable = ({noHeader, forceRefresh}) => {
<Row>
<Col>
<Space>
- <Button type='primary' onClick={handleShowLayer}>{t('common.action.create')}</Button>
+ {canWrite && (
+ <Button type='primary' onClick={handleShowLayer}>
+ {t('common.action.create')}
+ </Button>
+ )}
<Button onClick={handleRefresh}>{t('common.action.refresh')}</Button>
- <Button onClick={handleDeleteBatch}>{t('schema.common.batch_delete')}</Button>
+ {canWrite && (
+ <Button onClick={handleDeleteBatch}>
+ {t('schema.common.batch_delete')}
+ </Button>
+ )}
</Space>
</Col>
</Row>
@@ -167,7 +175,7 @@ const PropertyTable = ({noHeader, forceRefresh}) => {
<Table
columns={columns}
dataSource={data}
- rowSelection={noHeader ? null : {
+ rowSelection={noHeader || !canWrite ? null : {
type: 'checkbox',
onChange: selectedRowKeys => {
setSelectedItems(selectedRowKeys);
@@ -179,7 +187,7 @@ const PropertyTable = ({noHeader, forceRefresh}) => {
loading={loading}
/>
- {!noHeader
+ {!noHeader && canWrite
&& (
<EditPropertyLayer
visible={editLayerVisible}
diff --git a/hugegraph-hubble/hubble-fe/src/pages/Meta/Vertex/index.js b/hugegraph-hubble/hubble-fe/src/pages/Meta/Vertex/index.js
index e7fd924ec..11f3824fb 100644
--- a/hugegraph-hubble/hubble-fe/src/pages/Meta/Vertex/index.js
+++ b/hugegraph-hubble/hubble-fe/src/pages/Meta/Vertex/index.js
@@ -30,7 +30,7 @@ import * as api from '../../../api';
const VERTEX_IN_USE_KEY = 'schema.vertex.in_use';
const DELETE_REQUEST_CONFIG = {suppressBusinessErrorToast: true};
-const VertexTable = () => {
+const VertexTable = ({canWrite = true}) => {
const [editLayerVisible, setEditLayerVisible] = useState(false);
const [refresh, setRefresh] = useState(false);
const [selectedItems, setSelectedItems] = useState([]);
@@ -152,7 +152,7 @@ const VertexTable = () => {
ellipsis: true,
render: val => val.map(item => item.name).join(';'),
},
- {
+ canWrite && {
title: t('common.operation'),
align: 'center',
render: val => (
@@ -166,7 +166,7 @@ const VertexTable = () => {
</Space>
),
},
- ];
+ ].filter(Boolean);
useEffect(() => {
api.manage.getMetaPropertyList(graphspace, graph, {page_size: -1}).then(res => {
@@ -184,9 +184,17 @@ const VertexTable = () => {
<>
<TableHeader>
<Space>
- <Button type='primary' onClick={handleCreate}>{t('common.create')}</Button>
+ {canWrite && (
+ <Button type='primary' onClick={handleCreate}>
+ {t('common.create')}
+ </Button>
+ )}
<Button onClick={handleRefresh}>{t('common.refresh')}</Button>
- <Button onClick={handleDeleteBatch}>{t('common.batch_delete')}</Button>
+ {canWrite && (
+ <Button onClick={handleDeleteBatch}>
+ {t('common.batch_delete')}
+ </Button>
+ )}
</Space>
</TableHeader>
@@ -194,12 +202,12 @@ const VertexTable = () => {
<Table
columns={columns}
dataSource={data}
- rowSelection={{
+ rowSelection={canWrite ? {
type: 'checkbox',
onChange: selectedRowKeys => {
setSelectedItems(selectedRowKeys);
},
- }}
+ } : null}
pagination={pagination}
onChange={handleTable}
rowKey={rowKey}
@@ -207,7 +215,7 @@ const VertexTable = () => {
scroll={{x: 'max-content'}}
/>
- <EditVertexLayer
+ {canWrite && <EditVertexLayer
visible={editLayerVisible}
onCancle={handleHideLayer}
graph={graph}
@@ -215,7 +223,7 @@ const VertexTable = () => {
refresh={handleRefresh}
name={vertexName}
propertyList={propertyList}
- />
+ />}
</>
);
};
diff --git a/hugegraph-hubble/hubble-fe/src/pages/Meta/meta-read-only.test.js b/hugegraph-hubble/hubble-fe/src/pages/Meta/meta-read-only.test.js
new file mode 100644
index 000000000..86743812b
--- /dev/null
+++ b/hugegraph-hubble/hubble-fe/src/pages/Meta/meta-read-only.test.js
@@ -0,0 +1,141 @@
+/*
+ *
+ * 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 {render, screen} from '@testing-library/react';
+import PropertyTable from './Property';
+import VertexTable from './Vertex';
+import EdgeTable from './Edge';
+import * as api from '../../api';
+
+let mockRows = [];
+
+jest.mock('react-i18next', () => ({
+ useTranslation: () => ({t: key => key}),
+}));
+
+jest.mock('react-router-dom', () => ({
+ useParams: () => ({graphspace: 'space', graph: 'graph'}),
+}));
+
+jest.mock('./common/useMetaTable', () => () => ({
+ data: mockRows,
+ pagination: {current: 1, pageSize: 10, total: mockRows.length},
+ loading: false,
+ error: false,
+ retry: jest.fn(),
+ handleTable: jest.fn(),
+}));
+
+jest.mock('./Property/EditLayer', () => ({EditPropertyLayer: () => (
+ <div>property editor</div>
+)}));
+jest.mock('./Vertex/EditLayer', () => ({EditVertexLayer: () => (
+ <div>vertex editor</div>
+)}));
+jest.mock('./Edge/EditLayer', () => ({EditEdgeLayer: () => (
+ <div>edge editor</div>
+)}));
+
+jest.mock('../../api', () => ({
+ manage: {
+ getMetaPropertyList: jest.fn(),
+ getMetaVertexList: jest.fn(),
+ },
+}));
+
+beforeEach(() => {
+ window.matchMedia = jest.fn().mockImplementation(query => ({
+ matches: false,
+ media: query,
+ addListener: jest.fn(),
+ removeListener: jest.fn(),
+ addEventListener: jest.fn(),
+ removeEventListener: jest.fn(),
+ }));
+});
+
+beforeEach(() => {
+ jest.clearAllMocks();
+ mockRows = [];
+ api.manage.getMetaPropertyList.mockReturnValue(new Promise(() => {}));
+ api.manage.getMetaVertexList.mockReturnValue(new Promise(() => {}));
+});
+
+test('keeps the property table read-only', () => {
+ mockRows = [{
+ name: 'name',
+ data_type: 'TEXT',
+ cardinality: 'SINGLE',
+ }];
+
+ render(<PropertyTable canWrite={false} />);
+
+ expect(screen.getByText('name')).toBeInTheDocument();
+ expect(screen.getByRole('button', {name: 'common.action.refresh'}))
+ .toBeInTheDocument();
+ expect(screen.queryByRole('button', {name: 'common.action.create'}))
+ .not.toBeInTheDocument();
+ expect(screen.queryByText('common.action.delete')).not.toBeInTheDocument();
+ expect(screen.queryByText('property editor')).not.toBeInTheDocument();
+});
+
+test('keeps the vertex table read-only', () => {
+ mockRows = [{
+ name: 'person',
+ properties: [],
+ id_strategy: 'PRIMARY_KEY',
+ primary_keys: [],
+ open_label_index: false,
+ property_indexes: [],
+ }];
+
+ render(<VertexTable canWrite={false} />);
+
+ expect(screen.getByText('person')).toBeInTheDocument();
+ expect(screen.getByRole('button', {name: 'common.refresh'}))
+ .toBeInTheDocument();
+ expect(screen.queryByRole('button', {name: 'common.create'}))
+ .not.toBeInTheDocument();
+ expect(screen.queryByText('common.edit')).not.toBeInTheDocument();
+ expect(screen.queryByText('common.delete')).not.toBeInTheDocument();
+ expect(screen.queryByText('vertex editor')).not.toBeInTheDocument();
+});
+
+test('keeps the edge table read-only', () => {
+ mockRows = [{
+ name: 'knows',
+ edgelabel_type: 'NORMAL',
+ source_label: 'person',
+ target_label: 'person',
+ properties: [],
+ sort_keys: [],
+ open_label_index: false,
+ property_indexes: [],
+ }];
+
+ render(<EdgeTable canWrite={false} />);
+
+ expect(screen.getByText('knows')).toBeInTheDocument();
+ expect(screen.getByRole('button', {name: 'common.refresh'}))
+ .toBeInTheDocument();
+ expect(screen.queryByRole('button', {name: 'common.create'}))
+ .not.toBeInTheDocument();
+ expect(screen.queryByText('common.edit')).not.toBeInTheDocument();
+ expect(screen.queryByText('common.delete')).not.toBeInTheDocument();
+ expect(screen.queryByText('edge editor')).not.toBeInTheDocument();
+});
diff --git a/hugegraph-hubble/hubble-fe/src/pages/Schema/index.js b/hugegraph-hubble/hubble-fe/src/pages/Schema/index.js
index 23dc2a1b7..c6514214f 100644
--- a/hugegraph-hubble/hubble-fe/src/pages/Schema/index.js
+++ b/hugegraph-hubble/hubble-fe/src/pages/Schema/index.js
@@ -31,6 +31,8 @@ import CodeEditor from '../../components/CodeEditor';
import {BUILTIN_SCHEMA_TEMPLATES} from './builtinSchemaTemplates';
import {isPdEnabled} from '../../utils/config';
import {readWorkbenchGraphContext} from '../../utils/workbenchGraphContext';
+import {useGraphspaceAccess} from '../../auth/graphspaceAccess';
+import {useAuthContext} from '../../auth/AuthContext';
const PAGE_ERROR_CONFIG = {suppressBusinessErrorToast: true};
const HIDDEN_BUILTINS_KEY = 'hubble.schema.hiddenBuiltinStartingPoints.v1';
@@ -106,6 +108,10 @@ const Schema = () => {
const {graphspace} = useParams();
const navigate = useNavigate();
const pdMode = isPdEnabled();
+ const {canManage, canWrite} = useGraphspaceAccess(graphspace);
+ const {context: authContext} = useAuthContext();
+ const username = authContext?.username;
+ const templateWriteEnabled = pdMode && canWrite;
const workbenchContext = readWorkbenchGraphContext();
const currentGraph = workbenchContext.graphspace === graphspace
? workbenchContext.graph
@@ -117,17 +123,27 @@ const Schema = () => {
const {current} = pagination;
const listKey = JSON.stringify([graphspace, query, current]);
+ const canEditTemplate = useCallback(row => (
+ canManage || (canWrite && row.creator === username)
+ ), [canManage, canWrite, username]);
+
const editSchema = useCallback(data => {
+ if (!canEditTemplate(data)) {
+ return;
+ }
setMode('edit');
setDetail(data);
setEditLayer(true);
- }, []);
+ }, [canEditTemplate]);
const createSchema = useCallback((startingPoint = {}) => {
+ if (!templateWriteEnabled) {
+ return;
+ }
setMode('create');
setDetail(startingPoint);
setEditLayer(true);
- }, []);
+ }, [templateWriteEnabled]);
const applyBuiltin = useCallback(name => {
createSchema({name, schema: BUILTIN_SCHEMA_TEMPLATES[name]});
@@ -155,10 +171,10 @@ const Schema = () => {
useEffect(() => {
const params = new URLSearchParams(window.location.search);
- if (pdMode && params.get('create') === 'true') {
+ if (templateWriteEnabled && params.get('create') === 'true') {
createSchema();
}
- }, [createSchema, pdMode]);
+ }, [createSchema, templateWriteEnabled]);
const handleTable = useCallback(newPagination => {
setPagination(newPagination);
@@ -179,6 +195,9 @@ const Schema = () => {
}, []);
const deleteSchema = useCallback(row => {
+ if (!canEditTemplate(row)) {
+ return;
+ }
Modal.confirm({
title: t('schema_template.delete_confirm', {name: row.name}),
onOk: () => {
@@ -193,7 +212,7 @@ const Schema = () => {
}).catch(() => message.error(t('common.msg.operation_failed')));
},
});
- }, [graphspace, t]);
+ }, [canEditTemplate, graphspace, t]);
const handleBack = useCallback(() => navigate('/graphspace'), [navigate]);
const hideEditLayer = useCallback(() => setEditLayer(false), []);
@@ -219,10 +238,10 @@ const Schema = () => {
dataIndex: 'creator',
},
];
- if (pdMode) {
+ if (templateWriteEnabled) {
columns.push({
title: t('schema_template.column.operation'),
- render: row => (
+ render: row => canEditTemplate(row) && (
<SchemaActions
row={row}
onEdit={editSchema}
@@ -314,7 +333,7 @@ const Schema = () => {
: {};
const visibleData = listDataKey === listKey ? data : [];
const visibleBuiltins = Object.entries(BUILTIN_SCHEMA_TEMPLATES).filter(
- ([name]) => !pdMode || !hiddenBuiltins.includes(name)
+ ([name]) => !templateWriteEnabled || !hiddenBuiltins.includes(name)
);
const visibleGraphspaceName = graphspace === 'DEFAULT'
? t('graphspace.default_name')
@@ -338,7 +357,7 @@ const Schema = () => {
>
<Row justify='space-between'>
<Col>
- {pdMode && (
+ {templateWriteEnabled && (
<Space>
<Button type='primary' onClick={openCreate}>
{t('schema_template.create')}
@@ -361,13 +380,13 @@ const Schema = () => {
<DataPreparationNav active='schema' graphspace={graphspace} />
<div className='container'>
- {!pdMode && (
+ {!templateWriteEnabled && (
<Alert
showIcon
type='info'
message={t('schema_template.read_only.title')}
description={t('schema_template.read_only.description')}
- action={(
+ action={!pdMode ? (
<Button type='primary' href={templateApplyPath}>
{currentGraph
? t('schema_template.read_only.apply_to_graph', {
@@ -375,7 +394,7 @@ const Schema = () => {
})
: t('schema_template.read_only.choose_graph')}
</Button>
- )}
+ ) : undefined}
/>
)}
{graphspaceError && graphspaceDataKey === graphspace && (
@@ -443,7 +462,7 @@ const Schema = () => {
</Empty>
) : (
<Empty description={t('schema_template.empty')}>
- {pdMode && (
+ {templateWriteEnabled && (
<Button type='primary' onClick={openCreate}>
{t('schema_template.create')}
</Button>
@@ -464,7 +483,7 @@ const Schema = () => {
{t('schema_template.builtin_section.description')}
</Typography.Paragraph>
</Col>
- {pdMode && hiddenBuiltins.length > 0 && (
+ {templateWriteEnabled && hiddenBuiltins.length > 0 && (
<Col>
<Button onClick={restoreBuiltins}>
{t('schema_template.builtin_section.restore')}
@@ -478,7 +497,7 @@ const Schema = () => {
<Card
size='small'
title={t(`schema_template.builtin.${name}`)}
- extra={pdMode ? (
+ extra={templateWriteEnabled ? (
<Space size={4}>
<Button
type='link'
@@ -514,7 +533,7 @@ const Schema = () => {
<Typography.Paragraph type='secondary'>
{t(`schema_template.builtin_description.${name}`)}
</Typography.Paragraph>
- {!pdMode && (
+ {!templateWriteEnabled && (
<CodeEditor
value={schema}
lang='groovy'
@@ -536,7 +555,7 @@ const Schema = () => {
{t('schema_template.docs.link')}
</a>
</Typography.Paragraph>
- {pdMode && (
+ {templateWriteEnabled && (
<EditLayer
visible={editLayer}
detail={detail}
diff --git a/hugegraph-hubble/hubble-fe/src/pages/Schema/schema-list-recovery.test.js b/hugegraph-hubble/hubble-fe/src/pages/Schema/schema-list-recovery.test.js
index 5c159d49d..e1dce7c69 100644
--- a/hugegraph-hubble/hubble-fe/src/pages/Schema/schema-list-recovery.test.js
+++ b/hugegraph-hubble/hubble-fe/src/pages/Schema/schema-list-recovery.test.js
@@ -23,6 +23,8 @@ import * as api from '../../api';
let mockGraphspace = 'SPACE';
let mockPdEnabled = true;
let mockWorkbenchContext = {};
+let mockAccess = {canManage: true, canWrite: true};
+let mockAuthContext = {context: {username: 'alice'}};
const mockTranslate = (key, values) => ({
'schema_template.title': `${values?.name || 'unknown'} - Schema templates`,
'schema_template.create': 'Create template',
@@ -96,6 +98,12 @@ jest.mock('../../utils/config', () => ({
jest.mock('../../utils/workbenchGraphContext', () => ({
readWorkbenchGraphContext: () => mockWorkbenchContext,
}));
+jest.mock('../../auth/graphspaceAccess', () => ({
+ useGraphspaceAccess: () => mockAccess,
+}));
+jest.mock('../../auth/AuthContext', () => ({
+ useAuthContext: () => mockAuthContext,
+}));
jest.mock('react-router-dom', () => ({
useNavigate: () => jest.fn(),
useParams: () => ({graphspace: mockGraphspace}),
@@ -121,6 +129,8 @@ afterEach(() => {
mockGraphspace = 'SPACE';
mockPdEnabled = true;
mockWorkbenchContext = {};
+ mockAccess = {canManage: true, canWrite: true};
+ mockAuthContext = {context: {username: 'alice'}};
jest.clearAllMocks();
window.localStorage.clear();
});
@@ -165,6 +175,70 @@ it('keeps non-PD Schema templates accessible as a read-only library', async () =
await waitForLoadingToFinish();
});
+it('keeps a PD read-only account from mutating schema templates', async () => {
+ mockAccess = {canManage: false, canWrite: false};
+ window.history.replaceState({}, '', '/graphspace/SPACE/schema?create=true');
+ api.manage.getGraphSpace.mockResolvedValue({
+ status: 200,
+ data: {nickname: 'Space'},
+ });
+ api.manage.getSchemaList.mockResolvedValue({
+ status: 200,
+ data: {
+ records: [{
+ name: 'saved_schema',
+ creator: 'alice',
+ schema: 'schema.propertyKey("name").asText().create()',
+ }],
+ total: 1,
+ },
+ });
+
+ render(<Schema />);
+
+ expect(await screen.findByText('saved_schema')).toBeInTheDocument();
+ expect(screen.queryByRole('button', {name: 'Create template'}))
+ .not.toBeInTheDocument();
+ expect(screen.queryByRole('button', {name: 'Edit saved_schema'}))
+ .not.toBeInTheDocument();
+ expect(screen.queryByRole('button', {name: 'Delete saved_schema'}))
+ .not.toBeInTheDocument();
+ expect(screen.queryByRole('button', {name: 'Use example People network'}))
+ .not.toBeInTheDocument();
+ expect(screen.queryByTestId('schema-edit-layer')).not.toBeInTheDocument();
+});
+
+it('lets read-write users manage only their own saved templates', async () => {
+ mockAccess = {canManage: false, canWrite: true};
+ api.manage.getGraphSpace.mockResolvedValue({
+ status: 200,
+ data: {nickname: 'Space'},
+ });
+ api.manage.getSchemaList.mockResolvedValue({
+ status: 200,
+ data: {
+ records: [
+ {name: 'owned_schema', creator: 'alice'},
+ {name: 'shared_schema', creator: 'bob'},
+ ],
+ total: 2,
+ },
+ });
+
+ render(<Schema />);
+
+ expect(await screen.findByRole('button', {name: 'Create template'}))
+ .toBeInTheDocument();
+ expect(screen.getByRole('button', {name: 'Edit owned_schema'}))
+ .toBeInTheDocument();
+ expect(screen.getByRole('button', {name: 'Delete owned_schema'}))
+ .toBeInTheDocument();
+ expect(screen.queryByRole('button', {name: 'Edit shared_schema'}))
+ .not.toBeInTheDocument();
+ expect(screen.queryByRole('button', {name: 'Delete shared_schema'}))
+ .not.toBeInTheDocument();
+});
+
it('links a non-PD read-only library without graph context to the graph overview', async () => {
mockGraphspace = 'DEFAULT';
mockPdEnabled = false;
diff --git a/hugegraph-hubble/hubble-fe/src/utils/rules.test.js b/hugegraph-hubble/hubble-fe/src/utils/rules.test.js
index c84bf35b9..662d39e0a 100644
--- a/hugegraph-hubble/hubble-fe/src/utils/rules.test.js
+++ b/hugegraph-hubble/hubble-fe/src/utils/rules.test.js
@@ -37,7 +37,8 @@ jest.mock('../i18n', () => ({
'common.validation.jdbc_rule':
'Enter a valid JDBC URL, for example: jdbc:mysql://127.0.0.1:3306/db_name',
'common.validation.account_name_rule':
- 'Account name must be within 16 characters and cannot start or end with an underscore',
+ 'Use 1–16 characters without spaces; letters, numbers, Chinese/CJK '
+ + 'forms, and underscores are supported; underscores cannot be first or last',
'common.validation.favorite_name_rule':
'Use Chinese characters, letters, numbers, or underscores only, up to 48 characters',
'common.validation.invalid_data_format': 'Invalid data format',
@@ -54,7 +55,9 @@ jest.mock('../i18n', () => ({
'common.validation.normal_name_rule': '只能包含中文、字母、数字、_,最多 48 个字符',
'common.validation.jdbc_rule':
'请输入正确的jdbc url, 例如:jdbc:mysql://127.0.0.1:3306/db_name',
- 'common.validation.account_name_rule': '账号名不超过16个字符,且不能以下划线开始和结尾',
+ 'common.validation.account_name_rule':
+ '使用 1–16 个不含空格的字符,支持中文/东亚兼容字符、字母、数字和下划线;'
+ + '下划线不能位于首尾',
'common.validation.favorite_name_rule': '只能包含中文、字母、数字、_, 不能超过48个字符',
'common.validation.invalid_data_format': '非法的数据格式',
},
@@ -124,7 +127,8 @@ describe('rules i18n defaults', () => {
],
[
rules.isAccountName(),
- 'Account name must be within 16 characters and cannot start or end with an underscore',
+ 'Use 1–16 characters without spaces; letters, numbers, Chinese/CJK '
+ + 'forms, and underscores are supported; underscores cannot be first or last',
],
[rules.isUUID(), 'Invalid data format'],
[rules.isInt(), 'Invalid data format'],
@@ -144,8 +148,19 @@ describe('rules i18n defaults', () => {
});
it('rejects invalid account names with an Error object', async () => {
- await expect(rules.isAccountName().validator(null, 'name_too_long_123'))
- .rejects.toBeInstanceOf(Error);
+ const validator = rules.isAccountName().validator;
+
+ await expect(validator(null, '中文_Name123')).resolves.toBeUndefined();
+ await expect(validator(null, 'ABC123')).resolves.toBeUndefined();
+ for (const value of [
+ 'name with space',
+ '_leading',
+ 'trailing_',
+ '',
+ '12345678901234567',
+ ]) {
+ await expect(validator(null, value)).rejects.toBeInstanceOf(Error);
+ }
});
it('accepts only backend-compatible favorite names', async () => {
@@ -177,7 +192,11 @@ describe('rules i18n defaults', () => {
[rules.isPropertyName(), '只能包含中文、字母、数字、_'],
[rules.isNoramlName(), '只能包含中文、字母、数字、_,最多 48 个字符'],
[rules.isJDBC(), '请输入正确的jdbc url, 例如:jdbc:mysql://127.0.0.1:3306/db_name'],
- [rules.isAccountName(), '账号名不超过16个字符,且不能以下划线开始和结尾'],
+ [
+ rules.isAccountName(),
+ '使用 1–16 个不含空格的字符,支持中文/东亚兼容字符、字母、数字和下划线;'
+ + '下划线不能位于首尾',
+ ],
[rules.isFavoriteName(), '只能包含中文、字母、数字、_, 不能超过48个字符'],
[rules.isUUID(), '非法的数据格式'],
[rules.isInt(), '非法的数据格式'],