segmentstream-connections-runtime 0.1.0a1__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.
- segmentstream_connections_runtime/__init__.py +6 -0
- segmentstream_connections_runtime/__main__.py +22 -0
- segmentstream_connections_runtime/_application.py +137 -0
- segmentstream_connections_runtime/_definitions.py +29 -0
- segmentstream_connections_runtime/_http.py +190 -0
- segmentstream_connections_runtime/_inspector.py +25 -0
- segmentstream_connections_runtime/_server.py +41 -0
- segmentstream_connections_runtime/_transport.py +65 -0
- segmentstream_connections_runtime/py.typed +0 -0
- segmentstream_connections_runtime-0.1.0a1.dist-info/METADATA +48 -0
- segmentstream_connections_runtime-0.1.0a1.dist-info/RECORD +15 -0
- segmentstream_connections_runtime-0.1.0a1.dist-info/WHEEL +4 -0
- segmentstream_connections_runtime-0.1.0a1.dist-info/entry_points.txt +2 -0
- segmentstream_connections_runtime-0.1.0a1.dist-info/licenses/LICENSE +201 -0
- segmentstream_connections_runtime-0.1.0a1.dist-info/licenses/NOTICE +2 -0
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
"""Private runtime host for workspace connection definitions."""
|
|
2
|
+
|
|
3
|
+
from segmentstream_connections_runtime._application import ConnectionRuntime
|
|
4
|
+
from segmentstream_connections_runtime._definitions import load_connection_definitions
|
|
5
|
+
|
|
6
|
+
__all__ = ["ConnectionRuntime", "load_connection_definitions"]
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import pathlib
|
|
2
|
+
import sys
|
|
3
|
+
|
|
4
|
+
from segmentstream_connections_runtime._inspector import inspect_connection_definitions
|
|
5
|
+
from segmentstream_connections_runtime._server import serve_connections
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def main() -> None:
|
|
9
|
+
arguments = sys.argv[1:]
|
|
10
|
+
if arguments == ["serve"]:
|
|
11
|
+
serve_connections()
|
|
12
|
+
return
|
|
13
|
+
if len(arguments) == 2 and arguments[0] == "inspect":
|
|
14
|
+
inspect_connection_definitions(pathlib.Path(arguments[1]))
|
|
15
|
+
return
|
|
16
|
+
raise RuntimeError(
|
|
17
|
+
"Usage: python -m segmentstream_connections_runtime serve | inspect OUTPUT_PATH"
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
if __name__ == "__main__":
|
|
22
|
+
main()
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import re
|
|
3
|
+
from collections.abc import Mapping
|
|
4
|
+
|
|
5
|
+
from segmentstream.connections import (
|
|
6
|
+
ConnectionDefinitions,
|
|
7
|
+
OAuth2Connection,
|
|
8
|
+
OAuth2TokenSet,
|
|
9
|
+
PostOAuth2TokenRequest,
|
|
10
|
+
ResolveSecret,
|
|
11
|
+
SecretReference,
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
_ENVIRONMENT_SECRET_PREFIX = "SEGMENTSTREAM_CONNECTION_SECRET_"
|
|
15
|
+
_NON_ENVIRONMENT_CHARACTER = re.compile(r"[^A-Z0-9]")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class ConnectionRuntimeConfigurationError(RuntimeError):
|
|
19
|
+
"""The deployed runtime is missing required platform configuration."""
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class EnvironmentSecretResolver:
|
|
23
|
+
"""Resolves customer-owned secret references injected into the service."""
|
|
24
|
+
|
|
25
|
+
async def __call__(self, reference: SecretReference) -> str:
|
|
26
|
+
variable = _ENVIRONMENT_SECRET_PREFIX + _NON_ENVIRONMENT_CHARACTER.sub(
|
|
27
|
+
"_", reference.name.upper()
|
|
28
|
+
)
|
|
29
|
+
value = os.environ.get(variable)
|
|
30
|
+
if not value:
|
|
31
|
+
raise ConnectionRuntimeConfigurationError(
|
|
32
|
+
f"Required connection secret {reference.name!r} is unavailable"
|
|
33
|
+
)
|
|
34
|
+
return value
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class ConnectionRuntime:
|
|
38
|
+
"""Dispatches private runtime operations to executable definitions."""
|
|
39
|
+
|
|
40
|
+
def __init__(
|
|
41
|
+
self,
|
|
42
|
+
definitions: ConnectionDefinitions,
|
|
43
|
+
*,
|
|
44
|
+
resolve_secret: ResolveSecret,
|
|
45
|
+
post_token_request: PostOAuth2TokenRequest,
|
|
46
|
+
) -> None:
|
|
47
|
+
self._definitions = definitions
|
|
48
|
+
self._resolve_secret = resolve_secret
|
|
49
|
+
self._post_token_request = post_token_request
|
|
50
|
+
|
|
51
|
+
async def start_authorization(
|
|
52
|
+
self,
|
|
53
|
+
connection_key: str,
|
|
54
|
+
*,
|
|
55
|
+
redirect_uri: str,
|
|
56
|
+
state: str,
|
|
57
|
+
code_challenge: str | None,
|
|
58
|
+
) -> str:
|
|
59
|
+
connection = self._connection(connection_key)
|
|
60
|
+
return await connection.authorization_uri(
|
|
61
|
+
redirect_uri=redirect_uri,
|
|
62
|
+
state=state,
|
|
63
|
+
code_challenge=code_challenge,
|
|
64
|
+
resolve_secret=self._resolve_secret,
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
async def exchange_code(
|
|
68
|
+
self,
|
|
69
|
+
connection_key: str,
|
|
70
|
+
*,
|
|
71
|
+
code: str,
|
|
72
|
+
redirect_uri: str,
|
|
73
|
+
code_verifier: str | None,
|
|
74
|
+
) -> OAuth2TokenSet:
|
|
75
|
+
connection = self._connection(connection_key)
|
|
76
|
+
return await connection.exchange_code(
|
|
77
|
+
code=code,
|
|
78
|
+
redirect_uri=redirect_uri,
|
|
79
|
+
code_verifier=code_verifier,
|
|
80
|
+
resolve_secret=self._resolve_secret,
|
|
81
|
+
post_token_request=self._post_token_request,
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
async def refresh_access_token(
|
|
85
|
+
self,
|
|
86
|
+
connection_key: str,
|
|
87
|
+
*,
|
|
88
|
+
refresh_token: str,
|
|
89
|
+
) -> OAuth2TokenSet:
|
|
90
|
+
connection = self._connection(connection_key)
|
|
91
|
+
return await connection.refresh_access_token(
|
|
92
|
+
refresh_token=refresh_token,
|
|
93
|
+
resolve_secret=self._resolve_secret,
|
|
94
|
+
post_token_request=self._post_token_request,
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
def manifest(self) -> Mapping[str, object]:
|
|
98
|
+
return {
|
|
99
|
+
"schemaVersion": 1,
|
|
100
|
+
"definitionsFile": "definitions.py",
|
|
101
|
+
"connections": [
|
|
102
|
+
{
|
|
103
|
+
"type": connection.type,
|
|
104
|
+
"key": connection.key,
|
|
105
|
+
"provider": connection.provider,
|
|
106
|
+
"authorizationUrl": connection.authorization_url,
|
|
107
|
+
"tokenUrl": connection.token_url,
|
|
108
|
+
"clientIdSecret": connection.client_id.model_dump(mode="json"),
|
|
109
|
+
"clientSecretSecret": connection.client_secret.model_dump(mode="json"),
|
|
110
|
+
"scopes": list(connection.scopes),
|
|
111
|
+
"authorizationParameters": {
|
|
112
|
+
parameter.name: parameter.value
|
|
113
|
+
for parameter in connection.authorization_parameters
|
|
114
|
+
},
|
|
115
|
+
"tokenParameters": {
|
|
116
|
+
parameter.name: parameter.value for parameter in connection.token_parameters
|
|
117
|
+
},
|
|
118
|
+
"clientAuthentication": connection.client_authentication,
|
|
119
|
+
"pkce": connection.pkce,
|
|
120
|
+
"requireRefreshToken": connection.require_refresh_token,
|
|
121
|
+
}
|
|
122
|
+
for connection in self._definitions.connections
|
|
123
|
+
],
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
def _connection(self, connection_key: str) -> OAuth2Connection:
|
|
127
|
+
try:
|
|
128
|
+
return self._definitions.get(connection_key)
|
|
129
|
+
except KeyError as error:
|
|
130
|
+
raise LookupError(f"Connection {connection_key!r} is not defined") from error
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
__all__ = [
|
|
134
|
+
"ConnectionRuntime",
|
|
135
|
+
"ConnectionRuntimeConfigurationError",
|
|
136
|
+
"EnvironmentSecretResolver",
|
|
137
|
+
]
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import importlib.util
|
|
2
|
+
import pathlib
|
|
3
|
+
|
|
4
|
+
from segmentstream.connections import ConnectionDefinitions
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def connection_definitions_path() -> pathlib.Path:
|
|
8
|
+
return pathlib.Path.cwd() / "definitions.py"
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def load_connection_definitions() -> ConnectionDefinitions:
|
|
12
|
+
path = connection_definitions_path()
|
|
13
|
+
spec = importlib.util.spec_from_file_location(
|
|
14
|
+
"_segmentstream_workspace_connection_definitions",
|
|
15
|
+
path,
|
|
16
|
+
)
|
|
17
|
+
if spec is None or spec.loader is None:
|
|
18
|
+
raise RuntimeError("Could not load connection definitions.py")
|
|
19
|
+
module = importlib.util.module_from_spec(spec)
|
|
20
|
+
spec.loader.exec_module(module)
|
|
21
|
+
definitions = getattr(module, "defs", None)
|
|
22
|
+
if not isinstance(definitions, ConnectionDefinitions):
|
|
23
|
+
raise TypeError(
|
|
24
|
+
"connections/definitions.py must export a ConnectionDefinitions object named defs"
|
|
25
|
+
)
|
|
26
|
+
return definitions
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
__all__ = ["connection_definitions_path", "load_connection_definitions"]
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
from collections.abc import Awaitable, Callable
|
|
2
|
+
from typing import Annotated
|
|
3
|
+
|
|
4
|
+
from fastapi import FastAPI, Path, Request, Response
|
|
5
|
+
from fastapi.exceptions import RequestValidationError
|
|
6
|
+
from fastapi.responses import JSONResponse
|
|
7
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
8
|
+
from segmentstream.connections import OAuth2ProviderResponseError, OAuth2TokenSet
|
|
9
|
+
|
|
10
|
+
from segmentstream_connections_runtime._application import (
|
|
11
|
+
ConnectionRuntime,
|
|
12
|
+
ConnectionRuntimeConfigurationError,
|
|
13
|
+
)
|
|
14
|
+
from segmentstream_connections_runtime._transport import OAuth2ProviderError
|
|
15
|
+
|
|
16
|
+
ConnectionKey = Annotated[str, Path(pattern=r"^[a-z][a-z0-9_]{0,63}$")]
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class _RuntimeModel(BaseModel):
|
|
20
|
+
model_config = ConfigDict(extra="forbid", populate_by_name=True)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class StartAuthorizationRequest(_RuntimeModel):
|
|
24
|
+
redirect_uri: str = Field(alias="redirectUri")
|
|
25
|
+
state: str
|
|
26
|
+
code_challenge: str | None = Field(default=None, alias="codeChallenge")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class StartAuthorizationResponse(_RuntimeModel):
|
|
30
|
+
authorization_url: str = Field(alias="authorizationUrl")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class ExchangeCodeRequest(_RuntimeModel):
|
|
34
|
+
code: str
|
|
35
|
+
redirect_uri: str = Field(alias="redirectUri")
|
|
36
|
+
code_verifier: str | None = Field(default=None, alias="codeVerifier")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class RefreshAccessTokenRequest(_RuntimeModel):
|
|
40
|
+
refresh_token: str = Field(alias="refreshToken")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class TokenResponse(_RuntimeModel):
|
|
44
|
+
access_token: str = Field(alias="accessToken")
|
|
45
|
+
refresh_token: str | None = Field(alias="refreshToken")
|
|
46
|
+
token_type: str = Field(alias="tokenType")
|
|
47
|
+
expires_in: int | None = Field(alias="expiresIn")
|
|
48
|
+
scopes: tuple[str, ...]
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class HealthResponse(_RuntimeModel):
|
|
52
|
+
status: str
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def create_runtime_application(runtime: ConnectionRuntime) -> FastAPI:
|
|
56
|
+
application = FastAPI(
|
|
57
|
+
title="SegmentStream Connections Runtime",
|
|
58
|
+
version="1",
|
|
59
|
+
docs_url=None,
|
|
60
|
+
redoc_url=None,
|
|
61
|
+
openapi_url="/internal/v1/openapi.json",
|
|
62
|
+
)
|
|
63
|
+
_register_error_handlers(application)
|
|
64
|
+
|
|
65
|
+
@application.middleware("http")
|
|
66
|
+
async def prevent_response_caching(
|
|
67
|
+
request: Request,
|
|
68
|
+
call_next: Callable[[Request], Awaitable[Response]],
|
|
69
|
+
) -> Response:
|
|
70
|
+
response = await call_next(request)
|
|
71
|
+
response.headers["Cache-Control"] = "no-store"
|
|
72
|
+
return response
|
|
73
|
+
|
|
74
|
+
@application.get("/health", response_model=HealthResponse)
|
|
75
|
+
async def health() -> HealthResponse:
|
|
76
|
+
return HealthResponse(status="ok")
|
|
77
|
+
|
|
78
|
+
@application.post(
|
|
79
|
+
"/internal/v1/connections/{connection_key}/authorization/start",
|
|
80
|
+
response_model=StartAuthorizationResponse,
|
|
81
|
+
)
|
|
82
|
+
async def start_authorization(
|
|
83
|
+
connection_key: ConnectionKey,
|
|
84
|
+
body: StartAuthorizationRequest,
|
|
85
|
+
) -> StartAuthorizationResponse:
|
|
86
|
+
authorization_url = await runtime.start_authorization(
|
|
87
|
+
connection_key,
|
|
88
|
+
redirect_uri=body.redirect_uri,
|
|
89
|
+
state=body.state,
|
|
90
|
+
code_challenge=body.code_challenge,
|
|
91
|
+
)
|
|
92
|
+
return StartAuthorizationResponse(authorization_url=authorization_url)
|
|
93
|
+
|
|
94
|
+
@application.post(
|
|
95
|
+
"/internal/v1/connections/{connection_key}/token/exchange",
|
|
96
|
+
response_model=TokenResponse,
|
|
97
|
+
)
|
|
98
|
+
async def exchange_code(
|
|
99
|
+
connection_key: ConnectionKey,
|
|
100
|
+
body: ExchangeCodeRequest,
|
|
101
|
+
) -> TokenResponse:
|
|
102
|
+
tokens = await runtime.exchange_code(
|
|
103
|
+
connection_key,
|
|
104
|
+
code=body.code,
|
|
105
|
+
redirect_uri=body.redirect_uri,
|
|
106
|
+
code_verifier=body.code_verifier,
|
|
107
|
+
)
|
|
108
|
+
return _token_response(tokens)
|
|
109
|
+
|
|
110
|
+
@application.post(
|
|
111
|
+
"/internal/v1/connections/{connection_key}/token/refresh",
|
|
112
|
+
response_model=TokenResponse,
|
|
113
|
+
)
|
|
114
|
+
async def refresh_access_token(
|
|
115
|
+
connection_key: ConnectionKey,
|
|
116
|
+
body: RefreshAccessTokenRequest,
|
|
117
|
+
) -> TokenResponse:
|
|
118
|
+
tokens = await runtime.refresh_access_token(
|
|
119
|
+
connection_key,
|
|
120
|
+
refresh_token=body.refresh_token,
|
|
121
|
+
)
|
|
122
|
+
return _token_response(tokens)
|
|
123
|
+
|
|
124
|
+
return application
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _register_error_handlers(application: FastAPI) -> None:
|
|
128
|
+
@application.exception_handler(RequestValidationError)
|
|
129
|
+
async def handle_invalid_request(
|
|
130
|
+
_request: Request,
|
|
131
|
+
_error: RequestValidationError,
|
|
132
|
+
) -> JSONResponse:
|
|
133
|
+
return _error_response(400, "invalid_request")
|
|
134
|
+
|
|
135
|
+
@application.exception_handler(ValueError)
|
|
136
|
+
async def handle_invalid_runtime_value(
|
|
137
|
+
_request: Request,
|
|
138
|
+
_error: ValueError,
|
|
139
|
+
) -> JSONResponse:
|
|
140
|
+
return _error_response(400, "invalid_request")
|
|
141
|
+
|
|
142
|
+
@application.exception_handler(LookupError)
|
|
143
|
+
async def handle_unknown_connection(
|
|
144
|
+
_request: Request,
|
|
145
|
+
_error: LookupError,
|
|
146
|
+
) -> JSONResponse:
|
|
147
|
+
return _error_response(404, "connection_not_found")
|
|
148
|
+
|
|
149
|
+
@application.exception_handler(OAuth2ProviderError)
|
|
150
|
+
@application.exception_handler(OAuth2ProviderResponseError)
|
|
151
|
+
async def handle_provider_error(
|
|
152
|
+
_request: Request,
|
|
153
|
+
_error: Exception,
|
|
154
|
+
) -> JSONResponse:
|
|
155
|
+
return _error_response(502, "oauth_provider_unavailable")
|
|
156
|
+
|
|
157
|
+
@application.exception_handler(ConnectionRuntimeConfigurationError)
|
|
158
|
+
async def handle_runtime_configuration_error(
|
|
159
|
+
_request: Request,
|
|
160
|
+
_error: ConnectionRuntimeConfigurationError,
|
|
161
|
+
) -> JSONResponse:
|
|
162
|
+
return _error_response(503, "runtime_unavailable")
|
|
163
|
+
|
|
164
|
+
@application.exception_handler(Exception)
|
|
165
|
+
async def handle_internal_error(
|
|
166
|
+
_request: Request,
|
|
167
|
+
_error: Exception,
|
|
168
|
+
) -> JSONResponse:
|
|
169
|
+
return _error_response(500, "internal_error")
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _token_response(tokens: OAuth2TokenSet) -> TokenResponse:
|
|
173
|
+
return TokenResponse(
|
|
174
|
+
access_token=tokens.access_token,
|
|
175
|
+
refresh_token=tokens.refresh_token,
|
|
176
|
+
token_type=tokens.token_type,
|
|
177
|
+
expires_in=tokens.expires_in,
|
|
178
|
+
scopes=tokens.scopes,
|
|
179
|
+
)
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def _error_response(status_code: int, code: str) -> JSONResponse:
|
|
183
|
+
return JSONResponse(
|
|
184
|
+
status_code=status_code,
|
|
185
|
+
content={"error": {"code": code}},
|
|
186
|
+
headers={"Cache-Control": "no-store"},
|
|
187
|
+
)
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
__all__ = ["create_runtime_application"]
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import pathlib
|
|
3
|
+
|
|
4
|
+
from segmentstream_connections_runtime._application import (
|
|
5
|
+
ConnectionRuntime,
|
|
6
|
+
EnvironmentSecretResolver,
|
|
7
|
+
)
|
|
8
|
+
from segmentstream_connections_runtime._definitions import load_connection_definitions
|
|
9
|
+
from segmentstream_connections_runtime._transport import UrlLibOAuth2TokenTransport
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def inspect_connection_definitions(output_path: pathlib.Path) -> None:
|
|
13
|
+
definitions = load_connection_definitions()
|
|
14
|
+
runtime = ConnectionRuntime(
|
|
15
|
+
definitions,
|
|
16
|
+
resolve_secret=EnvironmentSecretResolver(),
|
|
17
|
+
post_token_request=UrlLibOAuth2TokenTransport(),
|
|
18
|
+
)
|
|
19
|
+
output_path.write_text(
|
|
20
|
+
json.dumps(runtime.manifest(), indent=2, sort_keys=True) + "\n",
|
|
21
|
+
encoding="utf-8",
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
__all__ = ["inspect_connection_definitions"]
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import os
|
|
2
|
+
|
|
3
|
+
import uvicorn
|
|
4
|
+
|
|
5
|
+
from segmentstream_connections_runtime._application import (
|
|
6
|
+
ConnectionRuntime,
|
|
7
|
+
EnvironmentSecretResolver,
|
|
8
|
+
)
|
|
9
|
+
from segmentstream_connections_runtime._definitions import load_connection_definitions
|
|
10
|
+
from segmentstream_connections_runtime._http import create_runtime_application
|
|
11
|
+
from segmentstream_connections_runtime._transport import UrlLibOAuth2TokenTransport
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def serve_connections() -> None:
|
|
15
|
+
definitions = load_connection_definitions()
|
|
16
|
+
runtime = ConnectionRuntime(
|
|
17
|
+
definitions,
|
|
18
|
+
resolve_secret=EnvironmentSecretResolver(),
|
|
19
|
+
post_token_request=UrlLibOAuth2TokenTransport(),
|
|
20
|
+
)
|
|
21
|
+
port = _runtime_port()
|
|
22
|
+
uvicorn.run(
|
|
23
|
+
create_runtime_application(runtime),
|
|
24
|
+
host="0.0.0.0",
|
|
25
|
+
port=port,
|
|
26
|
+
server_header=False,
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _runtime_port() -> int:
|
|
31
|
+
raw_port = os.environ.get("PORT", "8080")
|
|
32
|
+
try:
|
|
33
|
+
port = int(raw_port)
|
|
34
|
+
except ValueError as error:
|
|
35
|
+
raise RuntimeError("PORT must be an integer") from error
|
|
36
|
+
if not 1 <= port <= 65_535:
|
|
37
|
+
raise RuntimeError("PORT must be between 1 and 65535")
|
|
38
|
+
return port
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
__all__ = ["serve_connections"]
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import json
|
|
3
|
+
import urllib.error
|
|
4
|
+
import urllib.parse
|
|
5
|
+
import urllib.request
|
|
6
|
+
from collections.abc import Mapping
|
|
7
|
+
from typing import cast
|
|
8
|
+
|
|
9
|
+
_TOKEN_REQUEST_TIMEOUT_SECONDS = 20
|
|
10
|
+
_MAX_TOKEN_RESPONSE_BYTES = 1_048_576
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class OAuth2ProviderError(RuntimeError):
|
|
14
|
+
"""A sanitized OAuth provider failure safe to expose to the control plane."""
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class UrlLibOAuth2TokenTransport:
|
|
18
|
+
async def __call__(
|
|
19
|
+
self,
|
|
20
|
+
*,
|
|
21
|
+
url: str,
|
|
22
|
+
data: Mapping[str, str],
|
|
23
|
+
headers: Mapping[str, str],
|
|
24
|
+
) -> Mapping[str, object]:
|
|
25
|
+
return await asyncio.to_thread(self._post, url=url, data=data, headers=headers)
|
|
26
|
+
|
|
27
|
+
def _post(
|
|
28
|
+
self,
|
|
29
|
+
*,
|
|
30
|
+
url: str,
|
|
31
|
+
data: Mapping[str, str],
|
|
32
|
+
headers: Mapping[str, str],
|
|
33
|
+
) -> Mapping[str, object]:
|
|
34
|
+
request = urllib.request.Request(
|
|
35
|
+
url,
|
|
36
|
+
data=urllib.parse.urlencode(data).encode(),
|
|
37
|
+
headers={
|
|
38
|
+
"Accept": "application/json",
|
|
39
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
40
|
+
**headers,
|
|
41
|
+
},
|
|
42
|
+
method="POST",
|
|
43
|
+
)
|
|
44
|
+
try:
|
|
45
|
+
with urllib.request.urlopen(
|
|
46
|
+
request,
|
|
47
|
+
timeout=_TOKEN_REQUEST_TIMEOUT_SECONDS,
|
|
48
|
+
) as response:
|
|
49
|
+
payload = response.read(_MAX_TOKEN_RESPONSE_BYTES + 1)
|
|
50
|
+
except (urllib.error.HTTPError, urllib.error.URLError, TimeoutError) as error:
|
|
51
|
+
raise OAuth2ProviderError("OAuth provider token request failed") from error
|
|
52
|
+
if len(payload) > _MAX_TOKEN_RESPONSE_BYTES:
|
|
53
|
+
raise OAuth2ProviderError("OAuth provider token response is too large")
|
|
54
|
+
try:
|
|
55
|
+
decoded = json.loads(payload)
|
|
56
|
+
except (UnicodeDecodeError, json.JSONDecodeError) as error:
|
|
57
|
+
raise OAuth2ProviderError(
|
|
58
|
+
"OAuth provider returned an invalid token response"
|
|
59
|
+
) from error
|
|
60
|
+
if not isinstance(decoded, dict):
|
|
61
|
+
raise OAuth2ProviderError("OAuth provider returned an invalid token response")
|
|
62
|
+
return cast(dict[str, object], decoded)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
__all__ = ["OAuth2ProviderError", "UrlLibOAuth2TokenTransport"]
|
|
File without changes
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: segmentstream-connections-runtime
|
|
3
|
+
Version: 0.1.0a1
|
|
4
|
+
Summary: Private OAuth connection runtime for SegmentStream workspaces
|
|
5
|
+
Project-URL: Homepage, https://segmentstream.com
|
|
6
|
+
Author: SegmentStream
|
|
7
|
+
License-Expression: Apache-2.0
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
License-File: NOTICE
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
15
|
+
Classifier: Typing :: Typed
|
|
16
|
+
Requires-Python: <3.14,>=3.12
|
|
17
|
+
Requires-Dist: fastapi<1,>=0.117
|
|
18
|
+
Requires-Dist: pydantic<3,>=2.10
|
|
19
|
+
Requires-Dist: segmentstream-pipeline==0.1.0a7
|
|
20
|
+
Requires-Dist: uvicorn<1,>=0.35
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
|
|
23
|
+
# SegmentStream connections runtime
|
|
24
|
+
|
|
25
|
+
`segmentstream-connections-runtime` is the private Cloud Run host for custom
|
|
26
|
+
OAuth 2.0 definitions authored with the SegmentStream SDK. It loads the
|
|
27
|
+
workspace's `connections/definitions.py`, resolves customer-owned secret
|
|
28
|
+
references, and performs authorization-code and refresh-token exchanges.
|
|
29
|
+
|
|
30
|
+
The runtime is an infrastructure component, not a public user-facing API. Its
|
|
31
|
+
Cloud Run service must require IAM authentication.
|
|
32
|
+
|
|
33
|
+
```shell
|
|
34
|
+
python -m segmentstream_connections_runtime inspect manifest.json
|
|
35
|
+
python -m segmentstream_connections_runtime serve
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
The server listens on `PORT`, defaulting to `8080`. A declaration such as
|
|
39
|
+
`secret_ref("google-oauth-client-id")` is resolved from
|
|
40
|
+
`SEGMENTSTREAM_CONNECTION_SECRET_GOOGLE_OAUTH_CLIENT_ID` in the isolated runtime
|
|
41
|
+
environment. Client secrets use the same mapping convention.
|
|
42
|
+
|
|
43
|
+
## Releases
|
|
44
|
+
|
|
45
|
+
Releases use the version in `pyproject.toml` and are published from the
|
|
46
|
+
`connections-runtime-v<version>` Git tag by the protected
|
|
47
|
+
`connections-runtime-release.yml` workflow. PyPI releases are immutable, so the
|
|
48
|
+
package version must be incremented before creating another release tag.
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
segmentstream_connections_runtime/__init__.py,sha256=HEdEs3eBsUh4v2mQi5Ep2keykJuTvF2PwYM603o8v4w,294
|
|
2
|
+
segmentstream_connections_runtime/__main__.py,sha256=M0GjNolUDc1lO6joZXbo3zpAeUNke7ofeaA4ehdHHwI,611
|
|
3
|
+
segmentstream_connections_runtime/_application.py,sha256=Cxobjoy_7vCpBC9h6EifTUpzT1bDfx-6fEU3Fj4trH4,4592
|
|
4
|
+
segmentstream_connections_runtime/_definitions.py,sha256=YWILuDUNSv8PCN8HmqxuCCucQ1uusZXn8VFNL9AgNEQ,970
|
|
5
|
+
segmentstream_connections_runtime/_http.py,sha256=xqDP4CsNq2VciUJek1f19xsO2dtN0F6PMWkdqLx2iPk,6134
|
|
6
|
+
segmentstream_connections_runtime/_inspector.py,sha256=HDMoF7X2mAMW_wJsKgesPaz5BiuyLDzwcb5aMVCIHVc,786
|
|
7
|
+
segmentstream_connections_runtime/_server.py,sha256=LRaqtH0rWfDpefO0WAn77CP3vrB8NKV18zy3jr02tf8,1169
|
|
8
|
+
segmentstream_connections_runtime/_transport.py,sha256=wjZRiQxlkz26A9BdBX8Kp5KWjJzkunZ4FyuJJAphSzs,2177
|
|
9
|
+
segmentstream_connections_runtime/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
10
|
+
segmentstream_connections_runtime-0.1.0a1.dist-info/METADATA,sha256=leMuxrDWzvlREhOx1GvOMMNww2RypgPu53yjHc3rx1M,1939
|
|
11
|
+
segmentstream_connections_runtime-0.1.0a1.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
|
|
12
|
+
segmentstream_connections_runtime-0.1.0a1.dist-info/entry_points.txt,sha256=W1voiZAV76Cjk9wEn9iDUBzfpm3bPCNq8Bj_6jz6kts,102
|
|
13
|
+
segmentstream_connections_runtime-0.1.0a1.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
|
|
14
|
+
segmentstream_connections_runtime-0.1.0a1.dist-info/licenses/NOTICE,sha256=qKh3GntlNVPhUXKX_CMlflcKk8TFYUsv_xEqtvJIo9Y,63
|
|
15
|
+
segmentstream_connections_runtime-0.1.0a1.dist-info/RECORD,,
|
|
@@ -0,0 +1,201 @@
|
|
|
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,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|