Пример #1
0
    def test_good_user_cache_expire_config(self):
        auth = authentication.Authentication(
            authentication.AuthenticationConfig(['32555940559'],
                                                ['.gserviceaccount.com'], 1))
        token = "testtoken"
        expected_user_info = authentication.UserInfo("193481341723041",
                                                     "*****@*****.**", token, 100)

        def token_fn(token):
            token_data = {
                "audience": "32555940559.apps.googleusercontent.com",
                "user_id": expected_user_info.id,
                "expires_in": expected_user_info.expires_in,
                "email": expected_user_info.email,
                "verified_email": True
            }
            return json.dumps(token_data)

        auth.require_user_info(TestRequestState('bearer ' + token), token_fn)

        def token_fn2(token):
            raise Exception("should detect this exception")

        import time
        time.sleep(2)

        with self.assertRaises(Exception):
            auth.require_user_info(TestRequestState('bearer ' + token),
                                   token_fn2)
Пример #2
0
def authentication_engine():
    '''
    验证引擎
    :param proxyDict: 代理 IP 字典
    :return: 通过验证后,赋值给响应逻辑器LOGIC_RESPONSE
    '''
    LOG.info("[*] 开始执行验证引擎")
    auth = authentication.Authentication(headers=HEADERS)
    # 避免每次创建对象都开辟块内存,调用四个进程池,特别占内存
    proxyOP = proxyPool.IPOperator(headers=HEADERS)
    global VALID_URL
    try:
        #### 验证 HTTP ####
        # 遍历 url 列表进行 http 验证请求,将有效的 url 存储在 VALID_URL 中
        LOG.info("[+] 验证 HTTP")  # 写入日志
        for url in URL_LIST.values():
            if auth.httpCodeVerify(url):
                VALID_URL.append(url)

        # 遍历新加入的 url 列表
        for url_zb in URL_LIST_ZB.values():
            if auth.httpCodeVerify(url_zb):
                VALID_URL.append(url_zb)

        # 遍历有效的 URL
        print("-" * 40)
        print("[+] 有效的 URL({0})".format(len(VALID_URL)))
        for valid_url in VALID_URL:
            print(str(valid_url))
        print("-" * 40)
    except Exception, e:
        LOG.error("[-] {0}".format(str(e.message)))  # 写入日志
Пример #3
0
    def __init__(self):
        def create_provider(provider_name):
            client_id = config.get(provider_name, 'CLIENT_ID')
            client_secret = config.get(provider_name, 'CLIENT_SECRET')
            open_id_config_url = config.get(provider_name,
                                            'OPEN_ID_CONFIG_URL')
            fence_base_url = config.get(provider_name, 'FENCE_BASE_URL')
            user_name_path_expr = config.get(provider_name,
                                             'USER_NAME_PATH_EXPR')

            sam_base_url = config.get('sam', 'BASE_URL')

            oauth_adapter = OauthAdapter(client_id, client_secret,
                                         open_id_config_url, provider_name)
            fence_api = FenceApi(fence_base_url)
            sam_api = SamApi(sam_base_url)

            fence_tvm = FenceTokenVendingMachine(fence_api, sam_api,
                                                 oauth_adapter, provider_name)
            return BondProvider(
                fence_tvm,
                Bond(oauth_adapter, fence_api, sam_api, fence_tvm,
                     provider_name, user_name_path_expr))

        self.providers = {
            provider_name: create_provider(provider_name)
            for provider_name in config.sections() if provider_name != 'sam'
        }
        self.auth = authentication.Authentication(
            authentication.default_config())
Пример #4
0
def test_send_auth_message(sheets: Sheets, test_users: List[User]):
    user = test_users[0]

    class FooCrypto:
        def encrypt(self, value: str) -> str:
            return "foo"

        def decrypt(self, value: str) -> str:
            return "foo"

    class TestEmail:
        def __init__(self, to_email):
            self.to_email = user.email

        def send(self, to_email: str, subject: str, body: str) -> None:
            assert to_email == self.to_email
            assert subject == "Welcome to the Looker Hackathon!"
            assert (body == f"""<h1>Welcome to the Looker Hackathon!</h1>
Please click https://foo.com/auth/foo to authenticate your email so you can use the Hackathon application
and participate in the Hackathon
""")

    auth_service = authentication.Authentication(crypto=FooCrypto(),
                                                 sheet=sheets,
                                                 email=TestEmail(user.email))
    auth_service.send_auth_message(user, "https://foo.com/")
