def runTest(self):
        auth = EdgeGridAuth(
            client_token=self.testdata['client_token'],
            client_secret=self.testdata['client_secret'],
            access_token=self.testdata['access_token'],
            headers_to_sign=self.testdata['headers_to_sign'],
            max_body=self.testdata['max_body']
        )

        headers = { }
        if 'headers' in self.testcase['request']:
            for h in self.testcase['request']['headers']:
                for k,v in h.iteritems():
                    headers[k] = v

        request = requests.Request(
            method=self.testcase['request']['method'],
            url=urljoin(self.testdata['base_url'],self.testcase['request']['path']),   
            headers=headers,
            data=self.testcase['request'].get('data') if self.testcase['request'].get('data') \
                                                      else None
        )

        try:
            auth_header = auth.make_auth_header(
                request.prepare(), self.testdata['timestamp'], self.testdata['nonce']
            )
        except Exception, e:
            logger.debug('Got exception from make_auth_header', exc_info=True)
            self.assertEquals(str(e), self.testcase['failsWithMessage'])
            return
    def runTest(self):
        auth = EdgeGridAuth(
            client_token=self.testdata['client_token'],
            client_secret=self.testdata['client_secret'],
            access_token=self.testdata['access_token'],
        )

        params = {
            'extended': 'true',
        }

        data = {
            'key':'value',
        }

        request = requests.Request(
            method='POST',
            url=urljoin(self.testdata['base_url'],'/testapi/v1/t3'),
            params=params,
            json=data,
        )

        auth_header = auth.make_auth_header(
            request.prepare(), self.testdata['timestamp'], self.testdata['nonce']
        )

        self.assertEqual(auth_header, self.testdata['jsontest_hash'])
Exemplo n.º 3
0
    def __init__(self, edgedns_creds):
        logger.debug("creating _EdgeDNSClient")
        pathhost = ""
        if EDGEGRID_CREDS["edgerc_path"]:
            section = 'default'
            if EDGEGRID_CREDS["edgerc_section"]:
                section = EDGEGRID_CREDS["edgerc_section"]
            pathhost = EdgeRc(EDGEGRID_CREDS["edgerc_path"]).get(section, 'host')
            self.edgegrid_auth = EdgeGridAuth.from_edgerc(EDGEGRID_CREDS["edgerc_path"], section)
        else:
            pathhost = EDGEGRID_CREDS["host"]
            self.edgegrid_auth = EdgeGridAuth(client_token = EDGEGRID_CREDS["client_token"],
                                              client_secret = EDGEGRID_CREDS["client_secret"],
                                              access_token = EDGEGRID_CREDS["access_token"])
        # Error checking the .edgerc file
        if pathhost.find('://') > 0:
            raise errors.PluginError('{0}: You have specified an invalid host entry '
                                         'Please remove the http(s):// at the beginning.'
            )
        root_path = self.BASEURL.format(pathhost)
        self.EDGEDNSROOTURL = urljoin(root_path, "/config-dns/v2/") 
        self.EDGEDNSZONESURL = self.EDGEDNSROOTURL + "zones/"
        self.EDGEDNSCHANGESURL = self.EDGEDNSROOTURL + "changelists"

        self.recordset_semaphore = threading.Semaphore()

        return
Exemplo n.º 4
0
    def runTest(self):
        auth = EdgeGridAuth(client_token=self.testdata['client_token'],
                            client_secret=self.testdata['client_secret'],
                            access_token=self.testdata['access_token'],
                            headers_to_sign=self.testdata['headers_to_sign'],
                            max_body=self.testdata['max_body'])

        headers = {}
        if 'headers' in self.testcase['request']:
            for h in self.testcase['request']['headers']:
                for k, v in h.items():
                    headers[k] = v

        request = requests.Request(
            method=self.testcase['request']['method'],
            url=urljoin(self.testdata['base_url'],self.testcase['request']['path']),
            headers=headers,
            data=self.testcase['request'].get('data') if self.testcase['request'].get('data') \
                                                      else None
        )

        try:
            auth_header = auth.make_auth_header(request.prepare(),
                                                self.testdata['timestamp'],
                                                self.testdata['nonce'])
        except Exception as e:
            logger.debug('Got exception from make_auth_header', exc_info=True)
            self.assertEquals(str(e), self.testcase['failsWithMessage'])
            return

        self.assertEqual(auth_header, self.testcase['expectedAuthorization'])
    def runTest(self):
        auth = EdgeGridAuth(
            client_token=self.testdata['client_token'],
            client_secret=self.testdata['client_secret'],
            access_token=self.testdata['access_token'],
        )

        params = {
            'extended': 'true',
        }

        data = {
            'key': 'value',
        }

        request = requests.Request(
            method='POST',
            url=urljoin(self.testdata['base_url'], '/testapi/v1/t3'),
            params=params,
            json=data,
        )

        auth_header = auth.make_auth_header(request.prepare(),
                                            self.testdata['timestamp'],
                                            self.testdata['nonce'])

        self.assertEqual(auth_header, self.testdata['jsontest_hash'])
