-
Notifications
You must be signed in to change notification settings - Fork 15
/
client.py
421 lines (348 loc) · 12.5 KB
/
client.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
import os
import platform
import tarfile
import urllib.parse
from io import BytesIO
from pathlib import Path
from typing import Any, Dict, List, Optional, Union, cast
import click
import requests
from requests import Response, Session, codes
from .config import (
DEFAULT_API_VERSION,
DEFAULT_BASE_URI,
DEFAULT_TIMEOUT,
MULTI_DOCUMENT_LIMIT,
)
from .iac_models import (
IaCScanParameters,
IaCScanParametersSchema,
IaCScanResult,
IaCScanResultSchema,
)
from .models import (
Detail,
Document,
HealthCheckResponse,
MultiScanResult,
QuotaResponse,
ScanResult,
)
# max files size to create a tar from
MAX_TAR_CONTENT_SIZE = 30 * 1024 * 1024
class Versions:
app_version: Optional[str] = None
secrets_engine_version: Optional[str] = None
VERSIONS = Versions()
def load_detail(resp: Response) -> Detail:
"""
load_detail loads a Detail from a response
be it JSON or html.
:param resp: API response
:type resp: Response
:return: detail object of response
:rtype: Detail
"""
if resp.headers["content-type"] == "application/json":
data = resp.json()
else:
data = {"detail": resp.text}
return cast(Detail, Detail.SCHEMA.load(data))
def is_ok(resp: Response) -> bool:
"""
is_ok returns True is the API responded with 200
and the content type is JSON.
"""
return (
resp.headers["content-type"] == "application/json"
and resp.status_code == codes.ok
)
def _create_tar(root_path: Path, filenames: List[str]) -> bytes:
"""
:param root_path: the root_path from which the tar is created
:param files: the files which need to be added to the tar, filenames should be the paths relative to the root_path
:return: a bytes object containing the tar.gz created from the files, with paths relative to root_path
"""
tar_stream = BytesIO()
current_dir_size = 0
with tarfile.open(fileobj=tar_stream, mode="w:gz") as tar:
for filename in filenames:
full_path = root_path / filename
current_dir_size += os.path.getsize(full_path)
if current_dir_size > MAX_TAR_CONTENT_SIZE:
raise click.ClickException(
f"The total size of the files processed exceeds {MAX_TAR_CONTENT_SIZE / (1024 * 1024):.0f}MB, "
f"please try again with less files"
)
tar.add(full_path, filename)
return tar_stream.getvalue()
class GGClient:
_version = "undefined"
session: Session
api_key: str
base_uri: str
timeout: Optional[float]
user_agent: str
extra_headers: Dict
def __init__(
self,
api_key: str,
base_uri: Optional[str] = None,
session: Optional[Session] = None,
user_agent: Optional[str] = None,
timeout: Optional[float] = DEFAULT_TIMEOUT,
):
"""
:param api_key: API Key to be added to requests
:param base_uri: Base URI for the API, defaults to "https://api.gitguardian.com"
:param session: custom requests session, defaults to requests.Session()
:param user_agent: user agent to identify requests, defaults to ""
:param timeout: request timeout, defaults to 20s
:raises ValueError: if the protocol or the api_key is invalid
"""
if isinstance(base_uri, str):
if not base_uri.startswith(("http://", "https://")):
raise ValueError("Invalid protocol, prepend with http:// or https://")
else:
base_uri = DEFAULT_BASE_URI
if not isinstance(api_key, str):
raise TypeError("api_key is not a string")
try:
# The requests module encodes headers in latin-1, if api_key contains
# characters which cannot be encoded in latin-1, the raised exception is
# going to be very obscure. Catch the problem early to raise a clearer
# exception.
# See https://github.com/GitGuardian/ggshield/issues/101
api_key.encode("latin-1")
except UnicodeEncodeError:
raise ValueError(
"Invalid value for API Key: must be only latin-1 characters."
)
self.base_uri = base_uri
self.api_key = api_key
self.session = session if isinstance(session, Session) else Session()
self.timeout = timeout
self.user_agent = "pygitguardian/{0} ({1};py{2})".format(
self._version, platform.system(), platform.python_version()
)
if isinstance(user_agent, str):
self.user_agent = " ".join([self.user_agent, user_agent])
self.session.headers.update(
{
"User-Agent": self.user_agent,
"Authorization": "Token {0}".format(api_key),
},
)
def request(
self,
method: str,
endpoint: str,
version: Optional[str] = DEFAULT_API_VERSION,
extra_headers: Optional[Dict[str, str]] = None,
**kwargs: Any,
) -> Response:
url = self._url_from_endpoint(endpoint, version)
headers = (
{**self.session.headers, **extra_headers}
if extra_headers
else self.session.headers
)
response: Response = self.session.request(
method=method, url=url, timeout=self.timeout, headers=headers, **kwargs
)
self.app_version = response.headers.get("X-App-Version", self.app_version)
self.secrets_engine_version = response.headers.get(
"X-Secrets-Engine-Version", self.secrets_engine_version
)
return response
def _url_from_endpoint(self, endpoint: str, version: Optional[str]) -> str:
if version:
endpoint = urllib.parse.urljoin(version + "/", endpoint)
return urllib.parse.urljoin(self.base_uri + "/", endpoint)
@property
def app_version(self) -> Optional[str]:
global VERSIONS
return VERSIONS.app_version
@app_version.setter
def app_version(self, value: Optional[str]) -> None:
global VERSIONS
VERSIONS.app_version = value
@property
def secrets_engine_version(self) -> Optional[str]:
global VERSIONS
return VERSIONS.secrets_engine_version
@secrets_engine_version.setter
def secrets_engine_version(self, value: Optional[str]) -> None:
global VERSIONS
VERSIONS.secrets_engine_version = value
def get(
self,
endpoint: str,
version: Optional[str] = DEFAULT_API_VERSION,
extra_headers: Optional[Dict[str, str]] = None,
**kwargs: Any,
) -> Response:
return self.request(
method="get",
endpoint=endpoint,
version=version,
extra_headers=extra_headers,
**kwargs,
)
def post(
self,
endpoint: str,
data: Optional[Dict[str, str]] = None,
version: str = DEFAULT_API_VERSION,
extra_headers: Optional[Dict[str, str]] = None,
**kwargs: Any,
) -> Response:
return self.request(
"post",
endpoint=endpoint,
json=data,
version=version,
extra_headers=extra_headers,
**kwargs,
)
def health_check(self) -> HealthCheckResponse:
"""
health_check handles the /health endpoint of the API
use Detail.status_code to check the response status code of the API
200 if server is online and api_key is valid
:return: Detail response and status code
"""
resp = self.get(endpoint="health")
return HealthCheckResponse(
detail=load_detail(resp).detail,
status_code=resp.status_code,
app_version=self.app_version,
secrets_engine_version=self.secrets_engine_version,
)
def content_scan(
self,
document: str,
filename: Optional[str] = None,
extra_headers: Optional[Dict[str, str]] = None,
) -> Union[Detail, ScanResult]:
"""
content_scan handles the /scan endpoint of the API.
If document contains `0` bytes, they will be replaced with the Unicode
replacement character.
:param filename: name of file, example: "intro.py"
:param document: content of file
:param extra_headers: additional headers to add to the request
:return: Detail or ScanResult response and status code
"""
doc_dict = {"document": document}
if filename:
doc_dict["filename"] = filename
request_obj = Document.SCHEMA.load(doc_dict)
resp = self.post(
endpoint="scan",
data=request_obj,
extra_headers=extra_headers,
)
obj: Union[Detail, ScanResult]
if is_ok(resp):
obj = ScanResult.SCHEMA.load(resp.json())
else:
obj = load_detail(resp)
obj.status_code = resp.status_code
return obj
def multi_content_scan(
self,
documents: List[Dict[str, str]],
extra_headers: Optional[Dict[str, str]] = None,
ignore_known_secrets: Optional[bool] = None,
) -> Union[Detail, MultiScanResult]:
"""
multi_content_scan handles the /multiscan endpoint of the API.
If documents contain `0` bytes, they will be replaced with the Unicode
replacement character.
:param documents: List of dictionaries containing the keys document
and, optionally, filename.
example: [{"document":"example content","filename":"intro.py"}]
:param extra_headers: additional headers to add to the request
:param ignore_known_secrets: indicates whether known secrets should be ignored
:return: Detail or ScanResult response and status code
"""
if len(documents) > MULTI_DOCUMENT_LIMIT:
raise ValueError(
"too many documents submitted for scan (max={0})".format(
MULTI_DOCUMENT_LIMIT
)
)
if all(isinstance(doc, dict) for doc in documents):
request_obj = Document.SCHEMA.load(documents, many=True)
else:
raise TypeError("each document must be a dict")
params = (
{"ignore_known_secrets": ignore_known_secrets}
if ignore_known_secrets
else {}
)
resp = self.post(
endpoint="multiscan",
data=request_obj,
extra_headers=extra_headers,
params=params,
)
obj: Union[Detail, MultiScanResult]
if is_ok(resp):
obj = MultiScanResult.SCHEMA.load(dict(scan_results=resp.json()))
else:
obj = load_detail(resp)
obj.status_code = resp.status_code
return obj
def quota_overview(
self,
extra_headers: Optional[Dict[str, str]] = None,
) -> Union[Detail, QuotaResponse]:
"""
quota_overview handles the /quotas endpoint of the API
:param extra_headers: additional headers to add to the request
:return: Detail or Quota response and status code
"""
resp = self.get(
endpoint="quotas",
extra_headers=extra_headers,
)
obj: Union[Detail, QuotaResponse]
if is_ok(resp):
obj = QuotaResponse.SCHEMA.load(resp.json())
else:
obj = load_detail(resp)
obj.status_code = resp.status_code
return obj
# For IaC Scans
def iac_directory_scan(
self,
directory: Path,
filenames: List[str],
scan_parameters: IaCScanParameters,
extra_headers: Optional[Dict[str, str]] = None,
) -> Union[Detail, IaCScanResult]:
tar = _create_tar(directory, filenames)
result: Union[Detail, IaCScanResult]
try:
resp = self.post(
endpoint="iac_scan",
extra_headers=extra_headers,
files={
"directory": tar,
},
data={
"scan_parameters": IaCScanParametersSchema().dumps(scan_parameters),
},
)
except requests.exceptions.ReadTimeout:
result = Detail("The request timed out.")
result.status_code = 504
else:
if is_ok(resp):
result = IaCScanResultSchema().load(resp.json())
else:
result = load_detail(resp)
result.status_code = resp.status_code
return result