Ejemplo n.º 1
0
    def get_organization_credentials(self, organization_id, cache=True):
        """ Retrieves a new set of temporary AWS credentials to allow access to an organization's
        S3 bucket. Typically used to upload log files. Will cache the response and return the same
        credentials if they have at least 10 minutes before expiration.
        :param organization_id: string with the UUID-style unique ID of the organization
        :param cache: boolean controlling whether credentials are cached in this connection
        :return: decoded JSON objects that represents the credentials
        """
        if not is_valid_uuid(organization_id):
            raise ValueError(
                "organization id should be a string in UUID format")

        # try cached response first, must have at least 10 minutes validity
        if cache:
            cached_response = self._org_creds_cache.get(organization_id, None)
            if cached_response:
                exp = iso8601.parse_date(cached_response['expiration'])
                if exp >= (datetime.datetime.now(UTC) +
                           datetime.timedelta(minutes=10)):
                    return cached_response
                else:
                    del self._org_creds_cache[organization_id]

        # get a new credential
        response = self._request_retry("GET",
                                       path='organizations/%s/credentials' %
                                       organization_id)
        if response.status_code == 200:
            cached_response = response.json()
            if cache:
                self._org_creds_cache[organization_id] = cached_response
            return cached_response
        else:
            response.raise_for_status()
Ejemplo n.º 2
0
    def _get_organization_wblist_entry(self, scope, organization_id, id):
        if not scope in (
                'white',
                'black',
        ):
            raise ValueError('scope should be either white or black')
        if not is_valid_uuid(organization_id):
            raise ValueError(
                "organization id should be a string in UUID format")
        if not is_valid_uuid(organization_id):
            raise ValueError("id should be a string in UUID format")

        path = 'organizations/%s/%slists/%s' % (organization_id, scope, id)
        response = self._request_retry("GET", path=path)
        if response.status_code == 200:
            return response.json()
        else:
            response.raise_for_status()
 def latest_alert_ids(self, latest_alert_ids):
     if latest_alert_ids is None:
         self._latest_alert_ids = set()
     else:
         if not isinstance(latest_alert_ids, Iterable):
             raise ValueError('latest alert IDs must be iterable')
         if latest_alert_ids and not all(
                 is_valid_uuid(x) for x in latest_alert_ids):
             raise ValueError('latest alert IDs must only contain UUIDs')
         self._latest_alert_ids = {x for x in latest_alert_ids}
    def __init__(self,
                 organization_id,
                 latest_batch_date=None,
                 latest_alert_ids=None):
        if not is_valid_uuid(organization_id):
            raise ValueError('invalid organization ID')
        self._organization_id = organization_id

        self._latest_alert_ids = set()
        self._latest_batch_date = None
        self.latest_batch_date = latest_batch_date
        self.latest_alert_ids = latest_alert_ids
Ejemplo n.º 5
0
    def iter_organization_alerts(self,
                                 organization_id,
                                 fromDate=None,
                                 toDate=None,
                                 sortBy="logDate",
                                 status=None):
        """ Generator that allows iteration over an organization's alerts, with optional filters.
        :param organization_id: string with the UUID-style unique ID of the organization
        :param fromDate: only list alerts with dates >= this parameter
        :param toDate: only list alerts with dates <= this parameter
        :param sortBy: one of 'logDate' or 'batchDate', controls which date field fromDate and
        toDate apply to
        :param status: a list or set containing one or more of 'new', 'under_investigation',
        'rejected', 'resolved'
        :return: an iterator over the decoded JSON objects that represent alerts.
        """
        if not is_valid_uuid(organization_id):
            raise ValueError(
                "organization id should be a string in UUID format")
        if not is_valid_alert_sortBy(sortBy):
            raise ValueError("sortBy must be either 'logDate' or 'batchDate'")
        if status is not None and not is_valid_alert_status(status):
            raise ValueError(
                "status must be an iterable with one or more of 'new', 'under_investigation', "
                + "'rejected' or 'resolved'")

        # loop over alert pages and yield them
        params = {'page': 1, 'size': _PAGE_SIZE, 'sortBy': sortBy}
        if fromDate:
            params['fromDate'] = parse_date(fromDate)
        if toDate:
            params['toDate'] = parse_date(toDate)
        if status:
            params['status'] = status

        while True:
            response = self._request_retry("GET",
                                           path='organizations/%s/alerts' %
                                           organization_id,
                                           params=params)
            if response.status_code == 200:
                alert_list = response.json()
                for alert in alert_list:
                    yield alert
                if len(alert_list) < _PAGE_SIZE:
                    return
            elif response.status_code == 404:
                return
            else:
                response.raise_for_status()
            params['page'] += 1
Ejemplo n.º 6
0
 def get_organization(self, organization_id):
     """ Retrieves detailed data from an organization this API key has accessed to based on its
     ID.
     :param organization_id: string with the UUID-style unique ID of the organization
     :return: decoded JSON objects that represents the organization or None if not found
     """
     if not is_valid_uuid(organization_id):
         raise ValueError(
             "organization id should be a string in UUID format")
     response = self._request_retry("GET",
                                    path='organizations/%s' %
                                    organization_id)
     if response.status_code == 200:
         return response.json()
     elif response.status_code == 404:
         return None
     else:
         response.raise_for_status()
    def __init__(self, connection, organization_id, start_date=None):
        """Initializes a persistent alert iterator.
        :param connection: an instance of magnetsdk2.Connection
        :param organization_id: a string containing an organization ID in UUID format
        :param start_date: optional date that represents the initial batch date to load alerts from
        """
        if not isinstance(connection, Connection):
            raise ValueError('invalid connection')
        self._connection = connection

        if not is_valid_uuid(organization_id):
            raise ValueError('invalid organization ID')
        self._organization_id = organization_id

        if start_date is not None:
            self._start_date = parse_date(start_date)
        else:
            self._start_date = None
        self._persistence_entry = None
        self._alerts = []
Ejemplo n.º 8
0
    def list_organization_alert_dates(self, organization_id, sortBy="logDate"):
        """ Lists all log or batch dates for which alerts exist on the organization.
        :param organization_id: string with the UUID-style unique ID of the organization
        :param sortBy: one of 'logDate' or 'batchDate', controls which date field to return
        :return: a set of ISO 8601 dates for which alerts exist
        """
        if not is_valid_uuid(organization_id):
            raise ValueError(
                "organization id should be a string in UUID format")
        if not is_valid_alert_sortBy(sortBy):
            raise ValueError("sortBy must be either 'logDate' or 'batchDate'")

        response = self._request_retry("GET",
                                       path='organizations/%s/alerts/dates' %
                                       organization_id,
                                       params={'sortBy': sortBy})
        if response.status_code == 200:
            return set(response.json())
        elif response.status_code == 404:
            return set()
        else:
            response.raise_for_status()
 def add_alert_id(self, alert_id):
     if not is_valid_uuid(alert_id):
         raise ValueError("invalid alert ID")
     self._latest_alert_ids.add(alert_id)