Exemplo n.º 6
0
def main():
    params = demisto.params()
    client = Client(base_url=urljoin(params.get('host'), '/siem/v1/configs'),
                    verify=not params.get('insecure', False),
                    proxy=params.get('proxy'),
                    auth=EdgeGridAuth(
                        client_token=params.get('clientToken'),
                        access_token=params.get('accessToken'),
                        client_secret=params.get('clientSecret')))
    commands = {
        f"test-module": test_module_command,
        f"{INTEGRATION_COMMAND_NAME}-get-events": get_events_command
    }
    command = demisto.command()
    demisto.debug(f'Command being called is {command}')
    try:
        if command == 'fetch-incidents':
            incidents, new_last_run = fetch_incidents_command(
                client,
                fetch_time=params.get('fetchTime'),
                fetch_limit=params.get('fetchLimit'),
                config_ids=params.get('configIds'),
                last_run=demisto.getLastRun().get('lastRun'))
            demisto.incidents(incidents)
            demisto.setLastRun(new_last_run)
        else:
            human_readable, entry_context, raw_response = commands[command](
                client, **demisto.args())
            return_outputs(human_readable, entry_context, raw_response)

    except Exception as e:
        err_msg = f'Error in {INTEGRATION_NAME} Integration [{e}]'
        return_error(err_msg, error=e)
Exemplo n.º 7
0
def get_property_hostnames(latestVersion, propertyId, contractId, groupId,
                           path, section, switchkey):
    # setting up authentication as in https://github.com/akamai/AkamaiOPEN-edgegrid-python
    property_hostnames_list = []
    edgerc = EdgeRc(path)
    baseurl = 'https://%s' % edgerc.get(section, "host")
    http_request = requests.Session()
    http_request.auth = EdgeGridAuth.from_edgerc(edgerc, section)
    # setting up request headers
    headers = {}
    headers['PAPI-Use-Prefixes'] = "true"
    http_request.headers = headers
    # getting the list of groups and contracts associated to groups: https://developer.akamai.com/api/core_features/property_manager/v1.html#getgroups
    http_response = http_request.get(
        urljoin(
            baseurl, '/papi/v1/properties/' + propertyId + '/versions/' +
            str(latestVersion) + '/hostnames?contractId=' + contractId +
            '&groupId=' + groupId +
            '&validateHostnames=false&accountSwitchKey=' + switchkey))
    http_status_code = http_response.status_code
    http_content = json.loads(http_response.text)
    try:
        test = http_content['hostnames']['items']
    except KeyError:
        pass
    else:
        for item in http_content['hostnames']['items']:
            property_hostnames_list = property_hostnames_list + [
                item['cnameFrom']
            ]
    return (property_hostnames_list)
Exemplo n.º 8
0
def get_properties(contractId, groupId, path, section, switchkey):
    # setting up authentication as in https://github.com/akamai/AkamaiOPEN-edgegrid-python
    dict_list = []
    edgerc = EdgeRc(path)
    baseurl = 'https://%s' % edgerc.get(section, "host")
    http_request = requests.Session()
    http_request.auth = EdgeGridAuth.from_edgerc(edgerc, section)
    # setting up request headers
    headers = {}
    headers['PAPI-Use-Prefixes'] = "true"
    http_request.headers = headers
    # getting the latest property version: https://developer.akamai.com/api/core_features/property_manager/v1.html#getproperties
    http_response = http_request.get(
        urljoin(
            baseurl, '/papi/v1/properties?contractId=' + contractId +
            '&groupId=' + groupId + '&accountSwitchKey=' + switchkey))
    http_status_code = http_response.status_code
    http_content = json.loads(http_response.text)
    for item in http_content['properties']['items']:
        dict_list = dict_list + [{
            "latestVersion": item['latestVersion'],
            "propertyId": item['propertyId'],
            "contractId": contractId,
            "groupId": groupId
        }]
    return (dict_list)