Пример #5
0
    def __init__(self):
        self.verbosity = 0
        self.configfile = "xfltreat.conf"
        self.servermode = 0
        self.clientmode = 0
        self.checkmode = 0
        self.splitmode = 0  # split tunnelling
        self.ignoredependencies = 0  # ignoring missing dependencies

        self.short = "hsc"
        self.long = [
            "help", "server", "client", "check", "split", "config=",
            "verbose=", "ignore-dependencies"
        ]

        # modules that should not be loaded
        self.forbidden_modules = [
            "Generic_module", "Stateful_module", "Stateless_module"
        ]
        self.forbidden_modules_instance = [
            Generic_module, Stateful_module, Stateless_module
        ]

        self.authentication = authentication.Authentication()
        self.encryption = encryption.Encryption()
Пример #6
0
def test_auth_user(sheets: Sheets, test_users: List[User]):
    auth_service = authentication.Authentication(crypto=NoopCrypto(),
                                                 sheet=sheets,
                                                 email=NoopEmail())
    user = test_users[0]
    auth_code = auth_service.get_user_auth_code(user)
    authenticated_user = auth_service.auth_user(auth_code)
    assert authenticated_user == user
Пример #7
0
 def setUp(self):
     # First, create an instance of the Testbed class.
     self.testbed = testbed.Testbed()
     # Then activate the testbed, which prepares the service stubs for use.
     self.testbed.activate()
     # Next, declare which service stubs you want to use.
     self.testbed.init_memcache_stub()
     self.auth = authentication.Authentication(
         authentication.AuthenticationConfig(['32555940559'],
                                             ['.gserviceaccount.com'], 600))
Пример #8
0
def test_get_user_auth_code(sheets: Sheets):
    user = User(
        first_name="Hundy",
        last_name="P",
        email="*****@*****.**",
        organization="company",
        role="BI analyst",
        tshirt_size="M",
    )

    auth_service = authentication.Authentication(crypto=NoopCrypto(),
                                                 sheet=sheets,
                                                 email=NoopEmail())
    auth_code = auth_service.get_user_auth_code(user)
    email, date = auth_code.split("~")
    assert email == "*****@*****.**"
Пример #9
0
def independent_proxy_engine(url):
    '''
    独立代理引擎,用于重新获取单个异常网页的代理
    :param url: 异常网页的 url 链接
    :return:
    '''
    LOG.info("[+] 开始重新获取代理")
    Console_Color.print_color(str="[*] 开始重新获取代理", forecolor="洋红")
    global VALID_URL_PROXY
    auth = authentication.Authentication(headers=HEADERS)
    proxyOP = proxyPool.IPOperator(headers=HEADERS)
    while True:
        proxyDict = proxy_engine(proxyOP)
        if auth.proxyVerify(url, proxyDict["protocol"], proxyDict["ip"], proxyDict["port"]):
            global VALID_URL_PROXY
            VALID_URL_PROXY[url] = proxyDict
            break
 def create_schema(self, schema_name):
     if schema_name in os.listdir(self.schemas_directory):
         print("Error! Schema already exists.")
         self.events_logger.error("Error! Schema already exists.")
     elif "$" + self.schema_name in os.listdir(self.schemas_directory):
         print("Error! Schema already exists.")
         self.events_logger.error("Error! Schema already exists.")
     else:
         json.dump({},
                   open(os.path.join(self.schemas_directory, schema_name),
                        "w+"),
                   indent=2)
         auth = authentication.Authentication()
         auth.add_schema_to_user(self.user_name, schema_name,
                                 ["C", "R", "U", "D"])
         print("Schema created with name:", schema_name)
         self.events_logger.info("Schema created with name:" + schema_name)
         self.events_logger.info("Query : " + self.query)
Пример #11
0
def lambda_handler(event, context):
    client = authentication.Authentication()

    subject = event['Records'][0]['Sns']['Subject']
    message_json = json.loads(event['Records'][0]['Sns']['Message'])
    message_desc = message_json['Description']
    message_event = message_json['Event']
    print(subject)
    print(message_desc)
    print(message_event)
    print(context.invoked_function_arn)
    print(context.invoked_function_arn.split(":")[4])

    log_message = {
        "subject": subject,
        "description": message_desc,
        "asg_event": message_event
    }

    return log_message
 def use_schema(self, schema_name):
     if schema_name in os.listdir(self.schemas_directory):
         # call a method and send user_name and schema_name to check for access
         auth = authentication.Authentication()
         access_level = auth.check_access(self.user_name, schema_name)
         if access_level is None:
             print("You don't have access to this schema")
             self.events_logger.error(
                 "You don't have access to this schema" + schema_name)
             return
         else:
             self.user_access = access_level
         self.schema = json.load(
             open(os.path.join(self.schemas_directory, schema_name), "r"))
         self.schema_name = schema_name
         print("Current Schema:", self.schema_name)
         self.events_logger.info("Query : " + self.query)
     elif "$" + schema_name in os.listdir(self.schemas_directory):
         print("Schema is being locked by other user. Please try later.")
         self.events_logger.info("Schema is being locked by other user." +
                                 schema_name)
     else:
         print("No such schema exists!")
         self.events_logger.error("Schema not found!" + schema_name)
