Skip to content

Commit

Permalink
feat: add iam methods to templates (#545)
Browse files Browse the repository at this point in the history
* feat: add iam methods to templates

* fix: fix typo

* chore: fix formatting

* fix: fix ref to option

* chore(deps): add iam dependency

* chore: add circleci

* chore: take 2

* chore: only test with 3.8

Co-authored-by: Dov Shlachter <dovs@google.com>
  • Loading branch information
busunkim96 and software-dov authored Jul 22, 2020
1 parent bbc6b36 commit 3f42c3c
Show file tree
Hide file tree
Showing 12 changed files with 1,227 additions and 1 deletion.
32 changes: 32 additions & 0 deletions .circleci/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,14 @@ workflows:
filters:
tags:
only: /^v\d+\.\d+\.\d+$/
- showcase-unit-add-iam-methods:
requires:
- unit-3.6
- unit-3.7
- unit-3.8
filters:
tags:
only: /^v\d+\.\d+\.\d+$/
- showcase-mypy:
requires:
- mypy
Expand Down Expand Up @@ -502,6 +510,30 @@ jobs:
- run:
name: Run unit tests.
command: nox -s showcase_unit_alternative_templates-3.8
showcase-unit-add-iam-methods:
docker:
- image: python:3.8-slim
steps:
- checkout
- run:
name: Install system dependencies.
command: |
apt-get update
apt-get install -y curl pandoc unzip
- run:
name: Install protoc 3.12.1.
command: |
mkdir -p /usr/src/protoc/
curl --location https://github.com/google/protobuf/releases/download/v3.12.1/protoc-3.12.1-linux-x86_64.zip --output /usr/src/protoc/protoc-3.12.1.zip
cd /usr/src/protoc/
unzip protoc-3.12.1.zip
ln -s /usr/src/protoc/bin/protoc /usr/local/bin/protoc
- run:
name: Install nox.
command: pip install nox
- run:
name: Run unit tests.
command: nox -s showcase_unit_add_iam_methods-3.8
showcase-mypy:
docker:
- image: python:3.8-slim
Expand Down
3 changes: 3 additions & 0 deletions gapic/generator/options.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ class Options:
templates: Tuple[str, ...] = dataclasses.field(default=('DEFAULT',))
lazy_import: bool = False
old_naming: bool = False
add_iam_methods: bool = False

# Class constants
PYTHON_GAPIC_PREFIX: str = 'python-gapic-'
Expand All @@ -47,6 +48,7 @@ class Options:
'retry-config', # takes a path
'samples', # output dir
'lazy-import', # requires >= 3.7
'add-iam-methods', # microgenerator implementation for `reroute_to_grpc_interface`
))

@classmethod
Expand Down Expand Up @@ -131,6 +133,7 @@ def tweak_path(p):
templates=tuple(path.expanduser(i) for i in templates),
lazy_import=bool(opts.pop('lazy-import', False)),
old_naming=bool(opts.pop('old-naming', False)),
add_iam_methods=bool(opts.pop('add-iam-methods', False)),
)

# Note: if we ever need to recursively check directories for sample
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ from google.oauth2 import service_account # type: ignore
{{ ref_type.ident.python_import }}
{% endfor -%}
{% endfor -%}
{% if opts.add_iam_methods %}
from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore
from google.iam.v1 import policy_pb2 as policy # type: ignore
{% endif %}
{% endfilter %}
from .transports.base import {{ service.name }}Transport
from .transports.grpc_asyncio import {{ service.grpc_asyncio_transport_name }}
Expand Down Expand Up @@ -256,6 +260,272 @@ class {{ service.async_client_name }}:
{% endfor %}


{% if opts.add_iam_methods %}
async def set_iam_policy(
self,
request: iam_policy.SetIamPolicyRequest = None,
*,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> policy.Policy:
r"""Sets the IAM access control policy on the specified
function. Replaces any existing policy.
Args:
request (:class:`~.iam_policy.SetIamPolicyRequest`):
The request object. Request message for `SetIamPolicy`
method.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
Returns:
~.policy.Policy:
Defines an Identity and Access Management (IAM) policy.
It is used to specify access control policies for Cloud
Platform resources.
A ``Policy`` is a collection of ``bindings``. A
``binding`` binds one or more ``members`` to a single
``role``. Members can be user accounts, service
accounts, Google groups, and domains (such as G Suite).
A ``role`` is a named list of permissions (defined by
IAM or configured by users). A ``binding`` can
optionally specify a ``condition``, which is a logic
expression that further constrains the role binding
based on attributes about the request and/or target
resource.
**JSON Example**
::
{
"bindings": [
{
"role": "roles/resourcemanager.organizationAdmin",
"members": [
"user:mike@example.com",
"group:admins@example.com",
"domain:google.com",
"serviceAccount:my-project-id@appspot.gserviceaccount.com"
]
},
{
"role": "roles/resourcemanager.organizationViewer",
"members": ["user:eve@example.com"],
"condition": {
"title": "expirable access",
"description": "Does not grant access after Sep 2020",
"expression": "request.time <
timestamp('2020-10-01T00:00:00.000Z')",
}
}
]
}
**YAML Example**
::
bindings:
- members:
- user:mike@example.com
- group:admins@example.com
- domain:google.com
- serviceAccount:my-project-id@appspot.gserviceaccount.com
role: roles/resourcemanager.organizationAdmin
- members:
- user:eve@example.com
role: roles/resourcemanager.organizationViewer
condition:
title: expirable access
description: Does not grant access after Sep 2020
expression: request.time < timestamp('2020-10-01T00:00:00.000Z')
For a description of IAM and its features, see the `IAM
developer's
guide <https://cloud.google.com/iam/docs>`__.
"""
# Create or coerce a protobuf request object.

# The request isn't a proto-plus wrapped type,
# so it must be constructed via keyword expansion.
if isinstance(request, dict):
request = iam_policy.SetIamPolicyRequest(**request)

# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = gapic_v1.method_async.wrap_method(
self._client._transport.set_iam_policy,
default_timeout=None,
client_info=_client_info,
)