Exemplo n.º 9
0
def init_config(edgerc_file, section):
    global baseurl, session
    # Check if the edgerc_file variable or the AKAMAI_EDGERC env var exist then use a default value if they don't exist.
    if not edgerc_file:
        if not os.getenv("AKAMAI_EDGERC"):
            edgerc_file = os.path.join(os.path.expanduser("~"), '.edgerc')
        else:
            edgerc_file = os.getenv("AKAMAI_EDGERC")

    if not os.access(edgerc_file, os.R_OK):
        print("Unable to read edgerc file \"%s\"" % edgerc_file)
        exit(1)

    if not section:
        if not os.getenv("AKAMAI_EDGERC_SECTION"):
            section = "default"
        else:
            section = os.getenv("AKAMAI_EDGERC_SECTION")

    try:
        edgerc = EdgeRc(edgerc_file)
        baseurl = 'https://%s' % edgerc.get(section, 'host')

        session = requests.Session()
        session.auth = EdgeGridAuth.from_edgerc(edgerc, section)

        return (baseurl, session)

    except configparser.NoSectionError:
        print("Edgerc section \"%s\" not found" % section)
        exit(1)
    except Exception:
        print("Unknown error occurred trying to read edgerc file (%s)" %
              edgerc_file)
        exit(1)
Exemplo n.º 10
0
 def _get_dns_info(self, rrecord):
    aka_cust_object = MISPObject('misc')
    tagInfo=["source:AkamaiETP"]
    _text = ""
    dimensions = ['deviceId','site']
    for dimension in dimensions:
        #_result = self._run_custom_request(self, rrecord, dimension)
        session  = requests.Session()
        session.auth = EdgeGridAuth(
           client_token  = self.ctoken,
           client_secret = self.csecret,
           access_token  = self.atoken
        )
        confID = self.configID
        epoch_time = int(time.time())
        last_30_days = epoch_time - 3600 * 24 * 30  # last month by default for now
        url = f'/etp-report/v2/configs/{str(confID)}' + \
              f'/dns-activities/aggregate?cardinality=2500&dimension={dimension}&endTimeSec={epoch_time}&filters' + \
              f'=%7B%22domain%22:%7B%22in%22:%5B%22{rrecord}%22%5D%7D%7D&startTimeSec={last_30_days}'
        _result = session.get(urljoin(self.baseurl, url)).json()
        if _result['dimension']['total'] != 0:
             _text += dimension + ' involved\n\n'
             if 'aggregations' in _result:
                for el in _result['aggregations']:
                    name = el['name']
                    _text += f"{name} : {el['total']} connections \n"
                aka_cust_object.add_attribute('Customer Attribution', type='text', value=str(_text), Tag=tagInfo, disable_correlation=True)
             self.incident_flag = "true"
             self.misp_event.add_object(**aka_cust_object)
Exemplo n.º 11
0
 def __init__(self, credfile='.edgerc', section='default'):
     self.credfile = credfile
     self.section = section
     self.edgerc = EdgeRc(self.credfile)
     self.baseurl = 'https://{}'.format(self.edgerc.get(section, 'host'))
     self.s = requests.Session()
     self.s.auth = EdgeGridAuth.from_edgerc(self.edgerc, self.section)
Exemplo n.º 12
0
 def __init__(self, baseurl, client_token, client_secret, access_token):
     self.baseurl = baseurl
     self.session = requests.Session()
     self.session.auth = EdgeGridAuth(client_token=client_token,
                                      client_secret=client_secret,
                                      access_token=access_token,
                                      max_body=128 * 1024)
Exemplo n.º 13
0
 def executeAPI(self,
                api_command,
                api_payload,
                query,
                verb='GET',
                headers={}):
     api_base_url = self.baseurl
     action = api_command
     url = urljoin(self.baseurl, action)
     request_headers = {
         'Content-Type': 'application/json',
         'Accept': 'application/json'
     }
     request_headers.update(headers)
     session = requests.Session()
     session.auth = EdgeGridAuth.from_edgerc(self.edgerc,
                                             self.edgerc_section)
     r = session.request(verb,
                         url,
                         headers=request_headers,
                         json=api_payload,
                         params=query)
     self.http_status = r.status_code
     self.http_content = r.content
     content = r.content
     return (content)