Пример #13
0
	def __init__(self, conf, dht, sysInfo):
		self.dht = dht
		self.sysInfo = sysInfo
		self.api_ver = "1"
		self.authentication = Auth.Authentication(conf.getAccPassword()) 
class ManagementInterface:
    data_plane_config_file = None
    data_plane_config_filepath = 'Emulator/config/data_plane_config.json'
    pending_mgmt_config_filepath = 'Emulator/config/mgmt_config.json.pending'
    mgmt_config_filepath = 'Emulator/config/mgmt_config.json'
    schema_filepath = '/usr/src/app/openapi/schema.json'
    versioning_filepath = '/usr/src/app/VERSIONING'
    authentication = authentication.Authentication(
        authentication_backend=set_authentication_backend())
    access_controller = RequestAccessControl(authentication)
    default_syslog_config = []
    default_ntp_config = []
    default_tls_config = {
        "certificate":
        "-----BEGIN CERTIFICATE-----\nMIIDOzCCAiOgAwIBAgIUN5q2Bu2aYaFLIciHgLWQnhGfV7QwDQYJKoZIhvcNAQELBQAwLTELMAkGA1UEBhMCR0IxHjAcBgNVBAMMFW1hbmFnZW1lbnQub2FrZG9vci5pbzAeFw0yMjA0MDYxNTQ1MDBaFw0yMzA0MDYxNTQ1MDBaMC0xCzAJBgNVBAYTAkdCMR4wHAYDVQQDDBVtYW5hZ2VtZW50Lm9ha2Rvb3IuaW8wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC/4qNnEKLv3f6bnqPX44d19FlhAJYOKUH6StM39U7jE5j3/Mh/sepTS6VpOp5y7kIZ5K042eM0nsljZcUWTl/SH2uqfx6vNgw86rI027h3IFPBg1GARXk5Tox0o78n/SccLi0OXyWQo9TN4pCjp4vV6x78iTJ1xh/qv3QvVRoA0vO0ZAXIOWjPyEmRaOhUVYoGS8SrD6JbIh50sjDlJs4jFreJAPGxVkwcpyOqh1ro7B7y08cbnFR3HXUe3b+ypYHyJCmn0aUYa2eo4po5me6bfHCDtOfodPAHosmCgMdXowBMSbQeFAE4TgPrZHqDBpWenni5uWi38KRGIvaeZ78zAgMBAAGjUzBRMB0GA1UdDgQWBBRcQvFH4rgx0qmLZdnmiYKKrZBoDzAfBgNVHSMEGDAWgBRcQvFH4rgx0qmLZdnmiYKKrZBoDzAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQAoz54OodDPlC6JC+hhdjhEOVSXLH0k/UVqmLoeuAX7WQB7jYe6pAkNnM+NjMjhmip/Ad8HjHPMGJkrTxohSVgJO+SUIq+cziFfunNWG6VImHpkHM37M9B7UkOE+7e6wo9WvF2fiKiMh5C9KrZoxBhM7oGwBL6Pnav1hRoZIs/5YAzUJ6BfvB21Z3GFPV2nxk62OXdhD2WrNj+1ULQg3DsD1LWUghgT95ITxTRMcvjzzEH93KD2Y4+yooMFmdPTq8gXdeRpeQqMpouuSHHigHJGGda32+vpi/6rMWPcUmPPONxE4oOKr79KY1ykMhu6wkERrBslQdCynfOU8+XWzAH7\n-----END CERTIFICATE-----",
        "key":
        "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC/4qNnEKLv3f6bnqPX44d19FlhAJYOKUH6StM39U7jE5j3/Mh/sepTS6VpOp5y7kIZ5K042eM0nsljZcUWTl/SH2uqfx6vNgw86rI027h3IFPBg1GARXk5Tox0o78n/SccLi0OXyWQo9TN4pCjp4vV6x78iTJ1xh/qv3QvVRoA0vO0ZAXIOWjPyEmRaOhUVYoGS8SrD6JbIh50sjDlJs4jFreJAPGxVkwcpyOqh1ro7B7y08cbnFR3HXUe3b+ypYHyJCmn0aUYa2eo4po5me6bfHCDtOfodPAHosmCgMdXowBMSbQeFAE4TgPrZHqDBpWenni5uWi38KRGIvaeZ78zAgMBAAECggEBAIuoVYuG9UAlz9DN5qwToxz7qi3Ksmw+JRIZcZ+xwCfPtK8RYZBnGohjb1GmY3p85MlZwaW2GALNawAYKxjwFBen3MHr4ZZefQu9OdT08k5pzevzOtdkOTW3cMzX/SIKw3NkPFDQeVPLme/7bZBfOoyIozXkWUCU4dgGXnawtstPex2FD2yAnXdVOoz4Gn5Mx2hv28K93KE4RkBz2Pp+L6+/p9/kJ1P3vEVvJv2TN6r8FhzUxqxR+ascpE2tNjy3VFfPjF8gm4R9iXzIO6AMHEP/+qaX3xn5WeU9+wNydFykBj/tYh+C28KFLlKp+WVvLaL8neHotOS7BnfFMh1RxaECgYEA6RQqN+h8fZD27GmjJbvZmBPIsaGtRHYVI4wqwxaZPMF3eHBzVOGTGrst9jTaXpOkycSQGjVYKn0xfElJAxWwYYf3A+rYzPqjHMDCNAnzPBpcV7VS2anzyOQxR8pWOCQWKcyhaF0TLTaRyGX2yT77cF7M/BYJpwzRYI7jwk8c6vECgYEA0sFqEICLISmVEP8pj+saJN+eaEm96NW73GShHk8miW7kjWs3I3EcI4L0qhJmwz+thmmc9Tl4+wZ+tWg4cO2gLXdtk79AzSPsA/FVGy5TsfN0/8mepSzqGYTrV2M960xi8ZoqvCUEZU+DlbQb5NMC/L/FdcyNkeJAlOtg1aIfJGMCgYAiAqJCdDcuL2gIiUWYLPgMW96uJNReqAhfnoVi4DpOBkEDnw0FNsE7ZlLHmWC/6jVih78rQ9twn8IHy73OqGyLXsapmKw4BN6mRG5SH52RiJsu5TOItWbwSnPycNDx8joVsVlgHCy/LTZKkq5XIUyZUgwBQMn5yUIIH/GWGeszUQKBgGRCgLuS+xzulCx+xn3hoRFTlB8WnZKLQxBoisFJdBLDP1ULYTKqF3HJVa0mjd5qh5k+2t1J1wTMJTEVgGwwjxeyDd3QiPpOEXQatZr1ofkw0ULx3lfDkyZKtk5fNtCeCR/YcGYK0hmEBxwLj41+2Jf2fvA4PEzfLkvp4aofsuLzAoGAb4ycDYI3h0Oaw/Sypwu+zKYRko6OpvHJndrsnF7QKynMpyZ0gsR7+C1rMO5cEhoQnH5cJiKls26d9s6ICse9+y/lhB3QtYJdAndMutXVWSrwp1oX9Lth3FOpvrB1199K2WfCltS+KAW7FuEcjl07WNjePzsbGf5d+YTk+rNyMHU=\n-----END PRIVATE KEY-----"
    }
    default_network_config = {
        "version": 2,
        "renderer": "networkd",
        "ethernets": {
            "eth0": {
                "dhcp4": False,
                "addresses": ["192.168.2.2/24"]
            },
            "eth1": {
                "dhcp4": True,
                "optional": True
            }
        }
    }
    default_mgmt_config = {
        "syslog": default_syslog_config,
        "ntp": default_ntp_config,
        "tls": default_tls_config,
        "network": default_network_config
    }

    @classmethod
    def update_mgmt_firmware(cls):
        return cls.access_controller.enforce_sequential_api_calls(
            cls._update_firmware)

    @classmethod
    def update_diode_firmware(cls):
        return cls.access_controller.enforce_sequential_api_calls(
            cls._update_firmware)

    @classmethod
    def _update_firmware(cls, role):
        if not UserRole.check_role_meets_minimum_rank(role, "admin"):
            return Response(
                json.dumps({
                    "error":
                    "Method doesn't exist or user has insufficient privileges"
                }), 401)
        if not len(connexion.request.get_data()):
            return Response(
                json.dumps({"error": "Exception processing API command"}), 500)
        return Response("", 200)

    @classmethod
    def get_config(cls):
        return cls.access_controller.enforce_sequential_api_calls(
            cls._get_config)

    @classmethod
    def _get_config(cls, role):
        if not UserRole.check_role_meets_minimum_rank(role, "readOnly"):
            return Response(
                json.dumps({
                    "error":
                    "Method doesn't exist or user has insufficient privileges"
                }), 401)
        if cls._file_exists(cls.data_plane_config_filepath):
            return Response(
                json.dumps(
                    cls._get_file_content(cls.data_plane_config_filepath)),
                200)
        else:
            return Response(json.dumps({"error": "Config file not found"}),
                            404)

    @staticmethod
    def _file_exists(filepath):
        return os.path.exists(filepath)

    @staticmethod
    def _get_file_content(filepath):
        with open(filepath, 'r') as file:
            return json.loads(file.read())

    @classmethod
    def get_config_schema(cls):
        return cls.access_controller.enforce_sequential_api_calls(
            cls._get_config_schema)

    @classmethod
    def _get_config_schema(cls, role):
        if not UserRole.check_role_meets_minimum_rank(role, "readOnly"):
            return Response(
                json.dumps({
                    "error":
                    "Method doesn't exist or user has insufficient privileges"
                }), 401)

        return Response(json.dumps(cls._get_file_content(cls.schema_filepath)),
                        200)

    @classmethod
    def do_config_update(cls):
        return cls.access_controller.enforce_sequential_api_calls(
            cls._do_config_update)

    @classmethod
    def _do_config_update(cls, role):
        if not UserRole.check_role_meets_minimum_rank(role, "admin"):
            return Response(
                json.dumps({
                    "error":
                    "Method doesn't exist or user has insufficient privileges"
                }), 401)
        try:
            cls.data_plane_config_file = cls._validate_config(
                connexion.request.get_data(as_text=True))
        except DataPlaneConfigError as exc:
            return Response(json.dumps({"error": f"{exc}"}), 400)
        cls._update_config()
        return Response("", 200)

    @classmethod
    def _validate_config(cls, request_data):
        return VerifyDataPlaneConfig().validate_and_return_json(request_data)

    @classmethod
    def _update_config(cls):
        with open(cls.data_plane_config_filepath, 'w') as config_file:
            json.dump(cls.data_plane_config_file, config_file)

    @classmethod
    def do_power_on(cls):
        return cls.access_controller.enforce_sequential_api_calls(
            PowerControl.do_power_on, cls._get_user_from_request())

    @classmethod
    def do_power_off(cls):
        return cls.access_controller.enforce_sequential_api_calls(
            PowerControl.do_power_off, cls._get_user_from_request())

    @classmethod
    def _get_user_from_request(cls):
        if os.getenv("ANONYMOUSACCESS") != "True":
            return cls.authentication.extract_credentials(
                connexion.request.headers["Authorization"])
        else:
            return "user"

    @classmethod
    def get_versioning_information(cls):
        return cls.access_controller.enforce_sequential_api_calls(
            cls._get_versioning_information)

    @classmethod
    def _get_versioning_information(cls, role):
        if not UserRole.check_role_meets_minimum_rank(role, "readOnly"):
            return Response(
                json.dumps({
                    "error":
                    "Method doesn't exist or user has insufficient privileges"
                }), 401)
        with open(cls.versioning_filepath, 'r') as versioning_file:
            version_number = versioning_file.read()
        status = {
            "Diode": {
                "Firmware": {
                    "F1": "0.0.0_rc0",
                    "F2": "0.0.0_rc0",
                    "F3": "0.0.0_rc0"
                }
            },
            "Management": {
                "Kernel":
                "0.00.00-cl-som-imx7-0.0 #1 SMP PREEMPT Mon Jan 01 00:00:00 UTC 1970",
                "RestAPI": f"{version_number}-a0000a0a",
                "RootFS": {
                    "Build": "000",
                    "Hash": "0a0a0000",
                    "MountPoint": "/dev/mmcblk2p0"
                },
                "DiskImage": {
                    "Build": "000",
                    "Hash": "0a0a0000"
                }
            }
        }
        return Response(json.dumps(status), 200)

    @classmethod
    def get_status_information(cls):
        return cls.access_controller.enforce_sequential_api_calls(
            cls._get_status_information)

    @classmethod
    def _get_status_information(cls, role):
        if not UserRole.check_role_meets_minimum_rank(role, "readOnly"):
            return Response(
                json.dumps({
                    "error":
                    "Method doesn't exist or user has insufficient privileges"
                }), 401)

        status = Status.get_status()

        status["Dataplane"]["PowerState"] = PowerControl.state.name.lower()
        if PowerControl.state == DataplanePowerState.ERROR and PowerControl.error_message is not None:
            status["Dataplane"]["PowerStateError"] = PowerControl.error_message

        return Response(json.dumps(status), 200)

    @classmethod
    def get_mgmt_config(cls):
        return cls.access_controller.enforce_sequential_api_calls(
            cls._get_mgmt_config)

    @classmethod
    def _get_mgmt_config(cls, role):
        if not UserRole.check_role_meets_minimum_rank(role, "support"):
            return Response(
                json.dumps({
                    "error":
                    "Method doesn't exist or user has insufficient privileges"
                }), 401)

        deployed_config = cls._get_sanitised_mgmt_config_from_file(
            cls.mgmt_config_filepath)
        pending_config = cls._get_sanitised_mgmt_config_from_file(
            cls.pending_mgmt_config_filepath)

        return Response(
            json.dumps({
                "deployed": deployed_config,
                "pending": pending_config
            }), 200)

    @classmethod
    def _get_sanitised_mgmt_config_from_file(cls, config_path):
        if cls._file_exists(config_path):
            return cls._get_sanitised_mgmt_config(
                cls._get_file_content(config_path))
        else:
            return {}

    @classmethod
    def _get_sanitised_mgmt_config(cls, config):
        if "tls" in config:
            config["tls"].pop("key")
        return config

    @classmethod
    def stage_mgmt_config(cls):
        return cls.access_controller.enforce_sequential_api_calls(
            cls._stage_mgmt_config)

    @classmethod
    def _stage_mgmt_config(cls, role):
        if not UserRole.check_role_meets_minimum_rank(role, "admin"):
            return Response(
                json.dumps({
                    "error":
                    "Method doesn't exist or user has insufficient privileges"
                }), 401)

        pending_mgmt_config = {}
        if os.path.exists(cls.pending_mgmt_config_filepath):
            with open(cls.pending_mgmt_config_filepath, 'r') as pending_config:
                pending_mgmt_config = json.load(pending_config)

        ManagementInterface._write_config_to_file(
            cls._get_updated_config(pending_mgmt_config,
                                    connexion.request.get_json()),
            cls.pending_mgmt_config_filepath)

        return Response("", 200)

    @classmethod
    def _get_updated_config(cls, base_config, updates):
        sections = set(base_config).union(set(updates))
        return {
            section: cls._get_updated_section(section, base_config, updates)
            for section in sections
        }

    @classmethod
    def _get_updated_section(cls, section_name, base_config, updates):
        section = updates[
            section_name] if section_name in updates else base_config[
                section_name]

        if len(section) == 0:
            section = cls.default_mgmt_config[section_name]

        return section

    @staticmethod
    def _write_config_to_file(config, file_path):
        with open(file_path, 'w') as config_file:
            json.dump(config, config_file)

    @classmethod
    def deploy_mgmt_config(cls):
        return cls.access_controller.enforce_sequential_api_calls(
            cls._deploy_mgmt_config)

    @classmethod
    def _deploy_mgmt_config(cls, role):
        if not UserRole.check_role_meets_minimum_rank(role, "admin"):
            return Response(
                json.dumps({
                    "error":
                    "Method doesn't exist or user has insufficient privileges"
                }), 401)

        if not os.path.exists(cls.pending_mgmt_config_filepath):
            return Response(
                json.dumps(
                    {"error": "No staged config could be found to deploy"}),
                400)

        cls._write_deployed_mgmt_config()
        os.remove(cls.pending_mgmt_config_filepath)
        return Response("", 200)

    @classmethod
    def _write_deployed_mgmt_config(cls):
        with open(cls.mgmt_config_filepath) as deployed_config, \
                open(cls.pending_mgmt_config_filepath) as pending_config:
            deployed_mgmt_config = json.load(deployed_config)
            pending_mgmt_config = json.load(pending_config)

        ManagementInterface._write_config_to_file(
            cls._get_updated_config(deployed_mgmt_config, pending_mgmt_config),
            cls.mgmt_config_filepath)

    @classmethod
    def basic_authentication(cls, username, password):
        return cls.authentication.authenticate(username, password)

    @classmethod
    def user_add(cls, username):
        return cls.access_controller.enforce_sequential_api_calls(
            lambda role: Response(*cls.authentication.add_user(
                username, connexion.request.get_json(), role)))

    @classmethod
    def update_user(cls, username):
        return cls.access_controller.enforce_sequential_api_calls(
            lambda role: Response(*cls.authentication.update_user(
                username, connexion.request.get_json(), role)),
            cls._get_user_from_request())

    @classmethod
    def list_users(cls):
        return cls.access_controller.enforce_sequential_api_calls(
            cls._list_users)

    @classmethod
    def _list_users(cls, role):
        if not UserRole.check_role_meets_minimum_rank(role, "support"):
            return Response(
                json.dumps({
                    "error":
                    "Method doesn't exist or user has insufficient privileges"
                }), 401)
        users = cls.authentication.list_users()
        return Response(json.dumps(users[0]), users[1])

    @classmethod
    def user_delete(cls, username):
        return cls.access_controller.enforce_sequential_api_calls(
            lambda role: Response(*cls.authentication.delete_user(
                username, role)))
