securespace 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.
securespace/__init__.py
ADDED
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
"""
|
|
2
|
+
securespace — SecureSpace Gateway client for Python (Module G3).
|
|
3
|
+
|
|
4
|
+
A thin client for the explicitly-addressed enforcement proxy (docs/12). It
|
|
5
|
+
deliberately does almost nothing: the Gateway is the security boundary, and a
|
|
6
|
+
client library that "helpfully" retried, followed redirects, or re-routed on
|
|
7
|
+
error would put a second, unaudited policy in front of it.
|
|
8
|
+
|
|
9
|
+
WHAT THIS SDK DELIBERATELY DOES NOT DO
|
|
10
|
+
|
|
11
|
+
- It does NOT follow redirects. The Gateway relays 3xx rather than chasing it
|
|
12
|
+
(a redirect target is never SSRF-validated), so a client that followed one
|
|
13
|
+
would bypass every check the Gateway performed.
|
|
14
|
+
- It does NOT retry. A 403 is a decision, and retrying a denied request is
|
|
15
|
+
both pointless and a way to turn a block into a nuisance.
|
|
16
|
+
- It does NOT resolve upstreams itself. You pass a NAME the tenant
|
|
17
|
+
registered. There is no code path here that accepts a raw URL, because the
|
|
18
|
+
reachable set is tenant configuration, not request input.
|
|
19
|
+
- It does NOT swallow the Gateway's error body. A blocked request carries a
|
|
20
|
+
machine-readable code; hiding it would make enforcement unexplainable to
|
|
21
|
+
the developer whose agent was blocked.
|
|
22
|
+
|
|
23
|
+
Requires only the standard library (urllib). The Gateway protocol is one HTTP
|
|
24
|
+
request; a dependency would be a cost with no benefit.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
from __future__ import annotations
|
|
28
|
+
|
|
29
|
+
import json
|
|
30
|
+
import re
|
|
31
|
+
import urllib.error
|
|
32
|
+
import urllib.parse
|
|
33
|
+
import urllib.request
|
|
34
|
+
from dataclasses import dataclass, field
|
|
35
|
+
from typing import Any, Mapping
|
|
36
|
+
|
|
37
|
+
__version__ = "0.1.0"
|
|
38
|
+
|
|
39
|
+
HEADER_API_KEY = "x-securespace-api-key"
|
|
40
|
+
"""
|
|
41
|
+
Optional. The agent's own claim about what it is doing.
|
|
42
|
+
|
|
43
|
+
This can only RAISE the classified verb, never lower it — the classifier
|
|
44
|
+
escalates independently and treats this as one more signal. Sending ``read``
|
|
45
|
+
for something the Gateway classifies as ``export`` does not downgrade it.
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
HEADER_DECLARED_VERB = "x-securespace-verb"
|
|
49
|
+
|
|
50
|
+
#: The grammar a registered upstream name uses, mirroring the CHECK constraint
|
|
51
|
+
#: on the ``upstreams`` table (migration 0009).
|
|
52
|
+
#:
|
|
53
|
+
#: Deliberately the same rule the database enforces, rather than a looser local
|
|
54
|
+
#: approximation. If the two diverge, this client would accept names the
|
|
55
|
+
#: database refuses, and the failure would surface as a confusing 404.
|
|
56
|
+
#:
|
|
57
|
+
#: Note that dots ARE legal, so a bare hostname-looking string is not rejected
|
|
58
|
+
#: here — it is a legal name that happens to be unregistered.
|
|
59
|
+
UPSTREAM_NAME_RE = re.compile(r"^[a-z0-9][a-z0-9._-]{0,62}$")
|
|
60
|
+
|
|
61
|
+
DEFAULT_TIMEOUT_S = 30.0
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@dataclass
|
|
65
|
+
class Decision:
|
|
66
|
+
"""The Gateway's own decision metadata, parsed off the response."""
|
|
67
|
+
|
|
68
|
+
action_id: str | None = None
|
|
69
|
+
decision_id: str | None = None
|
|
70
|
+
#: The verb the Gateway CLASSIFIED, which is not necessarily what was sent.
|
|
71
|
+
action: str | None = None
|
|
72
|
+
#: False when the Gateway refused before contacting the upstream.
|
|
73
|
+
#:
|
|
74
|
+
#: Surfaced explicitly because a blocked request and an upstream 500 look
|
|
75
|
+
#: similar otherwise, and only one of them is an enforcement outcome.
|
|
76
|
+
upstream_called: bool = True
|
|
77
|
+
#: True when the Gateway relayed a 3xx rather than following it.
|
|
78
|
+
redirect_not_followed: bool = False
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
@dataclass
|
|
82
|
+
class Response:
|
|
83
|
+
"""A Gateway response, parsed. Never raised for an enforcement outcome."""
|
|
84
|
+
|
|
85
|
+
status: int
|
|
86
|
+
headers: dict[str, str] = field(default_factory=dict)
|
|
87
|
+
body: Any = None
|
|
88
|
+
decision: Decision = field(default_factory=Decision)
|
|
89
|
+
#: True when the Gateway refused the request itself.
|
|
90
|
+
blocked: bool = False
|
|
91
|
+
#: The Gateway's machine-readable error code, when there is one.
|
|
92
|
+
error_code: str | None = None
|
|
93
|
+
error_message: str | None = None
|
|
94
|
+
#: Set only on ``upstream_blocked``: which control refused the destination.
|
|
95
|
+
#: A stable code for an operator. The resolved IP is never disclosed.
|
|
96
|
+
block_reason: str | None = None
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class SecureSpaceError(Exception):
|
|
100
|
+
"""Raised by :meth:`SecureSpaceClient.request_or_raise` on a block."""
|
|
101
|
+
|
|
102
|
+
def __init__(self, response: Response) -> None:
|
|
103
|
+
self.response = response
|
|
104
|
+
super().__init__(
|
|
105
|
+
f"SecureSpace Gateway {response.status} "
|
|
106
|
+
f"{response.error_code or 'error'}: "
|
|
107
|
+
f"{response.error_message or 'no message'}"
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _normalize_path(path: str) -> str:
|
|
112
|
+
"""Exactly one leading slash, no trailing one."""
|
|
113
|
+
trimmed = (path or "").strip()
|
|
114
|
+
if trimmed in ("", "/"):
|
|
115
|
+
return "/"
|
|
116
|
+
stripped = trimmed.rstrip("/")
|
|
117
|
+
return stripped if stripped.startswith("/") else f"/{stripped}"
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _build_query(query: Mapping[str, Any] | None) -> str:
|
|
121
|
+
if not query:
|
|
122
|
+
return ""
|
|
123
|
+
pairs = [(k, str(v)) for k, v in query.items() if v is not None]
|
|
124
|
+
if not pairs:
|
|
125
|
+
return ""
|
|
126
|
+
return "?" + urllib.parse.urlencode(pairs)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
class _NoRedirect(urllib.request.HTTPRedirectHandler):
|
|
130
|
+
"""Turn redirects into results instead of chasing them.
|
|
131
|
+
|
|
132
|
+
Without this, urllib would follow a 302 to a location the Gateway never
|
|
133
|
+
validated. The Gateway returns the 3xx precisely so the caller can see it
|
|
134
|
+
and decide; this handler is what makes that true in Python too.
|
|
135
|
+
"""
|
|
136
|
+
|
|
137
|
+
def redirect_request(self, req, fp, code, msg, headers, newurl): # type: ignore[no-untyped-def]
|
|
138
|
+
return None
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
class SecureSpaceClient:
|
|
142
|
+
"""Client for the SecureSpace Gateway.
|
|
143
|
+
|
|
144
|
+
Example:
|
|
145
|
+
>>> client = SecureSpaceClient("https://gateway.securespace.club", "ss_...")
|
|
146
|
+
>>> res = client.get("crm", "/contacts")
|
|
147
|
+
>>> if res.blocked:
|
|
148
|
+
... print("blocked:", res.error_code, res.decision.action)
|
|
149
|
+
"""
|
|
150
|
+
|
|
151
|
+
def __init__(
|
|
152
|
+
self,
|
|
153
|
+
base_url: str,
|
|
154
|
+
api_key: str,
|
|
155
|
+
*,
|
|
156
|
+
timeout_s: float = DEFAULT_TIMEOUT_S,
|
|
157
|
+
) -> None:
|
|
158
|
+
# Both validated here rather than at first request. A client that
|
|
159
|
+
# discovered a missing key at request time would surface a confusing 401
|
|
160
|
+
# from the Gateway instead of an obvious local error.
|
|
161
|
+
if not base_url or not base_url.strip():
|
|
162
|
+
raise ValueError("base_url is required")
|
|
163
|
+
if not api_key or not api_key.strip():
|
|
164
|
+
raise ValueError("api_key is required")
|
|
165
|
+
|
|
166
|
+
self._base_url = base_url.rstrip("/")
|
|
167
|
+
self._api_key = api_key
|
|
168
|
+
self._timeout_s = timeout_s
|
|
169
|
+
self._opener = urllib.request.build_opener(_NoRedirect)
|
|
170
|
+
|
|
171
|
+
def request(
|
|
172
|
+
self,
|
|
173
|
+
upstream: str,
|
|
174
|
+
method: str = "GET",
|
|
175
|
+
path: str = "/",
|
|
176
|
+
*,
|
|
177
|
+
query: Mapping[str, Any] | None = None,
|
|
178
|
+
body: Any = None,
|
|
179
|
+
headers: Mapping[str, str] | None = None,
|
|
180
|
+
declared_verb: str | None = None,
|
|
181
|
+
) -> Response:
|
|
182
|
+
"""Forward a request through the Gateway to a registered upstream.
|
|
183
|
+
|
|
184
|
+
``upstream`` is a NAME the tenant registered, never a URL. There is no
|
|
185
|
+
parameter accepting one, on purpose.
|
|
186
|
+
"""
|
|
187
|
+
if not upstream or not upstream.strip():
|
|
188
|
+
raise ValueError("upstream is required (a registered upstream name, not a URL)")
|
|
189
|
+
if not UPSTREAM_NAME_RE.match(upstream):
|
|
190
|
+
# Caught loudly at the call site. Catches a scheme, a path, a query,
|
|
191
|
+
# a fragment, whitespace, or an injection attempt — things that could
|
|
192
|
+
# not be a name at all. A bare hostname-shaped string is NOT caught,
|
|
193
|
+
# because dots are legal in a registered name.
|
|
194
|
+
raise ValueError(
|
|
195
|
+
f"upstream must be a registered NAME, not a URL or path (got: {upstream}). "
|
|
196
|
+
f"Names match {UPSTREAM_NAME_RE.pattern}. "
|
|
197
|
+
"Register the destination in SecureSpace, then address it by name."
|
|
198
|
+
)
|
|
199
|
+
|
|
200
|
+
url = (
|
|
201
|
+
f"{self._base_url}/v1/proxy/{urllib.parse.quote(upstream, safe='')}"
|
|
202
|
+
f"{_normalize_path(path)}{_build_query(query)}"
|
|
203
|
+
)
|
|
204
|
+
|
|
205
|
+
sent_headers = {HEADER_API_KEY: self._api_key}
|
|
206
|
+
if headers:
|
|
207
|
+
sent_headers.update(headers)
|
|
208
|
+
|
|
209
|
+
payload: bytes | None = None
|
|
210
|
+
if body is not None:
|
|
211
|
+
if isinstance(body, (bytes, bytearray)):
|
|
212
|
+
payload = bytes(body)
|
|
213
|
+
elif isinstance(body, str):
|
|
214
|
+
payload = body.encode("utf-8")
|
|
215
|
+
else:
|
|
216
|
+
payload = json.dumps(body).encode("utf-8")
|
|
217
|
+
sent_headers.setdefault("content-type", "application/json")
|
|
218
|
+
|
|
219
|
+
if declared_verb:
|
|
220
|
+
sent_headers[HEADER_DECLARED_VERB] = declared_verb
|
|
221
|
+
|
|
222
|
+
req = urllib.request.Request(
|
|
223
|
+
url, data=payload, headers=sent_headers, method=method.upper()
|
|
224
|
+
)
|
|
225
|
+
|
|
226
|
+
try:
|
|
227
|
+
with self._opener.open(req, timeout=self._timeout_s) as raw:
|
|
228
|
+
return self._parse(raw.status, dict(raw.headers), raw.read())
|
|
229
|
+
except urllib.error.HTTPError as err:
|
|
230
|
+
# A 4xx/5xx is a RESULT, not a transport failure. urllib raises for
|
|
231
|
+
# it; the Gateway's contract says these come back as values, so they
|
|
232
|
+
# are converted here rather than allowed to escape as exceptions.
|
|
233
|
+
return self._parse(err.code, dict(err.headers or {}), err.read())
|
|
234
|
+
|
|
235
|
+
def get(self, upstream: str, path: str = "/", **kwargs: Any) -> Response:
|
|
236
|
+
return self.request(upstream, "GET", path, **kwargs)
|
|
237
|
+
|
|
238
|
+
def post(self, upstream: str, path: str = "/", body: Any = None, **kwargs: Any) -> Response:
|
|
239
|
+
return self.request(upstream, "POST", path, body=body, **kwargs)
|
|
240
|
+
|
|
241
|
+
def request_or_raise(
|
|
242
|
+
self, upstream: str, method: str = "GET", path: str = "/", **kwargs: Any
|
|
243
|
+
) -> Response:
|
|
244
|
+
"""As :meth:`request`, but raises :class:`SecureSpaceError` on a block."""
|
|
245
|
+
res = self.request(upstream, method, path, **kwargs)
|
|
246
|
+
if res.blocked:
|
|
247
|
+
raise SecureSpaceError(res)
|
|
248
|
+
return res
|
|
249
|
+
|
|
250
|
+
def _parse(self, status: int, headers: dict[str, str], raw: bytes) -> Response:
|
|
251
|
+
lowered = {k.lower(): v for k, v in headers.items()}
|
|
252
|
+
text = raw.decode("utf-8", errors="replace") if raw else ""
|
|
253
|
+
|
|
254
|
+
body: Any = text
|
|
255
|
+
error_code: str | None = None
|
|
256
|
+
error_message: str | None = None
|
|
257
|
+
block_reason: str | None = None
|
|
258
|
+
|
|
259
|
+
if text:
|
|
260
|
+
try:
|
|
261
|
+
parsed = json.loads(text)
|
|
262
|
+
except json.JSONDecodeError:
|
|
263
|
+
# Not JSON. Kept as text — an HTML error page from a
|
|
264
|
+
# misconfigured upstream must not become a parse exception.
|
|
265
|
+
parsed = None
|
|
266
|
+
if isinstance(parsed, dict):
|
|
267
|
+
body = parsed
|
|
268
|
+
err = parsed.get("error")
|
|
269
|
+
if isinstance(err, dict):
|
|
270
|
+
error_code = err.get("code")
|
|
271
|
+
error_message = err.get("message")
|
|
272
|
+
reason = parsed.get("reason")
|
|
273
|
+
if isinstance(reason, str):
|
|
274
|
+
block_reason = reason
|
|
275
|
+
|
|
276
|
+
return Response(
|
|
277
|
+
status=status,
|
|
278
|
+
headers=lowered,
|
|
279
|
+
body=body,
|
|
280
|
+
decision=Decision(
|
|
281
|
+
action_id=lowered.get("x-securespace-action-id"),
|
|
282
|
+
decision_id=lowered.get("x-securespace-decision-id"),
|
|
283
|
+
action=lowered.get("x-securespace-action"),
|
|
284
|
+
upstream_called=lowered.get("x-securespace-upstream-called") != "false",
|
|
285
|
+
redirect_not_followed=lowered.get("x-securespace-redirect-not-followed") == "true",
|
|
286
|
+
),
|
|
287
|
+
blocked=error_code is not None,
|
|
288
|
+
error_code=error_code,
|
|
289
|
+
error_message=error_message,
|
|
290
|
+
block_reason=block_reason,
|
|
291
|
+
)
|
|
292
|
+
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: securespace
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Send your Python agent's calls through the SecureSpace Gateway, and handle its decisions.
|
|
5
|
+
Project-URL: Homepage, https://securespace.club
|
|
6
|
+
License: Copyright (c) 2026 SecureSpace. All rights reserved.
|
|
7
|
+
|
|
8
|
+
This software is provided to connect to the SecureSpace service and may be used
|
|
9
|
+
only for that purpose, under the SecureSpace Terms of Service:
|
|
10
|
+
https://securespace.club/legal/terms
|
|
11
|
+
|
|
12
|
+
You may not modify, reverse engineer, redistribute or sublicense it except as
|
|
13
|
+
those terms allow.
|
|
14
|
+
License-File: LICENSE
|
|
15
|
+
Keywords: ai-agents,gateway,policy,security
|
|
16
|
+
Classifier: License :: Other/Proprietary License
|
|
17
|
+
Classifier: Operating System :: OS Independent
|
|
18
|
+
Classifier: Programming Language :: Python :: 3
|
|
19
|
+
Requires-Python: >=3.9
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
|
|
22
|
+
# SecureSpace SDK for Python
|
|
23
|
+
|
|
24
|
+
Send your agent's calls to outside services through the SecureSpace Gateway. Each
|
|
25
|
+
call is checked against your organization's rules, and blocked calls come back
|
|
26
|
+
as a value you can handle, never a silent failure. Standard library only.
|
|
27
|
+
|
|
28
|
+
You need a SecureSpace account and an agent key: sign up at
|
|
29
|
+
https://securespace.club, then create an agent in the console.
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
pip install securespace
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
```python
|
|
36
|
+
import os
|
|
37
|
+
from securespace import SecureSpaceClient
|
|
38
|
+
|
|
39
|
+
client = SecureSpaceClient("https://gateway.securespace.club", os.environ["SECURESPACE_API_KEY"])
|
|
40
|
+
|
|
41
|
+
# "crm" is a service registered on the console's Upstreams page.
|
|
42
|
+
res = client.get("crm", "/contacts")
|
|
43
|
+
if res.blocked:
|
|
44
|
+
print("blocked:", res.error_code)
|
|
45
|
+
else:
|
|
46
|
+
print(res.body)
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Requires Python 3.9 or later.
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
securespace/__init__.py,sha256=maAw8lZCgVBjAV41Mj20-BpR-h5KNiPnZeMu9J1r-bM,11699
|
|
2
|
+
securespace-0.1.0.dist-info/METADATA,sha256=5L8W-liYYYhDyOHGzopk8oVWDi4P5T6eBeqpAtxaIJs,1679
|
|
3
|
+
securespace-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
4
|
+
securespace-0.1.0.dist-info/licenses/LICENSE,sha256=NtwHjNoNAg1UsaCcgnXOdjjtKT9JrGVKXwp32A722II,340
|
|
5
|
+
securespace-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
Copyright (c) 2026 SecureSpace. All rights reserved.
|
|
2
|
+
|
|
3
|
+
This software is provided to connect to the SecureSpace service and may be used
|
|
4
|
+
only for that purpose, under the SecureSpace Terms of Service:
|
|
5
|
+
https://securespace.club/legal/terms
|
|
6
|
+
|
|
7
|
+
You may not modify, reverse engineer, redistribute or sublicense it except as
|
|
8
|
+
those terms allow.
|