imbajin commented on code in PR #3008:
URL: https://github.com/apache/hugegraph/pull/3008#discussion_r3142071558
##########
hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/profile/GraphsAPI.java:
##########
@@ -136,6 +223,61 @@ public Object get(@Context GraphManager manager,
return ImmutableMap.of("name", g.name(), "backend", g.backend());
}
+ @GET
Review Comment:
‼️ **Critical: Using `GET` for state-changing operations violates REST
semantics**
Both `setDefault` and `unsetDefault` modify server state (they call
`authManager.setDefaultGraph` / `unsetDefaultGraph`) but use `@GET`. This is a
serious REST anti-pattern that can cause:
- **Browser/proxy prefetching** triggering unintended state changes
- **HTTP caches** serving stale responses instead of forwarding the request
- **Crawlers/link scanners** accidentally modifying user default graphs
These should use `@POST` (or `@PUT`) and `@DELETE` (or `@POST`) respectively:
```suggestion
@POST
@Timed
@Path("{name}/default")
```
##########
hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/space/SchemaTemplateAPI.java:
##########
@@ -0,0 +1,197 @@
+/*
+ * 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.api.space;
+
+import java.util.Date;
+import java.util.Set;
+
+import org.apache.commons.lang3.StringUtils;
+import org.apache.hugegraph.api.API;
+import org.apache.hugegraph.api.filter.StatusFilter;
+import org.apache.hugegraph.auth.HugeGraphAuthProxy;
+import org.apache.hugegraph.core.GraphManager;
+import org.apache.hugegraph.define.Checkable;
+import org.apache.hugegraph.exception.HugeException;
+import org.apache.hugegraph.server.RestServer;
+import org.apache.hugegraph.space.SchemaTemplate;
+import org.apache.hugegraph.util.E;
+import org.apache.hugegraph.util.Log;
+import org.slf4j.Logger;
+
+import com.codahale.metrics.annotation.Timed;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.google.common.collect.ImmutableMap;
+
+import io.swagger.v3.oas.annotations.tags.Tag;
+import jakarta.inject.Singleton;
+import jakarta.ws.rs.Consumes;
+import jakarta.ws.rs.DELETE;
+import jakarta.ws.rs.GET;
+import jakarta.ws.rs.POST;
+import jakarta.ws.rs.PUT;
+import jakarta.ws.rs.Path;
+import jakarta.ws.rs.PathParam;
+import jakarta.ws.rs.Produces;
+import jakarta.ws.rs.core.Context;
+import jakarta.ws.rs.core.SecurityContext;
+
+@Path("graphspaces/{graphspace}/schematemplates")
+@Singleton
+@Tag(name = "SchemaTemplateAPI")
+public class SchemaTemplateAPI extends API {
+
+ private static final Logger LOG = Log.logger(RestServer.class);
+
+ @GET
+ @Timed
+ @Produces(APPLICATION_JSON_WITH_CHARSET)
+ public Object list(@Context GraphManager manager,
+ @PathParam("graphspace") String graphSpace) {
+ LOG.debug("List all schema templates for graph space {}", graphSpace);
+
+ Set<String> templates = manager.schemaTemplates(graphSpace);
+ return ImmutableMap.of("schema_templates", templates);
+ }
+
+ @GET
+ @Timed
+ @Path("{name}")
+ @Produces(APPLICATION_JSON_WITH_CHARSET)
+ public Object get(@Context GraphManager manager,
+ @PathParam("graphspace") String graphSpace,
+ @PathParam("name") String name) {
+ LOG.debug("Get schema template by name '{}' for graph space {}",
+ name, graphSpace);
+
+ return manager.serializer().writeSchemaTemplate(
+ schemaTemplate(manager, graphSpace, name));
+ }
+
+ @POST
+ @Timed
+ @StatusFilter.Status(StatusFilter.Status.CREATED)
+ @Consumes(APPLICATION_JSON)
+ @Produces(APPLICATION_JSON_WITH_CHARSET)
+ public String create(@Context GraphManager manager,
+ @PathParam("graphspace") String graphSpace,
+ JsonSchemaTemplate jsonSchemaTemplate) {
+ LOG.debug("Create schema template {} for graph space: '{}'",
+ jsonSchemaTemplate, graphSpace);
+ jsonSchemaTemplate.checkCreate(false);
+
+ E.checkArgument(manager.graphSpace(graphSpace) != null,
+ "The graph space '%s' is not exist", graphSpace);
+
+ SchemaTemplate template = jsonSchemaTemplate.toSchemaTemplate();
+ template.create(new Date());
+ template.creator(HugeGraphAuthProxy.username());
+ manager.createSchemaTemplate(graphSpace, template);
+ return manager.serializer().writeSchemaTemplate(template);
+ }
+
+ @DELETE
+ @Timed
+ @Path("{name}")
+ @Produces(APPLICATION_JSON_WITH_CHARSET)
+ public void delete(@Context GraphManager manager,
+ @PathParam("graphspace") String graphSpace,
+ @PathParam("name") String name,
+ @Context SecurityContext sc) {
+ LOG.debug("Remove schema template by name '{}' for graph space",
+ name, graphSpace);
Review Comment:
‼️ **Bug: LOG format string has one `{}` placeholder but two arguments**
The format string `"Remove schema template by name '{}' for graph space"`
has only one `{}`, so `graphSpace` is silently ignored and won't appear in the
log output.
```suggestion
LOG.debug("Remove schema template by name '{}' for graph space '{}'",
name, graphSpace);
```
##########
hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/util/ConfigUtil.java:
##########
@@ -188,4 +192,30 @@ private static void validateGraphName(String graphName) {
"Graph name can only contain letters, numbers, hyphens
and underscores: %s",
graphName);
}
+
+ public static String writeConfigToString(HugeConfig config) {
+ String content;
+ try {
+ if (config.file() == null) {
+ Map<String, Object> configMap = new HashMap<>();
+ Iterator<String> iterator = config.getKeys();
+ while (iterator.hasNext()) {
+ String key = iterator.next();
+ configMap.put(key, config.getProperty(key));
+ }
+ content = JsonUtil.toJson(configMap);
+ } else {
+ File file = config.file();
Review Comment:
‼️ **Bug: Duplicate null check — the `else` branch already guarantees
`config.file() != null`**
The outer `if (config.file() == null)` at line 198 means the `else` branch
is only reached when `config.file()` is non-null. The inner `if (file == null)`
check on this line is dead code and can never be true.
```suggestion
File file = config.file();
content = FileUtils.readFileToString(file);
```
##########
hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/space/SchemaTemplateAPI.java:
##########
@@ -0,0 +1,197 @@
+/*
+ * 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.api.space;
+
+import java.util.Date;
+import java.util.Set;
+
+import org.apache.commons.lang3.StringUtils;
+import org.apache.hugegraph.api.API;
+import org.apache.hugegraph.api.filter.StatusFilter;
+import org.apache.hugegraph.auth.HugeGraphAuthProxy;
+import org.apache.hugegraph.core.GraphManager;
+import org.apache.hugegraph.define.Checkable;
+import org.apache.hugegraph.exception.HugeException;
+import org.apache.hugegraph.server.RestServer;
+import org.apache.hugegraph.space.SchemaTemplate;
+import org.apache.hugegraph.util.E;
+import org.apache.hugegraph.util.Log;
+import org.slf4j.Logger;
+
+import com.codahale.metrics.annotation.Timed;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.google.common.collect.ImmutableMap;
+
+import io.swagger.v3.oas.annotations.tags.Tag;
+import jakarta.inject.Singleton;
+import jakarta.ws.rs.Consumes;
+import jakarta.ws.rs.DELETE;
+import jakarta.ws.rs.GET;
+import jakarta.ws.rs.POST;
+import jakarta.ws.rs.PUT;
+import jakarta.ws.rs.Path;
+import jakarta.ws.rs.PathParam;
+import jakarta.ws.rs.Produces;
+import jakarta.ws.rs.core.Context;
+import jakarta.ws.rs.core.SecurityContext;
+
+@Path("graphspaces/{graphspace}/schematemplates")
+@Singleton
+@Tag(name = "SchemaTemplateAPI")
+public class SchemaTemplateAPI extends API {
+
Review Comment:
⚠️ **Security: All SchemaTemplateAPI endpoints are missing `@RolesAllowed`
annotations**
Other APIs in this project (`GraphsAPI`, `GraphSpaceAPI`) consistently use
`@RolesAllowed` for access control. The `delete` and `update` methods do manual
permission checks via `isSpaceManager`, but `list`, `get`, and `create` have no
access control at all. This means any authenticated user can create and view
schema templates regardless of their role.
Consider adding appropriate `@RolesAllowed` annotations (e.g.,
`@RolesAllowed({"space_member", "$dynamic"})` for read operations,
`@RolesAllowed({"space"})` for write operations) to be consistent with the rest
of the codebase.
##########
hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/profile/GraphsAPI.java:
##########
@@ -120,6 +128,85 @@ public Object list(@Context GraphManager manager,
return ImmutableMap.of("graphs", filterGraphs);
}
+ @GET
+ @Timed
+ @Path("profile")
+ @Produces(APPLICATION_JSON_WITH_CHARSET)
+ @RolesAllowed({"space_member", "$dynamic"})
+ public Object listProfile(@Context GraphManager manager,
+ @Parameter(description = "The graph space name")
+ @PathParam("graphspace") String graphSpace,
+ @Parameter(description = "Filter graphs by name
or nickname prefix")
+ @QueryParam("prefix") String prefix,
+ @Context SecurityContext sc) {
+ LOG.debug("List graph profiles in graph space {}", graphSpace);
+ if (null == manager.graphSpace(graphSpace)) {
+ throw new HugeException("Graphspace not exist!");
+ }
+ GraphSpace gs = manager.graphSpace(graphSpace);
+ String gsNickname = gs.nickname();
+
+ AuthManager authManager = manager.authManager();
+ String user = HugeGraphAuthProxy.username();
+ Map<String, Date> defaultGraphs =
authManager.getDefaultGraph(graphSpace, user);
+
+ SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+ Set<String> graphs = manager.graphs(graphSpace);
+ List<Map<String, Object>> profiles = new ArrayList<>();
+ List<Map<String, Object>> defaultProfiles = new ArrayList<>();
+ for (String graph : graphs) {
+ String role = RequiredPerm.roleFor(graphSpace, graph,
+ HugePermission.READ);
+ if (!sc.isUserInRole(role)) {
+ continue;
+ }
+ try {
+ HugeGraph hg = graph(manager, graphSpace, graph);
+ HugeConfig config = (HugeConfig) hg.configuration();
+ String configResp = ConfigUtil.writeConfigToString(config);
+ Map<String, Object> profile =
+ JsonUtil.fromJson(configResp, Map.class);
+ profile.put("name", graph);
+ profile.put("nickname", hg.nickname());
+ if (!isPrefix(profile, prefix)) {
+ continue;
+ }
+ profile.put("graphspace_nickname", gsNickname);
+
+ boolean isDefault = defaultGraphs.containsKey(graph);
+ profile.put("default", isDefault);
+ if (isDefault) {
+ profile.put("default_update_time",
defaultGraphs.get(graph));
+ }
+
+ Date createTime = hg.createTime();
+ if (createTime != null) {
+ profile.put("create_time", format.format(createTime));
+ }
+
+ if (isDefault) {
+ defaultProfiles.add(profile);
+ } else {
+ profiles.add(profile);
+ }
+ } catch (ForbiddenException ignored) {
+ // ignore graphs the current user has no access to
+ }
+ }
+ defaultProfiles.addAll(profiles);
+ return defaultProfiles;
+ }
+
Review Comment:
⚠️ **Code quality: `isPrefix` should be `private static`, and `nickname` can
be null causing NPE**
1. This method is only used within `listProfile` — it should be `private
static`, not `public`.
2. `hg.nickname()` can return `null` (graphs may not have a nickname set).
When `nickname` is null, `nickname.toString().startsWith(prefix)` will throw
`NullPointerException`.
```suggestion
private static boolean isPrefix(Map<String, Object> profile, String
prefix) {
if (StringUtils.isEmpty(prefix)) {
return true;
}
String name = profile.get("name").toString();
Object nickname = profile.get("nickname");
return name.startsWith(prefix) ||
(nickname != null && nickname.toString().startsWith(prefix));
}
```
##########
hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/profile/GraphsAPI.java:
##########
@@ -155,6 +297,76 @@ public void drop(@Context GraphManager manager,
manager.dropGraph(graphSpace, name, true);
}
+ @PUT
+ @Timed
+ @Path("{name}")
+ @Consumes(APPLICATION_JSON)
+ @Produces(APPLICATION_JSON_WITH_CHARSET)
+ @RolesAllowed({"space"})
+ public Map<String, String> manage(@Context GraphManager manager,
+ @Parameter(description = "The graph
space name")
+ @PathParam("graphspace") String
graphSpace,
+ @Parameter(description = "The graph
name")
+ @PathParam("name") String name,
+ @Parameter(description = "Action map:
{'action':'update','update':{...}}")
+ Map<String, Object> actionMap) {
+ LOG.debug("Manage graph '{}' with action '{}'", name, actionMap);
+ E.checkArgument(actionMap != null && actionMap.size() == 2 &&
+ actionMap.containsKey(GRAPH_ACTION),
+ "Invalid request body '%s'", actionMap);
+ Object value = actionMap.get(GRAPH_ACTION);
+ E.checkArgument(value instanceof String,
+ "Invalid action type '%s', must be string",
+ value.getClass());
+ String action = (String) value;
+ switch (action) {
+ case UPDATE:
+ E.checkArgument(actionMap.containsKey(UPDATE),
+ "Please pass '%s' for graph update",
+ UPDATE);
+ value = actionMap.get(UPDATE);
+ E.checkArgument(value instanceof Map,
+ "The '%s' must be map, but got %s",
+ UPDATE, value.getClass());
+ @SuppressWarnings("unchecked")
+ Map<String, Object> graphMap = (Map<String, Object>) value;
+ String graphName = (String) graphMap.get("name");
+ E.checkArgument(graphName != null && graphName.equals(name),
+ "Different name in update body '%s' with path
'%s'",
+ graphName, name);
+ HugeGraph exist = graph(manager, graphSpace, name);
+ String nickname = (String) graphMap.get("nickname");
+ if (!Strings.isEmpty(nickname)) {
+ GraphManager.checkNickname(nickname);
+
E.checkArgument(!manager.isExistedGraphNickname(graphSpace, nickname) ||
+ nickname.equals(exist.nickname()),
Review Comment:
⚠️ **Large commented-out code block should be removed**
~15 lines of commented-out code (`GRAPH_ACTION_CLEAR` and
`GRAPH_ACTION_RELOAD` cases) should not be checked in. If these features are
planned for a future PR, track them in an issue instead. The unused constants
`CLEAR_SCHEMA` and `GRAPH_ACTION_CLEAR` defined earlier should also be removed
since they're not referenced by active code.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]