Пример #15
0
def development_mode(config_file, args=[]):

    servicename = path.basename(
        config_file)  # take the file name like amazon.cfg
    configfile = config_file  # the dir + file name
    logfilename = path.splitext(servicename)[0]  # remove the extension

    # check for existence of the config file
    if not path.exists(configfile):
        raise Exception("Configuration file %s not found." % configfile)

    suite = BasicWorkflowTestSuite(logfilename, args=args)
    fixtures = []
    '''check if configuration file we read from the ServiceList exist'''
    try:
        path.exists(configfile) and path.isfile(configfile) and access(
            configfile, R_OK)
    except IOError:
        sys.exit(1)

    suite.configfile = configfile
    suite.smapiservice = SMAPIService(suite.configfile,
                                      wsdl=parser.wsdl,
                                      content_file=parser.options.content_file,
                                      logger=suite.logger,
                                      console_logger=suite.console_logger)
    suite.client = suite.smapiservice.buildservice()
    suite.client.login()
    suite.logger.info("Service Name: %s" %
                      safe_str(suite.smapiservice.svcName))
    suite.console_logger.info("Service Name: %s" %
                              safe_str(suite.smapiservice.svcName))

    getuserinfo.suite = suite
    f = getuserinfo.GetUserInfoTest(suite.client, suite.smapiservice)
    fixtures.append(f)

    # Relying on the fact that order is maintained in python lists, the updatetestcontent suite must run before any test
    # case that can change user's favorites (i.e., playlists, favorites, ratings)
    updatetestcontent.suite = suite
    f = updatetestcontent.UpdateTestContent(suite.client, suite.smapiservice)
    f.initialize()
    fixtures.append(f)

    smapimethodvalidation.suite = suite
    f = smapimethodvalidation.SMAPIMethodValidation(suite.client,
                                                    suite.smapiservice)
    fixtures.append(f)

    playlist.suite = suite
    f = playlist.CreatePlaylist(suite.client, suite.smapiservice)
    f.create_playlist_with_seed_generator = playlist.generate_function_name_strings(
    )
    f.playlist_in_folder_with_seed_generator = playlist.generate_function_name_strings(
    )
    fixtures.append(f)

    f = playlist.DeletePlaylist(suite.client, suite.smapiservice)
    fixtures.append(f)

    f = playlist.RenamePlaylist(suite.client, suite.smapiservice)
    fixtures.append(f)

    f = playlist.AddToPlaylist(suite.client, suite.smapiservice)
    f.cannot_add_to_noneditable_playlist_generator = playlist.generate_items_for_addtoContainer_playlist_test(
    )
    f.can_add_to_playlist_generator = playlist.generate_items_for_addtoContainer_playlist_test(
    )
    fixtures.append(f)

    f = playlist.ReorderPlaylistContainer(suite.client, suite.smapiservice)
    f.generate_can_reorder_data = playlist.generate_reordering_data()
    f.generate_cannot_reorder_data = playlist.generate_cannot_reordering_data()
    fixtures.append(f)

    albumart.suite = suite
    f = albumart.Albumart(suite.client, suite.smapiservice)
    f.create_local_dir()
    f.create_html_result_file()
    fixtures.append(f)

    ratings.suite = suite
    fixtures.append(ratings.Ratings(suite.client, suite.smapiservice))

    favorites.suite = suite
    f = favorites.Favorites(suite.client, suite.smapiservice)
    f.favorite_type_add = favorites.generate_name_strings()
    f.favorite_type_remove = favorites.generate_name_strings()
    fixtures.append(f)

    browse.suite = suite
    f = browse.Browse(suite.client, suite.smapiservice)
    f.test_scroll_driller = f.generate_iterative_list_drill(
        f.determiner_browse_scroll)
    f.test_leaf_driller = f.generate_iterative_list_drill(
        f.determiner_browse_leaf)
    f.pagination_total_count = f.generate_iterative_list_drill(
        f.determiner_browse_pagination)
    f.pagination_container = browse.generate_pagination_container(
        f.generate_iterative_list_drill(f.determiner_pagination_container))
    f.pagination_container_nooverlap = browse.generate_pagination_container(
        f.generate_iterative_list_drill(f.determiner_pagination_container))
    fixtures.append(f)

    httpverifications.suite = suite
    fixtures.append(
        httpverifications.HTTPBasedTests(suite.client, suite.smapiservice))

    search.suite = suite
    f = search.Search(suite.client, suite.smapiservice)
    f.initialize()
    fixtures.append(f)

    progvalidation.suite = suite
    f = progvalidation.Progvalidation(suite.client, suite.smapiservice)
    f.test_program_driller = f.generate_iterative_list_drill(
        f.determiner_program)
    f.test_pagination_total_count = f.generate_iterative_list_drill(
        f.determiner_browse_pagination)
    fixtures.append(f)

    streamvalidation.suite = suite
    f = streamvalidation.StreamValidation(suite.client, suite.smapiservice)
    f.test_stream_driller = f.generate_iterative_list_drill(
        f.determiner_stream)
    fixtures.append(f)

    stringtable.suite = suite
    f = stringtable.Stringtable(suite.client, suite.smapiservice)
    f.language = stringtable.generate_language_list()
    fixtures.append(f)

    presentationmap.suite = suite
    f = presentationmap.Presentationmap(suite.client, suite.smapiservice)
    fixtures.append(f)

    extendedmetadatavalidations.suite = suite
    f = extendedmetadatavalidations.ExtendedMetadataValidations(
        suite.client, suite.smapiservice)
    f.metadata_data = extendedmetadatavalidations.generate_test_data()
    fixtures.append(f)

    getlastupdate.suite = suite
    fixtures.append(
        getlastupdate.PollingIntervalTest(suite.client, suite.smapiservice))

    authentication.suite = suite
    fixtures.append(
        authentication.Authentication(suite.client, suite.smapiservice))

    smapi_reporting.suite = suite
    f = smapi_reporting.SMAPIReporting(suite.client, suite.smapiservice)
    fixtures.append(f)

    # ssl_validation.suite = suite
    # f = ssl_validation.ssl_validation(suite.client, suite.smapiservice)
    # fixtures.append(f)

    try:
        import servicecatalog
        import mslogo

        servicecatalog.suite = suite
        f = servicecatalog.ServiceCatalog(suite.client, suite.smapiservice)
        fixtures.append(f)

        mslogo.suite = suite
        f = mslogo.MSLogo(suite.client, suite.smapiservice)
        fixtures.append(f)
    except:
        pass

    # Run it
    suite.run(fixtures)
 def setUp(cls):
     cls.authentication_backend_spy = authentication.EphemeralAuthenticationBackend(
     )
     cls.authentication = authentication.Authentication(
         cls.authentication_backend_spy)
