├── CHANGELOG.md ├── LICENSE ├── README.md ├── convert_egcurl.pl ├── egcurl ├── examples ├── README.md ├── create-credentials.md ├── delete-credentials.md ├── get-credentials.md └── update-credentials.md └── requirements.txt /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # RELEASE NOTES 2 | 3 | ## 2022-04-14 4 | 5 | * Reorder list of arguments before parsing it, moving URL to the beginning. 6 | 7 | ## 2022-04-13 8 | 9 | * Pass unknown argument before known ones, to let -q be passed in 1st position and honored. 10 | 11 | ## 2021-04-22 12 | 13 | * Added PATCH as a valid method argument. 14 | 15 | ## 2017-07-27 16 | 17 | * Add --eg-json argument to pretty-format JSON responses. 18 | 19 | ## 2016-11-07 20 | 21 | * Add support for EdgeRc configuration files. 22 | 23 | ## 2016-08-25 24 | 25 | * Use EdgeGridAuth to sign requests. 26 | * Automatically use hostname specified by configuration section. 27 | 28 | ## 2016-06-01 29 | 30 | * Use logging module for logging. 31 | * Replace getopt argument parsing code with argparse (requires python 2.7+) 32 | 33 | ## 2014-05-13 34 | 35 | * (GRID-231) A POST request body larger than the content hash max-body is allowed but only the first (max-body) bytes are used in the [Content hash aspect of the request signature](https://developer.akamai.com/stuff/Getting_Started_with_OPEN_APIs/Client_Auth.html). -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, and 10 | distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by the copyright 13 | owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all other entities 16 | that control, are controlled by, or are under common control with that entity. 17 | For the purposes of this definition, "control" means (i) the power, direct or 18 | indirect, to cause the direction or management of such entity, whether by 19 | contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the 20 | outstanding shares, or (iii) beneficial ownership of such entity. 21 | 22 | "You" (or "Your") shall mean an individual or Legal Entity exercising 23 | permissions granted by this License. 24 | 25 | "Source" form shall mean the preferred form for making modifications, including 26 | but not limited to software source code, documentation source, and configuration 27 | files. 28 | 29 | "Object" form shall mean any form resulting from mechanical transformation or 30 | translation of a Source form, including but not limited to compiled object code, 31 | generated documentation, and conversions to other media types. 32 | 33 | "Work" shall mean the work of authorship, whether in Source or Object form, made 34 | available under the License, as indicated by a copyright notice that is included 35 | in or attached to the work (an example is provided in the Appendix below). 36 | 37 | "Derivative Works" shall mean any work, whether in Source or Object form, that 38 | is based on (or derived from) the Work and for which the editorial revisions, 39 | annotations, elaborations, or other modifications represent, as a whole, an 40 | original work of authorship. For the purposes of this License, Derivative Works 41 | shall not include works that remain separable from, or merely link (or bind by 42 | name) to the interfaces of, the Work and Derivative Works thereof. 43 | 44 | "Contribution" shall mean any work of authorship, including the original version 45 | of the Work and any modifications or additions to that Work or Derivative Works 46 | thereof, that is intentionally submitted to Licensor for inclusion in the Work 47 | by the copyright owner or by an individual or Legal Entity authorized to submit 48 | on behalf of the copyright owner. For the purposes of this definition, 49 | "submitted" means any form of electronic, verbal, or written communication sent 50 | to the Licensor or its representatives, including but not limited to 51 | communication on electronic mailing lists, source code control systems, and 52 | issue tracking systems that are managed by, or on behalf of, the Licensor for 53 | the purpose of discussing and improving the Work, but excluding communication 54 | that is conspicuously marked or otherwise designated in writing by the copyright 55 | owner as "Not a Contribution." 56 | 57 | "Contributor" shall mean Licensor and any individual or Legal Entity on behalf 58 | of whom a Contribution has been received by Licensor and subsequently 59 | incorporated within the Work. 60 | 61 | 2. Grant of Copyright License. 62 | 63 | Subject to the terms and conditions of this License, each Contributor hereby 64 | grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, 65 | irrevocable copyright license to reproduce, prepare Derivative Works of, 66 | publicly display, publicly perform, sublicense, and distribute the Work and such 67 | Derivative Works in Source or Object form. 68 | 69 | 3. Grant of Patent License. 70 | 71 | Subject to the terms and conditions of this License, each Contributor hereby 72 | grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, 73 | irrevocable (except as stated in this section) patent license to make, have 74 | made, use, offer to sell, sell, import, and otherwise transfer the Work, where 75 | such license applies only to those patent claims licensable by such Contributor 76 | that are necessarily infringed by their Contribution(s) alone or by combination 77 | of their Contribution(s) with the Work to which such Contribution(s) was 78 | submitted. If You institute patent litigation against any entity (including a 79 | cross-claim or counterclaim in a lawsuit) alleging that the Work or a 80 | Contribution incorporated within the Work constitutes direct or contributory 81 | patent infringement, then any patent licenses granted to You under this License 82 | for that Work shall terminate as of the date such litigation is filed. 83 | 84 | 4. Redistribution. 85 | 86 | You may reproduce and distribute copies of the Work or Derivative Works thereof 87 | in any medium, with or without modifications, and in Source or Object form, 88 | provided that You meet the following conditions: 89 | 90 | You must give any other recipients of the Work or Derivative Works a copy of 91 | this License; and 92 | You must cause any modified files to carry prominent notices stating that You 93 | changed the files; and 94 | You must retain, in the Source form of any Derivative Works that You distribute, 95 | all copyright, patent, trademark, and attribution notices from the Source form 96 | of the Work, excluding those notices that do not pertain to any part of the 97 | Derivative Works; and 98 | If the Work includes a "NOTICE" text file as part of its distribution, then any 99 | Derivative Works that You distribute must include a readable copy of the 100 | attribution notices contained within such NOTICE file, excluding those notices 101 | that do not pertain to any part of the Derivative Works, in at least one of the 102 | following places: within a NOTICE text file distributed as part of the 103 | Derivative Works; within the Source form or documentation, if provided along 104 | with the Derivative Works; or, within a display generated by the Derivative 105 | Works, if and wherever such third-party notices normally appear. The contents of 106 | the NOTICE file are for informational purposes only and do not modify the 107 | License. You may add Your own attribution notices within Derivative Works that 108 | You distribute, alongside or as an addendum to the NOTICE text from the Work, 109 | provided that such additional attribution notices cannot be construed as 110 | modifying the License. 111 | You may add Your own copyright statement to Your modifications and may provide 112 | additional or different license terms and conditions for use, reproduction, or 113 | distribution of Your modifications, or for any such Derivative Works as a whole, 114 | provided Your use, reproduction, and distribution of the Work otherwise complies 115 | with the conditions stated in this License. 116 | 117 | 5. Submission of Contributions. 118 | 119 | Unless You explicitly state otherwise, any Contribution intentionally submitted 120 | for inclusion in the Work by You to the Licensor shall be under the terms and 121 | conditions of this License, without any additional terms or conditions. 122 | Notwithstanding the above, nothing herein shall supersede or modify the terms of 123 | any separate license agreement you may have executed with Licensor regarding 124 | such Contributions. 125 | 126 | 6. Trademarks. 127 | 128 | This License does not grant permission to use the trade names, trademarks, 129 | service marks, or product names of the Licensor, except as required for 130 | reasonable and customary use in describing the origin of the Work and 131 | reproducing the content of the NOTICE file. 132 | 133 | 7. Disclaimer of Warranty. 134 | 135 | Unless required by applicable law or agreed to in writing, Licensor provides the 136 | Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, 137 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, 138 | including, without limitation, any warranties or conditions of TITLE, 139 | NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are 140 | solely responsible for determining the appropriateness of using or 141 | redistributing the Work and assume any risks associated with Your exercise of 142 | permissions under this License. 143 | 144 | 8. Limitation of Liability. 145 | 146 | In no event and under no legal theory, whether in tort (including negligence), 147 | contract, or otherwise, unless required by applicable law (such as deliberate 148 | and grossly negligent acts) or agreed to in writing, shall any Contributor be 149 | liable to You for damages, including any direct, indirect, special, incidental, 150 | or consequential damages of any character arising as a result of this License or 151 | out of the use or inability to use the Work (including but not limited to 152 | damages for loss of goodwill, work stoppage, computer failure or malfunction, or 153 | any and all other commercial damages or losses), even if such Contributor has 154 | been advised of the possibility of such damages. 155 | 156 | 9. Accepting Warranty or Additional Liability. 157 | 158 | While redistributing the Work or Derivative Works thereof, You may choose to 159 | offer, and charge a fee for, acceptance of support, warranty, indemnity, or 160 | other liability obligations and/or rights consistent with this License. However, 161 | in accepting such obligations, You may act only on Your own behalf and on Your 162 | sole responsibility, not on behalf of any other Contributor, and only if You 163 | agree to indemnify, defend, and hold each Contributor harmless for any liability 164 | incurred by, or claims asserted against, such Contributor by reason of your 165 | accepting any such warranty or additional liability. 166 | 167 | END OF TERMS AND CONDITIONS 168 | 169 | APPENDIX: How to apply the Apache License to your work 170 | 171 | To apply the Apache License to your work, attach the following boilerplate 172 | notice, with the fields enclosed by brackets "[]" replaced with your own 173 | identifying information. (Don't include the brackets!) The text should be 174 | enclosed in the appropriate comment syntax for the file format. We also 175 | recommend that a file or class name and description of purpose be included on 176 | the same "printed page" as the copyright notice for easier identification within 177 | third-party archives. 178 | 179 | Copyright 2025 Akamai Technologies, Inc. All rights reserved. 180 | 181 | Licensed under the Apache License, Version 2.0 (the "License"); 182 | you may not use these files except in compliance with the License. 183 | You may obtain a copy of the License at 184 | 185 | http://www.apache.org/licenses/LICENSE-2.0 186 | 187 | Unless required by applicable law or agreed to in writing, software 188 | distributed under the License is distributed on an "AS IS" BASIS, 189 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 190 | See the License for the specific language governing permissions and 191 | limitations under the License. 192 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # EdgeGrid for cURL 2 | 3 | This library implements an Authentication handler for HTTP requests using the [Akamai EdgeGrid Authentication](https://techdocs.akamai.com/developer/docs/authenticate-with-edgegrid) scheme for cURL. 4 | 5 | `egcurl` is a simple Python-based command wrapper around the traditional [cURL](https://curl.se) command to sign requests for Akamai OPEN APIs. The script intercepts a subset of cURL command arguments to produce a request signature. Then it uses cURL to make the API call with all the original arguments and the computed request signature. 6 | 7 | > **Note:** There is now a simpler command line tool available, httpie. You don't need to be familiar with cURL to use httpie. It's available on the [httpie-edgegrid](https://github.com/akamai-open/httpie-edgegrid) GitHub repository. 8 | > 9 | > The examples and guides on the [developer portal](https://techdocs.akamai.com/home/page/apis) are moving to this new tool, thus consider using it for your API calls. 10 | 11 | ## Install 12 | 13 | 1. Install Python 3.6 or later on your system. You can download it from https://www.python.org/downloads/. If you're running GNU/Linux or macOS, you probably already have it. 14 | 15 | > __NOTE:__ Python 2 is no longer supported by the [Python Software Foundation](https://www.python.org/doc/sunset-python-2/). You won't be able to use the library with Python 2. 16 | 17 | 2. Install [cURL](https://curl.se/download.html). The script expects to find it in your path. 18 | 19 | 3. Install the `edgegrid-python` authentication handler to sign your requests by running this command: 20 | 21 | ``` 22 | pip install edgegrid-python 23 | ``` 24 | 25 | 4. Clone this repository and then execute `egcurl` directly from the cloned repository. 26 | 27 | ## Authentication 28 | 29 | We provide authentication credentials through an API client. Requests to the API are signed with a timestamp and are executed immediately. 30 | 31 | 1. [Create authentication credentials](https://techdocs.akamai.com/developer/docs/set-up-authentication-credentials). 32 | 33 | 2. Place your credentials in an EdgeGrid resource file `~/.edgerc`, in the `[default]` section. 34 | 35 | ``` 36 | [default] 37 | client_secret = C113nt53KR3TN6N90yVuAgICxIRwsObLi0E67/N8eRN= 38 | host = akab-h05tnam3wl42son7nktnlnnx-kbob3i3v.luna.akamaiapis.net 39 | access_token = akab-acc35t0k3nodujqunph3w7hzp7-gtm6ij 40 | client_token = akab-c113ntt0k3n4qtari252bfxxbsl-yvsdj 41 | ``` 42 | 43 | 3. Use `egcurl` to sign your requests along with and `--eg-edgerc` argument to point to the path of your `.edgerc` configuration file and an `--eg-section` argument to specify the credentials' section header. 44 | 45 | ```shell 46 | python3 egcurl --eg-edgerc ~/.edgerc --eg-section default --request GET 47 | ``` 48 | 49 | ### `~/.egcurl` configuration 50 | 51 | `egcurl` supports an older non-standard configuration file, specified by `--eg-config`. If you use this argument or if the `~/.egcurl` file exists, this configuration file will be consulted first to retrieve your client configuration. If the file doesn't exist or the section isn't found, `egcurl` will look for the client configuration in your `~/.edgerc` file automatically. 52 | 53 | The older `~/.egcurl` configuration is **deprecated**. Support for this file and format will be removed on or shortly after 2017-05-01. You can easily convert an older `~/.egcurl` configuration to an `~/.edgerc` with the `convert_egcurl.pl` script. For example: 54 | 55 | ``` 56 | $ ./convert_egcurl.pl < ~/.egcurl > ~/.edgerc 57 | $ mv ~/.egcurl ~/.egcurl-backup 58 | ``` 59 | 60 | ## Use 61 | 62 | To use the library, provide the credential's section header of your `.edgerc` file and the appropriate endpoint information. 63 | 64 | ```shell 65 | python3 egcurl --eg-edgerc ~/.edgerc --eg-section default --request GET \ 66 | --url "https://luna.akamaiapis.net/identity-management/v3/user-profile" \ 67 | --header 'accept: application/json' 68 | ``` 69 | 70 | ### Query string parameters 71 | 72 | When entering query parameters, you can first save them as variables and then pass them in the url after a question mark ("?") at the end of the main URL path. 73 | 74 | ```shell 75 | auth_grants=true 76 | notifications=true 77 | actions=true 78 | 79 | python3 egcurl --eg-edgerc ~/.edgerc --eg-section default --request GET \ 80 | --url "https://luna.akamaiapis.net/identity-management/v3/user-profile?authGrants=$auth_grants¬ifications=$notifications&actions=$actions" \ 81 | --header 'accept: application/json' 82 | ``` 83 | 84 | ### Headers 85 | 86 | Enter request headers in the `--header` argument. 87 | 88 | > **Note:** You don't need to include the `Content-Type` and `Content-Length` headers. The authentication layer adds these values. 89 | 90 | ```shell 91 | python3 egcurl --eg-edgerc ~/.edgerc --eg-section default --request GET \ 92 | --url "https://luna.akamaiapis.net/identity-management/v3/user-profile" \ 93 | --header 'accept: application/json' 94 | ``` 95 | 96 | ### Body data 97 | 98 | Provide the request body as an object in the `--data` argument. 99 | 100 | ```shell 101 | python3 egcurl --eg-edgerc ~/.edgerc --eg-section default --request PUT \ 102 | --url "https://luna.akamaiapis.net/identity-management/v3/user-profile/basic-info" \ 103 | --header 'accept: application/json' \ 104 | --header 'content-type: application/json' \ 105 | --data ' 106 | { 107 | "contactType": "Billing", 108 | "country": "USA", 109 | "firstName": "John", 110 | "lastName": "Smith", 111 | "preferredLanguage": "English", 112 | "sessionTimeOut": 30, 113 | "timeZone": "GMT", 114 | "phone": "3456788765" 115 | }' 116 | ``` 117 | 118 | ### Debug 119 | 120 | Use the `--eg-verbose` argument to enable debugging and get additional information on the HTTP request and response. 121 | 122 | ```Shell 123 | python3 egcurl --eg-verbose --eg-edgerc ~/.edgerc --eg-section default --request GET \ 124 | --url "https://luna.akamaiapis.net/identity-management/v3/user-profile" \ 125 | --header 'accept: application/json' 126 | ``` 127 | 128 | ## Command line 129 | 130 | `egcurl` is a wrapper around the traditional cURL command, thus it supports nearly all arguments for cURL. 131 | 132 | ### Arguments 133 | 134 | `egcurl` has these optional non-standard arguments available: 135 | 136 | | Argument | Description | 137 | | --------- | ----------- | 138 | | `--eg-edgerc ` | Location of your `.edgerc` configuration file. | 139 | | `--eg-section
` | The credential's section header of your `.edgerc` configuration file. | 140 | |`--eg-json` | Automatically applies JSON pretty-format to the response.| 141 | |`--eg-verbose` | Increases logging verbosity. Can be repeated to further increase verbosity. | 142 | 143 | 144 | > **Note:** `egcurl` doesn't support these arguments: 145 | > 146 | > - `-F`, `--form`, `--form-string` 147 | > - `--data-urlencode` 148 | > - `-G`, `--get` 149 | 150 | ### Limitations 151 | 152 | There're several things you need to take into account when specifying the request data for POST requests. 153 | 154 | - The POST requests support only `-d`, `--data` and `--data-ascii` for ascii data and `--data-binary` for binary data. 155 | 156 | - You can use only one data option on the same command line. 157 | 158 | - If the data starts with the `@` character, the rest is treated as the name of the file to read the data from. You can specify only one file on the same command line. 159 | 160 | ### Help 161 | 162 | Use `./egcurl --help` to get detailed information on `egcurl` and the available arguments. 163 | 164 | ```shell 165 | $ ./egcurl --help 166 | usage: egcurl [-h] [-H HEADER] [--eg-edgerc EG_EDGERC | --eg-config EG_CONFIG] 167 | [--eg-json] [--eg-section EG_SECTION] [--eg-verbose] 168 | [-d DATA | --data-binary DATA_BINARY] [-X {DELETE,GET,PATCH,POST,PUT}] 169 | url 170 | 171 | Akamai {OPEN} API utility for signed API requests with cURL. 172 | 173 | positional arguments: 174 | url Request URL 175 | 176 | optional arguments: 177 | -h, --help show this help message and exit 178 | -H HEADER, --header HEADER 179 | HTTP headers to pass on to cURL (repeatable) 180 | --eg-edgerc EG_EDGERC 181 | Location of EdgeRc configuration ini file. 182 | --eg-config EG_CONFIG 183 | Location of older configuration file (DEPRECATED). 184 | --eg-json Automatically apply JSON pretty-format to the response. 185 | --eg-section EG_SECTION 186 | Section of the config file for the desired OPEN API credentials. 187 | --eg-verbose Enable verbose logging output (repeat for even more) 188 | -d DATA, --data DATA, --data-ascii DATA 189 | ASCII data content for POST body 190 | --data-binary DATA_BINARY 191 | binary data content for POST body 192 | -X {DELETE,GET,PATCH,POST,PUT}, --method {DELETE,GET,PATCH,POST,PUT}, --request {DELETE,GET,PATCH,POST,PUT} 193 | HTTP method for the request 194 | 195 | Several arguments above as well as any unlisted arguments are passed on to cURL, 196 | starting with unlisted arguments followed by URL. The argument should always be 197 | the first item starting with "https://". The URL hostname will automatically be replaced 198 | with the one specified by the selected configuration section. 199 | ``` 200 | 201 | 202 | ## Bugs 203 | 204 | This tool indirectly uses pyOpenSSL for Python < 3 via [EdgeGrid for Python](https://github.com/akamai/AkamaiOPEN-edgegrid-python/), which is used to produce request signatures. macOS includes a very old version of it (0.13.1) by default, which is incompatible with EdgeGrid for Python. 205 | 206 | If you're using macOS and are incorrectly receiving an instruction to run `pip install edgegrid-python`, the issue is likely that your pyOpenSSL dependency is too old and needs to be upgraded. 207 | 208 | Run this command to fix the problem: 209 | 210 | ``` 211 | pip install -U pyOpenSSL 212 | ``` 213 | 214 | > **Note:** DO NOT RUN THIS COMMAND AS ROOT. It's not possible to upgrade the system installation of pyOpenSSL on macOS. Attempting to upgrade it will fail with inexplicable errors. 215 | 216 | ## Reporting issues 217 | 218 | To report an issue or make a suggestion, create a new [GitHub issue](https://github.com/akamai/edgegrid-curl/issues). 219 | 220 | ## License 221 | 222 | Copyright 2025 Akamai Technologies, Inc. All rights reserved. 223 | 224 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use these files except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0. 225 | 226 | Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -------------------------------------------------------------------------------- /convert_egcurl.pl: -------------------------------------------------------------------------------- 1 | #!/usr/bin/perl 2 | 3 | use strict; 4 | use warnings; 5 | 6 | while () { 7 | if ($_ =~ /^\s*($|#|;)/o || $_ =~ /^\s*\[(.+?)\]\s*$/) { 8 | print($_); 9 | next; 10 | } 11 | chomp($_); 12 | $_ =~ s/secret/client_secret/go; 13 | my @options = split(/ +/, $_); 14 | @options = sort(@options); 15 | foreach my $thing (@options) { 16 | $thing =~ s/:/ = /go; 17 | print($thing . "\n"); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /egcurl: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import sys 3 | if sys.version_info[0] >= 3: 4 | # python3 5 | from urllib import parse 6 | else: 7 | # python2.7 8 | import urlparse as parse 9 | 10 | import argparse 11 | import json 12 | import logging 13 | import os 14 | import re 15 | import subprocess 16 | from pprint import pformat 17 | 18 | # data handling 19 | # only handles -d/--data/--data-ascii/--data-binary 20 | # no name 21 | # only one entry, no repeats 22 | # can handle @ 23 | 24 | logging.basicConfig() 25 | log = logging.getLogger(__name__) 26 | 27 | class MockRequest: 28 | def __init__(self, data_ascii, data_binary, headers, method, url): 29 | self.body = self.get_data(data_ascii, data_binary) 30 | log.info("body: %s", self.body) 31 | self.headers= headers or {} 32 | self.method = method 33 | self.url = url 34 | 35 | def get_data(self, data_ascii, data_binary): 36 | data = '' 37 | if data_ascii: 38 | data = data_ascii 39 | elif data_binary: 40 | data = data_binary 41 | # only hash POST for now 42 | if data and data.startswith("@"): 43 | data_file = data.lstrip("@") 44 | try: 45 | if not os.path.isfile(data_file): 46 | raise Exception('%s is not a file' %(data_file)) 47 | filesize = os.stat(data_file).st_size 48 | # read the file content, and assign to data 49 | with open(data_file, "r") as f: 50 | data = f.read() 51 | if data_ascii: 52 | data = ''.join(data.splitlines()) 53 | return data 54 | except IOError: 55 | raise 56 | return data 57 | 58 | def register_hook(self, ignoredA, ignoredB): 59 | return 60 | 61 | def get_config(edgerc_filename, egconf_filename, section): 62 | if os.path.isfile(os.path.expanduser(egconf_filename)): 63 | configs = _parse_egcurl(egconf_filename) 64 | if section in configs: 65 | logging.warning("Using configuraton from deprecated egconfig file '%s'. Please migrate to ~/.edgerc.", egconf_filename) 66 | config = configs[section] 67 | return config 68 | 69 | config = _parse_edgerc(os.path.expanduser(edgerc_filename), section) 70 | return config 71 | 72 | def _parse_edgerc(file, section): 73 | if not os.path.isfile(file): 74 | return None 75 | edgerc = EdgeRc(file) 76 | config = { 77 | "access_token": edgerc.get(section, 'access_token'), 78 | "client_token": edgerc.get(section, 'client_token'), 79 | "host": edgerc.get(section, 'host'), 80 | "max-body": edgerc.getint(section, 'max-body'), 81 | "secret": edgerc.get(section, 'client_secret'), 82 | "signed-header": edgerc.get(section, 'headers_to_sign') 83 | } 84 | 85 | # The EdgeRc library ensures the whole file must be valid. If host is empty then there's no config found. 86 | if config['host'] is None: 87 | return None 88 | 89 | return config 90 | 91 | def _parse_egcurl(file): 92 | configs = {} 93 | with open(file, "r") as f: 94 | current_section = None 95 | for line in f.readlines(): 96 | if re.match("^\\s*($|#|;)", line): continue 97 | 98 | m = re.match("^\\s*\\[(.+?)\\]\\s*$", line) 99 | if m: 100 | current_section = m.group(1) 101 | continue 102 | 103 | config = { 104 | "access_token": None, 105 | "client_token": None, 106 | "host": None, 107 | "max-body": None, 108 | "secret": None, 109 | "signed-header": [] 110 | } 111 | _parse_fields(config, line) 112 | if config["max-body"]: 113 | config["max-body"] = int(config["max-body"]) 114 | else: 115 | config["max-body"] = 131072 116 | 117 | if None in config.values(): 118 | log.warning("Bad config line in section '%s': %s", current_section, line) 119 | else: 120 | configs[current_section] = config 121 | 122 | return configs 123 | 124 | def _parse_fields(config, line): 125 | fields = line.split() 126 | for field in fields: 127 | log.debug("Config Field: [%s]", field) 128 | 129 | match = re.match("^([^:]+):(.+)$", field) 130 | if not match: 131 | log.error("Config line: [%s] has invalid field [%s].", line, field) 132 | return 133 | 134 | key = match.group(1) 135 | value = match.group(2) 136 | log.debug("Config Key: [%s] Value: [%s]", key, value) 137 | 138 | if key not in config.keys(): 139 | log.error("Config line: [%s] has nonexistent variable [%s].", line, key) 140 | return 141 | 142 | if type(config[key]) == list: 143 | config[key].append(value) 144 | elif not config[key]: 145 | config[key] = value 146 | else: 147 | log.error("Config line: [%s] has duplicate variable [%s].", line, key) 148 | break 149 | 150 | def get_parser(): 151 | parser = argparse.ArgumentParser(description='Akamai {OPEN} API utility for signed API requests with cURL.', 152 | epilog='Several arguments above as well as any unlisted arguments are passed on to cURL, starting with unlisted arguments followed by URL. The argument should always be the first item starting with "https://". The URL hostname will automatically be replaced with the one specified by the selected configuration section.') 153 | parser.add_argument('-H', '--header', 154 | action='append', 155 | default = [], 156 | help='HTTP headers to pass on to cURL (repeatable)') 157 | group = parser.add_mutually_exclusive_group() 158 | group.add_argument("--eg-edgerc", 159 | default=os.path.expanduser("~/.edgerc"), 160 | help='Location of EdgeRc configuration ini file.') 161 | group.add_argument("--eg-config", 162 | default=os.path.expanduser("~/.egcurl"), 163 | help='Location of older configuration file (DEPRECATED).') 164 | parser.add_argument("--eg-json", 165 | default=False, 166 | help='Automatically apply JSON pretty-format to the response.', 167 | action='store_true') 168 | parser.add_argument("--eg-section", 169 | default = "default", 170 | help='Section of the config file for the desired OPEN API credentials.') 171 | parser.add_argument('--eg-verbose', 172 | default=False, 173 | help='Enable verbose logging output (repeat for even more)', 174 | action='count') 175 | group = parser.add_mutually_exclusive_group() 176 | group.add_argument('-d', '--data', '--data-ascii', 177 | help='ASCII data content for POST body') 178 | group.add_argument('--data-binary', 179 | help='binary data content for POST body') 180 | parser.add_argument('-X', '--method', '--request', 181 | choices=['DELETE', 'GET', 'PATCH', 'POST', 'PUT'], 182 | help='HTTP method for the request', 183 | default='GET') 184 | parser.add_argument('url', 185 | help='Request URL') 186 | 187 | # Reorder list of arguments before parsing it, moving URL to the beginning 188 | # This assumes that the URL is the first item starting with "https://" 189 | # This requires in particular that: 190 | # - there is no cURL arguments like --data or --doh-url provided before the URL with a value starting also with "https://" 191 | # - cURL option like --proto-default https is not used to pass URL that don't start with "https://" (as in curl --proto-default https www.example.com) 192 | 193 | # Index of all items starting with "https://" 194 | url_indexes=[sys.argv.index(x) for x in sys.argv if x.startswith("https://")] 195 | if len(url_indexes) != 0: 196 | # Old position of URL 197 | url_index = url_indexes[0] 198 | # New position of URL 199 | url_index_new = 1 200 | if url_index_new < url_index: 201 | # Items before new position of URL 202 | args_ordered = sys.argv[0:url_index_new] 203 | # URL 204 | args_ordered += [sys.argv[url_index]] 205 | # Items between new and old position of URL 206 | args_ordered += sys.argv[url_index_new:url_index] 207 | # Items after old position of URL 208 | args_ordered += sys.argv[url_index+1:len(sys.argv)] 209 | else: 210 | # URL can't be moved closer to the beginnig. Parse arguments without reordering them 211 | args_ordered = sys.argv.copy() 212 | else: 213 | # URL not found. Parse arguments without reordering them 214 | args_ordered = sys.argv.copy() 215 | # Don't parse 1st item (program path) 216 | args_ordered = args_ordered[1:] 217 | 218 | (args, args_unknown) = parser.parse_known_args(args_ordered) 219 | if args.eg_verbose == 1: 220 | log.setLevel(logging.INFO) 221 | elif args.eg_verbose >= 2: 222 | log.setLevel(logging.DEBUG) 223 | 224 | log.info('Parsed known arguments: %s', pformat(args)) 225 | log.debug('Pass-through cURL arguments: %s', pformat(args_unknown)) 226 | 227 | disallowed_parser = argparse.ArgumentParser() 228 | disallowed_parser.add_argument("-F") 229 | disallowed_parser.add_argument("--form") 230 | disallowed_parser.add_argument("--form-string") 231 | disallowed_parser.add_argument("--data-urlencode") 232 | disallowed_parser.add_argument("-G", "--get", default=None, action='store_true') 233 | (args_bad, args_remainder) = disallowed_parser.parse_known_args(args_unknown) 234 | 235 | unacceptable = [] 236 | for (key, val) in vars(args_bad).items(): 237 | if val != None: 238 | unacceptable.append(key) 239 | 240 | if len(unacceptable) != 0: 241 | log.debug('Disallowed cURL arguments: %s', pformat(args_bad)) 242 | parser.error("Unsupported cURL arguments found: " + ', '.join(unacceptable)) 243 | 244 | return (args, args_unknown) 245 | 246 | def main(): 247 | (args, args_unknown) = get_parser() 248 | 249 | section = args.eg_section 250 | method = args.method 251 | data_ascii = args.data 252 | data_binary = args.data_binary 253 | url = args.url 254 | 255 | headers = {} 256 | if args.header: 257 | for header in args.header: 258 | header_field = header.strip() 259 | header_name, header_value = header_field.split(':') 260 | if header_name: 261 | header_name = header_name.strip() 262 | if not header_name: 263 | log.error("Invalid header value: %s", header_name) 264 | sys.exit(1) 265 | if header_value: 266 | header_value = header_value.strip() 267 | if header_value: 268 | headers[header_name.lower()] = header_value 269 | 270 | config = get_config(args.eg_edgerc, args.eg_config, section) 271 | 272 | if not config: 273 | raise ValueError("Config section was invalid or not found.") 274 | 275 | if 'host' in headers and headers['host'] != config['host']: 276 | raise ValueError("Host header does not match config host") 277 | 278 | if config['max-body'] == 8192: 279 | log.warning("The max-body value '8192' is likely incorrect. Signing POST requests may fail. Try removing that from your configuration.") 280 | 281 | segments = parse.urlsplit(url) 282 | if segments.netloc != config['host']: 283 | log.warning("Requested hostname '%s' will be replaced by config host '%s'", segments.netloc, config['host']) 284 | url = parse.urlunsplit(segments._replace(netloc = config['host'])) 285 | 286 | # update the args with the signature 287 | log.info("Authorization config: %s", pformat(config)) 288 | 289 | auth = EdgeGridAuth( 290 | access_token=config['access_token'], 291 | client_secret=config['secret'], 292 | client_token=config['client_token'], 293 | headers_to_sign=config['signed-header'], 294 | max_body=config['max-body'] 295 | ) 296 | 297 | r = MockRequest(data_ascii, data_binary, headers, method, url) 298 | auth(r) 299 | auth_header = r.headers['Authorization'] 300 | log.info("Authorization header: %s", auth_header) 301 | 302 | curl_args = ([ 'curl' ]) 303 | # Pass unknown args before known ones, so that -q can be passed in 1st position 304 | curl_args.extend( args_unknown ) 305 | # Append several specific headers we need to make proper requests. 306 | curl_args.extend([ '-X', method, '-H', 'Authorization:' + auth_header ]) 307 | # For POST and PUT requests, cURL adds `Expect: 100-continue` by default. 308 | # This behavior is part of RFC 2616, for making a speculative preflight 309 | # request to ensure the origin will accept the body size. This is not 310 | # useful behavior for egcurl, so we unset the `Expect` header. 311 | if method.upper() in [ 'POST', 'PUT' ]: 312 | curl_args.extend([ '-H', 'Expect:' ]) 313 | for header in args.header: 314 | curl_args.extend([ '-H', header ]) 315 | if args.data: 316 | curl_args.extend([ '--data', args.data ]) 317 | if args.data_binary: 318 | curl_args.extend([ '--data-binary', args.data_binary ]) 319 | curl_args.extend([ url ]) 320 | 321 | log.info("cURL command: %s", " ".join(curl_args)) 322 | sys.stdout.flush() 323 | 324 | stdoutType = None 325 | if args.eg_json: 326 | stdoutType = subprocess.PIPE 327 | proc = subprocess.Popen(args = curl_args, 328 | stderr = None, 329 | stdout = stdoutType, 330 | universal_newlines = True) 331 | 332 | if args.eg_json: 333 | json_stdout = proc.stdout.read() 334 | try: 335 | json_data = json.loads(json_stdout) 336 | print(json.dumps(json_data, sort_keys=True, indent=4, separators=(',', ': '))) 337 | except ValueError: 338 | if len(json_stdout) == 0: 339 | log.warning("Response was actually empty, not JSON.") 340 | else: 341 | log.error("Exception parsing JSON response! Raw value will be printed to STDOUT.") 342 | print(json_stdout) 343 | 344 | proc.wait() 345 | return proc.returncode 346 | 347 | if __name__ == "__main__": 348 | try: 349 | from akamai.edgegrid import EdgeGridAuth 350 | from akamai.edgegrid import EdgeRc 351 | except ImportError: 352 | print(""" 353 | This tool has been updated to use the Akamai EdgeGrid for Python library 354 | to sign requests. That library will need to be installed before you can 355 | make a request. 356 | 357 | Please run this command to install the required library: 358 | 359 | pip install edgegrid-python""") 360 | sys.exit(1) 361 | 362 | sys.exit(main()) 363 | -------------------------------------------------------------------------------- /examples/README.md: -------------------------------------------------------------------------------- 1 | # Examples 2 | 3 | This directory contains executable CRUD examples for Akamai API using a Python-based command wrapper for cURL. API calls used in these examples are available to all users. But, if you find one of the write examples doesn't work for you, talk with your account's admin about your privilege level. 4 | 5 | ## Run 6 | 7 | To run any of the files: 8 | 9 | 1. Open a Terminal or shell instance. 10 | 2. Copy the egcurl statement from the `.md` file and paste it to the Terminal or shell instance. 11 | 12 | - Specify the location of your `.edgerc` file. The default is set to the home directory. 13 | - Provide the section header for the set of credentials you'd like to use. The default is `default`. 14 | - For update and delete operations, replace the dummy `credential_id` with your valid `credential_id`. 15 | 16 | > **Important:** Don't use the credentials you're actively using when running the update (inactivation) and delete operations. Otherwise, you'll block your access to the Akamai APIs. 17 | 18 | 3. Press `Enter` to run the egcurl statement. 19 | 20 | ## Sample files 21 | 22 | The example in each file contains a call to one of the Identity and Access Management (IAM) API endpoints. See the [IAM API reference](https://techdocs.akamai.com/iam-api/reference/api) doc for more information on each of the calls used. 23 | 24 | | Operation | Method | Endpoint | 25 | | --- | --- | --- | 26 | | [List your API client credentials.](/examples/get-credentials.md) | `GET` | `/identity-management/v3/api-clients/self/credentials` | 27 | | [Create new API client credentials.](/examples/create-credentials.md)
This is a *quick* client and grants you the default permissions associated with your account. | `POST` | `/identity-management/v3/api-clients/self/credentials` | 28 | | [Update your credentials by ID.](/examples/update-credentials.md) | `PUT` | `/identity-management/v3/api-clients/self/credentials/{credentialId}` | 29 | | [Delete your credentials by ID.](/examples/delete-credentials.md) | `DELETE` | `/identity-management/v3/api-clients/self/credentials/{credentialId}` | 30 | 31 | Suggested chained call order: 32 | 33 | 1. Get credentials to see your base information. 34 | 2. Create a client to create a new set of credentials. 35 | 3. Update credentials to inactivate the newly created set from step 2. 36 | 4. Delete a client to delete the inactivated credentials. 37 | 5. Get credentials to verify if they're gone (the status will be `DELETED`). -------------------------------------------------------------------------------- /examples/create-credentials.md: -------------------------------------------------------------------------------- 1 | This example creates your new API client credentials. 2 | 3 | To run this example: 4 | 5 | 1. Open a Terminal or shell instance. 6 | 7 | 2. Copy the below egcurl statement and paste it to the Terminal or shell instance. 8 | 9 | 3. Specify the location of your `.edgerc` file and the section header of the set of credentials to use. 10 | 11 | 5. Press `Enter` to run the egcurl statement. 12 | 13 | A successful call returns a new API client with its `credentialId`. Use this ID in both the update and delete examples. 14 | 15 | For more information on the call used in this example, see https://techdocs.akamai.com/iam-api/reference/post-self-credentials. 16 | 17 | ``` 18 | python3 egcurl --eg-edgerc ~/.edgerc --eg-section default --request POST \ 19 | --url "https://luna.akamaiapis.net/identity-management/v3/api-clients/self/credentials" \ 20 | --header 'accept: application/json' 21 | ``` -------------------------------------------------------------------------------- /examples/delete-credentials.md: -------------------------------------------------------------------------------- 1 | This example deletes your API client credentials. 2 | 3 | To run this example: 4 | 5 | 1. Open a Terminal or shell instance. 6 | 7 | 2. Copy the below egcurl statement and paste it to the Terminal or shell instance. 8 | 9 | 3. Specify the location of your `.edgerc` file and the section header of the set of credentials to use. 10 | 11 | The defaults here expect the `.edgerc` at your home directory and use the credentials under the heading of default. 12 | 13 | 4. Add the `credential_id` from the update example to the path. You can only delete inactive credentials. Sending the request on an active set will return a 400. Use the update credentials example for deactivation. 14 | 15 | > **Important:** Don't use the credentials you're actively using when deleting a set of credentials. Otherwise, you'll block your access to the Akamai APIs. 16 | 17 | 5. Press `Enter` to run the egcurl statement. 18 | 19 | A successful call returns "" null. 20 | 21 | For more information on the call used in this example, see https://techdocs.akamai.com/iam-api/reference/delete-self-credential. 22 | 23 | ``` 24 | credential_id=123456 25 | 26 | python3 egcurl --eg-edgerc ~/.edgerc --eg-section default --request DELETE \ 27 | --url "https://luna.akamaiapis.net/identity-management/v3/api-clients/self/credentials/$credential_id" \ 28 | --header 'accept: application/json' 29 | ``` -------------------------------------------------------------------------------- /examples/get-credentials.md: -------------------------------------------------------------------------------- 1 | This example returns a list of your API client credentials. 2 | 3 | To run this example: 4 | 5 | 1. Open a Terminal or shell instance. 6 | 7 | 2. Copy the below egcurl statement and paste it to the Terminal or shell instance. 8 | 9 | 3. Append the path to your `.edgerc` file and the section header of the set of credentials to use. 10 | 11 | The defaults here expect the `.edgerc` at your home directory and use the credentials under the heading of default. 12 | 13 | 4. Press `Enter` to run the egcurl statement. 14 | 15 | A successful call returns your credentials grouped by `credential_id`. 16 | 17 | For more information on the call used in this example, see https://techdocs.akamai.com/iam-api/reference/get-self-credentials. 18 | 19 | ``` 20 | python3 egcurl --eg-edgerc ~/.edgerc --eg-section default --request GET \ 21 | --url "https://luna.akamaiapis.net/identity-management/v3/api-clients/self/credentials" \ 22 | --header "Accept: application/json" 23 | ``` -------------------------------------------------------------------------------- /examples/update-credentials.md: -------------------------------------------------------------------------------- 1 | This example updates the credentials from the create credentials example. 2 | 3 | To run this example: 4 | 5 | 1. Open a Terminal or shell instance. 6 | 7 | 2. Copy the below egcurl statement and paste it to the Terminal or shell instance. 8 | 9 | 3. Specify the location of your `.edgerc` file and the section header of the set of credentials to use. 10 | 11 | The defaults here expect the `.edgerc` at your home directory and use the credentials under the heading of default. 12 | 13 | 4. Add the `credential_id` for the set of credentials created using the create example as a path parameter. 14 | 15 | 5. Edit the `expiresOn` date to today's date. Optionally, you can change the `description` value. The date cannot be more than two years out or it will return a 400. 16 | 17 | > **Important:** Don't use the credentials you're actively using when inactivating a set of credentials. Otherwise, you'll block your access to the Akamai APIs. 18 | 19 | 6. Press `Enter` to run the egcurl statement. 20 | 21 | A successful call returns. 22 | 23 | For more information on the call used in this example, see https://techdocs.akamai.com/iam-api/reference/put-self-credential. 24 | 25 | ``` 26 | credential_id=123456 27 | 28 | python3 egcurl --eg-edgerc ~/.edgerc --eg-section default --request PUT \ 29 | --url "https://luna.akamaiapis.net/identity-management/v3/api-clients/self/credentials/$credential_id" \ 30 | --header "Accept: application/json" \ 31 | --header "Content-Type: application/json" \ 32 | --data ' 33 | { 34 | "status": "ACTIVE", 35 | "expiresOn": "2024-06-11T23:06:59.000Z", 36 | "description": "Update this credential" 37 | }' 38 | ``` -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | edgegrid-python 2 | pyOpenSSL>=17.0.0 3 | --------------------------------------------------------------------------------