def test_reverse_proxy_endpoint_redirection_identity(self):
        def _callback(pipeline_request):
            assert pipeline_request.http_request.url.startswith("https://apim.contoso.com/")
            raise ValueError("Success!")
        wps_endpoint = "https://wps.contoso.com/"
        apim_endpoint = "https://apim.contoso.com/"
        credential = self.get_credential(WebPubSubServiceClient)
        client = WebPubSubServiceClient(wps_endpoint, "Hub", credential, reverse_proxy_endpoint=apim_endpoint)
        request = build_send_to_all_request('Hub', content='test_webpubsub_send_request', content_type='text/plain')

        with pytest.raises(ValueError) as ex:
            client.send_request(request, raw_request_hook=_callback)
        assert "Success!" in str(ex.value)
Exemple #2
0
def test_build_stream_request():
    stream = io.BytesIO(b'1234')
    client = WebPubSubServiceClient('https://www.microsoft.com/api',
                                    AzureKeyCredential('abcd'))
    request = build_send_to_all_request(
        'hub', content=stream, content_type='application/octet-stream')
    assert request.headers['content-type'] == 'application/octet-stream'
def test_generate_uri_contains_expected_payloads_dto(user_id, roles):
    client = WebPubSubServiceClient.from_connection_string(
        "Endpoint=http://localhost;Port=8080;AccessKey={};Version=1.0;".format(
            access_key), "hub")
    minutes_to_expire = 5
    token = client.get_client_access_token(user_id=user_id,
                                           roles=roles,
                                           minutes_to_expire=minutes_to_expire)
    assert token
    assert len(token) == 3
    assert set(token.keys()) == set(["baseUrl", "url", "token"])
    assert "access_token={}".format(token['token']) == urlparse(
        token["url"]).query
    token = token['token']
    decoded_token = _decode_token(client, token)
    assert decoded_token['aud'] == "{}/client/hubs/hub".format(
        client._config.endpoint)

    # default expire should be around 5 minutes
    assert decoded_token['exp'] - decoded_token[
        'iat'] >= minutes_to_expire * 60 - 5
    assert decoded_token['exp'] - decoded_token[
        'iat'] <= minutes_to_expire * 60 + 5
    if user_id:
        assert decoded_token['sub'] == user_id
    else:
        assert not decoded_token.get('sub')

    if roles:
        assert decoded_token['role'] == roles
    else:
        assert not decoded_token.get('role')
Exemple #4
0
def handle_event():
    if request.method == 'OPTIONS' or request.method == 'GET':
        if request.headers.get('WebHook-Request-Origin'):
            res = Response()
            res.headers['WebHook-Allowed-Origin'] = '*'
            res.status_code = 200
            return res
    elif request.method == 'POST':
        user_id = request.headers.get('ce-userid')
        if request.headers.get('ce-type') == 'azure.webpubsub.sys.connected':
            return user_id + ' connected', 200
        elif request.headers.get('ce-type') == 'azure.webpubsub.user.message':
            client = WebPubSubServiceClient.from_connection_string(sys.argv[1])
            client.send_request(
                build_send_to_all_request(hub_name,
                                          json={
                                              'from':
                                              user_id,
                                              'message':
                                              request.data.decode('UTF-8')
                                          }))
            res = Response(content_type='text/plain', status=200)
            return res
        else:
            return 'Not found', 404
Exemple #5
0
 def create_client(self, endpoint=None, hub=None, reverse_proxy_endpoint=None, **kwargs):
     if kwargs.get("connection_string"):
         return WebPubSubServiceClient.from_connection_string(kwargs.pop("connection_string"), hub, **kwargs)
     credential = self.get_credential(WebPubSubServiceClient)
     return self.create_client_from_credential(
         WebPubSubServiceClient,
         credential=credential,
         endpoint=endpoint,
         hub=hub,
         reverse_proxy_endpoint=reverse_proxy_endpoint
     )
Exemple #6
0
def test_build_send_message_exclude():
    stream = io.BytesIO(b'{ "hello": "web" }')
    client = WebPubSubServiceClient('https://www.microsoft.com/api',
                                    AzureKeyCredential('abcd'))
    request = build_send_to_all_request('hub',
                                        content=stream,
                                        content_type='application/octet-json',
                                        excluded=['a', 'b', 'c'])
    assert 'excluded=a&' in request.url
    assert 'excluded=b&' in request.url
    assert 'excluded=c' in request.url
    assert 'excluded=d' not in request.url