Пример #17
0
from common_docker import *

import time
import json
import pytest
import os
import authentication
import admission
import deployments
import artifacts
import inventory
import device_authentication

logger = logging.getLogger('root')

auth = authentication.Authentication()
adm = admission.Admission(auth)
deploy = deployments.Deployments(auth, adm)
image = artifacts.Artifacts()
inv = inventory.Inventory(auth)
deviceauth = device_authentication.DeviceAuthentication(auth)
# -- When adding something here, also add a reset method and add it below --


def reset_mender_api():
    auth.reset()
    adm.reset()
    deploy.reset()
    image.reset()
    inv.reset()
    deviceauth.reset()
Пример #18
0
def authentication_engine():
    '''
    验证引擎
    :param proxyDict: 代理 IP 字典
    :return: 通过验证后,赋值给响应逻辑器LOGIC_RESPONSE
    '''
    LOG.info("[*] 开始执行验证引擎")
    auth = authentication.Authentication(headers=HEADERS)
    # 避免每次创建对象都开辟块内存,调用四个进程池,特别占内存
    proxyOP = proxyPool.IPOperator(headers=HEADERS)
    global VALID_URL
    try:
        #### 验证 HTTP ####
        # 遍历 url 列表进行 http 验证请求,将有效的 url 存储在 VALID_URL 中
        LOG.info("[+] 验证 HTTP")  # 写入日志
        for url in URL_LIST.values():
            if auth.httpCodeVerify(url):
                VALID_URL.append(url)

        # 遍历新加入的 url 列表
        for url_zb in URL_LIST_ZB.values():
            if auth.httpCodeVerify(url_zb):
                VALID_URL.append(url_zb)

        # 遍历有效的 URL
        print("-" * 40)
        print("[+] 有效的 URL({0})".format(len(VALID_URL)))
        for valid_url in VALID_URL:
            print(str(valid_url))
        print("-" * 40)
    except Exception as e:
        LOG.error("[-] {0}".format(str(e.message)))  # 写入日志

    try:
        #### 验证代理 ####
        # 遍历有效的 url 列表
        LOG.info("[+] 验证代理")  # 写入日志
        for url in VALID_URL:
            # 循环取出代理进行代理验证,将有效的代理与对应的 url 存储在字典中
            while True:
                proxyDict = proxy_engine(proxyOP)
                if auth.proxyVerify(url, proxyDict["protocol"],
                                    proxyDict["ip"], proxyDict["port"]):
                    global VALID_URL_PROXY
                    VALID_URL_PROXY[url] = proxyDict
                    break
                # 每进行一次 url 的代理验证,释放一次内存
                gc.collect()

        # 遍历 VALID_URL_PROXY 字典
        print("-" * 40)
        print("[+] 有效网址和代理")
        for valid_url in VALID_URL_PROXY:
            protocol = VALID_URL_PROXY[valid_url]['protocol']
            ip = VALID_URL_PROXY[valid_url]['ip']
            port = VALID_URL_PROXY[valid_url]['port']
            print("{0}--({1}:{2}:{3})".format(valid_url, protocol, ip, port))
        print("-" * 40)

        # 存储完成,赋值全局变量
        global LOGIC_RESPONSE
        LOGIC_RESPONSE = True
    except Exception as e:
        LOG.error("[-] {0}".format(str(e.message)))  # 写入日志

    try:
        #### 验证数据库 ####
        LOG.info("[+] 验证数据库")
        if LOGIC_RESPONSE:
            global LOGIC_EXECUTE
            LOGIC_EXECUTE = auth.dataBaseVerify(DATABASE_PARAM)
    except Exception as e:
        LOG.error("[-] {0}".format(str(e.message)))  # 写入日志

    LOG.info("[+] 清理内存")
    # 删除 auth 和 proxyOP 对象
    del auth, proxyOP
    # 清理内存
    gc.collect()