# Certain fields should be provided within the metadata header;
# add these here.
metadata = tuple(metadata) + (
gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)),
)

# Send the request.
response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,)

# Done; return the response.
return response

async def get_iam_policy(
self,
request: iam_policy.GetIamPolicyRequest = None,
*,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> policy.Policy:
r"""Gets the IAM access control policy for a function.
Returns an empty policy if the function exists and does
not have a policy set.
Args:
request (:class:`~.iam_policy.GetIamPolicyRequest`):
The request object. Request message for `GetIamPolicy`
method.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
Returns:
~.policy.Policy:
Defines an Identity and Access Management (IAM) policy.
It is used to specify access control policies for Cloud
Platform resources.
A ``Policy`` is a collection of ``bindings``. A
``binding`` binds one or more ``members`` to a single
``role``. Members can be user accounts, service
accounts, Google groups, and domains (such as G Suite).
A ``role`` is a named list of permissions (defined by
IAM or configured by users). A ``binding`` can
optionally specify a ``condition``, which is a logic
expression that further constrains the role binding
based on attributes about the request and/or target
resource.
**JSON Example**
::
{
"bindings": [
{
"role": "roles/resourcemanager.organizationAdmin",
"members": [
"user:mike@example.com",
"group:admins@example.com",
"domain:google.com",
"serviceAccount:my-project-id@appspot.gserviceaccount.com"
]
},
{
"role": "roles/resourcemanager.organizationViewer",
"members": ["user:eve@example.com"],
"condition": {
"title": "expirable access",
"description": "Does not grant access after Sep 2020",
"expression": "request.time <
timestamp('2020-10-01T00:00:00.000Z')",
}
}
]
}
**YAML Example**
::
bindings:
- members:
- user:mike@example.com
- group:admins@example.com
- domain:google.com
- serviceAccount:my-project-id@appspot.gserviceaccount.com
role: roles/resourcemanager.organizationAdmin
- members:
- user:eve@example.com
role: roles/resourcemanager.organizationViewer
condition:
title: expirable access
description: Does not grant access after Sep 2020
expression: request.time < timestamp('2020-10-01T00:00:00.000Z')
For a description of IAM and its features, see the `IAM
developer's
guide <https://cloud.google.com/iam/docs>`__.
"""
# Create or coerce a protobuf request object.

# The request isn't a proto-plus wrapped type,
# so it must be constructed via keyword expansion.
if isinstance(request, dict):
request = iam_policy.GetIamPolicyRequest(**request)

# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = gapic_v1.method_async.wrap_method(
self._client._transport.get_iam_policy,
default_timeout=None,
client_info=_client_info,
)

# Certain fields should be provided within the metadata header;
# add these here.
metadata = tuple(metadata) + (
gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)),
)

# Send the request.
response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,)

# Done; return the response.
return response

async def test_iam_permissions(
self,
request: iam_policy.TestIamPermissionsRequest = None,
*,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> iam_policy.TestIamPermissionsResponse:
r"""Tests the specified permissions against the IAM access control
policy for a function. If the function does not exist, this will
return an empty set of permissions, not a NOT_FOUND error.
Args:
request (:class:`~.iam_policy.TestIamPermissionsRequest`):
The request object. Request message for
`TestIamPermissions` method.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
Returns:
~.iam_policy.TestIamPermissionsResponse:
Response message for ``TestIamPermissions`` method.
"""
# Create or coerce a protobuf request object.

# The request isn't a proto-plus wrapped type,
# so it must be constructed via keyword expansion.
if isinstance(request, dict):
request = iam_policy.TestIamPermissionsRequest(**request)

# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = gapic_v1.method_async.wrap_method(
self._client._transport.test_iam_permissions,
default_timeout=None,
client_info=_client_info,
)

# Certain fields should be provided within the metadata header;
# add these here.
metadata = tuple(metadata) + (
gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)),
)

# Send the request.
response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,)

# Done; return the response.
return response
{% endif %}

try:
_client_info = gapic_v1.client_info.ClientInfo(
gapic_version=pkg_resources.get_distribution(
Expand Down
Loading

0 comments on commit 3f42c3c

Please sign in to comment.