feat: Add new gcloud commands, API clients, and third-party libraries across various services.

This commit is contained in:
2026-01-01 20:26:35 +01:00
parent 5e23cbece0
commit a19e592eb7
25221 changed files with 8324611 additions and 0 deletions

View File

@@ -0,0 +1,25 @@
# -*- coding: utf-8 -*- #
# Copyright 2018 Google LLC. All Rights Reserved.
#
# Licensed 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.
"""The Policy base group for Binary Authorization policy management."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
class Policy(base.Group):
"""Create and manage Google Binary Authorization policies."""

View File

@@ -0,0 +1,34 @@
release_tracks: [ALPHA, BETA, GA]
help_text:
brief: Add IAM policy binding to a Binary Authorization policy.
description: |
Add an IAM policy binding to the IAM policy of a Binary Authorization policy. One binding consists of a member,
a role, and an optional condition.
examples: |
To add an IAM policy binding for the role of 'roles/binaryauthorization.attestationAuthoritiesEditor' for the user 'test-user@gmail.com'
on the current project's Binary Authorization policy, run:
$ {command} --member='user:test-user@gmail.com' --role='roles/binaryauthorization.attestationAuthoritiesEditor'
To add an IAM policy binding which expires at the end of the year 2018 for the role of
'roles/binaryauthorization.attestationAuthoritiesEditor' and the user 'test-user@gmail.com'
on the current project's Binary Authorization policy, run:
$ {command} --member='user:test-user@gmail.com' --role='roles/binaryauthorization.attestationAuthoritiesEditor' --condition='expression=request.time < timestamp("2019-01-01T00:00:00Z"),title=expires_end_of_2018,description=Expires at midnight on 2018-12-31'
See https://cloud.google.com/iam/docs/managing-policies for details of
policy role and member types.
iam:
enable_condition: true
policy_version: 3
get_iam_policy_version_path: options_requestedPolicyVersion
request:
collection: binaryauthorization.projects.policy
arguments:
resource:
help_text: The Binary Authorization policy whose IAM policy to add an IAM policy binding to.
spec: !REF googlecloudsdk.command_lib.container.resources:policy

View File

@@ -0,0 +1,86 @@
# -*- coding: utf-8 -*- #
# Copyright 2022 Google LLC. All Rights Reserved.
#
# Licensed 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.
"""Create policy command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.container.binauthz import apis
from googlecloudsdk.api_lib.container.binauthz import platform_policy
from googlecloudsdk.api_lib.util import messages as messages_util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.container.binauthz import flags
from googlecloudsdk.command_lib.container.binauthz import parsing
import six
@base.DefaultUniverseOnly
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.ALPHA)
class Create(base.CreateCommand):
r"""Create a Binary Authorization platform policy.
## EXAMPLES
To create a policy for GKE in the current project:
$ {command} my-policy --platform=gke --policy-file=my_policy.yaml
To create a policy for GKE in a specific project:
$ {command} my-policy --platform=gke --project=my-project-id \
--policy-file=my_policy.yaml
or
$ {command} /projects/my-project-id/platforms/gke/policies/my-policy
\
--policy-file=my_policy.yaml
"""
@staticmethod
def Args(parser):
flags.AddPlatformPolicyResourceArg(parser, 'to create')
parser.add_argument(
'--policy-file',
required=True,
help='The JSON or YAML file containing the new policy.')
parser.display_info.AddFormat('yaml')
def Run(self, args):
"""Runs the command.
Args:
args: argparse.Namespace with command-line arguments.
Returns:
The policy resource.
"""
policy_resource_name = args.CONCEPTS.policy_resource_name.Parse()
# Load the policy file into a Python dict.
policy_obj = parsing.LoadResourceFile(
# Avoid 'u' prefix in Python 2 when this file path gets embedded in
# error messages.
six.ensure_str(args.policy_file))
# Decode the dict into a PlatformPolicy message, allowing DecodeErrors to
# bubble up to the user if they are raised.
policy = messages_util.DictToMessageWithErrorCheck(
policy_obj,
# The API is only available in v1.
apis.GetMessagesModule('v1').PlatformPolicy)
return platform_policy.Client('v1').Create(policy_resource_name, policy)