Exemplo n.º 14
0
def papi_products(account_key, cid, verbose):
    """ Getting a list of products """

    if not cid:
        print(
            'Contract ID is required to get a list of Products.  '
            'To get a list of contracts, use "./' +
            os.path.basename(__file__) + ' contracts"', '\n')
        raise SystemExit

    gssapi = ''
    if account_key:
        gssapi = '&accountSwitchKey=' + account_key
    session = requests.Session()
    session.auth = EdgeGridAuth.from_edgerc(EDGERC, SECTION)
    result = session.get(
        urljoin(BASEURL, '/papi/v1/products?contractId=' + cid + gssapi))

    # Get result of dictionaries and put them into a list
    list_dict = result.json()

    verbose_check(verbose, list_dict,
                  inspect.currentframe().f_code.co_name, [account_key, cid])
    success_check(result.status_code, "200", list_dict, verbose)

    print('accountId:', list_dict["accountId"])
    print('contractId:', list_dict["contractId"])
    print('Products:')
    sorted_groups = sorted(list_dict["products"]["items"],
                           key=lambda x: x['productName'])
    print('\t', 'productName;', 'productId;')
    for items in sorted_groups:
        print('\t', items['productName'] + ';', items['productId'] + ';')
    print('\n')
Exemplo n.º 15
0
def init_config(edgerc_file, section):
    if not edgerc_file:
        if not os.getenv("AKAMAI_EDGERC"):
            edgerc_file = os.path.join(os.path.expanduser("~"), '.edgerc')
        else:
            edgerc_file = os.getenv("AKAMAI_EDGERC")

    if not os.access(edgerc_file, os.R_OK):
        root_logger.error("Unable to read edgerc file \"%s\"" % edgerc_file)
        exit(1)

    if not section:
        if not os.getenv("AKAMAI_EDGERC_SECTION"):
            section = "papi"
        else:
            section = os.getenv("AKAMAI_EDGERC_SECTION")


    try:
        edgerc = EdgeRc(edgerc_file)
        base_url = edgerc.get(section, 'host')

        session = requests.Session()
        session.auth = EdgeGridAuth.from_edgerc(edgerc, section)

        return base_url, session
    except configparser.NoSectionError:
        root_logger.error("Edgerc section \"%s\" not found" % section)
        exit(1)
    except Exception:
        root_logger.info(
            "Unknown error occurred trying to read edgerc file (%s)" %
            edgerc_file)
        exit(1)
Exemplo n.º 16
0
Arquivo: run.py Projeto: oways/AWP
def main():
    s = requests.Session()
    # Akamai auth
    s.auth = EdgeGridAuth.from_edgerc(edgerc, section)
    url = 'https://{}/siem/v1/configs/{}?offset={}&from={}&to={}&limit={}'.format(
        edgerc.get(section, 'host'), configIds, offset, firstTS, currentTS,
        limit)
    result = s.get(url)
    content = result.content.decode("utf-8")
    data = []
    lines = content.splitlines()
    lastLine = json.loads(lines[len(lines) - 1])
    for l in lines[:-1]:
        try:
            j = json.loads(l)
            tags = decoder(j['attackData']['ruleTags'])
            # Filtering logs for only builtin Akamai web attacks and polices (ex. sqli, xss & rce)
            if "WEB_ATTACK" in tags or "/POLICY/" in tags:
                data.append(decodeData(j))
        except Exception as e:
            print(e)

    with open(offsetPath, "w+") as f:
        f.write(lastLine['offset'])

    # Send data to syslog server
    sendSyslog(data)
    # Checking if every thing went will
    healthCheck()
Exemplo n.º 17
0
 def __session(self):
     session = getattr(self.__local, 'session', None)
     if not session:
         session = requests.Session()
         session.auth = EdgeGridAuth(**self.__auth)
         self.__local.session = session
     return session
Exemplo n.º 18
0
 def test_edgerc_unparseable(self):
     try:
         auth = EdgeGridAuth.from_edgerc(
             os.path.join(mydir, 'edgerc_test_doesnt_parse'))
         self.fail("should have thrown an exception")
     except:
         pass
def api_record_create(zone: str, name: str, type: str, host: str,
                      client_secret: str, access_token: str, client_token: str,
                      switchkey: str, ip_list: list, ttl: int):
    url = 'https://' + host + '/config-dns/v2/zones/' + zone + '/names/' + name + '/types/' + type + '?accountSwitchKey=' + switchkey
    #print(url)

    # creating a http request
    http_request = requests.Session()

    # post request headers
    http_request.auth = EdgeGridAuth(client_token, client_secret, access_token)
    headers = {}
    headers['Content-type'] = "application/json"
    http_request.headers = headers

    # defining body of post request
    body = {}
    body['name'] = name
    body['type'] = type
    body['ttl'] = ttl
    body['rdata'] = ip_list
    #print(body)
    json_body = json.dumps(body)
    #print(json_body)
    #http_request.data = json_body
    http_response = http_request.post(url, data=json_body)
    return (http_response)
