yuqi1129 commented on code in PR #12199:
URL: https://github.com/apache/gravitino/pull/12199#discussion_r3775677924


##########
bundles/tencent/src/main/java/org/apache/gravitino/cos/credential/COSTokenGenerator.java:
##########
@@ -0,0 +1,354 @@
+/*
+ * 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.gravitino.cos.credential;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.base.Preconditions;
+import com.tencentcloudapi.common.Credential;
+import com.tencentcloudapi.common.exception.TencentCloudSDKException;
+import com.tencentcloudapi.sts.v20180813.StsClient;
+import com.tencentcloudapi.sts.v20180813.models.AssumeRoleRequest;
+import com.tencentcloudapi.sts.v20180813.models.AssumeRoleResponse;
+import java.io.IOException;
+import java.net.URI;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Stream;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.cos.credential.policy.Condition;
+import org.apache.gravitino.cos.credential.policy.Effect;
+import org.apache.gravitino.cos.credential.policy.Policy;
+import org.apache.gravitino.cos.credential.policy.Statement;
+import org.apache.gravitino.cos.credential.policy.StringLike;
+import org.apache.gravitino.credential.COSTokenCredential;
+import org.apache.gravitino.credential.CredentialContext;
+import org.apache.gravitino.credential.CredentialGenerator;
+import org.apache.gravitino.credential.PathBasedCredentialContext;
+import org.apache.gravitino.credential.config.COSCredentialConfig;
+
+/**
+ * Generates Tencent Cloud COS STS tokens scoped to the requested fileset 
paths.
+ *
+ * <p>The generator calls Tencent Cloud {@code sts:AssumeRole} with a session 
policy that allows
+ * only the read/write paths reported by the {@link 
PathBasedCredentialContext}, so the temporary
+ * credentials handed back to clients cannot reach data outside the requested 
locations.
+ */
+public class COSTokenGenerator implements 
CredentialGenerator<COSTokenCredential> {
+
+  private static final String POLICY_VERSION = "2.0";
+
+  private final ObjectMapper objectMapper = new ObjectMapper();
+
+  private String accessKeyId;
+  private String secretAccessKey;
+  private String roleArn;
+  private String externalId;
+  private String region;
+  private String appId;
+  private int tokenExpireSecs;
+
+  @Override
+  public void initialize(Map<String, String> properties) {
+    COSCredentialConfig config = new COSCredentialConfig(properties);
+    this.accessKeyId = config.accessKeyID();
+    this.secretAccessKey = config.secretAccessKey();
+    this.roleArn = config.cosRoleArn();
+    this.externalId = config.externalID();
+    this.region = config.region();
+    this.appId = config.appID();
+    this.tokenExpireSecs = config.tokenExpireInSecs();
+  }
+
+  @Override
+  public COSTokenCredential generate(CredentialContext context) throws 
Exception {
+    if (!(context instanceof PathBasedCredentialContext)) {
+      return null;
+    }
+
+    PathBasedCredentialContext pathContext = (PathBasedCredentialContext) 
context;
+
+    AssumeRoleResponse response =
+        callAssumeRole(
+            pathContext.getReadPaths(), pathContext.getWritePaths(), 
pathContext.getUserName());
+
+    com.tencentcloudapi.sts.v20180813.models.Credentials credentials = 
response.getCredentials();
+    Long expiredTime = response.getExpiredTime();
+    Preconditions.checkState(
+        credentials != null && expiredTime != null,
+        "Tencent STS AssumeRole returned an incomplete response, requestId: 
%s",
+        response.getRequestId());
+    // Tencent Cloud returns ExpiredTime in Unix seconds, convert to ms to 
match the
+    // Credential#expireTimeInMs() contract.
+    long expireTimeInMs = expiredTime * 1000L;
+    return new COSTokenCredential(
+        credentials.getTmpSecretId(),
+        credentials.getTmpSecretKey(),
+        credentials.getToken(),
+        expireTimeInMs);
+  }
+
+  private AssumeRoleResponse callAssumeRole(
+      Set<String> readLocations, Set<String> writeLocations, String userName)
+      throws TencentCloudSDKException {
+    Credential cred = new Credential(accessKeyId, secretAccessKey);
+    // COSCredentialConfig enforces cos-region to be non-blank, so we can pass 
it directly to
+    // the STS client to sign requests against the correct regional endpoint.
+    StsClient client = new StsClient(cred, region);
+
+    AssumeRoleRequest request = new AssumeRoleRequest();
+    request.setRoleArn(roleArn);
+    request.setRoleSessionName(getRoleSessionName(userName));
+    request.setDurationSeconds((long) tokenExpireSecs);
+    if (StringUtils.isNotBlank(externalId)) {
+      request.setExternalId(externalId);
+    }
+    request.setPolicy(buildPolicy(readLocations, writeLocations));
+
+    return client.AssumeRole(request);
+  }
+
+  private String buildPolicy(Set<String> readLocations, Set<String> 
writeLocations) {
+    Preconditions.checkArgument(
+        !readLocations.isEmpty() || !writeLocations.isEmpty(),
+        "COS token generator requires at least one read or write location");
+    Policy.Builder policyBuilder = Policy.builder().version(POLICY_VERSION);
+
+    Statement.Builder readObjectStatement =
+        Statement.builder()
+            .effect(Effect.ALLOW)
+            .addAction("cos:GetObject")
+            .addAction("cos:HeadObject");
+
+    // Use LinkedHashMap so the resulting policy JSON has a deterministic 
statement order; this
+    // makes logs easier to diff and avoids spurious cache key churn.
+    Map<String, Statement.Builder> bucketListStatements = new 
LinkedHashMap<>();
+    Map<String, Statement.Builder> bucketMetadataStatements = new 
LinkedHashMap<>();
+
+    Stream.concat(readLocations.stream(), writeLocations.stream())
+        .distinct()
+        .forEach(
+            location -> {
+              URI uri = URI.create(location);
+              addObjectResources(readObjectStatement, uri);
+              String bucketResource = getBucketResource(uri);
+              String bucketWildcardResource = getBucketWildcardResource(uri);
+              // Tencent Cloud CAM requires distinct resource ARN forms for 
cos:GetBucket vs
+              // the bucket-metadata actions: cos:GetBucket needs the wildcard 
form (bucket/*),
+              // whereas cos:HeadBucket / cos:GetBucketLocation need the plain 
form (bucket/).
+              // The cos:prefix condition uses "xxx*" (no slash) so it matches 
both the fileset
+              // root prefix (e.g. "xxx/") and any sub-path (e.g. "xxx/foo/") 
that hadoop-cos
+              // may pass in a list request.
+              bucketListStatements.computeIfAbsent(
+                  bucketWildcardResource,
+                  key ->
+                      Statement.builder()
+                          .effect(Effect.ALLOW)
+                          .addAction("cos:GetBucket")
+                          .addResource(key)
+                          .condition(buildPrefixCondition(uri)));
+              // hadoop-cos calls headBucket during FileSystem.initialize(); 
cos:HeadBucket must
+              // be granted here or the temporary credentials will fail with 
403 Forbidden.
+              bucketMetadataStatements.computeIfAbsent(
+                  bucketResource,
+                  key ->
+                      Statement.builder()
+                          .effect(Effect.ALLOW)
+                          .addAction("cos:GetBucketLocation")
+                          .addAction("cos:HeadBucket")
+                          .addResource(key));
+            });
+
+    if (!writeLocations.isEmpty()) {
+      Statement.Builder writeObjectStatement =
+          Statement.builder()
+              .effect(Effect.ALLOW)
+              .addAction("cos:PutObject")
+              .addAction("cos:DeleteObject")
+              .addAction("cos:InitiateMultipartUpload")
+              .addAction("cos:UploadPart")
+              .addAction("cos:CompleteMultipartUpload")
+              .addAction("cos:AbortMultipartUpload");
+      writeLocations.forEach(
+          location -> addObjectResources(writeObjectStatement, 
URI.create(location)));
+      policyBuilder.addStatement(writeObjectStatement.build());
+    }
+
+    if (!bucketListStatements.isEmpty()) {
+      bucketListStatements.values().forEach(builder -> 
policyBuilder.addStatement(builder.build()));
+    }
+    bucketMetadataStatements
+        .values()
+        .forEach(builder -> policyBuilder.addStatement(builder.build()));
+
+    policyBuilder.addStatement(readObjectStatement.build());
+
+    try {
+      return objectMapper.writeValueAsString(policyBuilder.build());
+    } catch (JsonProcessingException e) {
+      throw new RuntimeException("Failed to serialize COS session policy", e);
+    }
+  }
+
+  /**
+   * Build the {@code cos:prefix} condition for a fileset location.
+   *
+   * <p>hadoop-cos may pass the fileset prefix itself (e.g. {@code xxx/}) or 
the prefix plus a
+   * sub-path (e.g. {@code xxx/foo/}) as the {@code prefix} of a list request. 
Tencent Cloud CAM's
+   * {@code string_like} matcher requires the pattern to be {@code xxx*} (no 
trailing slash) to
+   * cover both forms; the alternative {@code xxx/*} fails to match {@code 
xxx/} and returns
+   * AccessDenied. The pattern is still anchored to the fileset prefix, so it 
cannot broaden the
+   * scope of the token.
+   */
+  private Condition buildPrefixCondition(URI uri) {
+    return Condition.builder()
+        
.stringLike(StringLike.builder().addPrefix(trimLeadingSlash(uri.getPath()) + 
"*").build())

Review Comment:
   Appending "*" directly will cause the following problem:
   ```
   .../orders -> .../order*  // it will make get the priviledge for paths like 
`orders_backup/..`
   ```
   



##########
bundles/tencent/src/main/java/org/apache/gravitino/cos/credential/policy/StringLike.java:
##########
@@ -0,0 +1,62 @@
+/*
+ * 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.gravitino.cos.credential.policy;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Tencent Cloud CAM {@code string_like} condition value. The {@code 
cos:prefix} key is used to
+ * restrict {@code cos:GetBucket}/{@code ListObjects} to a specific prefix 
inside the bucket.
+ */
+@JsonInclude(JsonInclude.Include.NON_NULL)
+public class StringLike {
+
+  @JsonProperty("cos:prefix")

Review Comment:
   Value "cos:prefix" is not so common in Java. Is there any special reason 
that we use this format?



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

Reply via email to