View File

@@ -0,0 +1,52 @@
# -*- coding: utf-8 -*- #
# Copyright 2022 Google LLC. All Rights Reserved.
#
# Licensed 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.
"""Describe policy command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.container.binauthz import platform_policy
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.container.binauthz import flags
from googlecloudsdk.core import log
@base.DefaultUniverseOnly
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.ALPHA)
class Delete(base.DeleteCommand):
"""Delete a Binary Authorization platform policy.
## EXAMPLES
To delete a policy using its resource name:
$ {command} projects/my_proj/platforms/gke/policies/policy1
To delete the same policy using flags:
$ {command} policy1 --platform=gke --project=my_proj
"""
@staticmethod
def Args(parser):
flags.AddPlatformPolicyResourceArg(parser, 'to delete')
def Run(self, args):
policy_ref = args.CONCEPTS.policy_resource_name.Parse().RelativeName()
# The API is only available in v1.
result = platform_policy.Client('v1').Delete(policy_ref)
log.DeletedResource(policy_ref, kind='Policy')
return result

View File

@@ -0,0 +1,49 @@
# -*- coding: utf-8 -*- #
# Copyright 2022 Google LLC. All Rights Reserved.
#
# Licensed 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.
"""Describe policy command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.container.binauthz import platform_policy
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.container.binauthz import flags
@base.DefaultUniverseOnly
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.ALPHA)
class Describe(base.DescribeCommand):
"""Describe a Binary Authorization platform policy.
## EXAMPLES
To describe an existing policy using its resource name:
$ {command} projects/my_proj/platforms/gke/policies/policy1
To describe the same policy using flags:
$ {command} policy1 --platform=gke --project=my_proj
"""
@staticmethod
def Args(parser):
flags.AddPlatformPolicyResourceArg(parser, 'to describe')
def Run(self, args):
policy_ref = args.CONCEPTS.policy_resource_name.Parse().RelativeName()
# The API is only available in v1.
return platform_policy.Client('v1').Describe(policy_ref)

View File