Exemplo n.º 20
0
    def __init__(self, log=None, section_name="papi"):
        self.log = log
        self.session = requests.Session()
        self.debug = False
        self.verbose = False
        self.section_name = section_name
        self.account = None

        # If all parameters are set already, use them.  Otherwise
        # use the config
        self.config = EdgeGridConfig({}, self.section_name)

        if hasattr(self.config, "debug") and self.config.debug:
            self.debug = True

        if hasattr(self.config, "verbose") and self.config.verbose:
            self.verbose = True

        # Set the config options
        self.session.auth = EdgeGridAuth(
            client_token=self.config.client_token,
            client_secret=self.config.client_secret,
            access_token=self.config.access_token)

        if hasattr(self.config, 'headers'):
            self.session.headers.update(self.config.headers)

        self.baseurl = '%s://%s/' % ('https', self.config.host)
        self.httpCaller = EdgeGridHttpCaller(self.session, self.debug,
                                             self.verbose, self.baseurl,
                                             self.log)
Exemplo n.º 21
0
 def purge(self, url):
     auth = EdgeGridAuth(
         client_token=self.client_token,
         client_secret=self.client_secret,
         access_token=self.access_token
     )
     headers = {'content-type': 'application/json'}
     payload = {
         'action': 'invalidate',
         'objects': [url]
     }
     resp = requests.post(
         self.fast_purge_url,
         headers=headers,
         data=json.dumps(payload),
         auth=auth
     )
     logger.info(
         u'Attempted to invalidate page {url}, '
         'got back response {message}'.format(
             url=url,
             message=resp.text
         )
     )
     resp.raise_for_status()
Exemplo n.º 22
0
def papi_hostnames(account_key, cid, gid, pid, vid, verbose):
    """ Not doing any checks because you should call this directly.  There is no value. """

    gssapi = ''
    if account_key:
        gssapi = '&accountSwitchKey=' + account_key
    session = requests.Session()
    session.auth = EdgeGridAuth.from_edgerc(EDGERC, SECTION)
    result = session.get(
        urljoin(
            BASEURL, '/papi/v1/properties/' + pid + '/versions/' + vid +
            '/hostnames?contractId=' + cid + '&groupId=' + gid + gssapi))

    # Get result of dictionaries and put them into a list
    list_dict = result.json()

    verbose_check(verbose, list_dict,
                  inspect.currentframe().f_code.co_name,
                  [account_key, cid, gid, pid, vid])
    success_check(result.status_code, "200", list_dict, verbose)

    # etag is needed for authentication
    etag = list_dict['etag']
    hosts = list_dict['hostnames']['items']

    return (etag, hosts)
Exemplo n.º 23
0
def papi_config(account_key, cid, gid, pid, vid, verbose):
    """ Getting a config detail in JSON format """

    if not cid or not gid or not pid or not vid:
        print(
            'Contract ID, Group ID, Property ID, and Version ID is required to get a the '
            'property config details.  This will be printed in JSON format.')
        raise SystemExit

    gssapi = ''
    if account_key:
        gssapi = '&accountSwitchKey=' + account_key
    session = requests.Session()
    session.auth = EdgeGridAuth.from_edgerc(EDGERC, SECTION)
    result = session.get(
        urljoin(
            BASEURL, '/papi/v1/properties/' + pid + '/versions/' + vid +
            '/rules?contractId=' + cid + '&groupId=' + gid + gssapi))

    # Get result of dictionaries and put them into a list
    list_dict = result.json()

    verbose_check(verbose, list_dict,
                  inspect.currentframe().f_code.co_name,
                  [account_key, cid, gid, pid, vid])
    success_check(result.status_code, "200", list_dict, verbose)

    print(json.dumps(list_dict))
Exemplo n.º 24
0
def papi_latest(account_key, cid, gid, pid, version_source, verbose):
    """ Not doing any checks because you should call this directly.  There is no value. """

    gssapi = ''
    if account_key:
        gssapi = '&accountSwitchKey=' + account_key
    session = requests.Session()
    session.auth = EdgeGridAuth.from_edgerc(EDGERC, SECTION)
    result = session.get(
        urljoin(
            BASEURL, '/papi/v1/properties/' + pid + '?contractId=' + cid +
            '&groupId=' + gid + gssapi))

    # Get result of dictionaries and put them into a list
    list_dict = result.json()

    verbose_check(verbose, list_dict,
                  inspect.currentframe().f_code.co_name,
                  [account_key, cid, gid, pid, version_source])
    success_check(result.status_code, "200", list_dict, verbose)

    if version_source == "PRODUCTION":
        source_json = json.dumps(
            list_dict["properties"]["items"][0]["productionVersion"])
    elif version_source == "STAGING":
        source_json = json.dumps(
            list_dict["properties"]["items"][0]["stagingVersion"])
    else:
        source_json = json.dumps(
            list_dict["properties"]["items"][0]["latestVersion"])

    return source_json