def test_generate_url_use_same_kid_with_same_key(connection_string, hub,
                                                 expected_url):
    client = WebPubSubServiceClient.from_connection_string(
        connection_string, hub)
    url_1 = client.get_client_access_token()['url']
    url_2 = client.get_client_access_token()['url']

    assert url_1.split("?")[0] == url_2.split("?")[0] == expected_url

    token_1 = urlparse(url_1).query[len("access_token="):]
    token_2 = urlparse(url_2).query[len("access_token="):]

    decoded_token_1 = _decode_token(client, token_1)
    decoded_token_2 = _decode_token(client, token_2)

    assert len(decoded_token_1) == len(decoded_token_2) == 3
    assert decoded_token_1['aud'] == decoded_token_2[
        'aud'] == expected_url.replace('ws', 'http')
    assert abs(decoded_token_1['iat'] - decoded_token_2['iat']) < 5
    assert abs(decoded_token_1['exp'] - decoded_token_2['exp']) < 5
Exemple #8
0
from azure.core.exceptions import HttpResponseError

logging.basicConfig(level=logging.DEBUG)
LOG = logging.getLogger()

try:
    connection_string = os.environ['WEBPUBSUB_CONNECTION_STRING']
    reverse_proxy_endpoint = os.environ["WEBPUBSUB_REVERSE_PROXY_ENDPOINT"]
except KeyError:
    LOG.error("Missing environment variable 'WEBPUBSUB_CONNECTION_STRING' or 'WEBPUBSUB_REVERSE_PROXY_ENDPOINT' - please set if before running the example")
    exit()

# Build a client from the connection string. And for this example, we have enabled debug
# tracing. For production code, this should be turned off.
# If you want to know more about the effect of `reverse_proxy_endpoint`, please reference: https://github.com/Azure/azure-webpubsub/issues/194
client = WebPubSubServiceClient.from_connection_string(connection_string, hub='hub', logging_enable=True, reverse_proxy_endpoint=reverse_proxy_endpoint)

try:
    # Raise an exception if the service rejected the call
    client.send_to_all(message={'Hello': 'connection_string_reverse_proxy!'})
    print('Successfully sent a JSON message')
except HttpResponseError as e:
    print('Failed to send JSON message: {}'.format(e.response.json()))

# Send a text message to everybody on the given hub...
try:
    # Raise an exception if the service rejected the call
    client.send_to_all(message='hello, connection_string_reverse_proxy!', content_type='text/plain')
    print('Successfully sent a JSON message')
except HttpResponseError as e:
    print('Failed to send JSON message: {}'.format(e.response.json()))
Exemple #9
0
import sys
from azure.messaging.webpubsubservice import (WebPubSubServiceClient)
from azure.messaging.webpubsubservice.rest import *

if len(sys.argv) != 4:
    print('Usage: python publish.py <connection-string> <hub-name> <message>')
    exit(1)

connection_string = sys.argv[1]
hub_name = sys.argv[2]
message = sys.argv[3]

service_client = WebPubSubServiceClient.from_connection_string(
    connection_string)
res = service_client.send_request(
    build_send_to_all_request(hub_name,
                              content=message,
                              content_type='text/plain'))
print(res)
Exemple #10
0
def test_build_json_request():
    client = WebPubSubServiceClient('https://www.microsoft.com/api',
                                    AzureKeyCredential('abcd'))
    request = build_send_to_all_request('hub', json={'hello': 'world'})
    assert request.headers['content-type'] == 'application/json'
logging.basicConfig(level=logging.DEBUG)
LOG = logging.getLogger()

try:
    connection_string = os.environ['WEBPUBSUB_CONNECTION_STRING']
except KeyError:
    LOG.error(
        "Missing environment variable 'WEBPUBSUB_CONNECTION_STRING' - please set if before running the example"
    )
    exit()

# Build a client from the connection string. And for this example, we have enabled debug
# tracing. For production code, this should be turned off.
client = WebPubSubServiceClient.from_connection_string(connection_string,
                                                       hub='hub',
                                                       logging_enable=True)

try:
    # Raise an exception if the service rejected the call
    client.send_to_all(message={'Hello': 'all!'})
    print('Successfully sent a JSON message')
