akeyless-cloudrun-rta 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.
- akeyless_cloudrun_rta/__init__.py +13 -0
- akeyless_cloudrun_rta/ara.py +262 -0
- akeyless_cloudrun_rta/auth.py +134 -0
- akeyless_cloudrun_rta/caller.py +65 -0
- akeyless_cloudrun_rta/client.py +208 -0
- akeyless_cloudrun_rta/config.py +249 -0
- akeyless_cloudrun_rta/http_ara.py +225 -0
- akeyless_cloudrun_rta/tools/__init__.py +17 -0
- akeyless_cloudrun_rta/tools/mcp.py +346 -0
- akeyless_cloudrun_rta/tools/service.py +160 -0
- akeyless_cloudrun_rta-0.1.0.dist-info/METADATA +105 -0
- akeyless_cloudrun_rta-0.1.0.dist-info/RECORD +15 -0
- akeyless_cloudrun_rta-0.1.0.dist-info/WHEEL +4 -0
- akeyless_cloudrun_rta-0.1.0.dist-info/entry_points.txt +2 -0
- akeyless_cloudrun_rta-0.1.0.dist-info/licenses/LICENSE +19 -0
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"""Akeyless Agentic Runtime Authority (RTA/ARA) for Google Cloud Run."""
|
|
2
|
+
|
|
3
|
+
from akeyless_cloudrun_rta.client import AkeylessRtaClient, get_default_client
|
|
4
|
+
from akeyless_cloudrun_rta.ara import AraSecretSummary, OAuthAuthorizationRequiredError
|
|
5
|
+
|
|
6
|
+
__all__ = [
|
|
7
|
+
"AkeylessRtaClient",
|
|
8
|
+
"AraSecretSummary",
|
|
9
|
+
"OAuthAuthorizationRequiredError",
|
|
10
|
+
"get_default_client",
|
|
11
|
+
]
|
|
12
|
+
|
|
13
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
"""ARA list-items mapping and producer-type helpers.
|
|
2
|
+
|
|
3
|
+
Ported from claude-akeyless-connector ``ara.ts`` to match gateway ListARASecrets
|
|
4
|
+
behavior and MCP tool routing.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from typing import Any, Literal
|
|
11
|
+
|
|
12
|
+
ARA_DB_PRODUCER_TYPES = frozenset(
|
|
13
|
+
{
|
|
14
|
+
"mysql",
|
|
15
|
+
"postgres",
|
|
16
|
+
"mssql",
|
|
17
|
+
"oracle",
|
|
18
|
+
"snowflake",
|
|
19
|
+
"hana",
|
|
20
|
+
"redshift",
|
|
21
|
+
"mongodb",
|
|
22
|
+
"redis",
|
|
23
|
+
"cassandra",
|
|
24
|
+
}
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
ARA_SERVICE_PRODUCER_TYPES = frozenset(
|
|
28
|
+
{
|
|
29
|
+
"aws",
|
|
30
|
+
"gcp",
|
|
31
|
+
"azure",
|
|
32
|
+
"k8s",
|
|
33
|
+
"eks",
|
|
34
|
+
"gke",
|
|
35
|
+
"github",
|
|
36
|
+
}
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
# Kinds executed as a remote command on a host over SSH or WinRM (Go:
|
|
40
|
+
# types.ARARemoteProducerTypes): the producer type of a dynamic secret (rdp,
|
|
41
|
+
# ldap) or the target type of a rotated secret (ssh, windows, ldap, linked).
|
|
42
|
+
ARA_REMOTE_PRODUCER_TYPES = frozenset({"ssh", "windows", "rdp", "ldap", "linked"})
|
|
43
|
+
|
|
44
|
+
# secret_type of an SSH certificate issuer (Go: types.ARASecretTypeSSHCertIssuer).
|
|
45
|
+
SSH_CERT_ISSUER_SECRET_TYPE = "ssh-cert-issuer"
|
|
46
|
+
|
|
47
|
+
# Synthetic label for static-secret custom MCP configs (Go: CustomMCPTargetType).
|
|
48
|
+
CUSTOM_MCP_TARGET_TYPE = "custom-mcp"
|
|
49
|
+
|
|
50
|
+
# Go: types.ARAItemTypes.
|
|
51
|
+
ARA_LIST_ITEM_TYPES = ["dynamic-secret", "rotated-secret", "static-secret", "ssh-cert-issuer"]
|
|
52
|
+
|
|
53
|
+
SecretTypeLabel = Literal["dynamic-secret", "rotated-secret", "static-secret", "ssh-cert-issuer"]
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def is_ara_db_producer_type(producer_type: str) -> bool:
|
|
57
|
+
return producer_type.lower() in ARA_DB_PRODUCER_TYPES
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def is_ara_service_producer_type(producer_type: str) -> bool:
|
|
61
|
+
normalized = producer_type.lower()
|
|
62
|
+
return normalized in ARA_SERVICE_PRODUCER_TYPES or normalized == CUSTOM_MCP_TARGET_TYPE
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def is_ara_remote_producer_type(producer_type: str) -> bool:
|
|
66
|
+
"""Remote items run one command (or file transfer) on a host; they go through service-execute."""
|
|
67
|
+
return producer_type.lower() in ARA_REMOTE_PRODUCER_TYPES
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def is_ara_supported_producer_type(producer_type: str) -> bool:
|
|
71
|
+
normalized = producer_type.lower()
|
|
72
|
+
return (
|
|
73
|
+
normalized in ARA_DB_PRODUCER_TYPES
|
|
74
|
+
or normalized in ARA_SERVICE_PRODUCER_TYPES
|
|
75
|
+
or normalized in ARA_REMOTE_PRODUCER_TYPES
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def normalize_item_type(raw: str | None) -> str:
|
|
80
|
+
return (raw or "").strip().lower().replace("_", "-")
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
@dataclass(frozen=True)
|
|
84
|
+
class AraSecretSummary:
|
|
85
|
+
name: str
|
|
86
|
+
secret_type: SecretTypeLabel
|
|
87
|
+
target_type: str | None = None
|
|
88
|
+
description: str | None = None
|
|
89
|
+
|
|
90
|
+
def to_dict(self) -> dict[str, Any]:
|
|
91
|
+
out: dict[str, Any] = {
|
|
92
|
+
"name": self.name,
|
|
93
|
+
"secret_type": self.secret_type,
|
|
94
|
+
}
|
|
95
|
+
if self.target_type:
|
|
96
|
+
out["target_type"] = self.target_type
|
|
97
|
+
if self.description:
|
|
98
|
+
out["description"] = self.description
|
|
99
|
+
return out
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def build_ara_list_items_body(
|
|
103
|
+
token: str,
|
|
104
|
+
*,
|
|
105
|
+
path: str | None = None,
|
|
106
|
+
ara_only: bool = True,
|
|
107
|
+
) -> dict[str, Any]:
|
|
108
|
+
body: dict[str, Any] = {
|
|
109
|
+
"token": token,
|
|
110
|
+
"filter": "",
|
|
111
|
+
"type": list(ARA_LIST_ITEM_TYPES),
|
|
112
|
+
"ara-only": ara_only,
|
|
113
|
+
"advanced-filter": "",
|
|
114
|
+
}
|
|
115
|
+
trimmed = (path or "").strip()
|
|
116
|
+
if trimmed:
|
|
117
|
+
body["path"] = trimmed
|
|
118
|
+
return body
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _item_get(item: Any, key: str, default: Any = None) -> Any:
|
|
122
|
+
if isinstance(item, dict):
|
|
123
|
+
return item.get(key, default)
|
|
124
|
+
return getattr(item, key, default)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _extract_dynamic_producer_type(item: Any) -> str | None:
|
|
128
|
+
general = _item_get(item, "item_general_info") or {}
|
|
129
|
+
if not isinstance(general, dict):
|
|
130
|
+
general = {
|
|
131
|
+
"dynamic_secret_producer_details": getattr(
|
|
132
|
+
general, "dynamic_secret_producer_details", None
|
|
133
|
+
)
|
|
134
|
+
}
|
|
135
|
+
details = general.get("dynamic_secret_producer_details") if isinstance(general, dict) else None
|
|
136
|
+
if details is None:
|
|
137
|
+
details = _item_get(item, "dynamic_secret_producer_details")
|
|
138
|
+
if details is None:
|
|
139
|
+
return None
|
|
140
|
+
if isinstance(details, dict):
|
|
141
|
+
producer = details.get("producer_type")
|
|
142
|
+
else:
|
|
143
|
+
producer = getattr(details, "producer_type", None)
|
|
144
|
+
if producer is None:
|
|
145
|
+
return None
|
|
146
|
+
trimmed = str(producer).strip().lower()
|
|
147
|
+
return trimmed or None
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _extract_rotated_target_type(item: Any) -> str | None:
|
|
151
|
+
assoc = _item_get(item, "item_targets_assoc") or []
|
|
152
|
+
if not assoc:
|
|
153
|
+
return None
|
|
154
|
+
first = assoc[0]
|
|
155
|
+
if isinstance(first, dict):
|
|
156
|
+
target = first.get("target_type")
|
|
157
|
+
else:
|
|
158
|
+
target = getattr(first, "target_type", None)
|
|
159
|
+
if target is None:
|
|
160
|
+
return None
|
|
161
|
+
trimmed = str(target).strip().lower()
|
|
162
|
+
return trimmed or None
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def map_ara_secrets(items: list[Any]) -> list[AraSecretSummary]:
|
|
166
|
+
results: list[AraSecretSummary] = []
|
|
167
|
+
|
|
168
|
+
for item in items:
|
|
169
|
+
name = _item_get(item, "item_name")
|
|
170
|
+
if not name or not str(name).strip():
|
|
171
|
+
continue
|
|
172
|
+
name = str(name).strip()
|
|
173
|
+
|
|
174
|
+
perms = _item_get(item, "client_permissions") or []
|
|
175
|
+
if "ara_allow_access" not in perms:
|
|
176
|
+
continue
|
|
177
|
+
|
|
178
|
+
item_type = normalize_item_type(str(_item_get(item, "item_type") or ""))
|
|
179
|
+
metadata = _item_get(item, "item_metadata")
|
|
180
|
+
description = str(metadata).strip() if metadata else None
|
|
181
|
+
if description == "":
|
|
182
|
+
description = None
|
|
183
|
+
|
|
184
|
+
if item_type == "dynamic-secret":
|
|
185
|
+
target_type = _extract_dynamic_producer_type(item)
|
|
186
|
+
if not target_type or not is_ara_supported_producer_type(target_type):
|
|
187
|
+
continue
|
|
188
|
+
results.append(
|
|
189
|
+
AraSecretSummary(
|
|
190
|
+
name=name,
|
|
191
|
+
secret_type="dynamic-secret",
|
|
192
|
+
target_type=target_type,
|
|
193
|
+
description=description,
|
|
194
|
+
)
|
|
195
|
+
)
|
|
196
|
+
continue
|
|
197
|
+
|
|
198
|
+
if item_type == "rotated-secret":
|
|
199
|
+
target_type = _extract_rotated_target_type(item)
|
|
200
|
+
if target_type and not is_ara_supported_producer_type(target_type):
|
|
201
|
+
continue
|
|
202
|
+
results.append(
|
|
203
|
+
AraSecretSummary(
|
|
204
|
+
name=name,
|
|
205
|
+
secret_type="rotated-secret",
|
|
206
|
+
target_type=target_type,
|
|
207
|
+
description=description,
|
|
208
|
+
)
|
|
209
|
+
)
|
|
210
|
+
continue
|
|
211
|
+
|
|
212
|
+
if item_type == "static-secret":
|
|
213
|
+
results.append(
|
|
214
|
+
AraSecretSummary(
|
|
215
|
+
name=name,
|
|
216
|
+
secret_type="static-secret",
|
|
217
|
+
target_type=CUSTOM_MCP_TARGET_TYPE,
|
|
218
|
+
description=description,
|
|
219
|
+
)
|
|
220
|
+
)
|
|
221
|
+
continue
|
|
222
|
+
|
|
223
|
+
if item_type == SSH_CERT_ISSUER_SECRET_TYPE:
|
|
224
|
+
# Commands run over SSH with a certificate signed for the call
|
|
225
|
+
# (Go: ListARASecrets SSHCertIssuer case).
|
|
226
|
+
results.append(
|
|
227
|
+
AraSecretSummary(
|
|
228
|
+
name=name,
|
|
229
|
+
secret_type=SSH_CERT_ISSUER_SECRET_TYPE,
|
|
230
|
+
target_type="ssh",
|
|
231
|
+
description=description,
|
|
232
|
+
)
|
|
233
|
+
)
|
|
234
|
+
|
|
235
|
+
results.sort(key=lambda s: s.name)
|
|
236
|
+
return results
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
class OAuthAuthorizationRequiredError(Exception):
|
|
240
|
+
"""Gateway returned 401 with an OAuth authorization_url + state challenge."""
|
|
241
|
+
|
|
242
|
+
def __init__(self, authorization_url: str, state: str) -> None:
|
|
243
|
+
self.authorization_url = authorization_url
|
|
244
|
+
self.state = state
|
|
245
|
+
super().__init__(f"OAuth authorization required: {authorization_url}")
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def format_oauth_required_message(
|
|
249
|
+
error: OAuthAuthorizationRequiredError, tool_name: str | None = None
|
|
250
|
+
) -> str:
|
|
251
|
+
"""Worded like the Go handlers: list-sub-tools has no auth-code or state, so it points at service-execute."""
|
|
252
|
+
next_step = (
|
|
253
|
+
"then call service-execute with the auth-code and state parameters to complete the flow."
|
|
254
|
+
if tool_name == "list-sub-tools"
|
|
255
|
+
else "then call this tool again with the auth-code and state parameters."
|
|
256
|
+
)
|
|
257
|
+
return (
|
|
258
|
+
"This secret requires OAuth authorization. "
|
|
259
|
+
"Please open the following URL in your browser to authorize, "
|
|
260
|
+
f"{next_step}\n\n"
|
|
261
|
+
f"Authorization URL: {error.authorization_url}\nState: {error.state}"
|
|
262
|
+
)
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"""Authenticate to Akeyless from Cloud Run (GCP service account first)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import time
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from datetime import datetime, timezone
|
|
8
|
+
|
|
9
|
+
import akeyless
|
|
10
|
+
from akeyless_cloud_id import CloudId
|
|
11
|
+
|
|
12
|
+
from akeyless_cloudrun_rta.config import AkeylessRtaConfig
|
|
13
|
+
|
|
14
|
+
ACCESS_KEY_DEFAULT_TTL_SECONDS = 14 * 60
|
|
15
|
+
ENV_TOKEN_TTL_SECONDS = 50 * 60
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass
|
|
19
|
+
class AuthSession:
|
|
20
|
+
token: str
|
|
21
|
+
expires_at: float
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _expiry_from_auth_output(auth_out: akeyless.AuthOutput, margin_seconds: float) -> float:
|
|
25
|
+
now = time.monotonic()
|
|
26
|
+
expiration = getattr(auth_out, "expiration", None)
|
|
27
|
+
if not expiration:
|
|
28
|
+
return now + ACCESS_KEY_DEFAULT_TTL_SECONDS - margin_seconds
|
|
29
|
+
|
|
30
|
+
raw = str(expiration).strip()
|
|
31
|
+
if not raw:
|
|
32
|
+
return now + ACCESS_KEY_DEFAULT_TTL_SECONDS - margin_seconds
|
|
33
|
+
|
|
34
|
+
try:
|
|
35
|
+
as_num = float(raw)
|
|
36
|
+
if as_num > 1e12:
|
|
37
|
+
return (as_num / 1000.0) - time.time() + now - margin_seconds
|
|
38
|
+
except ValueError:
|
|
39
|
+
pass
|
|
40
|
+
|
|
41
|
+
try:
|
|
42
|
+
as_date = datetime.fromisoformat(raw.replace("Z", "+00:00"))
|
|
43
|
+
if as_date.tzinfo is None:
|
|
44
|
+
as_date = as_date.replace(tzinfo=timezone.utc)
|
|
45
|
+
return as_date.timestamp() - time.time() + now - margin_seconds
|
|
46
|
+
except ValueError:
|
|
47
|
+
pass
|
|
48
|
+
|
|
49
|
+
return now + ACCESS_KEY_DEFAULT_TTL_SECONDS - margin_seconds
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def get_gcp_cloud_id(config: AkeylessRtaConfig) -> str:
|
|
53
|
+
"""Cloud ID from the service account's ID token (Cloud Run metadata server)."""
|
|
54
|
+
if config.cloud_id and config.cloud_id.strip():
|
|
55
|
+
return config.cloud_id.strip()
|
|
56
|
+
|
|
57
|
+
try:
|
|
58
|
+
cloud_id = CloudId().generateGcp(audience=config.gcp_audience)
|
|
59
|
+
except Exception as exc:
|
|
60
|
+
raise ValueError(
|
|
61
|
+
"Could not obtain a GCP ID token for Akeyless authentication "
|
|
62
|
+
f"({type(exc).__name__}). On Cloud Run, check that the service has a "
|
|
63
|
+
"service account attached; locally, run `gcloud auth application-default login` "
|
|
64
|
+
"with a service account or set AKEYLESS_CLOUD_ID."
|
|
65
|
+
) from exc
|
|
66
|
+
if not cloud_id or not str(cloud_id).strip():
|
|
67
|
+
raise ValueError("akeyless-cloud-id returned an empty GCP cloud ID")
|
|
68
|
+
return str(cloud_id).strip()
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def create_v2_api(sdk_gateway_url: str, ca_bundle: str | None = None) -> akeyless.V2Api:
|
|
72
|
+
"""Create V2Api pointed at the customer Gateway SDK base (…/api/v2)."""
|
|
73
|
+
configuration = akeyless.Configuration(host=sdk_gateway_url.rstrip("/"))
|
|
74
|
+
if ca_bundle:
|
|
75
|
+
configuration.ssl_ca_cert = ca_bundle
|
|
76
|
+
return akeyless.V2Api(akeyless.ApiClient(configuration))
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def authenticate(api: akeyless.V2Api, config: AkeylessRtaConfig) -> AuthSession:
|
|
80
|
+
now = time.monotonic()
|
|
81
|
+
|
|
82
|
+
if config.token and config.token.strip():
|
|
83
|
+
return AuthSession(
|
|
84
|
+
token=config.token.strip(),
|
|
85
|
+
expires_at=now + ENV_TOKEN_TTL_SECONDS,
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
access_type = config.access_type
|
|
89
|
+
|
|
90
|
+
if access_type == "gcp":
|
|
91
|
+
body = akeyless.Auth(
|
|
92
|
+
access_id=config.access_id,
|
|
93
|
+
access_type="gcp",
|
|
94
|
+
cloud_id=get_gcp_cloud_id(config),
|
|
95
|
+
gcp_audience=config.gcp_audience,
|
|
96
|
+
)
|
|
97
|
+
elif access_type in ("access_key", "api_key"):
|
|
98
|
+
body = akeyless.Auth(
|
|
99
|
+
access_id=config.access_id,
|
|
100
|
+
access_type="access_key",
|
|
101
|
+
access_key=config.access_key,
|
|
102
|
+
)
|
|
103
|
+
elif access_type == "universal_identity":
|
|
104
|
+
body = akeyless.Auth(
|
|
105
|
+
access_type="universal_identity",
|
|
106
|
+
uid_token=config.uid_token,
|
|
107
|
+
)
|
|
108
|
+
elif access_type == "jwt":
|
|
109
|
+
body = akeyless.Auth(
|
|
110
|
+
access_id=config.access_id,
|
|
111
|
+
access_type="jwt",
|
|
112
|
+
jwt=config.jwt,
|
|
113
|
+
)
|
|
114
|
+
else:
|
|
115
|
+
raise ValueError(f"Unsupported access type: {access_type}")
|
|
116
|
+
|
|
117
|
+
auth_out = api.auth(body)
|
|
118
|
+
token = getattr(auth_out, "token", None)
|
|
119
|
+
if not token or not str(token).strip():
|
|
120
|
+
raise ValueError("Akeyless authentication did not return a token")
|
|
121
|
+
|
|
122
|
+
return AuthSession(
|
|
123
|
+
token=str(token).strip(),
|
|
124
|
+
expires_at=_expiry_from_auth_output(auth_out, config.token_expiry_margin_seconds),
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def build_gateway_auth_header(session: AuthSession | str) -> dict[str, str]:
|
|
129
|
+
"""Authorization header for Gateway ARA config-port calls."""
|
|
130
|
+
token = session if isinstance(session, str) else session.token
|
|
131
|
+
trimmed = token.strip()
|
|
132
|
+
if not trimmed:
|
|
133
|
+
raise ValueError("Unable to build gateway authorization header: empty token")
|
|
134
|
+
return {"Authorization": f"Bearer {trimmed}"}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""Caller identity from the ID token that Cloud Run IAM already verified.
|
|
2
|
+
|
|
3
|
+
Cloud Run checks the invoker's Google ID token before the request reaches the
|
|
4
|
+
container and may strip its signature when forwarding, so the payload is only
|
|
5
|
+
decoded here, never verified. The result is audit metadata for the Gateway
|
|
6
|
+
(``original_user``), not an access-control decision: access control is Cloud Run
|
|
7
|
+
IAM (``roles/run.invoker``) plus the Akeyless role of the service account.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import base64
|
|
13
|
+
import json
|
|
14
|
+
from collections.abc import Mapping
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
SERVERLESS_AUTH_HEADER = "x-serverless-authorization"
|
|
18
|
+
AUTH_HEADER = "authorization"
|
|
19
|
+
MAX_IDENTITY_LENGTH = 256
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _jwt_payload(token: str) -> dict[str, Any] | None:
|
|
23
|
+
parts = token.split(".")
|
|
24
|
+
if len(parts) < 2 or not parts[1]:
|
|
25
|
+
return None
|
|
26
|
+
segment = parts[1] + "=" * (-len(parts[1]) % 4)
|
|
27
|
+
try:
|
|
28
|
+
decoded = json.loads(base64.urlsafe_b64decode(segment.encode("ascii")))
|
|
29
|
+
except (ValueError, UnicodeError):
|
|
30
|
+
return None
|
|
31
|
+
return decoded if isinstance(decoded, dict) else None
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _bearer(value: str | None) -> str | None:
|
|
35
|
+
if not value:
|
|
36
|
+
return None
|
|
37
|
+
scheme, _, token = value.strip().partition(" ")
|
|
38
|
+
if scheme.lower() != "bearer" or not token.strip():
|
|
39
|
+
return None
|
|
40
|
+
return token.strip()
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def caller_identity_from_headers(headers: Mapping[str, str] | None) -> str | None:
|
|
44
|
+
"""Return the invoker's email (or subject) from the Cloud Run auth headers."""
|
|
45
|
+
if not headers:
|
|
46
|
+
return None
|
|
47
|
+
lowered = {str(k).lower(): v for k, v in headers.items()}
|
|
48
|
+
for header in (SERVERLESS_AUTH_HEADER, AUTH_HEADER):
|
|
49
|
+
token = _bearer(lowered.get(header))
|
|
50
|
+
if not token:
|
|
51
|
+
continue
|
|
52
|
+
payload = _jwt_payload(token)
|
|
53
|
+
if not payload:
|
|
54
|
+
continue
|
|
55
|
+
identity = payload.get("email") or payload.get("sub")
|
|
56
|
+
if isinstance(identity, str) and identity.strip():
|
|
57
|
+
return identity.strip()[:MAX_IDENTITY_LENGTH]
|
|
58
|
+
return None
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def merge_original_user(agent_supplied: str | None, caller: str | None) -> str | None:
|
|
62
|
+
"""Combine the agent-reported end user with the IAM-verified caller for audit."""
|
|
63
|
+
if caller and agent_supplied and agent_supplied != caller:
|
|
64
|
+
return f"{agent_supplied} (via {caller})"
|
|
65
|
+
return caller or agent_supplied
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
"""Akeyless RTA/ARA client for agents on Google Cloud Run."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import time
|
|
6
|
+
from typing import Any, Callable
|
|
7
|
+
|
|
8
|
+
import akeyless
|
|
9
|
+
|
|
10
|
+
from akeyless_cloudrun_rta.ara import (
|
|
11
|
+
ARA_LIST_ITEM_TYPES,
|
|
12
|
+
AraSecretSummary,
|
|
13
|
+
map_ara_secrets,
|
|
14
|
+
)
|
|
15
|
+
from akeyless_cloudrun_rta.auth import (
|
|
16
|
+
AuthSession,
|
|
17
|
+
authenticate,
|
|
18
|
+
build_gateway_auth_header,
|
|
19
|
+
create_v2_api,
|
|
20
|
+
)
|
|
21
|
+
from akeyless_cloudrun_rta.config import AkeylessRtaConfig, config_from_env, validate_config
|
|
22
|
+
from akeyless_cloudrun_rta.http_ara import (
|
|
23
|
+
ListSubToolsResult,
|
|
24
|
+
TargetQueryResult,
|
|
25
|
+
post_list_sub_tools,
|
|
26
|
+
post_target_query,
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
HttpOpener = Callable[..., Any]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class AkeylessRtaClient:
|
|
33
|
+
"""Secretless ARA client: list eligible secrets and run query/execute via Gateway."""
|
|
34
|
+
|
|
35
|
+
def __init__(
|
|
36
|
+
self,
|
|
37
|
+
*,
|
|
38
|
+
_http_opener: HttpOpener | None = None,
|
|
39
|
+
_api: akeyless.V2Api | None = None,
|
|
40
|
+
**config_overrides: Any,
|
|
41
|
+
) -> None:
|
|
42
|
+
self._config = config_from_env(**config_overrides)
|
|
43
|
+
validate_config(self._config)
|
|
44
|
+
self._api = _api or create_v2_api(self._config.gateway_url, self._config.ca_bundle)
|
|
45
|
+
self._session: AuthSession | None = None
|
|
46
|
+
self._http_opener = _http_opener
|
|
47
|
+
|
|
48
|
+
@classmethod
|
|
49
|
+
def from_env(cls, **overrides: Any) -> AkeylessRtaClient:
|
|
50
|
+
return cls(**overrides)
|
|
51
|
+
|
|
52
|
+
@property
|
|
53
|
+
def config(self) -> AkeylessRtaConfig:
|
|
54
|
+
return self._config
|
|
55
|
+
|
|
56
|
+
def _get_session(self) -> AuthSession:
|
|
57
|
+
now = time.monotonic()
|
|
58
|
+
if self._session and now < self._session.expires_at:
|
|
59
|
+
return self._session
|
|
60
|
+
self._session = authenticate(self._api, self._config)
|
|
61
|
+
return self._session
|
|
62
|
+
|
|
63
|
+
def _get_token(self) -> str:
|
|
64
|
+
return self._get_session().token
|
|
65
|
+
|
|
66
|
+
def _gateway_auth_header(self) -> dict[str, str]:
|
|
67
|
+
return build_gateway_auth_header(self._get_session())
|
|
68
|
+
|
|
69
|
+
def list_secrets(self, path: str | None = None) -> list[AraSecretSummary]:
|
|
70
|
+
"""List ARA-enabled secrets (metadata only — never values)."""
|
|
71
|
+
token = self._get_token()
|
|
72
|
+
kwargs: dict[str, Any] = {
|
|
73
|
+
"token": token,
|
|
74
|
+
"filter": "",
|
|
75
|
+
"type": list(ARA_LIST_ITEM_TYPES),
|
|
76
|
+
"ara_only": True,
|
|
77
|
+
"advanced_filter": "",
|
|
78
|
+
}
|
|
79
|
+
trimmed = (path or "").strip()
|
|
80
|
+
if trimmed:
|
|
81
|
+
kwargs["path"] = trimmed
|
|
82
|
+
|
|
83
|
+
result = self._api.list_items(akeyless.ListItems(**kwargs))
|
|
84
|
+
items = getattr(result, "items", None) or []
|
|
85
|
+
return map_ara_secrets(list(items))
|
|
86
|
+
|
|
87
|
+
def _resolve_secret_name(self, secret_name: str | None) -> str:
|
|
88
|
+
name = (secret_name or self._config.default_secret_name or "").strip()
|
|
89
|
+
if not name:
|
|
90
|
+
raise ValueError(
|
|
91
|
+
"secret_name is required (or configure AKEYLESS_DEFAULT_SECRET_NAME)"
|
|
92
|
+
)
|
|
93
|
+
return name
|
|
94
|
+
|
|
95
|
+
def query_db(
|
|
96
|
+
self,
|
|
97
|
+
payload: str,
|
|
98
|
+
*,
|
|
99
|
+
secret_name: str | None = None,
|
|
100
|
+
agent_id: str | None = None,
|
|
101
|
+
original_user: str | None = None,
|
|
102
|
+
original_prompt: str | None = None,
|
|
103
|
+
auth_code: str | None = None,
|
|
104
|
+
state: str | None = None,
|
|
105
|
+
) -> TargetQueryResult:
|
|
106
|
+
"""Run a database query via Gateway ARA (credentials never returned)."""
|
|
107
|
+
resolved = self._resolve_secret_name(secret_name)
|
|
108
|
+
return self._execute_target_query(
|
|
109
|
+
secret_name=resolved,
|
|
110
|
+
payload=payload,
|
|
111
|
+
agent_id=agent_id,
|
|
112
|
+
original_user=original_user,
|
|
113
|
+
original_prompt=original_prompt,
|
|
114
|
+
auth_code=auth_code,
|
|
115
|
+
state=state,
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
def service_execute(
|
|
119
|
+
self,
|
|
120
|
+
payload: str,
|
|
121
|
+
*,
|
|
122
|
+
secret_name: str | None = None,
|
|
123
|
+
agent_id: str | None = None,
|
|
124
|
+
original_user: str | None = None,
|
|
125
|
+
original_prompt: str | None = None,
|
|
126
|
+
auth_code: str | None = None,
|
|
127
|
+
state: str | None = None,
|
|
128
|
+
) -> TargetQueryResult:
|
|
129
|
+
"""Run a cloud/K8s/GitHub/custom-MCP action, or a remote command on an SSH/Windows/LDAP host, via Gateway ARA.
|
|
130
|
+
|
|
131
|
+
For a remote item the payload is a plain command line, or a sub-tool call such as
|
|
132
|
+
``{"tool":"run","arguments":{"command":"uptime","host":"web1","cwd":"/"}}``.
|
|
133
|
+
"""
|
|
134
|
+
resolved = self._resolve_secret_name(secret_name)
|
|
135
|
+
return self._execute_target_query(
|
|
136
|
+
secret_name=resolved,
|
|
137
|
+
payload=payload,
|
|
138
|
+
agent_id=agent_id,
|
|
139
|
+
original_user=original_user,
|
|
140
|
+
original_prompt=original_prompt,
|
|
141
|
+
auth_code=auth_code,
|
|
142
|
+
state=state,
|
|
143
|
+
)
|
|
144
|
+
|
|
145
|
+
def _execute_target_query(
|
|
146
|
+
self,
|
|
147
|
+
*,
|
|
148
|
+
secret_name: str,
|
|
149
|
+
payload: str,
|
|
150
|
+
agent_id: str | None,
|
|
151
|
+
original_user: str | None,
|
|
152
|
+
original_prompt: str | None,
|
|
153
|
+
auth_code: str | None,
|
|
154
|
+
state: str | None,
|
|
155
|
+
) -> TargetQueryResult:
|
|
156
|
+
body: dict[str, Any] = {
|
|
157
|
+
"secret_name": secret_name,
|
|
158
|
+
"payload": payload,
|
|
159
|
+
"agent_id": agent_id or self._config.agent_id,
|
|
160
|
+
"mcp_id": self._config.mcp_id,
|
|
161
|
+
}
|
|
162
|
+
if auth_code:
|
|
163
|
+
body["auth_code"] = auth_code
|
|
164
|
+
if state:
|
|
165
|
+
body["state"] = state
|
|
166
|
+
if original_user:
|
|
167
|
+
body["original_user"] = original_user
|
|
168
|
+
if original_prompt:
|
|
169
|
+
body["original_prompt"] = original_prompt
|
|
170
|
+
|
|
171
|
+
return post_target_query(
|
|
172
|
+
self._config.ara_gateway_url,
|
|
173
|
+
self._gateway_auth_header(),
|
|
174
|
+
body,
|
|
175
|
+
opener=self._http_opener,
|
|
176
|
+
ca_bundle=self._config.ca_bundle,
|
|
177
|
+
)
|
|
178
|
+
|
|
179
|
+
def list_sub_tools(
|
|
180
|
+
self,
|
|
181
|
+
*,
|
|
182
|
+
secret_name: str | None = None,
|
|
183
|
+
agent_id: str | None = None,
|
|
184
|
+
) -> ListSubToolsResult:
|
|
185
|
+
"""Discover sub-tools for a service secret or remote item (optional before service_execute)."""
|
|
186
|
+
resolved = self._resolve_secret_name(secret_name)
|
|
187
|
+
body = {
|
|
188
|
+
"secret_name": resolved,
|
|
189
|
+
"agent_id": agent_id or self._config.agent_id,
|
|
190
|
+
"mcp_id": self._config.mcp_id,
|
|
191
|
+
}
|
|
192
|
+
return post_list_sub_tools(
|
|
193
|
+
self._config.ara_gateway_url,
|
|
194
|
+
self._gateway_auth_header(),
|
|
195
|
+
body,
|
|
196
|
+
opener=self._http_opener,
|
|
197
|
+
ca_bundle=self._config.ca_bundle,
|
|
198
|
+
)
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
_default_client: AkeylessRtaClient | None = None
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def get_default_client(**overrides: Any) -> AkeylessRtaClient:
|
|
205
|
+
global _default_client
|
|
206
|
+
if overrides or _default_client is None:
|
|
207
|
+
_default_client = AkeylessRtaClient(**overrides)
|
|
208
|
+
return _default_client
|