Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replace EventgridSharedAccessSignatureCredential with AzureSasCredential #16147

Merged
merged 8 commits into from
Jan 15, 2021
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions sdk/eventgrid/azure-eventgrid/azure/eventgrid/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,9 @@
from ._consumer import EventGridConsumer
from ._helpers import generate_shared_access_signature
from ._models import CloudEvent, CustomEvent, EventGridEvent
from ._shared_access_signature_credential import EventGridSharedAccessSignatureCredential
from ._version import VERSION

__all__ = ['EventGridPublisherClient', 'EventGridConsumer',
'CloudEvent', 'CustomEvent', 'EventGridEvent', 'generate_shared_access_signature',
'EventGridSharedAccessSignatureCredential']
'CloudEvent', 'CustomEvent', 'EventGridEvent', 'generate_shared_access_signature'
]
__version__ = VERSION
9 changes: 4 additions & 5 deletions sdk/eventgrid/azure-eventgrid/azure/eventgrid/_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,8 @@
from urllib2 import quote # type: ignore

from azure.core.pipeline.policies import AzureKeyCredentialPolicy
from azure.core.credentials import AzureKeyCredential
from ._shared_access_signature_credential import EventGridSharedAccessSignatureCredential
from ._signature_credential_policy import EventGridSharedAccessSignatureCredentialPolicy
from azure.core.credentials import AzureKeyCredential, AzureSasCredential
from ._signature_credential_policy import EventGridSasCredentialPolicy
from . import _constants as constants