@@ -0,0 +1,82 @@
# -*- coding: utf-8 -*- #
# Copyright 2023 Google LLC. All Rights Reserved.
#
# Licensed 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.
"""Evaluate policy command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.container.binauthz import apis
from googlecloudsdk.api_lib.container.binauthz import platform_policy
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.container.binauthz import flags
from googlecloudsdk.command_lib.container.binauthz import parsing
from googlecloudsdk.command_lib.container.binauthz import util
from googlecloudsdk.core.exceptions import Error
@base.DefaultUniverseOnly
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.ALPHA)
class Evaluate(base.Command):
"""Evaluate a Binary Authorization platform policy.
## EXAMPLES
To evaluate a policy using its resource name:
$ {command} projects/my-proj/platforms/gke/policies/my-policy
--resource=$KUBERNETES_RESOURCE
To evaluate the same policy using flags against an image:
$ {command} my-policy --platform=gke --project=my-proj --image=$IMAGE
"""
@staticmethod
def Args(parser):
flags.AddPlatformPolicyResourceArg(parser, 'to evaluate')
flags.AddEvaluationUnitArg(parser)
def Run(self, args):
policy_ref = args.CONCEPTS.policy_resource_name.Parse().RelativeName()
platform_id = policy_ref.split('/')[3]
if platform_id != 'gke':
raise Error(
"Found unsupported platform '{}'. Currently only 'gke' platform "
"policies are supported.".format(platform_id)
)
if args.resource:
resource_obj = parsing.LoadResourceFile(args.resource)
response = platform_policy.Client('v1').Evaluate(
policy_ref, resource_obj, False
)
else:
pod_spec = util.GeneratePodSpecFromImages(args.image)
response = platform_policy.Client('v1').Evaluate(
policy_ref, pod_spec, False
)
# Set non-zero exit code for non-conformant verdicts to improve the
# command's scriptability.
if (
response.verdict
!= apis.GetMessagesModule(
'v1'
).EvaluateGkePolicyResponse.VerdictValueValuesEnum.CONFORMANT
):
self.exit_code = 2
return response

View File

@@ -0,0 +1,142 @@
# -*- coding: utf-8 -*- #
# Copyright 2023 Google LLC. All Rights Reserved.
#
# Licensed 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.
"""Evaluate policy command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.container.binauthz import apis
from googlecloudsdk.api_lib.container.binauthz import platform_policy
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.container.binauthz import flags
from googlecloudsdk.command_lib.container.binauthz import parsing
from googlecloudsdk.command_lib.container.binauthz import sigstore_image
from googlecloudsdk.command_lib.container.binauthz import util
from googlecloudsdk.core import log
from googlecloudsdk.core import yaml
from googlecloudsdk.core.exceptions import Error
@base.Hidden
@base.DefaultUniverseOnly
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class EvaluateAndSign(base.Command):
"""Evaluate a Binary Authorization platform policy and sign the results, if conformant.
## EXAMPLES
To evaluate and sign a policy using its resource name:
$ {command} projects/my-proj/platforms/gke/policies/my-policy
--resource=$KUBERNETES_RESOURCE
To evaluate the same policy using flags against multiple images:
$ {command} my-policy --platform=gke --project=my-proj --image=$IMAGE1
--image=$IMAGE2
To return a modified resource with attestations added as an annotation on the
input resource, without uploading attestations to the registry:
$ {command} projects/my-proj/platforms/gke/policies/my-policy
--resource=$KUBERNETES_RESOURCE --output-file=$MODIFIED_RESOURCE --no-upload
To upload attestations using Docker credentials located in a custom directory:
$ {command} projects/my-proj/platforms/gke/policies/my-policy
--image=$IMAGE --use-docker-creds --docker-config-dir=$CUSTOM_DIR
"""
@staticmethod
def Args(parser):
flags.AddPlatformPolicyResourceArg(parser, 'to evaluate and sign')
flags.AddEvaluationUnitArg(parser)
flags.AddNoUploadArg(parser)
flags.AddOutputFileArg(parser)
flags.AddDockerCredsArgs(parser)
def Run(self, args):
policy_ref = args.CONCEPTS.policy_resource_name.Parse().RelativeName()
platform_id = policy_ref.split('/')[3]
if platform_id != 'gke':
raise Error(
"Found unsupported platform '{}'. Currently only 'gke' platform "
'policies are supported.'.format(platform_id)
)
if args.output_file and not args.resource:
raise util.Error('Cannot specify --output-file without --resource.')
if args.use_docker_creds and args.no_upload:
raise util.Error('Cannot specify --use-docker-creds with --no-upload.')
if args.docker_config_dir and not args.use_docker_creds:
raise util.Error(
'Cannot specify --docker-config-dir without --use-docker-creds.'
)
if args.resource:
resource_obj = parsing.LoadResourceFile(args.resource)
else:
resource_obj = util.GeneratePodSpecFromImages(args.image)
response = platform_policy.Client('v1').Evaluate(
policy_ref, resource_obj, True
)
# Set non-zero exit code for non-conformant verdicts to improve the
# command's scriptability.
if (
response.verdict
!= apis.GetMessagesModule(
'v1'
).EvaluateGkePolicyResponse.VerdictValueValuesEnum.CONFORMANT
):
self.exit_code = 2
return response
# Upload attestations.
if not args.no_upload:
for attestation in response.attestations:
image_url = sigstore_image.AttestationToImageUrl(attestation)
log.Print('Uploading attestation for {}'.format(image_url))
sigstore_image.UploadAttestationToRegistry(
image_url=image_url,
attestation=sigstore_image.StandardOrUrlsafeBase64Decode(
attestation
),
use_docker_creds=args.use_docker_creds,
docker_config_dir=args.docker_config_dir,
)
# Write inline attestations.
if args.output_file:
modified_resource = util.AddInlineAttestationsToResource(
resource_obj, response.attestations
)
if (
parsing.GetResourceFileType(args.resource)
== parsing.ResourceFileType.YAML
):
modified_resource = yaml.dump(modified_resource)
log.WriteToFileOrStdout(
args.output_file,
modified_resource,
overwrite=True,
binary=False,
private=True,
)
return response

