hexway-hive-api 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- hexway_hive_api-0.1.0/LICENSE +21 -0
- hexway_hive_api-0.1.0/PKG-INFO +49 -0
- hexway_hive_api-0.1.0/README.md +31 -0
- hexway_hive_api-0.1.0/hexway_hive_api/__init__.py +6 -0
- hexway_hive_api-0.1.0/hexway_hive_api/hive_client.py +2 -0
- hexway_hive_api-0.1.0/hexway_hive_api/rest/__init__.py +10 -0
- hexway_hive_api-0.1.0/hexway_hive_api/rest/enums.py +16 -0
- hexway_hive_api-0.1.0/hexway_hive_api/rest/error_handler.py +39 -0
- hexway_hive_api-0.1.0/hexway_hive_api/rest/exceptions.py +58 -0
- hexway_hive_api-0.1.0/hexway_hive_api/rest/http_client/__init__.py +7 -0
- hexway_hive_api-0.1.0/hexway_hive_api/rest/http_client/exceptions.py +23 -0
- hexway_hive_api-0.1.0/hexway_hive_api/rest/http_client/http_client.py +91 -0
- hexway_hive_api-0.1.0/hexway_hive_api/rest/models/__init__.py +0 -0
- hexway_hive_api-0.1.0/hexway_hive_api/rest/models/issue.py +23 -0
- hexway_hive_api-0.1.0/hexway_hive_api/rest/models/project.py +39 -0
- hexway_hive_api-0.1.0/hexway_hive_api/rest_client.py +145 -0
- hexway_hive_api-0.1.0/hexway_hive_api.egg-info/PKG-INFO +49 -0
- hexway_hive_api-0.1.0/hexway_hive_api.egg-info/SOURCES.txt +23 -0
- hexway_hive_api-0.1.0/hexway_hive_api.egg-info/dependency_links.txt +1 -0
- hexway_hive_api-0.1.0/hexway_hive_api.egg-info/requires.txt +5 -0
- hexway_hive_api-0.1.0/hexway_hive_api.egg-info/top_level.txt +1 -0
- hexway_hive_api-0.1.0/setup.cfg +4 -0
- hexway_hive_api-0.1.0/setup.py +26 -0
- hexway_hive_api-0.1.0/tests/test_issue.py +29 -0
- hexway_hive_api-0.1.0/tests/test_project.py +38 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Cur1iosity
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: hexway-hive-api
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Small wrapper for HexWay Hive API
|
|
5
|
+
Home-page: https://github.com/Cur1iosity/hexway-hive-api
|
|
6
|
+
Author: @Cur1iosity
|
|
7
|
+
Author-email: Cur1iosity@protonmail.com
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
10
|
+
Classifier: Operating System :: OS Independent
|
|
11
|
+
Requires-Python: >=3.12
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
License-File: LICENSE
|
|
14
|
+
Requires-Dist: requests>=2.31.0
|
|
15
|
+
Requires-Dist: pydantic>=2.4.0
|
|
16
|
+
Provides-Extra: dev
|
|
17
|
+
Requires-Dist: pytest; extra == "dev"
|
|
18
|
+
|
|
19
|
+
[](https://github.com/Cur1iosity/hivepy/actions/workflows/run-tests.yml)
|
|
20
|
+
[](https://pypi.org/project/hw-hivepy/)
|
|
21
|
+
[](https://hexway.io)
|
|
22
|
+
|
|
23
|
+
# HivePy
|
|
24
|
+
|
|
25
|
+
Unofficial flexible library for [HexWay Hive](https://hexway.io/hive/) Rest API.
|
|
26
|
+
|
|
27
|
+
#### Tested on HexWay Hive 0.62.8
|
|
28
|
+
|
|
29
|
+
## Installation
|
|
30
|
+
```bash
|
|
31
|
+
TBD
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Dependencies
|
|
35
|
+
|
|
36
|
+
- pydantic ~= 2.4
|
|
37
|
+
- requests ~= 2.31.0
|
|
38
|
+
|
|
39
|
+
## Usage
|
|
40
|
+
### Simple HiveClient
|
|
41
|
+
```python
|
|
42
|
+
def main() -> None:
|
|
43
|
+
... # TBD
|
|
44
|
+
|
|
45
|
+
if __name__ == "__main__":
|
|
46
|
+
main()
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
```
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
[](https://github.com/Cur1iosity/hivepy/actions/workflows/run-tests.yml)
|
|
2
|
+
[](https://pypi.org/project/hw-hivepy/)
|
|
3
|
+
[](https://hexway.io)
|
|
4
|
+
|
|
5
|
+
# HivePy
|
|
6
|
+
|
|
7
|
+
Unofficial flexible library for [HexWay Hive](https://hexway.io/hive/) Rest API.
|
|
8
|
+
|
|
9
|
+
#### Tested on HexWay Hive 0.62.8
|
|
10
|
+
|
|
11
|
+
## Installation
|
|
12
|
+
```bash
|
|
13
|
+
TBD
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
## Dependencies
|
|
17
|
+
|
|
18
|
+
- pydantic ~= 2.4
|
|
19
|
+
- requests ~= 2.31.0
|
|
20
|
+
|
|
21
|
+
## Usage
|
|
22
|
+
### Simple HiveClient
|
|
23
|
+
```python
|
|
24
|
+
def main() -> None:
|
|
25
|
+
... # TBD
|
|
26
|
+
|
|
27
|
+
if __name__ == "__main__":
|
|
28
|
+
main()
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
```
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
from hexway_hive_api.rest.enums import ClientState
|
|
2
|
+
from hexway_hive_api.rest import exceptions, http_client
|
|
3
|
+
from hexway_hive_api.rest.http_client.http_client import HTTPClient
|
|
4
|
+
|
|
5
|
+
__all__ = [
|
|
6
|
+
'HTTPClient',
|
|
7
|
+
'ClientState',
|
|
8
|
+
'exceptions',
|
|
9
|
+
'http_client',
|
|
10
|
+
]
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
from enum import StrEnum, auto
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class ClientState(StrEnum):
|
|
5
|
+
"""Enumeration of states."""
|
|
6
|
+
NOT_CONNECTED = auto()
|
|
7
|
+
CONNECTED = auto()
|
|
8
|
+
DISCONNECTED = auto()
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class Guard(StrEnum):
|
|
12
|
+
"""Enumeration of controls."""
|
|
13
|
+
# ClientControl = auto()
|
|
14
|
+
# USER_INPUT = auto()
|
|
15
|
+
SERVER_PROVIDING = auto() # Передан ли от пользователя адрес сервера
|
|
16
|
+
CONNECTION = auto() # Подключен ли к серверу
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import functools
|
|
2
|
+
import json
|
|
3
|
+
from typing import Callable, Any
|
|
4
|
+
|
|
5
|
+
from hexway_hive_api.rest import exceptions
|
|
6
|
+
from hexway_hive_api.rest.http_client.exceptions import ClientError
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def method_decorator(func) -> Callable:
|
|
10
|
+
"""Decorator for methods."""
|
|
11
|
+
@functools.wraps(func)
|
|
12
|
+
def wrapper(*args, **kwargs) -> Any:
|
|
13
|
+
"""Wrapper for methods."""
|
|
14
|
+
try:
|
|
15
|
+
result = func(*args, **kwargs)
|
|
16
|
+
except ClientError as e:
|
|
17
|
+
error = json.loads(e.content)
|
|
18
|
+
raise exceptions.HiveRestError(error)
|
|
19
|
+
return result
|
|
20
|
+
return wrapper
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def ErrorHandler(cls) -> Any:
|
|
24
|
+
"""Decorator for classes."""
|
|
25
|
+
original_init = cls.__init__
|
|
26
|
+
|
|
27
|
+
@functools.wraps(original_init)
|
|
28
|
+
def new_init(self, *args, **kwargs):
|
|
29
|
+
original_init(self, *args, **kwargs)
|
|
30
|
+
# Обернуть все методы экземпляра, кроме __init__
|
|
31
|
+
for attr_name in dir(self):
|
|
32
|
+
if not attr_name.startswith("__"): # Игнорируем служебные методы
|
|
33
|
+
attr_value = getattr(self, attr_name)
|
|
34
|
+
if callable(attr_value):
|
|
35
|
+
decorated_attr = method_decorator(attr_value)
|
|
36
|
+
setattr(self, attr_name, decorated_attr)
|
|
37
|
+
|
|
38
|
+
cls.__init__ = new_init
|
|
39
|
+
return cls
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
from typing import Dict
|
|
2
|
+
|
|
3
|
+
from hexway_hive_api.rest.enums import Guard
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class HiveRestError(Exception):
|
|
7
|
+
"""Base exception for Hive rest client."""
|
|
8
|
+
def __init__(self, params: Dict) -> None:
|
|
9
|
+
"""Initialize HiveRestError."""
|
|
10
|
+
self.detail = params.get('detail')
|
|
11
|
+
self.status = params.get('status')
|
|
12
|
+
self.title = params.get('title')
|
|
13
|
+
self.type = params.get('type')
|
|
14
|
+
|
|
15
|
+
def __str__(self) -> str:
|
|
16
|
+
"""Return string representation of the exception."""
|
|
17
|
+
return f'[{self.status}] {self.title}: {self.detail}'
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class RestConnectionError(Exception):
|
|
21
|
+
"""Exception for connection errors."""
|
|
22
|
+
pass
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class ClientNotConnected(RestConnectionError):
|
|
26
|
+
"""Exception for client not connected."""
|
|
27
|
+
def __init__(self) -> None:
|
|
28
|
+
"""Initialize ClientNotConnected."""
|
|
29
|
+
super().__init__('Client is not connected to server. You must authenticate first.')
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class ServerNotFound(RestConnectionError):
|
|
33
|
+
"""Exception for server not provided."""
|
|
34
|
+
def __init__(self) -> None:
|
|
35
|
+
"""Initialize ServerNotProvided."""
|
|
36
|
+
super().__init__(f'You must provide server or api_url.')
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class IncorrectServerUrl(RestConnectionError):
|
|
40
|
+
"""Exception for incorrect server URL."""
|
|
41
|
+
def __init__(self, message: str = None) -> None:
|
|
42
|
+
"""Initialize IncorrectServerUrl."""
|
|
43
|
+
if not message:
|
|
44
|
+
super().__init__('Incorrect server URL.')
|
|
45
|
+
else:
|
|
46
|
+
super().__init__(message)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class GuardError(Exception):
|
|
50
|
+
"""Exception for control errors."""
|
|
51
|
+
pass
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class GuardIsNotDefined(GuardError):
|
|
55
|
+
"""Exception for control is not defined."""
|
|
56
|
+
def __init__(self, guard_name: str = None) -> None:
|
|
57
|
+
"""Initialize ControlIsNotDefined."""
|
|
58
|
+
super().__init__(f'Control {guard_name} is not defined. You must provide guard from list: {", ".join(Guard)}.')
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
from typing import Optional
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class ClientError(Exception):
|
|
5
|
+
"""Base exception for Client."""
|
|
6
|
+
def __init__(self, message, content=None):
|
|
7
|
+
"""Initialize ClientError."""
|
|
8
|
+
super().__init__(message)
|
|
9
|
+
self.content: Optional[str] = content
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class ClientConnectionError(ClientError):
|
|
13
|
+
"""Exception for connection errors."""
|
|
14
|
+
def __init__(self, message):
|
|
15
|
+
"""Initialize ClientConnectionError."""
|
|
16
|
+
super().__init__(message)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class SocksProxyError(ClientConnectionError):
|
|
20
|
+
"""Exception for connection errors."""
|
|
21
|
+
def __init__(self, message="Couldn't connect via provided socks proxy. Check it."):
|
|
22
|
+
"""Initialize ClientConnectionError."""
|
|
23
|
+
super().__init__(message)
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
from http import HTTPStatus, HTTPMethod
|
|
2
|
+
from typing import Dict, Self, Union, List, MutableMapping
|
|
3
|
+
|
|
4
|
+
import requests.utils
|
|
5
|
+
from requests import Session, Response
|
|
6
|
+
|
|
7
|
+
from hexway_hive_api.rest.http_client.exceptions import *
|
|
8
|
+
|
|
9
|
+
SUCCESSFUL_STATUS_CODES = [status for status in HTTPStatus if 200 <= status < 300]
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class HTTPClient:
|
|
13
|
+
"""Base implementation of the HTTP client."""
|
|
14
|
+
session: Session = Session()
|
|
15
|
+
|
|
16
|
+
def _send(self, method: HTTPMethod, *args, **kwargs) -> Union[Dict, bytes]:
|
|
17
|
+
"""Universal method for sending requests."""
|
|
18
|
+
try:
|
|
19
|
+
response: Response = self.session.request(method, *args, **kwargs)
|
|
20
|
+
|
|
21
|
+
if response.status_code not in SUCCESSFUL_STATUS_CODES:
|
|
22
|
+
try:
|
|
23
|
+
message = response.json()
|
|
24
|
+
except requests.JSONDecodeError:
|
|
25
|
+
message = response.content
|
|
26
|
+
raise ClientError(f'Request failed with status code {response.status_code}\n{message}')
|
|
27
|
+
|
|
28
|
+
try:
|
|
29
|
+
return response.json()
|
|
30
|
+
except requests.JSONDecodeError:
|
|
31
|
+
return response.content
|
|
32
|
+
|
|
33
|
+
except requests.ConnectionError as e:
|
|
34
|
+
if 'SOCKSHTTPSConnectionPool' in str(e):
|
|
35
|
+
proxy = self.session.proxies.get('https')
|
|
36
|
+
raise SocksProxyError(f'Couldn\'t connect via "{proxy}". Check it.')
|
|
37
|
+
else:
|
|
38
|
+
raise ClientConnectionError(e)
|
|
39
|
+
|
|
40
|
+
def _update_params(self, **kwargs) -> Self:
|
|
41
|
+
"""Update session parameters if they are not None and exist in session."""
|
|
42
|
+
[setattr(self.session, key, value) for key, value in kwargs.items()
|
|
43
|
+
if value is not None and hasattr(self.session, key)]
|
|
44
|
+
return self
|
|
45
|
+
|
|
46
|
+
def get(self, *args, **kwargs) -> Union[Dict, List, bytes]:
|
|
47
|
+
"""Send GET request."""
|
|
48
|
+
return self._send(HTTPMethod.GET, *args, **kwargs)
|
|
49
|
+
|
|
50
|
+
def post(self, *args, **kwargs) -> Union[Dict, List, bytes]:
|
|
51
|
+
"""Send POST request."""
|
|
52
|
+
return self._send(HTTPMethod.POST, *args, **kwargs)
|
|
53
|
+
|
|
54
|
+
def put(self, *args, **kwargs) -> Dict:
|
|
55
|
+
"""Send PUT request."""
|
|
56
|
+
return self._send(HTTPMethod.PUT, *args, **kwargs)
|
|
57
|
+
|
|
58
|
+
def patch(self, *args, **kwargs) -> Dict:
|
|
59
|
+
"""Send PATCH request."""
|
|
60
|
+
return self._send(HTTPMethod.PATCH, *args, **kwargs)
|
|
61
|
+
|
|
62
|
+
def delete(self, *args, **kwargs) -> Dict:
|
|
63
|
+
"""Send DELETE request."""
|
|
64
|
+
return self._send(HTTPMethod.DELETE, *args, **kwargs)
|
|
65
|
+
|
|
66
|
+
def add_headers(self, headers: Dict) -> Self:
|
|
67
|
+
"""Method injects headers into session."""
|
|
68
|
+
self.session.headers.update(headers)
|
|
69
|
+
return self
|
|
70
|
+
|
|
71
|
+
def update_params(self, **kwargs) -> Self:
|
|
72
|
+
"""Method updates session parameters."""
|
|
73
|
+
self._update_params(**kwargs)
|
|
74
|
+
return self
|
|
75
|
+
|
|
76
|
+
@property
|
|
77
|
+
def proxies(self) -> MutableMapping[str, str]:
|
|
78
|
+
"""Method to get session proxies."""
|
|
79
|
+
return self.session.proxies
|
|
80
|
+
|
|
81
|
+
@proxies.setter
|
|
82
|
+
def proxies(self, proxies) -> None:
|
|
83
|
+
"""Method to set session proxies."""
|
|
84
|
+
if not proxies and not isinstance(proxies, dict):
|
|
85
|
+
proxies = {}
|
|
86
|
+
self.session.proxies.update(proxies)
|
|
87
|
+
|
|
88
|
+
@property
|
|
89
|
+
def params(self):
|
|
90
|
+
"""Method to get session parameters."""
|
|
91
|
+
return self.session.__dict__
|
|
File without changes
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
from typing import Union, Optional, Dict, List
|
|
2
|
+
from uuid import UUID
|
|
3
|
+
|
|
4
|
+
import pydantic
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class Issue(pydantic.BaseModel):
|
|
8
|
+
"""Issue model for Hive."""
|
|
9
|
+
id: Union[str, UUID] = pydantic.Field(default=None, alias='uuid')
|
|
10
|
+
name: str
|
|
11
|
+
status: str
|
|
12
|
+
assets: Optional[List[Dict]] = pydantic.Field(default=None)
|
|
13
|
+
weakness_type: Optional[str] = pydantic.Field(default=None, alias='weaknessType')
|
|
14
|
+
project_id: Optional[Union[str, UUID]] = pydantic.Field(default=None)
|
|
15
|
+
|
|
16
|
+
cvss_score: Optional[float] = pydantic.Field(default=None, alias='cvssScore')
|
|
17
|
+
cvss_vector: Optional[str] = pydantic.Field(default=None, alias='cvssVector')
|
|
18
|
+
|
|
19
|
+
requests: Optional[List[Dict]] = pydantic.Field(default=None)
|
|
20
|
+
files: Optional[List[Dict]] = pydantic.Field(default=None)
|
|
21
|
+
|
|
22
|
+
additional_fields: Optional[Dict] = pydantic.Field(default=None, alias='additionalFields')
|
|
23
|
+
model_config = pydantic.ConfigDict(populate_by_name=True)
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Purpose of this model is to provide project model for serialization and deserialization project that
|
|
3
|
+
compatible with Hive API PUT method.
|
|
4
|
+
"""
|
|
5
|
+
from typing import Union, Optional, Dict
|
|
6
|
+
from uuid import UUID
|
|
7
|
+
|
|
8
|
+
import pydantic
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class Project(pydantic.BaseModel):
|
|
12
|
+
"""Project model for Hive."""
|
|
13
|
+
id: Union[UUID, str]
|
|
14
|
+
group_id: Union[UUID, str] = pydantic.Field(alias='projectGroupId')
|
|
15
|
+
description: Optional[str] = pydantic.Field(default=None, alias='projectDescription')
|
|
16
|
+
name: str = pydantic.Field(alias='projectName')
|
|
17
|
+
start_date: str = pydantic.Field(alias='projectStartDate')
|
|
18
|
+
end_date: str = pydantic.Field(alias='projectEndDate')
|
|
19
|
+
data: Optional[Dict] = pydantic.Field(default=None)
|
|
20
|
+
|
|
21
|
+
model_config = pydantic.ConfigDict(populate_by_name=True)
|
|
22
|
+
|
|
23
|
+
@pydantic.model_validator(mode='before')
|
|
24
|
+
def preparing(cls, values) -> Dict:
|
|
25
|
+
"""Prepare project model before validation."""
|
|
26
|
+
values['projectGroupId'] = values.get('group').get('id')
|
|
27
|
+
return values
|
|
28
|
+
|
|
29
|
+
@pydantic.model_serializer(when_used='always')
|
|
30
|
+
def serialize(self) -> Dict:
|
|
31
|
+
"""Serialize project model to hive project json."""
|
|
32
|
+
return {
|
|
33
|
+
'projectName': self.name,
|
|
34
|
+
'projectDescription': self.description,
|
|
35
|
+
'projectStartDate': self.start_date,
|
|
36
|
+
'projectEndDate': self.end_date,
|
|
37
|
+
'projectGroupId': self.group_id,
|
|
38
|
+
'data': self.data
|
|
39
|
+
}
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import json
|
|
2
|
+
from typing import Optional, Dict, MutableMapping, List, Union
|
|
3
|
+
from uuid import UUID
|
|
4
|
+
|
|
5
|
+
from .rest import exceptions
|
|
6
|
+
from .rest.enums import ClientState
|
|
7
|
+
from .rest.http_client import HTTPClient
|
|
8
|
+
from .rest.models.project import Project
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class RestClient:
|
|
12
|
+
"""Rest client for Hive."""
|
|
13
|
+
def __init__(self,
|
|
14
|
+
*,
|
|
15
|
+
server=None,
|
|
16
|
+
api_url=None,
|
|
17
|
+
username=None,
|
|
18
|
+
password=None,
|
|
19
|
+
proxies=None,
|
|
20
|
+
**other
|
|
21
|
+
) -> None:
|
|
22
|
+
"""Initialize RestClient."""
|
|
23
|
+
self.http_client: HTTPClient = HTTPClient()
|
|
24
|
+
self.state: ClientState = ClientState.NOT_CONNECTED
|
|
25
|
+
|
|
26
|
+
self.server: Optional[str] = server
|
|
27
|
+
self.api_url: Optional[str] = api_url # In case server uses not standard api-route
|
|
28
|
+
self.username: Optional[str] = username
|
|
29
|
+
self.__password: Optional[str] = password
|
|
30
|
+
self.proxies = proxies
|
|
31
|
+
|
|
32
|
+
self.http_client.update_params(**other)
|
|
33
|
+
|
|
34
|
+
def authenticate(self,
|
|
35
|
+
*,
|
|
36
|
+
server: Optional[str] = None,
|
|
37
|
+
api_url: Optional[str] = None,
|
|
38
|
+
username: Optional[str] = None,
|
|
39
|
+
password: Optional[str] = None,
|
|
40
|
+
**other
|
|
41
|
+
) -> None:
|
|
42
|
+
"""Authenticate in Hive."""
|
|
43
|
+
if not any([server, self.server]) and not any([api_url, self.api_url]):
|
|
44
|
+
raise exceptions.ServerNotFound()
|
|
45
|
+
|
|
46
|
+
if not any([username, self.username]) and not any([password, self.__password]):
|
|
47
|
+
raise exceptions.RestConnectionError('You must provide username and password.')
|
|
48
|
+
|
|
49
|
+
self.http_client.update_params(**other)
|
|
50
|
+
|
|
51
|
+
self.server = server or self.server
|
|
52
|
+
self.api_url = api_url or self.api_url or self.make_api_url_from(self.server)
|
|
53
|
+
|
|
54
|
+
username = username or self.username
|
|
55
|
+
password = password or self.__password
|
|
56
|
+
|
|
57
|
+
if '@' not in username:
|
|
58
|
+
username = f'{username}@ro.ot'
|
|
59
|
+
|
|
60
|
+
response = self.http_client.session.post(f"{self.api_url}/session", json={
|
|
61
|
+
'userLogin': username,
|
|
62
|
+
'userPassword': password,
|
|
63
|
+
})
|
|
64
|
+
|
|
65
|
+
if not (cookie := response.cookies.get('BSESSIONID')):
|
|
66
|
+
raise exceptions.RestConnectionError('Could not get authentication cookie. Something wrong with credentials'
|
|
67
|
+
' or server.')
|
|
68
|
+
|
|
69
|
+
self.http_client.add_headers({'Cookie': f'BSESSIONID={cookie}'})
|
|
70
|
+
self.state = ClientState.CONNECTED
|
|
71
|
+
|
|
72
|
+
@staticmethod
|
|
73
|
+
def make_api_url_from(server: str, port: Optional[int] = None) -> str:
|
|
74
|
+
"""Create api URL from server and port."""
|
|
75
|
+
try:
|
|
76
|
+
proto, hostname, *str_port = server.split(':')
|
|
77
|
+
except ValueError:
|
|
78
|
+
raise exceptions.IncorrectServerUrl('Protocol not defined in server URL.')
|
|
79
|
+
|
|
80
|
+
if not proto:
|
|
81
|
+
raise exceptions.IncorrectServerUrl('Protocol not defined in server URL.')
|
|
82
|
+
|
|
83
|
+
if str_port:
|
|
84
|
+
port = int(str_port[0])
|
|
85
|
+
server = f'{proto}://{hostname}'
|
|
86
|
+
|
|
87
|
+
if server.startswith('https') and not port:
|
|
88
|
+
port = 443
|
|
89
|
+
elif server.startswith('http') and not port:
|
|
90
|
+
port = 80
|
|
91
|
+
|
|
92
|
+
return f'{server.strip("/")}:{port}/api'
|
|
93
|
+
|
|
94
|
+
def get_project(self, project_id: str) -> Dict[str, Union[str, List, Dict]]:
|
|
95
|
+
"""Get project by id."""
|
|
96
|
+
return self.http_client.get(f'{self.api_url}/project/{project_id}')
|
|
97
|
+
|
|
98
|
+
def get_projects(self, **params) -> Dict[str, str]:
|
|
99
|
+
"""Get all projects."""
|
|
100
|
+
return self.http_client.post(f'{self.api_url}/project/filter', params=params)
|
|
101
|
+
|
|
102
|
+
def get_file(self, project_id: str, file_id: str) -> bytes:
|
|
103
|
+
"""Get file from Hive."""
|
|
104
|
+
return self.http_client.get(f'{self.api_url}/project/{project_id}/graph/file/{file_id}')
|
|
105
|
+
|
|
106
|
+
def get_issues(self, project_id: str, offset: int = 0, limit: int = 100) -> Dict[str, str]:
|
|
107
|
+
"""Get issues from Hive."""
|
|
108
|
+
response = self.http_client.post(
|
|
109
|
+
url=f'{self.api_url}/project/{project_id}/graph/issue_list?offset={offset}&limit={limit}',
|
|
110
|
+
json={})
|
|
111
|
+
return response
|
|
112
|
+
|
|
113
|
+
def update_project(self, project_id: Union[str, UUID], fields: Dict) -> Dict[str, str]:
|
|
114
|
+
"""Update project."""
|
|
115
|
+
project = self.get_project(project_id)
|
|
116
|
+
# We need to merge data from project and fields to safely update project
|
|
117
|
+
# We also need model to adapt data because of its specific serialized structure ¯\_(ツ)_/¯
|
|
118
|
+
merged_data = project.pop('data', {}) | fields.pop('data', {})
|
|
119
|
+
merged_project = project | fields | {'data': merged_data}
|
|
120
|
+
merged_project = Project(**merged_project | {'id': project_id}).dict()
|
|
121
|
+
merged_project['data'] = json.dumps(merged_project['data'])
|
|
122
|
+
files = {k: (None, v) for k, v in merged_project.items()}
|
|
123
|
+
return self.http_client.put(f'{self.api_url}/project/{project_id}', files=files)
|
|
124
|
+
|
|
125
|
+
def update_issue(self, project_id: Union[str, UUID], issue_id: Union[str, UUID], fields: Dict) -> Dict[str, str]:
|
|
126
|
+
"""Update issue."""
|
|
127
|
+
return self.http_client.patch(f'{self.api_url}/project/{project_id}/graph/issues/{issue_id}', json=fields)
|
|
128
|
+
|
|
129
|
+
def archive_project(self, project_id: Union[str, UUID]) -> Dict[str, str]:
|
|
130
|
+
"""Send to archive project."""
|
|
131
|
+
return self.http_client.put(f'{self.api_url}/project/{project_id}/archive', json={'archived': True})
|
|
132
|
+
|
|
133
|
+
def activate_project(self, project_id: Union[str, UUID]) -> Dict[str, str]:
|
|
134
|
+
"""Take from archive project."""
|
|
135
|
+
return self.http_client.put(f'{self.api_url}/project/{project_id}/archive', json={'archived': False})
|
|
136
|
+
|
|
137
|
+
@property
|
|
138
|
+
def proxies(self) -> MutableMapping[str, str]:
|
|
139
|
+
"""Get proxies."""
|
|
140
|
+
return self.http_client.proxies
|
|
141
|
+
|
|
142
|
+
@proxies.setter
|
|
143
|
+
def proxies(self, proxies: Dict) -> None:
|
|
144
|
+
"""Set proxies."""
|
|
145
|
+
self.http_client.proxies = proxies
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: hexway-hive-api
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Small wrapper for HexWay Hive API
|
|
5
|
+
Home-page: https://github.com/Cur1iosity/hexway-hive-api
|
|
6
|
+
Author: @Cur1iosity
|
|
7
|
+
Author-email: Cur1iosity@protonmail.com
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
10
|
+
Classifier: Operating System :: OS Independent
|
|
11
|
+
Requires-Python: >=3.12
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
License-File: LICENSE
|
|
14
|
+
Requires-Dist: requests>=2.31.0
|
|
15
|
+
Requires-Dist: pydantic>=2.4.0
|
|
16
|
+
Provides-Extra: dev
|
|
17
|
+
Requires-Dist: pytest; extra == "dev"
|
|
18
|
+
|
|
19
|
+
[](https://github.com/Cur1iosity/hivepy/actions/workflows/run-tests.yml)
|
|
20
|
+
[](https://pypi.org/project/hw-hivepy/)
|
|
21
|
+
[](https://hexway.io)
|
|
22
|
+
|
|
23
|
+
# HivePy
|
|
24
|
+
|
|
25
|
+
Unofficial flexible library for [HexWay Hive](https://hexway.io/hive/) Rest API.
|
|
26
|
+
|
|
27
|
+
#### Tested on HexWay Hive 0.62.8
|
|
28
|
+
|
|
29
|
+
## Installation
|
|
30
|
+
```bash
|
|
31
|
+
TBD
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Dependencies
|
|
35
|
+
|
|
36
|
+
- pydantic ~= 2.4
|
|
37
|
+
- requests ~= 2.31.0
|
|
38
|
+
|
|
39
|
+
## Usage
|
|
40
|
+
### Simple HiveClient
|
|
41
|
+
```python
|
|
42
|
+
def main() -> None:
|
|
43
|
+
... # TBD
|
|
44
|
+
|
|
45
|
+
if __name__ == "__main__":
|
|
46
|
+
main()
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
```
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
setup.py
|
|
4
|
+
hexway_hive_api/__init__.py
|
|
5
|
+
hexway_hive_api/hive_client.py
|
|
6
|
+
hexway_hive_api/rest_client.py
|
|
7
|
+
hexway_hive_api.egg-info/PKG-INFO
|
|
8
|
+
hexway_hive_api.egg-info/SOURCES.txt
|
|
9
|
+
hexway_hive_api.egg-info/dependency_links.txt
|
|
10
|
+
hexway_hive_api.egg-info/requires.txt
|
|
11
|
+
hexway_hive_api.egg-info/top_level.txt
|
|
12
|
+
hexway_hive_api/rest/__init__.py
|
|
13
|
+
hexway_hive_api/rest/enums.py
|
|
14
|
+
hexway_hive_api/rest/error_handler.py
|
|
15
|
+
hexway_hive_api/rest/exceptions.py
|
|
16
|
+
hexway_hive_api/rest/http_client/__init__.py
|
|
17
|
+
hexway_hive_api/rest/http_client/exceptions.py
|
|
18
|
+
hexway_hive_api/rest/http_client/http_client.py
|
|
19
|
+
hexway_hive_api/rest/models/__init__.py
|
|
20
|
+
hexway_hive_api/rest/models/issue.py
|
|
21
|
+
hexway_hive_api/rest/models/project.py
|
|
22
|
+
tests/test_issue.py
|
|
23
|
+
tests/test_project.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
hexway_hive_api
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
from setuptools import setup, find_packages
|
|
2
|
+
|
|
3
|
+
setup(
|
|
4
|
+
name='hexway-hive-api',
|
|
5
|
+
version='0.1.0',
|
|
6
|
+
description='Small wrapper for HexWay Hive API',
|
|
7
|
+
long_description=open('README.md').read(),
|
|
8
|
+
long_description_content_type='text/markdown',
|
|
9
|
+
include_package_data=True,
|
|
10
|
+
author='@Cur1iosity',
|
|
11
|
+
author_email='Cur1iosity@protonmail.com',
|
|
12
|
+
url='https://github.com/Cur1iosity/hexway-hive-api',
|
|
13
|
+
packages=find_packages(),
|
|
14
|
+
install_requires=['requests>=2.31.0', 'pydantic>=2.4.0'],
|
|
15
|
+
extras_require={
|
|
16
|
+
'dev': [
|
|
17
|
+
'pytest',
|
|
18
|
+
],
|
|
19
|
+
},
|
|
20
|
+
classifiers=[
|
|
21
|
+
'Programming Language :: Python :: 3',
|
|
22
|
+
'License :: OSI Approved :: MIT License',
|
|
23
|
+
'Operating System :: OS Independent',
|
|
24
|
+
],
|
|
25
|
+
python_requires='>=3.12',
|
|
26
|
+
)
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import uuid
|
|
2
|
+
from typing import Dict
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def test_rest_issue_deserealization(get_issue, issue_model) -> None:
|
|
6
|
+
"""Test deserialization hive issue json to issue model."""
|
|
7
|
+
project_id = uuid.uuid4()
|
|
8
|
+
issue_dict = get_issue | {'issue_id': project_id}
|
|
9
|
+
Issue = issue_model
|
|
10
|
+
issue = Issue(**issue_dict)
|
|
11
|
+
|
|
12
|
+
assert issue.id
|
|
13
|
+
assert issue.additional_fields is None or isinstance(issue.additional_fields, Dict)
|
|
14
|
+
assert issue.name == get_issue.get('name')
|
|
15
|
+
assert issue.project_id == project_id
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def test_rest_issue_serealization(get_issue, issue_model) -> None:
|
|
19
|
+
"""Test serialization issue model to hive issue json."""
|
|
20
|
+
project_id = uuid.uuid4()
|
|
21
|
+
issue_dict = get_issue | {'issue_id': project_id}
|
|
22
|
+
Issue = issue_model
|
|
23
|
+
issue = Issue(**issue_dict)
|
|
24
|
+
issue_dict = issue.model_dump(by_alias=True)
|
|
25
|
+
|
|
26
|
+
assert issue_dict.get('uuid') == get_issue.get('uuid')
|
|
27
|
+
assert issue_dict.get('weaknessType') == get_issue.get('weaknessType')
|
|
28
|
+
assert issue_dict.get('cvssScore') == get_issue.get('cvssScore')
|
|
29
|
+
assert issue_dict.get('cvssVector') == get_issue.get('cvssVector')
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import uuid
|
|
2
|
+
from typing import Dict
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def test_rest_project_deserealization(get_project, project_model) -> None:
|
|
6
|
+
"""Test deserialization hive project json to project model."""
|
|
7
|
+
project_id = uuid.uuid4()
|
|
8
|
+
project_dict = get_project | {'id': project_id}
|
|
9
|
+
Project = project_model
|
|
10
|
+
project = Project(**project_dict)
|
|
11
|
+
|
|
12
|
+
assert project.id
|
|
13
|
+
assert project.group_id
|
|
14
|
+
assert project.start_date
|
|
15
|
+
assert project.end_date
|
|
16
|
+
assert project.data is None or isinstance(project.data, Dict)
|
|
17
|
+
assert isinstance(project.start_date, str)
|
|
18
|
+
assert isinstance(project.end_date, str)
|
|
19
|
+
assert project.name == get_project.get('projectName')
|
|
20
|
+
assert project.start_date == get_project.get('projectStartDate')
|
|
21
|
+
assert project.end_date == get_project.get('projectEndDate')
|
|
22
|
+
assert project.id == project_id
|
|
23
|
+
assert project.group_id == get_project.get('group').get('id')
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def test_rest_project_serealization(get_project, project_model) -> None:
|
|
27
|
+
"""Test serialization project model to hive project json."""
|
|
28
|
+
project_id = uuid.uuid4()
|
|
29
|
+
project_dict = get_project | {'id': project_id}
|
|
30
|
+
Project = project_model
|
|
31
|
+
project = Project(**project_dict)
|
|
32
|
+
project_dict = project.dict()
|
|
33
|
+
|
|
34
|
+
assert not project_dict.get('id')
|
|
35
|
+
assert not project_dict.get('group_id')
|
|
36
|
+
assert project_dict.get('projectName') == get_project.get('projectName')
|
|
37
|
+
assert project_dict.get('projectStartDate') == get_project.get('projectStartDate')
|
|
38
|
+
assert project_dict.get('projectEndDate') == get_project.get('projectEndDate')
|