o-nikolas commented on code in PR #36799:
URL: https://github.com/apache/airflow/pull/36799#discussion_r1452747800


##########
tests/providers/amazon/aws/auth_manager/cli/test_avp_commands.py:
##########
@@ -0,0 +1,168 @@
+# 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.
+from __future__ import annotations
+
+import importlib
+from unittest.mock import ANY, Mock, patch
+
+import pytest
+
+from airflow.cli import cli_parser
+from airflow.providers.amazon.aws.auth_manager.cli.avp_commands import 
init_avp, update_schema
+from tests.test_utils.config import conf_vars
+
+mock_boto3 = Mock()
+
+
[email protected]_test
+class TestAvpCommands:
+    def setup_method(self):
+        mock_boto3.reset_mock()
+
+    @classmethod
+    def setup_class(cls):
+        with conf_vars(
+            {
+                (
+                    "core",
+                    "auth_manager",
+                ): 
"airflow.providers.amazon.aws.auth_manager.aws_auth_manager.AwsAuthManager"
+            }
+        ):
+            importlib.reload(cli_parser)
+            cls.arg_parser = cli_parser.get_parser()
+
+    @pytest.mark.parametrize(
+        "dry_run, verbose",
+        [
+            (False, False),
+            (True, True),
+        ],
+    )
+    
@patch("airflow.providers.amazon.aws.auth_manager.cli.avp_commands._get_client")
+    def test_init_avp_with_no_existing_resources(self, mock_get_client, 
dry_run, verbose):
+        mock_get_client.return_value = mock_boto3
+
+        policy_store_description = "test-policy-store"
+        policy_store_id = "test-policy-store-id"
+
+        paginator = Mock()
+        paginator.paginate.return_value = []
+
+        mock_boto3.get_paginator.return_value = paginator
+        mock_boto3.create_policy_store.return_value = {"policyStoreId": 
policy_store_id}
+
+        with conf_vars({("database", "check_migrations"): "False"}):
+            params = [
+                "aws-auth-manager",
+                "init-avp",
+                "--policy-store-description",
+                policy_store_description,
+            ]
+            if dry_run:
+                params.append("--dry-run")
+            if verbose:
+                params.append("--verbose")
+            init_avp(self.arg_parser.parse_args(params))
+
+        if not dry_run:

Review Comment:
   Nothing is being asserted for the dry_run case. So as long as there is no 
uncaught exception the dry_run == true case is an automatic pass?
   
   I think it's worth asserting the boto3 apis are not called/called zero times 
in that case.
   Same with the schema test



##########
airflow/providers/amazon/aws/auth_manager/cli/avp_commands.py:
##########
@@ -0,0 +1,168 @@
+# 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.
+"""User sub-commands."""
+from __future__ import annotations
+
+import json
+import logging
+from pathlib import Path
+from typing import TYPE_CHECKING
+
+import boto3
+
+from airflow.configuration import conf
+from airflow.providers.amazon.aws.auth_manager.constants import 
CONF_REGION_NAME_KEY, CONF_SECTION_NAME
+from airflow.utils import cli as cli_utils
+from airflow.utils.providers_configuration_loader import 
providers_configuration_loaded
+
+if TYPE_CHECKING:
+    from botocore.client import BaseClient
+
+log = logging.getLogger(__name__)
+
+
+@cli_utils.action_cli
+@providers_configuration_loaded
+def init_avp(args):
+    """Initialize Amazon Verified Permissions resources."""
+    client = _get_client()
+
+    # Create the policy store if needed
+    policy_store_id, is_new_policy_store = _create_policy_store(client, args)
+
+    if not is_new_policy_store:
+        print(
+            f"Since an existing policy store with description 
'{args.policy_store_description}' has been found in Amazon Verified 
Permissions, "
+            "the CLI makes no changes to this policy store for security 
reasons. "
+            "Any modification to this policy store must be done manually.",
+        )
+    else:
+        # Set the schema
+        _set_schema(client, policy_store_id, args)
+
+    if not args.dry_run:
+        print("Amazon Verified Permissions resources created successfully.")
+        print("Please set them in Airflow configuration under 
AIRFLOW__AWS_AUTH_MANAGER__<config name>.")
+        print(json.dumps({"avp_policy_store_id": policy_store_id}, indent=4))
+
+
+@cli_utils.action_cli
+@providers_configuration_loaded
+def update_schema(args):
+    """Update Amazon Verified Permissions policy store schema."""
+    client = _get_client()
+    _set_schema(client, args.policy_store_id, args)
+
+    if not args.dry_run:
+        print("Amazon Verified Permissions policy store schema updated 
successfully.")
+
+
+def _get_client():
+    """Returns Amazon Verified Permissions client."""
+    region_name = conf.get(CONF_SECTION_NAME, CONF_REGION_NAME_KEY)
+    return boto3.client("verifiedpermissions", region_name=region_name)
+
+
+def _create_policy_store(client: BaseClient, args) -> tuple[str | None, bool]:
+    """
+    Create if needed the policy store.
+
+    This function returns two elements:
+    - the policy store ID
+    - whether the policy store ID returned refers to a newly created policy 
store.
+    """
+    paginator = client.get_paginator("list_policy_stores")
+    pages = paginator.paginate()
+    policy_stores = [application for page in pages for application in 
page["policyStores"]]
+    existing_policy_stores = [
+        policy_store
+        for policy_store in policy_stores
+        if policy_store.get("description") == args.policy_store_description
+    ]
+
+    if args.verbose:
+        log.debug("Policy stores found: %s", policy_stores)
+        log.debug("Existing policy stores found: %s", existing_policy_stores)
+
+    if len(existing_policy_stores) > 0:
+        print(
+            f"There is already a policy store with description 
'{args.policy_store_description}' in Amazon Verified Permissions: 
'{existing_policy_stores[0]['policyStoreId']}'."
+        )
+        return existing_policy_stores[0]["policyStoreId"], False
+    else:
+        print(f"No policy store with description 
'{args.policy_store_description}' found, creating one.")
+        if args.dry_run:
+            print("Dry run, not creating the policy store.")

Review Comment:
   maybe include the inputs you would have provided to the create_policy_store 
api in the dry run log message (same for the other methods as well)? That might 
make the dry run command more useful.



##########
airflow/providers/amazon/aws/auth_manager/cli/avp_commands.py:
##########
@@ -0,0 +1,168 @@
+# 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.
+"""User sub-commands."""
+from __future__ import annotations
+
+import json
+import logging
+from pathlib import Path
+from typing import TYPE_CHECKING
+
+import boto3
+
+from airflow.configuration import conf
+from airflow.providers.amazon.aws.auth_manager.constants import 
CONF_REGION_NAME_KEY, CONF_SECTION_NAME
+from airflow.utils import cli as cli_utils
+from airflow.utils.providers_configuration_loader import 
providers_configuration_loaded
+
+if TYPE_CHECKING:
+    from botocore.client import BaseClient
+
+log = logging.getLogger(__name__)
+
+
+@cli_utils.action_cli
+@providers_configuration_loaded
+def init_avp(args):
+    """Initialize Amazon Verified Permissions resources."""
+    client = _get_client()
+
+    # Create the policy store if needed
+    policy_store_id, is_new_policy_store = _create_policy_store(client, args)
+
+    if not is_new_policy_store:
+        print(
+            f"Since an existing policy store with description 
'{args.policy_store_description}' has been found in Amazon Verified 
Permissions, "
+            "the CLI makes no changes to this policy store for security 
reasons. "

Review Comment:
   ```suggestion
               "the CLI made no changes to this policy store for security 
reasons. "
   ```



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