View File

@@ -0,0 +1,56 @@
# -*- coding: utf-8 -*- #
# Copyright 2018 Google LLC. All Rights Reserved.
#
# Licensed 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.
"""Export Binary Authorization policy command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.container.binauthz import apis
from googlecloudsdk.api_lib.container.binauthz import policies
from googlecloudsdk.api_lib.container.binauthz import util
from googlecloudsdk.calliope import base
from googlecloudsdk.core.exceptions import Error
OLD_SYSTEM_POLICY_PROJECT_NAME = 'binauthz-global-policy'
@base.DefaultUniverseOnly
class Export(base.Command):
"""Export the Binary Authorization policy for the current project.
This function's default output is a valid policy YAML file. If dumped to a
file and edited, the new policy can be provided to the `$ {parent_command}
import` command to cause these edits to be reflected in the project policy.
## EXAMPLES
To export the current project's policy:
$ {command} > my_policy.yaml
"""
def Run(self, args):
api_version = apis.GetApiVersion(self.ReleaseTrack())
ref = util.GetPolicyRef()
if ref.Name() == OLD_SYSTEM_POLICY_PROJECT_NAME:
raise Error(
'The Binary Authorization system policy is no longer accessible via '
'the binauthz-global-policy project. Use the following command to '
'display the system policy:\n'
' $ gcloud alpha container binauthz policy export-system-policy\n'
'For details, see https://cloud.google.com/binary-authorization/docs/'
'key-concepts#google-maintained_system_images.')
return policies.Client(api_version).Get(ref)

View File

@@ -0,0 +1,68 @@
# -*- coding: utf-8 -*- #
# Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed 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.
"""Export Binary Authorization system policy command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.container.binauthz import apis
from googlecloudsdk.api_lib.container.binauthz import system_policy
from googlecloudsdk.api_lib.container.binauthz import util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.container.binauthz import arg_parsers
@base.DefaultUniverseOnly
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class ExportSystemPolicy(base.Command):
"""Export the Binary Authorization system policy.
For reliability reasons, the system policy is updated one region at a time.
Because of this precaution, the system policy can differ between regions
during an update. Use --location to view the system policy of a specific
region.
If --location is not specified, an arbitrary region is used. (Specifically, a
region in the last group of regions to receive updates. Since most changes are
additions, this will show the minimal set of system images that are allowed
in all regions.)
## EXAMPLES
To view the system policy:
$ {command}
To view the system policy in the region us-central1:
$ {command} --location=us-central1
"""
@classmethod
def Args(cls, parser):
parser.add_argument(
'--location',
# Although the name is "location" for consistency with other gcloud
# commands, only regions are allowed (not other locations, like zones).
choices=arg_parsers.BINAUTHZ_ENFORCER_REGIONS,
required=False,
default='global',
help='The region for which to get the system policy (or "global").')
def Run(self, args):
api_version = apis.GetApiVersion(self.ReleaseTrack())
return system_policy.Client(api_version).Get(
util.GetSystemPolicyRef(args.location))

View File

