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


##########
bundles/tencent/src/main/java/org/apache/gravitino/cos/credential/COSTokenGenerator.java:
##########
@@ -0,0 +1,309 @@
+/*
+ * 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. */
+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 STS returns ExpiredTime in seconds; the Credential contract 
uses ms.
+    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);
+    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");
+
+    // LinkedHashMap keeps the emitted statements in a deterministic order.
+    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);
+              // CAM requires different resource ARN forms per action: 
cos:GetBucket needs
+              // bucket/*, whereas cos:HeadBucket / cos:GetBucketLocation need 
bucket/.
+              bucketListStatements.computeIfAbsent(
+                  bucketWildcardResource,
+                  key ->
+                      Statement.builder()
+                          .effect(Effect.ALLOW)
+                          .addAction("cos:GetBucket")
+                          .addResource(key)
+                          .condition(buildPrefixCondition(uri)));
+              // hadoop-cos calls headBucket during FileSystem.initialize(); 
without
+              // cos:HeadBucket the vended credentials return 403.
+              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");

Review Comment:
   The generated write policy is missing `cos:ListParts`. The pinned 
`hadoop-cos` 3.3.0-8.3.23 calls `listParts(key, uploadId)` when `UploadPart` 
returns 409 to determine whether the part actually succeeded; with this session 
policy, that recovery request gets 403 and turns a recoverable multipart upload 
into a failure. Tencent Cloud also lists `cos:ListParts` as required for 
resumable multipart uploads: 
https://cloud.tencent.com/document/product/436/47231. Please add this action 
and assert the complete multipart action set in the policy test.



##########
bundles/tencent/src/main/java/org/apache/gravitino/cos/credential/COSTokenGenerator.java:
##########
@@ -0,0 +1,309 @@
+/*
+ * 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. */
+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 STS returns ExpiredTime in seconds; the Credential contract 
uses ms.
+    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);
+    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");
+
+    // LinkedHashMap keeps the emitted statements in a deterministic order.
+    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);
+              // CAM requires different resource ARN forms per action: 
cos:GetBucket needs
+              // bucket/*, whereas cos:HeadBucket / cos:GetBucketLocation need 
bucket/.
+              bucketListStatements.computeIfAbsent(
+                  bucketWildcardResource,
+                  key ->
+                      Statement.builder()
+                          .effect(Effect.ALLOW)
+                          .addAction("cos:GetBucket")
+                          .addResource(key)
+                          .condition(buildPrefixCondition(uri)));

Review Comment:
   This `computeIfAbsent` captures only the first URI for a bucket. If the 
context contains `cosn://bucket/path-a` and `cosn://bucket/path-b`, the object 
statements include both paths, but the single `GetBucket` statement retains 
only the `path-a` prefix condition, so listing `path-b` is denied. 
`CredentialOperationDispatcher` deliberately merges multiple `PathContext`s of 
the same credential type into one `PathBasedCredentialContext`, so this is a 
supported input shape. Please accumulate all prefixes per bucket (or emit one 
statement per prefix) and add regression coverage for two paths in the same 
bucket, including a read/write combination.



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