def test_generate_policy(self):
        event = {
            'methodArn':
            'arn:aws:execute-api:ap-northeast-1:000000000000:abcdefghij/*/GET/articles/images:batchGet',
            'authorizationToken': 'ABCDEFG'
        }
        authorizer = Authorizer(event, {})
        principal_id = 'hogehoge'
        effect = 'Allow'
        resource = event['methodArn']

        result = authorizer._Authorizer__generate_policy(
            principal_id, effect, resource)

        expected = {
            "principalId": 'hogehoge',
            "policyDocument": {
                "Version":
                "2012-10-17",
                "Statement": [{
                    "Action":
                    'execute-api:Invoke',
                    "Effect":
                    'Allow',
                    "Resource":
                    'arn:aws:execute-api:ap-northeast-1:000000000000:abcdefghij/*/GET/articles/images:batchGet'
                }]
            }
        }

        self.assertEqual(result, expected)
    def test_extract_method_and_path(self):
        event = {
            'methodArn':
            'arn:aws:execute-api:ap-northeast-1:000000000000:abcdefghij/*/GET/articles/images:batchGet',
            'authorizationToken': 'ABCDEFG'
        }
        authorizer = Authorizer(event, {})

        http_method, resource_path = authorizer._Authorizer__extract_method_and_path(
            event['methodArn'])
        self.assertEqual(http_method, 'GET')
        self.assertEqual(resource_path, 'articles/images:batchGet')
    def test_introspect(self):
        event = {
            'methodArn':
            'arn:aws:execute-api:ap-northeast-1:000000000000:abcdefghij/*/GET/articles/images:batchGet',
            'authorizationToken': 'ABCDEFG'
        }
        authorizer = Authorizer(event, {})
        scope = ['read', 'write']

        with self.assertRaises(Exception) as e:
            authorizer._Authorizer__introspect(scope)

        self.assertEqual(e.exception.args[0],
                         'Internal Server Error(RequestException)')
    def test_main_ok(self):
        event = {
            'methodArn':
            'arn:aws:execute-api:ap-northeast-1:000000000000:abcdefghij/*/GET/articles/images:batchGet',
            'authorizationToken': 'ABCDEFG'
        }

        result = Authorizer(event, {}).main()

        expected = {
            "principalId": 'John',
            "policyDocument": {
                "Version":
                "2012-10-17",
                "Statement": [{
                    "Action":
                    'execute-api:Invoke',
                    "Effect":
                    'Allow',
                    "Resource":
                    'arn:aws:execute-api:ap-northeast-1:000000000000:abcdefghij/*/GET/articles/images:batchGet'
                }]
            }
        }
        self.assertEqual(result, expected)
    def test_main_deny_api_call_with_unauthorized(self):
        event = {
            'methodArn':
            'arn:aws:execute-api:ap-northeast-1:000000000000:abcdefghij/*/GET/articles/images:batchGet',
            'authorizationToken': 'ABCDEFG'
        }

        expected = {
            "principalId": 'ng',
            "policyDocument": {
                "Version":
                "2012-10-17",
                "Statement": [{
                    "Action":
                    'execute-api:Invoke',
                    "Effect":
                    'Deny',
                    "Resource":
                    'arn:aws:execute-api:ap-northeast-1:000000000000:abcdefghij/*/GET/articles/images:batchGet'
                }]
            }
        }
        with patch('authorizer.Authorizer._Authorizer__introspect',
                   MagicMock(return_value={'action': 'UNAUTHORIZED'})):
            with self.subTest():
                result = Authorizer(event, {}).main()
                self.assertEqual(result, expected)
def test_deny_non_admin_user(mock_public_key):
    user = {
        'name': '*****@*****.**',
        'email': '*****@*****.**',
        'status': 'Approved',
        'firstName': 'John',
        'lastName': 'Doe',
        'roles': ['USER']
    }

    result = Authorizer(token=encoded_token(user), arn=ARN).policy()
    assert result == {
        'principalId': 'user_id',
        'policyDocument': {
            'Version':
            '2012-10-17',
            'Statement': [{
                'Action': 'execute-api:Invoke',
                'Effect': 'Deny',
                'Resource': '1234'
            }]
        },
        'context': {
            'name': '*****@*****.**',
            'email': '*****@*****.**',
            'status': 'Approved',
            'firstName': 'John',
            'lastName': 'Doe'
        }
    }
