stackit-ufw 0.1.0__py3-none-any.whl

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.
@@ -0,0 +1,162 @@
1
+ # coding: utf-8
2
+
3
+ """
4
+ STACKIT Unified Firewall API
5
+
6
+ API for managing and controlling the STACKIT Unified Firewall.
7
+
8
+ The version of the OpenAPI document: 1.0.0
9
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
10
+
11
+ Do not edit the class manually.
12
+ """ # noqa: E501
13
+
14
+ import sys
15
+ from typing import Dict, List, Optional, TypedDict
16
+
17
+ from typing_extensions import NotRequired
18
+
19
+ import os
20
+
21
+ ServerVariablesT = Dict[str, str]
22
+
23
+
24
+ class HostSettingVariable(TypedDict):
25
+ description: str
26
+ default_value: str
27
+ enum_values: List[str]
28
+
29
+
30
+ class HostSetting(TypedDict):
31
+ url: str
32
+ description: str
33
+ variables: NotRequired[Dict[str, HostSettingVariable]]
34
+
35
+
36
+ class HostConfiguration:
37
+ def __init__(
38
+ self,
39
+ region=None,
40
+ server_index=None,
41
+ server_variables=None,
42
+ server_operation_index=None,
43
+ server_operation_variables=None,
44
+ ignore_operation_servers=False,
45
+ ) -> None:
46
+ print(
47
+ "WARNING: STACKIT will move to a new way of specifying regions, where the region is provided\n",
48
+ "as a function argument instead of being set in the client configuration.\n"
49
+ "Once all services have migrated, the methods to specify the region in the client configuration "
50
+ "will be removed.",
51
+ file=sys.stderr,
52
+ )
53
+ """Constructor
54
+ """
55
+ self._base_path = "https://ufw.api.stackit.cloud"
56
+ """Default Base url
57
+ """
58
+ self.server_index = 0 if server_index is None else server_index
59
+ self.server_operation_index = server_operation_index or {}
60
+ """Default server index
61
+ """
62
+ self.server_variables = server_variables or {}
63
+ if region:
64
+ self.server_variables["region"] = "{}.".format(region)
65
+ self.server_operation_variables = server_operation_variables or {}
66
+ """Default server variables
67
+ """
68
+ self.ignore_operation_servers = ignore_operation_servers
69
+ """Ignore operation servers
70
+ """
71
+
72
+ def get_host_settings(self) -> List[HostSetting]:
73
+ """Gets an array of host settings
74
+
75
+ :return: An array of host settings
76
+ """
77
+ return [
78
+ {
79
+ "url": "https://ufw.api.stackit.cloud",
80
+ "description": "No description provided",
81
+ "variables": {
82
+ "region": {
83
+ "description": "No description provided",
84
+ "default_value": "global",
85
+ }
86
+ },
87
+ }
88
+ ]
89
+
90
+ def get_host_from_settings(
91
+ self,
92
+ index: Optional[int],
93
+ variables: Optional[ServerVariablesT] = None,
94
+ servers: Optional[List[HostSetting]] = None,
95
+ ) -> str:
96
+ """Gets host URL based on the index and variables
97
+ :param index: array index of the host settings
98
+ :param variables: hash of variable and the corresponding value
99
+ :param servers: an array of host settings or None
100
+ :error: if a region is given for a global url
101
+ :return: URL based on host settings
102
+ """
103
+ if index is None:
104
+ return self._base_path
105
+
106
+ variables = {} if variables is None else variables
107
+ servers = self.get_host_settings() if servers is None else servers
108
+
109
+ try:
110
+ server = servers[index]
111
+ except IndexError:
112
+ raise ValueError(
113
+ "Invalid index {0} when selecting the host settings. "
114
+ "Must be less than {1}".format(index, len(servers))
115
+ )
116
+
117
+ url = server["url"]
118
+
119
+ # check if environment variable was provided for region
120
+ # if nothing was set this is None
121
+ region_env = os.environ.get("STACKIT_REGION")
122
+
123
+ # go through variables and replace placeholders
124
+ for variable_name, variable in server.get("variables", {}).items():
125
+ # If a region is provided by the user for a global url
126
+ # return an error (except for providing via environment variable).
127
+ # The region is provided as a function argument instead of being set in the client configuration.
128
+ if (
129
+ variable_name == "region"
130
+ and (variable["default_value"] == "global" or variable["default_value"] == "")
131
+ and region_env is None
132
+ and variables.get(variable_name) is not None
133
+ ):
134
+ raise ValueError(
135
+ "this API does not support setting a region in the client configuration, "
136
+ "please check if the region can be specified as a function parameter"
137
+ )
138
+ used_value = variables.get(variable_name, variable["default_value"])
139
+
140
+ if "enum_values" in variable and used_value not in variable["enum_values"]:
141
+ given_value = variables[variable_name].replace(".", "")
142
+ valid_values = [v.replace(".", "") for v in variable["enum_values"]]
143
+ raise ValueError(
144
+ "The variable `{0}` in the host URL has invalid value '{1}'. Must be '{2}'.".format(
145
+ variable_name, given_value, valid_values
146
+ )
147
+ )
148
+
149
+ url = url.replace("{" + variable_name + "}", used_value)
150
+
151
+ return url
152
+
153
+ @property
154
+ def host(self) -> str:
155
+ """Return generated host."""
156
+ return self.get_host_from_settings(self.server_index, variables=self.server_variables)
157
+
158
+ @host.setter
159
+ def host(self, value: str) -> None:
160
+ """Fix base path."""
161
+ self._base_path = value
162
+ self.server_index = None
@@ -0,0 +1,217 @@
1
+ # coding: utf-8
2
+
3
+ """
4
+ STACKIT Unified Firewall API
5
+
6
+ API for managing and controlling the STACKIT Unified Firewall.
7
+
8
+ The version of the OpenAPI document: 1.0.0
9
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
10
+
11
+ Do not edit the class manually.
12
+ """ # noqa: E501
13
+
14
+ from typing import Any, Optional
15
+
16
+ from typing_extensions import Self
17
+
18
+
19
+ class OpenApiException(Exception):
20
+ """The base exception class for all OpenAPIExceptions"""
21
+
22
+
23
+ class ApiTypeError(OpenApiException, TypeError):
24
+ def __init__(self, msg, path_to_item=None, valid_classes=None, key_type=None) -> None:
25
+ """Raises an exception for TypeErrors
26
+
27
+ Args:
28
+ msg (str): the exception message
29
+
30
+ Keyword Args:
31
+ path_to_item (list): a list of keys an indices to get to the
32
+ current_item
33
+ None if unset
34
+ valid_classes (tuple): the primitive classes that current item
35
+ should be an instance of
36
+ None if unset
37
+ key_type (bool): False if our value is a value in a dict
38
+ True if it is a key in a dict
39
+ False if our item is an item in a list
40
+ None if unset
41
+ """
42
+ self.path_to_item = path_to_item
43
+ self.valid_classes = valid_classes
44
+ self.key_type = key_type
45
+ full_msg = msg
46
+ if path_to_item:
47
+ full_msg = "{0} at {1}".format(msg, render_path(path_to_item))
48
+ super(ApiTypeError, self).__init__(full_msg)
49
+
50
+
51
+ class ApiValueError(OpenApiException, ValueError):
52
+ def __init__(self, msg, path_to_item=None) -> None:
53
+ """
54
+ Args:
55
+ msg (str): the exception message
56
+
57
+ Keyword Args:
58
+ path_to_item (list) the path to the exception in the
59
+ received_data dict. None if unset
60
+ """
61
+
62
+ self.path_to_item = path_to_item
63
+ full_msg = msg
64
+ if path_to_item:
65
+ full_msg = "{0} at {1}".format(msg, render_path(path_to_item))
66
+ super(ApiValueError, self).__init__(full_msg)
67
+
68
+
69
+ class ApiAttributeError(OpenApiException, AttributeError):
70
+ def __init__(self, msg, path_to_item=None) -> None:
71
+ """
72
+ Raised when an attribute reference or assignment fails.
73
+
74
+ Args:
75
+ msg (str): the exception message
76
+
77
+ Keyword Args:
78
+ path_to_item (None/list) the path to the exception in the
79
+ received_data dict
80
+ """
81
+ self.path_to_item = path_to_item
82
+ full_msg = msg
83
+ if path_to_item:
84
+ full_msg = "{0} at {1}".format(msg, render_path(path_to_item))
85
+ super(ApiAttributeError, self).__init__(full_msg)
86
+
87
+
88
+ class ApiKeyError(OpenApiException, KeyError):
89
+ def __init__(self, msg, path_to_item=None) -> None:
90
+ """
91
+ Args:
92
+ msg (str): the exception message
93
+
94
+ Keyword Args:
95
+ path_to_item (None/list) the path to the exception in the
96
+ received_data dict
97
+ """
98
+ self.path_to_item = path_to_item
99
+ full_msg = msg
100
+ if path_to_item:
101
+ full_msg = "{0} at {1}".format(msg, render_path(path_to_item))
102
+ super(ApiKeyError, self).__init__(full_msg)
103
+
104
+
105
+ class ApiException(OpenApiException):
106
+
107
+ def __init__(
108
+ self,
109
+ status=None,
110
+ reason=None,
111
+ http_resp=None,
112
+ *,
113
+ body: Optional[str] = None,
114
+ data: Optional[Any] = None,
115
+ ) -> None:
116
+ self.status = status
117
+ self.reason = reason
118
+ self.body = body
119
+ self.data = data
120
+ self.headers = None
121
+
122
+ if http_resp:
123
+ if self.status is None:
124
+ self.status = http_resp.status
125
+ if self.reason is None:
126
+ self.reason = http_resp.reason
127
+ if self.body is None:
128
+ try:
129
+ self.body = http_resp.data.decode("utf-8")
130
+ except Exception: # noqa: S110
131
+ pass
132
+ self.headers = http_resp.headers
133
+
134
+ @classmethod
135
+ def from_response(
136
+ cls,
137
+ *,
138
+ http_resp,
139
+ body: Optional[str],
140
+ data: Optional[Any],
141
+ ) -> Self:
142
+ if http_resp.status == 400:
143
+ raise BadRequestException(http_resp=http_resp, body=body, data=data)
144
+
145
+ if http_resp.status == 401:
146
+ raise UnauthorizedException(http_resp=http_resp, body=body, data=data)
147
+
148
+ if http_resp.status == 403:
149
+ raise ForbiddenException(http_resp=http_resp, body=body, data=data)
150
+
151
+ if http_resp.status == 404:
152
+ raise NotFoundException(http_resp=http_resp, body=body, data=data)
153
+
154
+ # Added new conditions for 409 and 422
155
+ if http_resp.status == 409:
156
+ raise ConflictException(http_resp=http_resp, body=body, data=data)
157
+
158
+ if http_resp.status == 422:
159
+ raise UnprocessableEntityException(http_resp=http_resp, body=body, data=data)
160
+
161
+ if 500 <= http_resp.status <= 599:
162
+ raise ServiceException(http_resp=http_resp, body=body, data=data)
163
+ raise ApiException(http_resp=http_resp, body=body, data=data)
164
+
165
+ def __str__(self):
166
+ """Custom error messages for exception"""
167
+ error_message = "({0})\n" "Reason: {1}\n".format(self.status, self.reason)
168
+ if self.headers:
169
+ error_message += "HTTP response headers: {0}\n".format(self.headers)
170
+
171
+ if self.data or self.body:
172
+ error_message += "HTTP response body: {0}\n".format(self.data or self.body)
173
+
174
+ return error_message
175
+
176
+
177
+ class BadRequestException(ApiException):
178
+ pass
179
+
180
+
181
+ class NotFoundException(ApiException):
182
+ pass
183
+
184
+
185
+ class UnauthorizedException(ApiException):
186
+ pass
187
+
188
+
189
+ class ForbiddenException(ApiException):
190
+ pass
191
+
192
+
193
+ class ServiceException(ApiException):
194
+ pass
195
+
196
+
197
+ class ConflictException(ApiException):
198
+ """Exception for HTTP 409 Conflict."""
199
+
200
+ pass
201
+
202
+
203
+ class UnprocessableEntityException(ApiException):
204
+ """Exception for HTTP 422 Unprocessable Entity."""
205
+
206
+ pass
207
+
208
+
209
+ def render_path(path_to_item):
210
+ """Returns a string representation of a path"""
211
+ result = ""
212
+ for pth in path_to_item:
213
+ if isinstance(pth, int):
214
+ result += "[{0}]".format(pth)
215
+ else:
216
+ result += "['{0}']".format(pth)
217
+ return result
@@ -0,0 +1,29 @@
1
+ # coding: utf-8
2
+
3
+ # flake8: noqa
4
+ """
5
+ STACKIT Unified Firewall API
6
+
7
+ API for managing and controlling the STACKIT Unified Firewall.
8
+
9
+ The version of the OpenAPI document: 1.0.0
10
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
11
+
12
+ Do not edit the class manually.
13
+ """ # noqa: E501
14
+
15
+ # import models into model package
16
+ from stackit.ufw.models.container_response import ContainerResponse
17
+ from stackit.ufw.models.create_rule_payload import CreateRulePayload
18
+ from stackit.ufw.models.create_rule_response import CreateRuleResponse
19
+ from stackit.ufw.models.delete_rule_response import DeleteRuleResponse
20
+ from stackit.ufw.models.error_response import ErrorResponse
21
+ from stackit.ufw.models.list_containers_response import ListContainersResponse
22
+ from stackit.ufw.models.list_rules_response import ListRulesResponse
23
+ from stackit.ufw.models.provider_options_product_meta import ProviderOptionsProductMeta
24
+ from stackit.ufw.models.provider_options_response import ProviderOptionsResponse
25
+ from stackit.ufw.models.rule_response import RuleResponse
26
+ from stackit.ufw.models.update_rule_payload import UpdateRulePayload
27
+ from stackit.ufw.models.update_rule_response import UpdateRuleResponse
28
+ from stackit.ufw.models.update_ufw_request import UpdateUfwRequest
29
+ from stackit.ufw.models.version_response import VersionResponse
@@ -0,0 +1,84 @@
1
+ # coding: utf-8
2
+
3
+ """
4
+ STACKIT Unified Firewall API
5
+
6
+ API for managing and controlling the STACKIT Unified Firewall.
7
+
8
+ The version of the OpenAPI document: 1.0.0
9
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
10
+
11
+ Do not edit the class manually.
12
+ """ # noqa: E501
13
+
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import pprint
18
+ from typing import Any, ClassVar, Dict, List, Optional, Set
19
+
20
+ from pydantic import BaseModel, ConfigDict, StrictStr
21
+ from pydantic_core import to_jsonable_python
22
+ from typing_extensions import Self
23
+
24
+
25
+ class ContainerResponse(BaseModel):
26
+ """
27
+ ContainerResponse
28
+ """ # noqa: E501
29
+
30
+ id: StrictStr
31
+ name: StrictStr
32
+ type: StrictStr
33
+ __properties: ClassVar[List[str]] = ["id", "name", "type"]
34
+
35
+ model_config = ConfigDict(
36
+ validate_by_name=True,
37
+ validate_by_alias=True,
38
+ validate_assignment=True,
39
+ protected_namespaces=(),
40
+ )
41
+
42
+ def to_str(self) -> str:
43
+ """Returns the string representation of the model using alias"""
44
+ return pprint.pformat(self.model_dump(by_alias=True))
45
+
46
+ def to_json(self) -> str:
47
+ """Returns the JSON representation of the model using alias"""
48
+ return json.dumps(to_jsonable_python(self.to_dict()))
49
+
50
+ @classmethod
51
+ def from_json(cls, json_str: str) -> Optional[Self]:
52
+ """Create an instance of ContainerResponse from a JSON string"""
53
+ return cls.from_dict(json.loads(json_str))
54
+
55
+ def to_dict(self) -> Dict[str, Any]:
56
+ """Return the dictionary representation of the model using alias.
57
+
58
+ This has the following differences from calling pydantic's
59
+ `self.model_dump(by_alias=True)`:
60
+
61
+ * `None` is only added to the output dict for nullable fields that
62
+ were set at model initialization. Other fields with value `None`
63
+ are ignored.
64
+ """
65
+ excluded_fields: Set[str] = set([])
66
+
67
+ _dict = self.model_dump(
68
+ by_alias=True,
69
+ exclude=excluded_fields,
70
+ exclude_none=True,
71
+ )
72
+ return _dict
73
+
74
+ @classmethod
75
+ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
76
+ """Create an instance of ContainerResponse from a dict"""
77
+ if obj is None:
78
+ return None
79
+
80
+ if not isinstance(obj, dict):
81
+ return cls.model_validate(obj)
82
+
83
+ _obj = cls.model_validate({"id": obj.get("id"), "name": obj.get("name"), "type": obj.get("type")})
84
+ return _obj
@@ -0,0 +1,128 @@
1
+ # coding: utf-8
2
+
3
+ """
4
+ STACKIT Unified Firewall API
5
+
6
+ API for managing and controlling the STACKIT Unified Firewall.
7
+
8
+ The version of the OpenAPI document: 1.0.0
9
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
10
+
11
+ Do not edit the class manually.
12
+ """ # noqa: E501
13
+
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import pprint
18
+ from typing import Any, ClassVar, Dict, List, Optional, Set
19
+
20
+ from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr
21
+ from pydantic_core import to_jsonable_python
22
+ from typing_extensions import Self
23
+
24
+
25
+ class CreateRulePayload(BaseModel):
26
+ """
27
+ The request body for creating a new security rule.
28
+ """ # noqa: E501
29
+
30
+ description: Optional[StrictStr] = Field(default=None, description="A description for the rule.")
31
+ direction: Optional[StrictStr] = Field(
32
+ default=None, description='The direction of the traffic, typically "ingress" or "egress".'
33
+ )
34
+ ether_type: Optional[StrictStr] = Field(
35
+ default=None, description="Specifies the bound of the rule.", alias="etherType"
36
+ )
37
+ instance_id: StrictStr = Field(description="The ID of the product, similar to a project ID.", alias="instanceId")
38
+ offset: Optional[StrictInt] = Field(default=None, description="Position in the list.")
39
+ port_range: Optional[StrictStr] = Field(
40
+ default=None, description="The Port range to which the rule applies.", alias="portRange"
41
+ )
42
+ product: StrictStr = Field(description="The source service (e.g., Load Balancer, Redis).")
43
+ protocol: Optional[StrictStr] = Field(
44
+ default=None, description='The network protocol (e.g., "TCP", "UDP", "ICMP").'
45
+ )
46
+ security_group_id: Optional[StrictStr] = Field(
47
+ default=None, description="The ID of the Group.", alias="securityGroupId"
48
+ )
49
+ source_ip: StrictStr = Field(description="The IP (CIDR) to which the rule applies.", alias="sourceIP")
50
+ type: StrictStr = Field(description='The type of the rule (e.g., "ACL", "PublicIP", "SecurityRule").')
51
+ __properties: ClassVar[List[str]] = [
52
+ "description",
53
+ "direction",
54
+ "etherType",
55
+ "instanceId",
56
+ "offset",
57
+ "portRange",
58
+ "product",
59
+ "protocol",
60
+ "securityGroupId",
61
+ "sourceIP",
62
+ "type",
63
+ ]
64
+
65
+ model_config = ConfigDict(
66
+ validate_by_name=True,
67
+ validate_by_alias=True,
68
+ validate_assignment=True,
69
+ protected_namespaces=(),
70
+ )
71
+
72
+ def to_str(self) -> str:
73
+ """Returns the string representation of the model using alias"""
74
+ return pprint.pformat(self.model_dump(by_alias=True))
75
+
76
+ def to_json(self) -> str:
77
+ """Returns the JSON representation of the model using alias"""
78
+ return json.dumps(to_jsonable_python(self.to_dict()))
79
+
80
+ @classmethod
81
+ def from_json(cls, json_str: str) -> Optional[Self]:
82
+ """Create an instance of CreateRulePayload from a JSON string"""
83
+ return cls.from_dict(json.loads(json_str))
84
+
85
+ def to_dict(self) -> Dict[str, Any]:
86
+ """Return the dictionary representation of the model using alias.
87
+
88
+ This has the following differences from calling pydantic's
89
+ `self.model_dump(by_alias=True)`:
90
+
91
+ * `None` is only added to the output dict for nullable fields that
92
+ were set at model initialization. Other fields with value `None`
93
+ are ignored.
94
+ """
95
+ excluded_fields: Set[str] = set([])
96
+
97
+ _dict = self.model_dump(
98
+ by_alias=True,
99
+ exclude=excluded_fields,
100
+ exclude_none=True,
101
+ )
102
+ return _dict
103
+
104
+ @classmethod
105
+ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
106
+ """Create an instance of CreateRulePayload from a dict"""
107
+ if obj is None:
108
+ return None
109
+
110
+ if not isinstance(obj, dict):
111
+ return cls.model_validate(obj)
112
+
113
+ _obj = cls.model_validate(
114
+ {
115
+ "description": obj.get("description"),
116
+ "direction": obj.get("direction"),
117
+ "etherType": obj.get("etherType"),
118
+ "instanceId": obj.get("instanceId"),
119
+ "offset": obj.get("offset"),
120
+ "portRange": obj.get("portRange"),
121
+ "product": obj.get("product"),
122
+ "protocol": obj.get("protocol"),
123
+ "securityGroupId": obj.get("securityGroupId"),
124
+ "sourceIP": obj.get("sourceIP"),
125
+ "type": obj.get("type"),
126
+ }
127
+ )
128
+ return _obj