if TYPE_CHECKING:
Expand Down Expand Up @@ -79,8 +78,8 @@ def _get_authentication_policy(credential):
raise ValueError("Parameter 'self._credential' must not be None.")
if isinstance(credential, AzureKeyCredential):
authentication_policy = AzureKeyCredentialPolicy(credential=credential, name=constants.EVENTGRID_KEY_HEADER)
if isinstance(credential, EventGridSharedAccessSignatureCredential):
authentication_policy = EventGridSharedAccessSignatureCredentialPolicy(
if isinstance(credential, AzureSasCredential):
authentication_policy = EventGridSasCredentialPolicy(
credential=credential,
name=constants.EVENTGRID_TOKEN_HEADER
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,7 @@

if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from azure.core.credentials import AzureKeyCredential
from ._shared_access_signature_credential import EventGridSharedAccessSignatureCredential
from azure.core.credentials import AzureKeyCredential, AzureSasCredential
SendType = Union[
CloudEvent,
EventGridEvent,
Expand All @@ -63,11 +62,11 @@ class EventGridPublisherClient(object):
:param str topic_hostname: The topic endpoint to send the events to.
:param credential: The credential object used for authentication which
implements SAS key authentication or SAS token authentication.
:type credential: ~azure.core.credentials.AzureKeyCredential or EventGridSharedAccessSignatureCredential
:type credential: ~azure.core.credentials.AzureKeyCredential or AzureSasCredential
rakshith91 marked this conversation as resolved.
Show resolved Hide resolved
"""

def __init__(self, topic_hostname, credential, **kwargs):
# type: (str, Union[AzureKeyCredential, EventGridSharedAccessSignatureCredential], Any) -> None
# type: (str, Union[AzureKeyCredential, AzureSasCredential], Any) -> None
topic_hostname = _get_topic_hostname_only_fqdn(topic_hostname)

self._topic_hostname = topic_hostname
Expand All @@ -78,7 +77,7 @@ def __init__(self, topic_hostname, credential, **kwargs):

@staticmethod
def _policies(credential, **kwargs):
# type: (Union[AzureKeyCredential, EventGridSharedAccessSignatureCredential], Any) -> List[Any]
# type: (Union[AzureKeyCredential, AzureSasCredential], Any) -> List[Any]
auth_policy = _get_authentication_policy(credential)
sdk_moniker = 'eventgrid/{}'.format(VERSION)
policies = [
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -10,19 +10,19 @@
from azure.core.pipeline.policies import SansIOHTTPPolicy

if TYPE_CHECKING:
from ._shared_access_signature_credential import EventGridSharedAccessSignatureCredential
from azure.core.credentials import AzureSasCredential


class EventGridSharedAccessSignatureCredentialPolicy(SansIOHTTPPolicy):
class EventGridSasCredentialPolicy(SansIOHTTPPolicy):
"""Adds a token header for the provided credential.
:param credential: The credential used to authenticate requests.
:type credential: ~azure.eventgrid.EventGridSharedAccessSignatureCredential
:param credential: The credential used to authenticate requests.
rakshith91 marked this conversation as resolved.
Show resolved Hide resolved
:type credential: ~azure.core.credentials.AzureSasCredential
:param str name: The name of the token header used for the credential.
:raises: ValueError or TypeError
"""
def __init__(self, credential, name, **kwargs): # pylint: disable=unused-argument
# type: (EventGridSharedAccessSignatureCredential, str, Any) -> None
super(EventGridSharedAccessSignatureCredentialPolicy, self).__init__()
# type: (AzureSasCredential, str, Any) -> None
super(EventGridSasCredentialPolicy, self).__init__()
self._credential = credential
if not name:
raise ValueError("name can not be None or empty")
Expand All @@ -31,4 +31,5 @@ def __init__(self, credential, name, **kwargs): # pylint: disable=unused-argume
self._name = name

def on_request(self, request):
# Request must contain one of the following authorization signature: aeg-sas-token, aeg-sas-key
request.http_request.headers[self._name] = self._credential.signature
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
# --------------------------------------------------------------------------

from typing import Any, Union, List, Dict, cast
from azure.core.credentials import AzureKeyCredential
from azure.core.credentials import AzureKeyCredential, AzureSasCredential
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.pipeline.policies import (
RequestIdPolicy,
Expand All @@ -32,7 +32,6 @@
)
from .._generated.aio import EventGridPublisherClient as EventGridPublisherClientAsync
from .._generated.models import CloudEvent as InternalCloudEvent, EventGridEvent as InternalEventGridEvent
from .._shared_access_signature_credential import EventGridSharedAccessSignatureCredential
from .._version import VERSION

SendType = Union[
Expand All @@ -59,13 +58,13 @@ class EventGridPublisherClient():
:param str topic_hostname: The topic endpoint to send the events to.
:param credential: The credential object used for authentication which implements
SAS key authentication or SAS token authentication.
:type credential: ~azure.core.credentials.AzureKeyCredential or EventGridSharedAccessSignatureCredential
:type credential: ~azure.core.credentials.AzureKeyCredential or AzureSasCredential
rakshith91 marked this conversation as resolved.
Show resolved Hide resolved
"""

def __init__(
self,
topic_hostname: str,
credential: Union[AzureKeyCredential, EventGridSharedAccessSignatureCredential],
credential: Union[AzureKeyCredential, AzureSasCredential],
**kwargs: Any) -> None:
self._client = EventGridPublisherClientAsync(
policies=EventGridPublisherClient._policies(credential, **kwargs),
Expand All @@ -76,7 +75,7 @@ def __init__(

@staticmethod
def _policies(
credential: Union[AzureKeyCredential, EventGridSharedAccessSignatureCredential],
credential: Union[AzureKeyCredential, AzureSasCredential],
**kwargs: Any
) -> List[Any]:
auth_policy = _get_authentication_policy(credential)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,16 @@
"<YOUR-TOPIC-NAME>.<REGION-NAME>.eventgrid.azure.net".
"""
import os
from azure.eventgrid import EventGridPublisherClient, EventGridEvent, generate_shared_access_signature, EventGridSharedAccessSignatureCredential
from azure.core.credentials import AzureKeyCredential
from azure.eventgrid import EventGridPublisherClient, EventGridEvent, generate_shared_access_signature
from azure.core.credentials import AzureKeyCredential, AzureSasCredential
from datetime import datetime, timedelta

topic_key = os.environ["EG_ACCESS_KEY"]
topic_hostname = os.environ["EG_TOPIC_HOSTNAME"]
expiration_date_utc = datetime.utcnow() + timedelta(hours=1)

signature = generate_shared_access_signature(topic_hostname, topic_key, expiration_date_utc)
credential = EventGridSharedAccessSignatureCredential(signature)
credential = AzureSasCredential(signature)
client = EventGridPublisherClient(topic_hostname, credential)

client.send([
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@
import time

from datetime import datetime, timedelta

from azure.eventgrid import EventGridPublisherClient, CloudEvent, generate_shared_access_signature, EventGridSharedAccessSignatureCredential
from azure.core import AzureSasCredential
from azure.eventgrid import EventGridPublisherClient, CloudEvent, generate_shared_access_signature

key = os.environ["CLOUD_ACCESS_KEY"]
topic_hostname = os.environ["CLOUD_TOPIC_HOSTNAME"]
Expand All @@ -30,7 +30,7 @@
signature = generate_shared_access_signature(topic_hostname, key, expiration_date_utc)

# authenticate client
credential = EventGridSharedAccessSignatureCredential(signature)
credential = AzureSasCredential(signature)
client = EventGridPublisherClient(topic_hostname, credential)

team_members = ["Josh", "Kerri", "Kieran", "Laurent", "Lily", "Matt", "Soren", "Srikanta", "Swathi"] # possible values for data field
Expand Down
5 changes: 2 additions & 3 deletions sdk/eventgrid/azure-eventgrid/tests/eventgrid_preparer.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,11 +62,10 @@ def create_resource(self, name, **kwargs):
topic = Topic(location=self.parameter_location, tags=None, input_schema=CUSTOM_EVENT_SCHEMA, input_schema_mapping=CUSTOM_JSON_INPUT_SCHEMA_MAPPING)
else:
topic = Topic(location=self.parameter_location)
topic_operation = self.client.topics.create_or_update(
topic_operation = self.client.topics.begin_create_or_update(
group.name,
name,
topic,
{}
)
self.resource = topic_operation.result()
key = self.client.topics.list_shared_access_keys(group.name, name)
Expand All @@ -85,7 +84,7 @@ def create_resource(self, name, **kwargs):
def remove_resource(self, name, **kwargs):
if self.is_live:
group = self._get_resource_group(**kwargs)
self.client.topics.delete(group.name, name, polling=False)
self.client.topics.begin_delete(group.name, name, polling=False)

def _get_resource_group(self, **kwargs):
try:
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
interactions:
- request:
body: '[{"id": "af14b28c-d479-4533-beb9-83c990482f29", "subject": "sample", "data":
body: '[{"id": "af4a62e7-c39a-4d15-809b-ff39e30e9919", "subject": "sample", "data":
{"sample": "eventgridevent"}, "eventType": "Sample.EventGrid.Event", "eventTime":
"2020-10-01T23:05:33.235276Z", "dataVersion": "2.0"}]'
"2021-01-15T07:36:18.684481Z", "dataVersion": "2.0"}]'
headers:
Accept:
- '*/*'
Expand All @@ -15,9 +15,9 @@ interactions:
Content-Type:
- application/json; charset=utf-8
User-Agent:
- azsdk-python-eventgrid/2.0.0b1 Python/3.7.3 (Windows-10-10.0.18362-SP0)
- azsdk-python-eventgrid/2.0.0b5 Python/3.7.3 (Windows-10-10.0.18362-SP0)
aeg-sas-token:
- r=https%3A%2F%2Feventgridtestdjwda35y4hv.westus-1.eventgrid.azure.net%2Fapi%2Fevents%3FapiVersion%3D2018-01-01&e=2020-10-02%2000%3A05%3A33.233284%2B00%3A00&s=0B7T2a3eV56nQhuNXp6VyBbV6vo7bD%2BAyJWAQcVy%2BGE%3D
- r=https%3A%2F%2Feventgridtestxxgaujwsgkd.westus-1.eventgrid.azure.net%2Fapi%2Fevents%3FapiVersion%3D2018-01-01&e=2021-01-15%2008%3A36%3A18.682541%2B00%3A00&s=uWcUItHS%2F%2B6URmVXHNZl9GL6nX%2FkBdELT71nXMqw4Qo%3D
method: POST
uri: https://eventgridtestegtopic.westus-1.eventgrid.azure.net/api/events?api-version=2018-01-01
response:
Expand All @@ -29,7 +29,7 @@ interactions:
content-length:
- '0'
date:
- Thu, 01 Oct 2020 23:05:33 GMT
- Fri, 15 Jan 2021 07:36:18 GMT
server:
- Microsoft-HTTPAPI/2.0
strict-transport-security:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@
from devtools_testutils import AzureMgmtTestCase, CachedResourceGroupPreparer

from azure_devtools.scenario_tests import ReplayableTest
from azure.core.credentials import AzureKeyCredential
from azure.eventgrid import EventGridPublisherClient, CloudEvent, EventGridEvent, CustomEvent ,EventGridSharedAccessSignatureCredential, generate_shared_access_signature
from azure.core.credentials import AzureKeyCredential, AzureSasCredential
from azure.eventgrid import EventGridPublisherClient, CloudEvent, EventGridEvent, CustomEvent, generate_shared_access_signature

from eventgrid_preparer import (
CachedEventGridTopicPreparer
Expand Down Expand Up @@ -185,7 +185,7 @@ def test_send_cloud_event_dict(self, resource_group, eventgrid_topic, eventgrid_
def test_send_signature_credential(self, resource_group, eventgrid_topic, eventgrid_topic_primary_key, eventgrid_topic_endpoint):
expiration_date_utc = dt.datetime.now(UTC()) + timedelta(hours=1)
signature = generate_shared_access_signature(eventgrid_topic_endpoint, eventgrid_topic_primary_key, expiration_date_utc)
credential = EventGridSharedAccessSignatureCredential(signature)
credential = AzureSasCredential(signature)
client = EventGridPublisherClient(eventgrid_topic_endpoint, credential)
eg_event = EventGridEvent(
subject="sample",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@
from devtools_testutils import AzureMgmtTestCase, CachedResourceGroupPreparer

from azure_devtools.scenario_tests import ReplayableTest
from azure.core.credentials import AzureKeyCredential
from azure.eventgrid import CloudEvent, EventGridEvent, CustomEvent ,EventGridSharedAccessSignatureCredential, generate_shared_access_signature
from azure.core.credentials import AzureKeyCredential, AzureSasCredential
from azure.eventgrid import CloudEvent, EventGridEvent, CustomEvent, generate_shared_access_signature
from azure.eventgrid.aio import EventGridPublisherClient

from eventgrid_preparer import (
Expand Down Expand Up @@ -205,7 +205,7 @@ async def test_send_cloud_event_dict(self, resource_group, eventgrid_topic, even
async def test_send_signature_credential(self, resource_group, eventgrid_topic, eventgrid_topic_primary_key, eventgrid_topic_endpoint):
expiration_date_utc = dt.datetime.now(UTC()) + timedelta(hours=1)
signature = generate_shared_access_signature(eventgrid_topic_endpoint, eventgrid_topic_primary_key, expiration_date_utc)
credential = EventGridSharedAccessSignatureCredential(signature)
credential = AzureSasCredential(signature)
client = EventGridPublisherClient(eventgrid_topic_endpoint, credential)
eg_event = EventGridEvent(
subject="sample",
Expand Down