def test_build_policy_with_user():
    user = {
        'firstName': 'John',
        'lastName': 'Doe',
        'email': '*****@*****.**'
    }
    token = build_token(user)
    policy = Authorizer.build_policy(token, ARN, is_allowed=True)
    assert policy == {
        'principalId': 'user_id',
        'policyDocument': {
            'Version':
            '2012-10-17',
            'Statement': [{
                'Action': 'execute-api:Invoke',
                'Effect': 'Allow',
                'Resource': '1234'
            }]
        },
        'context': {
            'firstName': 'John',
            'lastName': 'Doe',
            'email': '*****@*****.**'
        }
    }
    def test_main_internal_server_error(self):
        event = {
            'methodArn':
            'arn:aws:execute-api:ap-northeast-1:000000000000:abcdefghij/*/GET/articles/images:batchGet',
            'authorizationToken': 'ABCDEFG'
        }

        with self.assertRaises(Exception) as e:
            Authorizer(event, {}).main()

        self.assertEqual(e.exception.args[0], 'Internal Server Error')
def test_raise_error_if_expired_token(mock_public_key):
    user = {
        'name': '*****@*****.**',
        'email': '*****@*****.**',
        'status': 'Approved',
        'firstName': 'John',
        'lastName': 'Doe',
        'roles': ['ADMIN']
    }
    expired_token = encoded_token(user,
                                  exp=(datetime.utcnow() - timedelta(hours=1)))

    with pytest.raises(ExpiredSignatureError):
        Authorizer(token=expired_token, arn=ARN).policy()
def test_build_policy_deny():
    token = build_token({})
    policy = Authorizer.build_policy(token, ARN, is_allowed=False)
    assert policy == {
        'principalId': 'user_id',
        'policyDocument': {
            'Version':
            '2012-10-17',
            'Statement': [{
                'Action': 'execute-api:Invoke',
                'Effect': 'Deny',
                'Resource': '1234'
            }]
        }
    }
    def test_get_required_scopes(self):
        # http_method, resource_path, expected(scope)の順でテストケースを定義
        cases = [['GET', 'me/unread_notification_managers', ['read']],
                 ['PUT', 'me/unread_notification_managers', ['read']],
                 [
                     'POST', 'me/unread_notification_managers',
                     ['read', 'write']
                 ], ['POST', 'me/users/fraud', ['read', 'write']]]

        authorizer = Authorizer({}, {})

        for case in cases:
            with self.subTest():
                scope = authorizer._Authorizer__get_required_scopes(
                    case[0], case[1])
                self.assertEqual(scope, case[2])
Example #12
0
def lambda_handler(event, context):
    authorizer = Authorizer(event=event, context=context)
    return authorizer.main()
 def setUp(self):
     self.mock_session = Mock()
     self.mock_token_generator = Mock()
     self.authorizer = Authorizer(self.mock_session,
                                  self.mock_token_generator)
     self.mock_event_queue = Mock()
def test_raise_error_if_invalid_token(mock_public_key):
    with pytest.raises(DecodeError):
        Authorizer(token='wrong_token', arn=ARN).policy()
Example #15
0
import csv
import tweepy
from authorizer import Authorizer

auth = Authorizer()
auth = auth.authorize()
api = tweepy.API(auth)
public_tweets = api.home_timeline()

file = open("tweets.csv", 'w+')
with file:
    writer = csv.writer(file)
    for tweet in public_tweets:
        writer.writerow(tweet.text)
        print("Writing {} to tweets.csv".format( (tweet.text[:10] + "..") if len(tweet.text) > 11 else tweet.text))

print("all done")
Example #16
0
import csv
import tweepy
from authorizer import Authorizer

auth = Authorizer()
auth = auth.authorize()
api = tweepy.API(auth)
public_tweets = api.home_timeline()

file = open("tweets.csv", 'w+')
with file:
    writer = csv.writer(file)
    for tweet in public_tweets:
        writer.writerow(tweet.text)
        print("Writing {} to tweets.csv".format((
            tweet.text[:10] + "..") if len(tweet.text) > 11 else tweet.text))