@@ -0,0 +1,44 @@
# -*- coding: utf-8 -*- #
# Copyright 2018 Google LLC. All Rights Reserved.
#
# Licensed 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.
"""Fetch the IAM policy for a Binary Authorization policy."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.container.binauthz import apis
from googlecloudsdk.api_lib.container.binauthz import iam
from googlecloudsdk.api_lib.container.binauthz import util
from googlecloudsdk.calliope import base
@base.DefaultUniverseOnly
class GetIamPolicy(base.ListCommand):
"""Get the IAM policy for a Binary Authorization policy.
Returns an empty policy if the resource does not have an existing IAM policy
set.
## EXAMPLES
The following command gets the IAM policy for the current project's Binary
Authorization policy:
$ {command}
"""
def Run(self, args):
api_version = apis.GetApiVersion(self.ReleaseTrack())
return iam.Client(api_version).Get(util.GetPolicyRef())

View File

@@ -0,0 +1,90 @@
# -*- coding: utf-8 -*- #
# Copyright 2018 Google LLC. All Rights Reserved.
#
# Licensed 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.
"""Import Binary Authorization policy command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.container.binauthz import apis
from googlecloudsdk.api_lib.container.binauthz import policies
from googlecloudsdk.api_lib.container.binauthz import util
from googlecloudsdk.api_lib.util import messages as messages_util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.container.binauthz import arg_parsers
from googlecloudsdk.command_lib.container.binauthz import parsing
from googlecloudsdk.core import log
from googlecloudsdk.core.console import console_io
@base.DefaultUniverseOnly
# TODO(b/77499756): Add help text for etags here (or maybe to the group help).
class Import(base.Command):
"""Import a Binary Authorization policy to the current project.
This command accepts a description of the desired policy in the form of a
YAML-formatted file. A representation of the current policy can be retrieved
using the $ {parent_command} export command. One method of modifying the
policy is to run `$ {parent_command} export`, dump the contents to a file,
modify the policy file to reflect the desired new policy, and provide this
modified file to `$ {command}`.
## EXAMPLES
To update the current project's policy:
$ {parent_command} export > my_policy.yaml
$ edit my_policy.yaml
$ {command} my_policy.yaml
"""
@classmethod
def Args(cls, parser):
parser.add_argument(
'policy_file',
type=arg_parsers.PolicyFileName,
help='The file containing the YAML-formatted policy description.')
parser.add_argument(
'--strict-validation',
action='store_true',
required=False,
help='Whether to perform additional checks on the validity of policy '
'contents.')
def Run(self, args):
api_version = apis.GetApiVersion(self.ReleaseTrack())
messages = apis.GetMessagesModule(api_version)
# Load the policy file into a Python object.
policy_obj = parsing.LoadResourceFile(args.policy_file)
if not policy_obj:
# NOTE: This is necessary because apitools falls over when you provide it
# with None and that's what the yaml returns when passed an empty string.
policy_obj = {}
# Make sure the user meant to do this.
log.warning('Empty Policy provided!')
console_io.PromptContinue(
prompt_string='Do you want to import an empty policy?',
cancel_on_no=True)
# Decode the dict into a Policy message, allowing DecodeErrors to bubble up
# to the user if they are raised.
policy = messages_util.DictToMessageWithErrorCheck(
policy_obj, messages.Policy)
return policies.Client(api_version).Set(util.GetPolicyRef(), policy)

View File

