bitflicker64 commented on code in PR #3273:
URL: https://github.com/apache/hugegraph/pull/3273#discussion_r4638630037


##########
pom.xml:
##########
@@ -308,6 +308,7 @@
                             <!-- sources generated by gRPC -->
                             
<exclude>**/src/main/java/org/apache/hugegraph/pd/grpc/**</exclude>
                             
<exclude>**/src/main/java/org/apache/hugegraph/store/grpc/**</exclude>
+                            <!-- Docker local data and notebook -->

Review Comment:
   Minor: the notebook and `docker/data` excludes are gone, but this comment 
still sits in the RAT `excludes` with nothing under it. Remove it.



##########
hugegraph-server/hugegraph-ranger-plugin/pom.xml:
##########
@@ -0,0 +1,227 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  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.
+  -->
+<project xmlns="http://maven.apache.org/POM/4.0.0";
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance";
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
http://maven.apache.org/xsd/maven-4.0.0.xsd";>
+    <modelVersion>4.0.0</modelVersion>
+
+    <parent>
+        <groupId>org.apache.hugegraph</groupId>
+        <artifactId>hugegraph-server</artifactId>
+        <version>${revision}</version>
+        <relativePath>../pom.xml</relativePath>
+    </parent>
+
+    <artifactId>hugegraph-ranger-plugin</artifactId>
+    <packaging>jar</packaging>
+
+    <name>${project.artifactId}</name>
+    <description>Apache Ranger authorization plugin for HugeGraph</description>
+
+    <properties>
+        <!-- Keep in step with the apache/ranger base image in
+             docker/hgRangerIntegration/Dockerfile.ranger. -->
+        <ranger.version>2.9.0</ranger.version>
+    </properties>
+
+    <dependencies>
+        <!-- HugeGraph internal dependencies -->
+        <dependency>
+            <groupId>org.apache.hugegraph</groupId>
+            <artifactId>hugegraph-core</artifactId>
+            <version>${revision}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.hugegraph</groupId>
+            <artifactId>hugegraph-api</artifactId>
+            <version>${revision}</version>
+        </dependency>
+
+        <!-- Apache Ranger plugin SDK -->
+        <dependency>
+            <groupId>org.apache.ranger</groupId>
+            <artifactId>ranger-plugins-common</artifactId>
+            <version>${ranger.version}</version>
+            <exclusions>
+                <!-- avoid hadoop/hbase version conflicts -->
+                <exclusion>
+                    <groupId>org.apache.hadoop</groupId>
+                    <artifactId>hadoop-common</artifactId>
+                </exclusion>
+                <exclusion>
+                    <groupId>org.apache.hadoop</groupId>
+                    <artifactId>hadoop-auth</artifactId>
+                </exclusion>
+            </exclusions>
+        </dependency>
+        <!-- Since Ranger 2.7 the audit destinations are separate artifacts;
+             ranger-plugins-common only brings ranger-audit-core (file
+             destination). Needed for xasecure.audit.destination.solr. -->
+        <dependency>
+            <groupId>org.apache.ranger</groupId>
+            <artifactId>ranger-audit-dest-solr</artifactId>
+            <version>${ranger.version}</version>
+            <exclusions>
+                <!-- It declares slf4j-api 2.x directly, which would win over
+                     HugeGraph's 1.7 line and get shaded into lib/; SLF4J 2.x
+                     ignores the log4j-slf4j-impl binding and turns all server
+                     logging into NOP. solrj 8.x only needs the 1.7 API. -->
+                <exclusion>
+                    <groupId>org.slf4j</groupId>
+                    <artifactId>slf4j-api</artifactId>
+                </exclusion>
+            </exclusions>
+        </dependency>
+
+        <!-- logging -->
+        <dependency>
+            <groupId>org.apache.logging.log4j</groupId>
+            <artifactId>log4j-api</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.logging.log4j</groupId>
+            <artifactId>log4j-core</artifactId>
+        </dependency>
+
+        <!-- Hadoop configuration is pulled in by ranger-plugins-common at 
runtime;
+             provided scope lets us compile against it without bundling it. -->
+        <dependency>
+            <groupId>org.apache.hadoop</groupId>
+            <artifactId>hadoop-common</artifactId>
+            <version>3.3.4</version>
+            <scope>provided</scope>
+            <exclusions>
+                <exclusion>
+                    <groupId>log4j</groupId>
+                    <artifactId>log4j</artifactId>
+                </exclusion>
+                <exclusion>
+                    <groupId>org.slf4j</groupId>
+                    <artifactId>slf4j-log4j12</artifactId>
+                </exclusion>
+            </exclusions>
+        </dependency>
+
+        <!-- test -->
+        <dependency>
+            <groupId>junit</groupId>
+            <artifactId>junit</artifactId>
+            <scope>test</scope>
+        </dependency>
+    </dependencies>
+
+    <build>
+        <plugins>
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-shade-plugin</artifactId>
+                <executions>
+                    <execution>
+                        <phase>package</phase>
+                        <goals>
+                            <goal>shade</goal>
+                        </goals>
+                        <configuration>
+                            <!--
+                              Produce a standalone "plugin" jar that Ranger's
+                              security-admin can pick up.  hugegraph-core and
+                              hugegraph-api are already on the server classpath
+                              so we exclude them to keep the artifact small.
+                            -->
+                            <artifactSet>
+                                <excludes>
+                                    
<exclude>org.apache.hugegraph:hugegraph-core</exclude>

Review Comment:
   Important: excluding only the `hugegraph-core` and `hugegraph-api` artifacts 
still shades their whole transitive tree, so the 290 MB `plugin` jar carries 
unrelocated copies of 220 libraries already in `lib/`, 31 of them at other 
versions (`guava` 32.0.1-jre vs 31.1-android, `commons-configuration2` 2.13.0 
vs 2.10.1, `jctools-core` 4.0.5 vs 2.1.1, `jakarta.xml.bind-api` 2.3.2 vs 
3.0.0). `hugegraph-server.sh` puts `hugegraph*.jar` first on the classpath, so 
those classes load from the plugin jar for the whole server. Declare the 
HugeGraph modules `provided` so their tree stays out of the shade, and relocate 
the Ranger-side libraries that overlap with `lib/`.



##########
hugegraph-server/hugegraph-ranger-plugin/src/main/java/org/apache/hugegraph/ranger/RangerAuthManager.java:
##########
@@ -0,0 +1,918 @@
+/*
+ * 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.ranger;
+
+import java.util.Date;
+import java.util.EnumSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.TimeUnit;
+import java.util.function.LongSupplier;
+
+import javax.security.sasl.AuthenticationException;
+
+import org.apache.hugegraph.auth.AuthManager;
+import org.apache.hugegraph.auth.HugeAccess;
+import org.apache.hugegraph.auth.HugeAuthenticator;
+import org.apache.hugegraph.auth.HugeBelong;
+import org.apache.hugegraph.auth.HugeDefaultRole;
+import org.apache.hugegraph.auth.HugeGroup;
+import org.apache.hugegraph.auth.HugePermission;
+import org.apache.hugegraph.auth.HugeProject;
+import org.apache.hugegraph.auth.HugeTarget;
+import org.apache.hugegraph.auth.HugeUser;
+import org.apache.hugegraph.auth.ResourceType;
+import org.apache.hugegraph.auth.RolePermission;
+import org.apache.hugegraph.auth.SchemaDefine.AuthElement;
+import org.apache.hugegraph.auth.UserWithRole;
+import org.apache.hugegraph.id.Id;
+import org.apache.hugegraph.util.JsonUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * AuthManager implementation that:
+ * <ul>
+ *   <li>Delegates all identity-management operations (users, groups, tokens) 
to
+ *       the underlying {@link AuthManager} (StandardAuthManager /
+ *       StandardAuthManagerV2).</li>
+ *   <li>Intercepts {@link #validateUser} / {@link #rolePermission} to merge
+ *       Ranger policy decisions into the returned {@link RolePermission}.</li>
+ * </ul>
+ *
+ * <h3>Ranger → RolePermission mapping</h3>
+ * <pre>
+ *   Ranger access type  │  HugePermission
+ *   ────────────────────┼────────────────
+ *   read                │  READ
+ *   write               │  WRITE
+ *   delete              │  DELETE
+ *   execute             │  EXECUTE
+ *   admin               │  ADMIN
+ * </pre>
+ */
+public class RangerAuthManager implements AuthManager {
+
+    private static final Logger LOG =
+            LoggerFactory.getLogger(RangerAuthManager.class);
+
+    /** Permissions probed at login, besides ADMIN which is checked first. */
+    private static final HugePermission[] PROBED_PERMS = {
+            HugePermission.READ, HugePermission.WRITE,
+            HugePermission.DELETE, HugePermission.EXECUTE
+    };
+
+    private static final int MAX_CACHED_USERS = 1024;
+
+    private final AuthManager delegate;
+    private final RangerHugeGraphPlugin rangerPlugin;
+    private final long roleCacheNanos;
+    private final LongSupplier nanoClock;
+    private final Map<String, CachedGrant> grantCache = new 
ConcurrentHashMap<>();
+
+    /**
+     * @param roleCacheExpireSeconds how long a user's Ranger grants are reused
+     *                               between logins; 0 queries Ranger every 
time
+     */
+    public RangerAuthManager(AuthManager delegate,
+                             String serviceName,
+                             String rangerConfigFile,
+                             int roleCacheExpireSeconds) {
+        this(delegate, createPlugin(serviceName, rangerConfigFile),
+             roleCacheExpireSeconds, System::nanoTime);
+    }
+
+    RangerAuthManager(AuthManager delegate, RangerHugeGraphPlugin plugin,
+                      int roleCacheExpireSeconds, LongSupplier nanoClock) {
+        if (roleCacheExpireSeconds < 0) {
+            throw new IllegalArgumentException(
+                    "The Ranger role cache expire must be >= 0, but got " +
+                    roleCacheExpireSeconds);
+        }
+        this.delegate = delegate;
+        this.rangerPlugin = plugin;
+        this.roleCacheNanos = TimeUnit.SECONDS.toNanos(roleCacheExpireSeconds);
+        this.nanoClock = nanoClock;
+    }
+
+    private static RangerHugeGraphPlugin createPlugin(String serviceName,
+                                                      String rangerConfigFile) 
{
+        RangerHugeGraphPlugin plugin =
+                new RangerHugeGraphPlugin(serviceName, rangerConfigFile);
+        plugin.init();
+        return plugin;
+    }
+
+    /**
+     * The underlying Ranger plugin instance, used by
+     * {@link RangerHugeGraphAuthenticator#setup} to register real per-request
+     * enforcement via {@code HugeGraphAuthProxy.setResourceAuthorizer}.
+     */
+    public RangerHugeGraphPlugin rangerPlugin() {
+        return this.rangerPlugin;
+    }
+
+    // ------------------------------------------------------------------
+    // Authentication helpers
+    // ------------------------------------------------------------------
+
+    /**
+     * Authenticate by username+password or token, then enrich the returned
+     * role with Ranger policy grants.  Called from
+     * {@link RangerHugeGraphAuthenticator#authenticate}.
+     */
+    public UserWithRole authenticate(String username, String password,
+                                     String token) {
+        UserWithRole base = (token != null && !token.isEmpty()) ?
+                            delegate.validateUser(token) :
+                            delegate.validateUser(username, password);
+        return enrichWithRanger(base);
+    }
+
+    @Override
+    public UserWithRole validateUser(String username, String password) {
+        return enrichWithRanger(delegate.validateUser(username, password));
+    }
+
+    @Override
+    public UserWithRole validateUser(String token) {
+        return enrichWithRanger(delegate.validateUser(token));
+    }
+
+    @Override
+    public RolePermission rolePermission(AuthElement element) {
+        RolePermission base = delegate.rolePermission(element);
+        if (base == null) {
+            base = RolePermission.none();
+        }
+        if (RolePermission.isAdmin(base)) {
+            return base;
+        }
+        String name = (element instanceof HugeUser) ?
+                      ((HugeUser) element).name() :
+                      element.id().asString();
+        // admin is a trusted bootstrap identity (same bypass as
+        // HugeGraphAuthProxy.verifyResPermission() and
+        // RangerHugeGraphAuthenticator.authenticate()) — no Ranger policy is
+        // expected to exist for it, so never probe Ranger on its behalf.
+        if (HugeAuthenticator.USER_ADMIN.equals(name)) {
+            return RolePermission.admin();
+        }
+        return mergeRangerRole(base, name);
+    }
+
+    // ------------------------------------------------------------------
+    // Private: Ranger enrichment
+    // ------------------------------------------------------------------
+
+    private UserWithRole enrichWithRanger(UserWithRole base) {
+        if (base == null || base.username() == null) {
+            return base;
+        }
+        // userId() is null when authentication failed (wrong password or 
unknown user).
+        // Do not grant Ranger permissions to unauthenticated identities.
+        if (base.userId() == null) {
+            return base;
+        }
+        RolePermission role = base.role();
+        if (role != null && RolePermission.isAdmin(role)) {
+            return base;
+        }
+        // admin is a trusted bootstrap identity — never probe Ranger for it,
+        // otherwise every login logs a spurious Denied admin/*/*/all/* audit
+        // entry even though RangerHugeGraphAuthenticator.authenticate()
+        // overrides the role with ROLE_ADMIN right after this call returns.
+        if (HugeAuthenticator.USER_ADMIN.equals(base.username())) {
+            return new UserWithRole(base.userId(), base.username(),
+                                    RolePermission.admin());
+        }
+        RolePermission enriched = mergeRangerRole(
+                role != null ? role : RolePermission.none(),
+                base.username());
+        // No grants from either HugeGraph's own role or Ranger policy: reject 
the
+        // login outright rather than admitting a role with no permissions.
+        //
+        // This MUST be the HugeAuthenticator.ROLE_NONE instance, not a fresh
+        // RolePermission.none(). HugeAuthenticator.verifyRole() tests 
identity:
+        //     return role != ROLE_NONE && role != null;
+        // so a newly built none() is not that reference, passes verifyRole() 
and
+        // logs the user in with an empty role.
+        if (isEffectivelyNone(enriched)) {
+            enriched = HugeAuthenticator.ROLE_NONE;
+        }
+        return new UserWithRole(base.userId(), base.username(), enriched);
+    }
+
+    /**
+     * Query Ranger for {@code username} and merge any grants into {@code 
base}.
+     *
+     * <p>Login only needs to know which actions the user may attempt at all,
+     * so each permission is probed with {@link
+     * RangerHugeGraphPlugin#hasAnyAccess}: a policy limited to one graph space
+     * or graph still counts. The grant is expressed under the {@code "*"}
+     * graph space and graph, which {@code RolePerm} treats as a wildcard, and
+     * the real graph space, graph and label of every request are decided by
+     * Ranger in {@link org.apache.hugegraph.auth.HugeGraphAuthProxy}.
+     *
+     * <p>We can't call the protected {@code RolePermission.add()} from outside
+     * the package, so we build a JSON role string and deserialise it instead —
+     * this goes through the same public factory path used everywhere else.
+     */
+    private RolePermission mergeRangerRole(RolePermission base,
+                                           String username) {
+        if (base == null) {
+            base = RolePermission.none();
+        }
+        CachedGrant grant = this.rangerGrant(username);
+        if (grant.admin) {
+            return RolePermission.admin();
+        }
+        if (grant.perms.isEmpty()) {
+            // Ranger denied everything — return base unchanged
+            return base;
+        }
+
+        StringBuilder sb = new StringBuilder("{\"roles\":{\"*\":{\"*\":{");

Review Comment:
   Minor: this `*`/`*` role passes every API-level role check, and 
`GraphsAPI.list` filters graphs only by `sc.isUserInRole(...)` without reaching 
the Ranger authorizer, so a user whose only policy covers `DEFAULT/hugegraph` 
sees the name of every graph in every graph space. Make the listing ask the 
authorizer for each graph, for example through a proxied call such as 
`backend()` inside the existing `ForbiddenException` catch.



-- 
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]

Reply via email to