Exemplo n.º 25
0
def purgeCPCode(CP=None):


    #Fetch Credentials from Env Variables from AWS
    AO_ACCESS_TOKEN = os.environ['AO_ACCESS_TOKEN']
    AO_CLIENT_SECRET = os.environ['AO_CLIENT_SECRET']
    AO_API_HOST = os.environ['AO_API_HOST']
    AO_CLIENT_TOKEN = os.environ['AO_CLIENT_TOKEN']
    
    apiRequest = requests.Session()
    apiRequest.auth = EdgeGridAuth(
        client_token=AO_CLIENT_TOKEN,
        client_secret=AO_CLIENT_SECRET,
        access_token=AO_ACCESS_TOKEN
    )
    apiBaseUrl = "https://"+AO_API_HOST
    apiEndpoint = apiBaseUrl+ "/ccu/v3/invalidate/cpcode/staging"
    # Change Path for production network Purge
    #apiEndpoint = apiBaseUrl+ "/ccu/v3/invalidate/cpcode/production"
    postbody = '{"objects": ["' + str(CP) + '"]}'
    response = apiRequest.post(apiEndpoint, postbody, headers={"Content-Type": "application/json"})
    return {
            'status':response.status_code,
            'body': json.dumps(response.text)
        }
Exemplo n.º 26
0
def papi_groups(account_key, verbose):
    """ Getting a list of groups """

    gssapi = ''
    if account_key:
        gssapi = '?accountSwitchKey=' + account_key
    session = requests.Session()
    session.auth = EdgeGridAuth.from_edgerc(EDGERC, SECTION)
    result = session.get(urljoin(BASEURL, '/papi/v1/groups' + gssapi))

    # Get result of dictionaries and put them into a list
    list_dict = result.json()

    verbose_check(verbose, list_dict,
                  inspect.currentframe().f_code.co_name, [account_key])
    success_check(result.status_code, "200", list_dict, verbose)

    print('accountId:', list_dict["accountId"])
    print('accountName:', list_dict["accountName"])
    print('Groups:')
    sorted_groups = sorted(list_dict["groups"]["items"],
                           key=lambda x: x['groupName'])
    print('\t', 'groupName;', 'groupId;', 'parentGroupId;')
    for items in sorted_groups:
        parent_id = items[
            "parentGroupId"] if "parentGroupId" in items else "n/a"
        print('\t', items['groupName'] + ';', items['groupId'] + ';',
              parent_id + ';')
    print('\n')
Exemplo n.º 27
0
    def load(self, edgerc_file, section, account_key):

        if not edgerc_file:
            if not os.getenv("AKAMAI_EDGERC"):
                edgerc_file = os.path.join(os.path.expanduser("~"), '.edgerc')
            else:
                edgerc_file = os.getenv("AKAMAI_EDGERC")

        if not os.access(edgerc_file, os.R_OK):
            raise ValueError(
                "Unable to read edgerc file {}".format(edgerc_file))

        if not section:
            if not os.getenv("AKAMAI_EDGERC_SECTION"):
                section = "default"
            else:
                section = os.getenv("AKAMAI_EDGERC_SECTION")

        try:
            edgerc = EdgeRc(edgerc_file)
            base_url = edgerc.get(section, 'host')

            session = requests.Session()
            session.auth = EdgeGridAuth.from_edgerc(edgerc, section)
            context = self.buildContext(base_url, account_key, session)
            return context

        except configparser.NoSectionError:
            raise ValueError("Edgerc section {} not found".format(section))

        except Exception:
            raise ValueError(
                "Unknown error occurred trying to read edgerc file {}".format(
                    edgerc_file))