print("all done")
class TestAuthorizer(unittest.TestCase):
    """ Test cases for Authorizer. """
    def setUp(self):
        self.mock_session = Mock()
        self.mock_token_generator = Mock()
        self.authorizer = Authorizer(self.mock_session,
                                     self.mock_token_generator)
        self.mock_event_queue = Mock()

    def testAuthorizationSuccess(self):
        """ Verify that for a valid identity the authorization returns True.

        Plan:
        1. Create a service instance from the apiauth schema.
        2. Set the following expectations:
           b. Verify that service is opened and successfully retrieved.
        3. Create an admin event to represent the authorization success.
        4. Call authorize()
        4. Verify the following:
           a. The service is opened and retrieved.
           b. A token is generated.
           c. An authorization request is sent.
           d. authorize() returns True.
        """
        self.mock_session.openService.return_value = True

        service = blpapi.test.deserializeService(APIAUTH_SCHEMA)
        self.mock_session.getService.return_value = service

        token = "abcdefg"
        self.mock_token_generator.generate.return_value = token

        event = blpapi.test.createEvent(blpapi.Event.RESPONSE)
        authorization_success = blpapi.Name("AuthorizationSuccess")
        schema_def = \
            blpapi.test.getAdminMessageDefinition(authorization_success)

        blpapi.test.appendMessage(event, schema_def)

        # The AuthorizationSuccess message does not have any fields, therefore
        # no formatting is required.

        self.mock_event_queue.nextEvent.return_value = event

        identity = Mock()
        authorization_result = self.authorizer.authorize(
            identity, self.mock_event_queue)

        self.mock_session.openService.assert_called_once()
        self.mock_session.getService.assert_called_once()
        self.mock_session.sendAuthorizationRequest.assert_called_once()

        self.mock_token_generator.generate.assert_called_once()
        self.mock_event_queue.nextEvent.assert_called_once()

        self.assertTrue(authorization_result)

    def testAuthorizationFailure(self):
        """ Verify that for a invalid identity the authorization returns False.

        Plan:
        1. Create a service instance from the apiauth schema.
        2. Create and format an event to represent the authorization failure.
        3. Call authorize()
        4. Verify the following:
           a. The service is opened and retrieved.
           b. A token is generated.
           c. An authorization request is sent.
           d. authorize() returns False.
        """
        self.mock_session.openService.return_value = True

        service = blpapi.test.deserializeService(APIAUTH_SCHEMA)
        self.mock_session.getService.return_value = service

        token = "abcdefg"
        self.mock_token_generator.generate.return_value = token

        event = blpapi.test.createEvent(blpapi.Event.RESPONSE)
        authorization_request = blpapi.Name("AuthorizationRequest")
        authorization_failure_index = 1
        schema_def = service \
                        .getOperation(authorization_request) \
                        .getResponseDefinitionAt(authorization_failure_index)

        formatter = blpapi.test.appendMessage(event, schema_def)

        message_content = {
            "reason": {
                "code": 101,
                "message": "Invalid user",
                "category": "BAD_ARGS",
                "subcategory": "INVALID_USER",
                "source": "test-source"
            }
        }

        formatter.formatMessageDict(message_content)

        self.mock_event_queue.nextEvent.return_value = event

        identity = Mock()
        authorization_result = self.authorizer.authorize(
            identity, self.mock_event_queue)

        self.mock_session.openService.assert_called_once()
        self.mock_session.getService.assert_called_once()
        self.mock_session.sendAuthorizationRequest.assert_called_once()

        self.mock_token_generator.generate.assert_called_once()
        self.mock_event_queue.nextEvent.assert_called_once()

        self.assertFalse(authorization_result)
Example #18
0
from authorizer import Authorizer

# Una vez el sistema reciba una notificacion del usuario se llama a la clase
# Authorizer para poder saber si el usuario queda autenticado o no
auth = Authorizer()
checkUserStatus = auth.verify('', 'user: admin password: ***',
                              '181.139.254.197')

if (checkUserStatus):
    print('El usuario ha accedido exitosamente')
else:
    print('El usuario no ha podido acceder al sistema')
Example #19
0
if __name__ == "__main__":
    options = appconfig.parseCmdLine()
    compute_engine = ComputeEngine()
    notifier = Notifier()
    event_processor = EventProcessor(notifier, compute_engine)

    so = blpapi.SessionOptions()
    for i, host in enumerate(options.hosts):
        so.setServerAddress(host, options.port, i)

    so.setAuthenticationOptions(options.auth['option'])

    session = blpapi.Session(so, event_processor.processEvent)

    token_generator = TokenGenerator(session)
    authorizer = Authorizer(session, token_generator)

    subscriber = Subscriber(session)

    application = Application(session, authorizer, subscriber, options)

    application.run()

    input("Press Enter to continue...\n")

__copyright__ = """
Copyright 2020. Bloomberg Finance L.P.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
Example #20
0
def handler(event, context):
    """Lambda authorizer that build a policy for a JWT token from EGO."""
    token = event['authorizationToken']
    arn = event['methodArn']
    authorizer = Authorizer(token, arn)
    return authorizer.policy()