except HttpResponseError as e:
    print('Failed to send JSON message: {}'.format(e.response.json()))

# Send a text message to everybody on the given hub...
try:
    # Raise an exception if the service rejected the call
    client.send_to_all(message='hello, text!', content_type='text/plain')
    print('Successfully sent a JSON message')
except HttpResponseError as e:
from azure.messaging.webpubsubservice import WebPubSubServiceClient
from azure.messaging.webpubsubservice.rest import *

logging.basicConfig(level=logging.DEBUG)
LOG = logging.getLogger()

try:
    connection_string = os.environ['WEBPUBSUB_CONNECTION_STRING']
except KeyError:
    LOG.error("Missing environment variable 'WEBPUBSUB_CONNECTION_STRING' - please set if before running the example")
    exit()

# Build a client from the connection string. And for this example, we have enabled debug
# tracing. For production code, this should be turned off. 
client = WebPubSubServiceClient.from_connection_string(connection_string, tracing_enabled=True)

# Send a json message to everybody on the given hub...
request = build_send_to_all_request('myHub', json={ 'Hello': 'all!' })
print(request.headers)
response = client.send_request(request)
try:
    # Raise an exception if the service rejected the call
    response.raise_for_status()
    print('Successfully sent a JSON message')
except:
    print('Failed to send JSON message: {}'.format(response))


# Send a text message to everybody on the given hub...
request = build_send_to_all_request('ahub', content='hello, text!', content_type='text/plain')
logging.basicConfig(level=logging.DEBUG)
LOG = logging.getLogger()

# Set the values of the client ID, tenant ID, and client secret of the AAD application as environment variables:
# AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET, WEBPUBSUB_ENDPOINT
try:
    endpoint = os.environ["WEBPUBSUB_ENDPOINT"]
except KeyError:
    LOG.error(
        "Missing environment variable 'WEBPUBSUB_ENDPOINT' - please set if before running the example"
    )
    exit()

# Build a client through AAD
client = WebPubSubServiceClient(endpoint=endpoint,
                                hub='hub',
                                credential=DefaultAzureCredential())

# Send a json message to everybody on the given hub...
try:
    # Raise an exception if the service rejected the call
    client.send_to_all(message={'Hello': 'all'})
    print('Successfully sent a JSON message')
except HttpResponseError as e:
    print('Failed to send JSON message: {}'.format(e.response.json()))

# Send a text message to everybody on the given hub...
try:
    # Raise an exception if the service rejected the call
    client.send_to_all(message='hello, text!', content_type='text/plain')
    print('Successfully sent a text message')
logging.basicConfig(level=logging.DEBUG)
LOG = logging.getLogger()

# Set the values of the client ID, tenant ID, and client secret of the AAD application as environment variables:
# AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET, WEBPUBSUB_ENDPOINT, WEBPUBSUB_CONNECTION_STRING
try:
    endpoint = os.environ["WEBPUBSUB_ENDPOINT"]
    connection_string = os.environ['WEBPUBSUB_CONNECTION_STRING']
except KeyError:
    LOG.error(
        "Missing environment variable 'WEBPUBSUB_ENDPOINT' or 'WEBPUBSUB_CONNECTION_STRING' - please set if before running the example"
    )
    exit()

# Build a client through AAD
client_aad = WebPubSubServiceClient(endpoint=endpoint,
                                    hub='hub',
                                    credential=DefaultAzureCredential())

# Build authentication token
token_aad = client_aad.get_client_access_token()
print('token by AAD: {}'.format(token_aad))

# Build a client through connection string
client_key = WebPubSubServiceClient.from_connection_string(connection_string,
                                                           hub='hub')

# Build authentication token
token_key = client_key.get_client_access_token()
print('token by access key: {}'.format(token_key))
def test_parse_connection_string(connection_string, endpoint):
    client = WebPubSubServiceClient.from_connection_string(
        connection_string, "hub")
    assert client._config.endpoint == endpoint
    assert isinstance(client._config.credential, AzureKeyCredential)
    assert client._config.credential.key == access_key
def test_pass_in_jwt_headers(connection_string):
    client = WebPubSubServiceClient.from_connection_string(
        connection_string, "hub")
    kid = '1234567890'
    token = client.get_client_access_token(jwt_headers={"kid": kid})['token']
    assert jwt.get_unverified_header(token)['kid'] == kid