@@ -0,0 +1,55 @@
# -*- coding: utf-8 -*- #
# Copyright 2022 Google LLC. All Rights Reserved.
#
# Licensed 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.
"""List policy command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.container.binauthz import platform_policy
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.container.binauthz import flags
@base.DefaultUniverseOnly
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.ALPHA)
class List(base.ListCommand):
"""List Binary Authorization platform policies.
## EXAMPLES
To list the policies for GKE in the current project:
$ {command} gke
To list the policies for GKE in a specific project:
$ {command} gke --project=my-project-id
or
$ {command} projects/my-project-id/gke
"""
@staticmethod
def Args(parser):
flags.AddPlatformResourceArg(parser, 'to list')
parser.display_info.AddFormat('list(name,description)')
def Run(self, args):
platform_ref = args.CONCEPTS.platform_resource_name.Parse().RelativeName()
# The API is only available in v1.
return platform_policy.Client('v1').List(
platform_ref, page_size=args.page_size, limit=args.limit)

View File

@@ -0,0 +1,34 @@
release_tracks: [ALPHA, BETA, GA]
help_text:
brief: Remove IAM policy binding of a Binary Authorization policy.
description: |
Remove an IAM policy binding from the IAM policy of a Binary Authorization policy. One binding consists of a member,
a role, and an optional condition.
examples: |
To remove an IAM policy binding for the role of 'roles/binaryauthorization.attestationAuthoritiesEditor' for the user 'test-user@gmail.com'
on the current project's Binary Authorization policy, run:
$ {command} --member='user:test-user@gmail.com' --role='roles/binaryauthorization.attestationAuthoritiesEditor'
To remove an IAM policy binding which expires at the end of the year 2018 for the role of
'roles/binaryauthorization.attestationAuthoritiesEditor' and the user 'test-user@gmail.com'
on the current project's Binary Authorization policy, run:
$ {command} --member='user:test-user@gmail.com' --role='roles/binaryauthorization.attestationAuthoritiesEditor' --condition='expression=request.time < timestamp("2019-01-01T00:00:00Z"),title=expires_end_of_2018,description=Expires at midnight on 2018-12-31'
See https://cloud.google.com/iam/docs/managing-policies for details of
policy role and member types.
iam:
enable_condition: true
policy_version: 3
get_iam_policy_version_path: options_requestedPolicyVersion
request:
collection: binaryauthorization.projects.policy
arguments:
resource:
help_text: The Binary Authorization policy whose IAM policy to remove an IAM policy binding from.
spec: !REF googlecloudsdk.command_lib.container.resources:policy

View File

@@ -0,0 +1,62 @@
# -*- coding: utf-8 -*- #
# Copyright 2018 Google LLC. All Rights Reserved.
#
# Licensed 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.
"""Set the IAM policy for a Binary Authorization policy."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.container.binauthz import apis
from googlecloudsdk.api_lib.container.binauthz import iam
from googlecloudsdk.api_lib.container.binauthz import util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.iam import iam_util
@base.DefaultUniverseOnly
class SetIamPolicy(base.Command):
"""Set the IAM policy for a Binary Authorization policy.
See https://cloud.google.com/iam/docs/managing-policies for details of
the policy file format and contents.
## EXAMPLES
The following command will read an IAM policy defined in a JSON file
'iam_policy.json' and set it for the current project's Binary Authorization
policy:
$ {command} iam_policy.json
"""
# The above text is based on output of
# iam_util.GetDetailedHelpForSetIamPolicy.
@classmethod
def Args(cls, parser):
parser.add_argument(
'policy_file',
help=('The JSON or YAML '
'file containing the IAM policy.'))
def Run(self, args):
api_version = apis.GetApiVersion(self.ReleaseTrack())
client = iam.Client(api_version)
policy_ref = util.GetPolicyRef()
policy, _ = iam_util.ParseYamlOrJsonPolicyFile(args.policy_file,
client.messages.IamPolicy)
result = client.Set(policy_ref, policy)
iam_util.LogSetIamPolicy(policy_ref.Name(), 'policy')
return result

View File

@@ -0,0 +1,66 @@
# -*- coding: utf-8 -*- #
# Copyright 2022 Google LLC. All Rights Reserved.
#
# Licensed 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.
"""Update policy command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.container.binauthz import apis
from googlecloudsdk.api_lib.container.binauthz import platform_policy
from googlecloudsdk.api_lib.util import messages as messages_util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.container.binauthz import flags
from googlecloudsdk.command_lib.container.binauthz import parsing
@base.DefaultUniverseOnly
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.ALPHA)
class Update(base.UpdateCommand):
# pylint: disable=line-too-long
"""Update a Binary Authorization platform policy.
## EXAMPLES
To update an existing policy using its resource name:
$ {command} projects/my_proj/platforms/gke/policies/policy1 --policy-file=policy1.json
To update the same policy using flags:
$ {command} policy1 --platform=gke --project=my_proj --policy-file=policy1.json
"""
# pylint: enable=line-too-long
@staticmethod
def Args(parser):
flags.AddPlatformPolicyResourceArg(parser, 'to update')
parser.add_argument(
'--policy-file',
required=True,
help='The JSON or YAML file containing the new policy.')
parser.display_info.AddFormat('yaml')
def Run(self, args):
# The API is only available in v1.
messages = apis.GetMessagesModule('v1')
policy_ref = args.CONCEPTS.policy_resource_name.Parse().RelativeName()
# Load the policy file into a Python dict.
policy_obj = parsing.LoadResourceFile(args.policy_file)
# Decode the dict into a PlatformPolicy message, allowing DecodeErrors to
# bubble up to the user if they are raised.
policy = messages_util.DictToMessageWithErrorCheck(policy_obj,
messages.PlatformPolicy)
return platform_policy.Client('v1').Update(policy_ref, policy)