Exemplo n.º 28
0
def api_session():
    edgerc = EdgeRc(os.path.expanduser('~/.edgerc'))
    section = 'default'
    baseurl = 'https://%s' % edgerc.get(section, 'host')
    s = requests.Session()
    s.auth = EdgeGridAuth.from_edgerc(edgerc, section)
    return [s, baseurl]
 def test_edgerc_from_object(self):
     auth = EdgeGridAuth.from_edgerc(EdgeRc(os.path.join(mydir, 'sample_edgerc')))
     self.assertEqual(auth.client_token, 'xxxx-xxxxxxxxxxxxxxxx-xxxxxxxxxxxxxxxx')
     self.assertEqual(auth.client_secret, 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=')
     self.assertEqual(auth.access_token, 'xxxx-xxxxxxxxxxxxxxxx-xxxxxxxxxxxxxxxx')
     self.assertEqual(auth.max_body, 131072)
     self.assertEqual(auth.headers_to_sign, [])
    def test_get_header_versions(self):
        auth = EdgeGridAuth.from_edgerc(os.path.join(mydir, 'sample_edgerc'), 'headers')
        header = auth.get_header_versions()
        self.assertFalse('user-agent' in header)

        header = auth.get_header_versions({'User-Agent': 'testvalue'})
        self.assertTrue('User-Agent' in header)

        os.environ["AKAMAI_CLI"] = '1.0.0'
        os.environ["AKAMAI_CLI_VERSION"] = '1.0.0'

        header = auth.get_header_versions()
        self.assertTrue('User-Agent' in header)
        self.assertEqual(header['User-Agent'], ' AkamaiCLI/1.0.0')

        os.environ["AKAMAI_CLI_COMMAND"] = '1.0.0'
        os.environ["AKAMAI_CLI_COMMAND_VERSION"] = '1.0.0'

        header = auth.get_header_versions()
        self.assertTrue('User-Agent' in header)
        self.assertEqual(header['User-Agent'], ' AkamaiCLI/1.0.0 AkamaiCLI-1.0.0/1.0.0')

        header = auth.get_header_versions({'User-Agent': 'testvalue'})
        self.assertTrue('User-Agent' in header)
        self.assertEqual(header['User-Agent'], 'testvalue AkamaiCLI/1.0.0 AkamaiCLI-1.0.0/1.0.0')

        del os.environ['AKAMAI_CLI']
        del os.environ['AKAMAI_CLI_VERSION']
        del os.environ['AKAMAI_CLI_COMMAND']
        del os.environ['AKAMAI_CLI_COMMAND_VERSION']

        self.assertFalse('AKAMAI_CLI' in os.environ)
        self.assertFalse('AKAMAI_CLI_VERSION' in os.environ)
        self.assertFalse('AKAMAI_CLI_COMMAND' in os.environ)
        self.assertFalse('AKAMAI_CLI_COMMAND_VERSION' in os.environ)
def create_session():
    session = requests.Session()
    # Set the config options
    session.auth = EdgeGridAuth(
        client_token=os.environ['ETP_CLIENT_TOKEN'].strip(),
        client_secret=os.environ['ETP_CLIENT_SECRET'].strip(),
        access_token=os.environ['ETP_ACCESS_TOKEN'].strip())
    return session
def get_session():
    s = requests.Session()
    s.auth = EdgeGridAuth(
        client_token=os.environ['AK_CLIENT_TOKEN'],
        client_secret=os.environ['AK_CLIENT_SECRET'],
        access_token=os.environ['AK_ACCESS_TOKEN'],
    )
    return s
Exemplo n.º 33
0
 def Akamai_report(self):
     s = requests.Session()
     s.auth = EdgeGridAuth(client_token='xxxxxxxxxxxxxxxxxxx',
                           client_secret='xxxxxxxxxxxxxxxxxxx',
                           access_token='xxxxxxxxxxxxxxxxxxx')
     baseurl = 'https://xxxxxxxxxxxxxxxxxxx.luna.akamaiapis.net/'
     credentials_list = [s, baseurl]
     return credentials_list
Exemplo n.º 34
0
def papi_get(edgerc_path, path):  
    edgerc = EdgeRc(edgerc_path)  
    section = 'default'  
  
    s = requests.Session()  
    s.auth = EdgeGridAuth.from_edgerc(edgerc, section)  
    baseurl = 'https://%s' % edgerc.get(section, 'host')  
  
    return s.get(urlparse.urljoin(baseurl, path))  
Exemplo n.º 35
0
def edge_session(env, config):
    s = requests.Session()
    s.auth = EdgeGridAuth(
        # This is akamai credential
        client_token=config.get(env, 'client_token'),
        client_secret=config.get(env, 'client_secret'),
        access_token=config.get(env, 'access_token'))

    return s
Exemplo n.º 36
0
def papi_get(edgerc_path, path):  
    edgerc = EdgeRc(edgerc_path)  
    section = 'default'  
  
    s = requests.Session()  
    s.auth = EdgeGridAuth.from_edgerc(edgerc, section)  
    baseurl = 'https://%s' % edgerc.get(section, 'host')  
    body = s.get(urlparse.urljoin(baseurl, path))
    if body.status_code > 200:
        print "Error, got HTTP status code %s" % body.status_code
        print body.content
        exit(1)
    if body.status_code == 200:
        return s.get(urlparse.urljoin(baseurl, path))  
Exemplo n.º 37
0
def load_edgegrid_client_settings():
    '''Load Akamai EdgeGrid configuration

    returns a (hostname, EdgeGridAuth) tuple from the following locations:

    1. Values specified directly in the Django settings::
        AKAMAI_CCU_CLIENT_SECRET
        AKAMAI_CCU_HOST
        AKAMAI_CCU_ACCESS_TOKEN
        AKAMAI_CCU_CLIENT_TOKEN
    2. An edgerc file specified in the AKAMAI_EDGERC_FILENAME settings
    3. The default ~/.edgerc file

    Both edgerc file load options will return the values from the “CCU” section
    by default. This may be customized using the AKAMAI_EDGERC_CCU_SECTION setting.
    '''

    if getattr(settings, 'AKAMAI_CCU_CLIENT_SECRET', None):
        # If the settings module has the values directly and they are not empty
        # we'll use them without checking for an edgerc file:

        host = settings.AKAMAI_CCU_HOST
        auth = EdgeGridAuth(access_token=settings.AKAMAI_CCU_ACCESS_TOKEN,
                            client_token=settings.AKAMAI_CCU_CLIENT_TOKEN,
                            client_secret=settings.AKAMAI_CCU_CLIENT_SECRET)
        return host, auth
    else:
        edgerc_section = getattr(settings, 'AKAMAI_EDGERC_CCU_SECTION', 'CCU')

        edgerc_path = getattr(settings, 'AKAMAI_EDGERC_FILENAME', '~/.edgerc')
        edgerc_path = os.path.expanduser(edgerc_path)

        if os.path.isfile(edgerc_path):
            edgerc = EdgeRc(edgerc_path)
            host = edgerc.get(edgerc_section, 'host')
            auth = EdgeGridAuth.from_edgerc(edgerc, section=edgerc_section)
            return host, auth

        raise InvalidAkamaiConfiguration('Cannot find Akamai client configuration!')
 def test_edgerc_headers(self):
     auth = EdgeGridAuth.from_edgerc(os.path.join(mydir, 'sample_edgerc'), 'headers')
     self.assertEqual(auth.headers_to_sign, ['x-mything1', 'x-mything2'])
 def test_edgerc_broken(self):
     auth = EdgeGridAuth.from_edgerc(os.path.join(mydir, 'sample_edgerc'), 'broken')
     self.assertEqual(auth.client_secret, 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=')
     self.assertEqual(auth.access_token, 'xxxx-xxxxxxxxxxxxxxxx-xxxxxxxxxxxxxxxx')
     self.assertEqual(auth.max_body, 128*1024)
     self.assertEqual(auth.headers_to_sign, [])
 def test_edgerc_unparseable(self):
     try:
         auth = EdgeGridAuth.from_edgerc(os.path.join(mydir, 'edgerc_that_doesnt_parse'))
         self.fail("should have thrown an exception")
     except:
         pass
 def test_edgerc_dashes(self):
     auth = EdgeGridAuth.from_edgerc(os.path.join(mydir, 'sample_edgerc'), 'dashes')
     self.assertEqual(auth.max_body, 128*1024)
Exemplo n.º 42
0
session = requests.Session()

logger = logging.getLogger(__name__)
parser = argparse.ArgumentParser(description='Process command line options.')
parser.add_argument('--verbose', '-v', default=False, action='count')
parser.add_argument('--debug', '-d', default=False, action='count')

args = parser.parse_args()
arguments = vars(args)
rc_path = os.path.expanduser("~/.edgerc")

edgerc = EdgeRc(rc_path)
baseurl = 'https://%s' % edgerc.get(section_name, 'host')

# Set the config options
session.auth = EdgeGridAuth.from_edgerc(edgerc, section_name)

if hasattr(edgerc, "debug") or arguments['debug']:
	client.HTTPConnection.debuglevel = 1
        logging.basicConfig()
        logging.getLogger().setLevel(logging.DEBUG)
        requests_log = logging.getLogger("requests.packages.urllib3")
        requests_log.setLevel(logging.DEBUG)
        requests_log.propagate = True
        debug = True

if hasattr(edgerc, "verbose") or arguments['verbose']:
  verbose = True

httpCaller = EdgeGridHttpCaller(session, debug,verbose, baseurl)