Пример #1
0
    def __init__(self,
                 project_id,
                 global_configs=None,
                 dry_run=False,
                 project_sema=None,
                 max_running_operations=0):
        """Initialize.

        Args:
          project_id: The project id for the project to enforce.
          global_configs (dict): Global configurations.
          dry_run: Set to true to ensure no actual changes are made to the
              project. EnforcePolicy will still return a ProjectResult proto
              showing the changes that would have been made.
          project_sema: An optional semaphore object, used to limit the number
              of concurrent projects getting written to.
          max_running_operations: Used to limit the number of concurrent running
              operations on an API.

        """
        self.project_id = project_id

        self.global_configs = global_configs
        self.result = enforcer_log_pb2.ProjectResult()
        self.result.project_id = self.project_id

        self._dry_run = dry_run

        self._project_sema = project_sema
        if max_running_operations:
            self._operation_sema = threading.BoundedSemaphore(
                value=max_running_operations)
        else:
            self._operation_sema = None
    def setUp(self):
        """Set up."""
        self.gce_service = mock.Mock()
        self.gce_service.networks().list().execute.return_value = (
            constants.SAMPLE_TEST_NETWORK_SELFLINK)

        self.project = constants.TEST_PROJECT
        self.policy = json.loads(constants.RAW_EXPECTED_JSON_POLICY)
        self.enforcer = project_enforcer.ProjectEnforcer(self.project,
                                                         dry_run=True)

        self.mock_time = mock.patch.object(project_enforcer.datelib,
                                           'Timestamp').start()

        self.mock_time.now().AsMicroTimestamp.return_value = MOCK_TIMESTAMP

        self.expected_proto = enforcer_log_pb2.ProjectResult(
            timestamp_sec=MOCK_TIMESTAMP,
            project_id=self.project,
        )

        self.expected_rules = copy.deepcopy(
            constants.EXPECTED_FIREWALL_RULES.values())

        response_403 = httplib2.Response({
            'status': '403',
            'content-type': 'application/json'
        })
        response_403.reason = 'Failed'
        self.error_403 = project_enforcer.errors.HttpError(
            response_403, '', '')

        self.addCleanup(mock.patch.stopall)
Пример #3
0
    def __init__(self,
                 project_id,
                 global_configs=None,
                 compute_service=None,
                 dry_run=False,
                 project_sema=None,
                 max_running_operations=0):
        """Initialize.

        Args:
            project_id (str): The project id for the project to enforce.
            global_configs (dict): Global configurations.
            compute_service (discovery.Resource): A Compute API service object.
                If not provided, one will be created using the default
                credentials.
            dry_run (bool): Set to true to ensure no actual changes are made to
                the project. EnforcePolicy will still return a ProjectResult
                proto showing the changes that would have been made.
            project_sema (threading.BoundedSemaphore): An optional semaphore
                object, used to limit the number of concurrent projects getting
                written to.
            max_running_operations (int): Used to limit the number of concurrent
                running operations on an API.
        """
        self.project_id = project_id

        if not compute_service:
            gce_api = compute.ComputeClient(global_configs)
            compute_service = gce_api.service

        self.firewall_api = fe.ComputeFirewallAPI(compute_service,
                                                  dry_run=dry_run)

        self.result = enforcer_log_pb2.ProjectResult()
        self.result.status = STATUS_UNSPECIFIED
        self.result.project_id = self.project_id
        self.result.timestamp_sec = datelib.Timestamp.now().AsMicroTimestamp()

        self._dry_run = dry_run

        self._project_sema = project_sema
        if max_running_operations:
            self._operation_sema = threading.BoundedSemaphore(
                value=max_running_operations)
        else:
            self._operation_sema = None
    def test_enforce_single_project(self):
        """Verifies enforce_single_project returns the correct results.

      Setup:
        * Set API calls to return the different firewall rules from the new
          policy on the first call, and the expected new firewall rules on the
          second call.
        * Load a mock policy file.
        * Create a temporary directory for writing the dremel recordio table out
          to.
        * Send the policy and project to EnforceSingleProject.

      Expected Results:
        * The results proto returned matches the expected results.
      """
        self.gce_service.firewalls().list().execute.side_effect = [
            constants.DEFAULT_FIREWALL_API_RESPONSE,
            constants.EXPECTED_FIREWALL_API_RESPONSE
        ]

        policy_filename = get_datafile_path(__file__, 'sample_policy.json')

        results = enforcer.enforce_single_project(self.enforcer, self.project,
                                                  policy_filename)

        self.expected_summary.projects_total = 1
        self.expected_summary.projects_success = 1
        self.expected_summary.projects_changed = 1
        self.expected_summary.projects_unchanged = 0

        self.assertEqual(self.expected_summary, results.summary)

        expected_results = enforcer_log_pb2.ProjectResult()
        text_format.Merge(constants.SAMPLE_ENFORCER_PROJECTRESULTS_ASCIIPB,
                          expected_results)
        expected_results.run_context = enforcer_log_pb2.ENFORCER_ONE_PROJECT
        expected_results.gce_firewall_enforcement.policy_path = policy_filename

        project_result = results.results[0]

        self.assertEqual(expected_results, project_result)
Пример #5
0
 def result_callback(result):
     expected_result = enforcer_log_pb2.ProjectResult()
     text_format.Merge(constants.SAMPLE_ENFORCER_PROJECTRESULTS_ASCIIPB,
                       expected_result)
     self.assertEqual(expected_result, result)
     callback_called[0] += 1