adxadmin 0.1.0rc1__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.
- adxadmin/__init__.py +1 -0
- adxadmin/cli.py +208 -0
- adxadmin/client.py +220 -0
- adxadmin/credentials.py +43 -0
- adxadmin/errors.py +34 -0
- adxadmin/py.typed +1 -0
- adxadmin-0.1.0rc1.dist-info/METADATA +45 -0
- adxadmin-0.1.0rc1.dist-info/RECORD +12 -0
- adxadmin-0.1.0rc1.dist-info/WHEEL +5 -0
- adxadmin-0.1.0rc1.dist-info/entry_points.txt +2 -0
- adxadmin-0.1.0rc1.dist-info/licenses/LICENSE +201 -0
- adxadmin-0.1.0rc1.dist-info/top_level.txt +1 -0
adxadmin/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""ADX remote administration client."""
|
adxadmin/cli.py
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
"""Command-line entry point for remote ADX administration."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import sys
|
|
7
|
+
import unicodedata
|
|
8
|
+
from collections.abc import Mapping, Sequence
|
|
9
|
+
from datetime import datetime, timezone
|
|
10
|
+
from importlib import metadata
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import TextIO
|
|
13
|
+
|
|
14
|
+
from .client import AdminClient, ClientOptions
|
|
15
|
+
from .credentials import read_token, write_secret
|
|
16
|
+
from .errors import AdminError
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def build_parser(environ: Mapping[str, str] | None = None) -> argparse.ArgumentParser:
|
|
20
|
+
values = os.environ if environ is None else environ
|
|
21
|
+
parser = argparse.ArgumentParser(
|
|
22
|
+
prog="adxadmin", description="Administer a remote ADX cluster"
|
|
23
|
+
)
|
|
24
|
+
parser.add_argument(
|
|
25
|
+
"--version", action="version", version=f"adxadmin {_package_version()}"
|
|
26
|
+
)
|
|
27
|
+
parser.add_argument(
|
|
28
|
+
"--endpoint",
|
|
29
|
+
default=values.get("ADX_ENDPOINT"),
|
|
30
|
+
required="ADX_ENDPOINT" not in values,
|
|
31
|
+
help="public ADX HTTPS origin (env: ADX_ENDPOINT)",
|
|
32
|
+
)
|
|
33
|
+
parser.add_argument(
|
|
34
|
+
"--ca",
|
|
35
|
+
dest="ca_file",
|
|
36
|
+
default=values.get("ADX_CA_FILE"),
|
|
37
|
+
help="additional PEM CA file (env: ADX_CA_FILE)",
|
|
38
|
+
)
|
|
39
|
+
parser.add_argument(
|
|
40
|
+
"--token-file",
|
|
41
|
+
type=Path,
|
|
42
|
+
default=values.get("ADX_ADMIN_TOKEN_FILE"),
|
|
43
|
+
required="ADX_ADMIN_TOKEN_FILE" not in values,
|
|
44
|
+
help="administrator API Key file (env: ADX_ADMIN_TOKEN_FILE)",
|
|
45
|
+
)
|
|
46
|
+
parser.add_argument(
|
|
47
|
+
"--verify-tls",
|
|
48
|
+
action="store_true",
|
|
49
|
+
help="verify the HTTPS certificate using system CAs; --ca also enables verification",
|
|
50
|
+
)
|
|
51
|
+
parser.add_argument(
|
|
52
|
+
"--output",
|
|
53
|
+
choices=("table", "json"),
|
|
54
|
+
default=values.get("ADX_ADMIN_OUTPUT", "table"),
|
|
55
|
+
)
|
|
56
|
+
parser.add_argument(
|
|
57
|
+
"--timeout-seconds",
|
|
58
|
+
type=float,
|
|
59
|
+
default=float(values.get("ADX_ADMIN_TIMEOUT_SECONDS", "30")),
|
|
60
|
+
)
|
|
61
|
+
parser.add_argument("--allow-loopback-http", action="store_true")
|
|
62
|
+
commands = parser.add_subparsers(dest="command", required=True)
|
|
63
|
+
key = commands.add_parser("key", help="manage tenant API Keys")
|
|
64
|
+
key_commands = key.add_subparsers(dest="key_command", required=True)
|
|
65
|
+
|
|
66
|
+
create = key_commands.add_parser("create", help="create a tenant API Key")
|
|
67
|
+
create.add_argument("--tenant", required=True)
|
|
68
|
+
expiry = create.add_mutually_exclusive_group()
|
|
69
|
+
expiry.add_argument("--expires-at", type=int, default=0)
|
|
70
|
+
expiry.add_argument("--no-expiry", action="store_true")
|
|
71
|
+
create.add_argument("--output-file", type=Path)
|
|
72
|
+
|
|
73
|
+
listing = key_commands.add_parser("list", help="list tenant Key metadata")
|
|
74
|
+
listing.add_argument("--tenant")
|
|
75
|
+
listing.add_argument("--page-size", type=int, default=100)
|
|
76
|
+
listing.add_argument("--page-token")
|
|
77
|
+
|
|
78
|
+
revoke = key_commands.add_parser("revoke", help="revoke a tenant Key")
|
|
79
|
+
revoke.add_argument("key_id")
|
|
80
|
+
return parser
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def run(
|
|
84
|
+
arguments: Sequence[str] | None = None,
|
|
85
|
+
*,
|
|
86
|
+
environ: Mapping[str, str] | None = None,
|
|
87
|
+
stdout: TextIO = sys.stdout,
|
|
88
|
+
) -> int:
|
|
89
|
+
options = build_parser(environ).parse_args(arguments)
|
|
90
|
+
token = read_token(Path(options.token_file))
|
|
91
|
+
client_options = ClientOptions(
|
|
92
|
+
endpoint=options.endpoint,
|
|
93
|
+
token=token,
|
|
94
|
+
timeout_seconds=options.timeout_seconds,
|
|
95
|
+
ca_file=options.ca_file,
|
|
96
|
+
allow_loopback_http=options.allow_loopback_http,
|
|
97
|
+
verify_tls=options.verify_tls,
|
|
98
|
+
)
|
|
99
|
+
with AdminClient(client_options) as client:
|
|
100
|
+
if options.key_command == "create":
|
|
101
|
+
created = client.create_key(options.tenant, options.expires_at)
|
|
102
|
+
if options.output_file:
|
|
103
|
+
write_secret(options.output_file, created["apiKey"])
|
|
104
|
+
created = {
|
|
105
|
+
"key": created["key"],
|
|
106
|
+
"outputFile": str(options.output_file),
|
|
107
|
+
}
|
|
108
|
+
_print_created(created, options.output, stdout)
|
|
109
|
+
elif options.key_command == "list":
|
|
110
|
+
page = client.list_keys(
|
|
111
|
+
tenant=options.tenant,
|
|
112
|
+
page_size=options.page_size,
|
|
113
|
+
page_token=options.page_token,
|
|
114
|
+
)
|
|
115
|
+
_print_page(page, options.output, stdout)
|
|
116
|
+
else:
|
|
117
|
+
client.revoke_key(options.key_id)
|
|
118
|
+
_print({"revoked": options.key_id}, options.output, stdout)
|
|
119
|
+
return 0
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def main() -> None:
|
|
123
|
+
try:
|
|
124
|
+
raise SystemExit(run())
|
|
125
|
+
except AdminError as error:
|
|
126
|
+
print(f"adxadmin: {error}", file=sys.stderr)
|
|
127
|
+
raise SystemExit(1) from error
|
|
128
|
+
except OSError as error:
|
|
129
|
+
print(f"adxadmin: {error}", file=sys.stderr)
|
|
130
|
+
raise SystemExit(1) from error
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _print_created(value: dict, output: str, stream: TextIO) -> None:
|
|
134
|
+
if output == "json":
|
|
135
|
+
_print(value, output, stream)
|
|
136
|
+
return
|
|
137
|
+
_print_key_table([value["key"]], stream)
|
|
138
|
+
if "apiKey" in value:
|
|
139
|
+
print(f"API_KEY\t{value['apiKey']}", file=stream)
|
|
140
|
+
elif "outputFile" in value:
|
|
141
|
+
print(f"OUTPUT_FILE\t{value['outputFile']}", file=stream)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _print_page(value: dict, output: str, stream: TextIO) -> None:
|
|
145
|
+
if output == "json":
|
|
146
|
+
_print(value, output, stream)
|
|
147
|
+
return
|
|
148
|
+
_print_key_table(value["items"], stream)
|
|
149
|
+
if value["nextPageToken"]:
|
|
150
|
+
print(f"NEXT_PAGE_TOKEN\t{value['nextPageToken']}", file=stream)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _display_width(value: str) -> int:
|
|
154
|
+
return sum(
|
|
155
|
+
0
|
|
156
|
+
if unicodedata.combining(char)
|
|
157
|
+
else 2
|
|
158
|
+
if unicodedata.east_asian_width(char) in ("W", "F")
|
|
159
|
+
else 1
|
|
160
|
+
for char in value
|
|
161
|
+
)
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _print_key_table(keys: Sequence[dict], stream: TextIO) -> None:
|
|
165
|
+
rows = [["ID", "TENANT", "EXPIRES_AT"]]
|
|
166
|
+
rows.extend(
|
|
167
|
+
[key["id"], key["tenantId"], _expiry(key["expiresAtUnixSeconds"])]
|
|
168
|
+
for key in keys
|
|
169
|
+
)
|
|
170
|
+
widths = [max(_display_width(row[column]) for row in rows) for column in range(3)]
|
|
171
|
+
for row in rows:
|
|
172
|
+
cells = [
|
|
173
|
+
row[index] + " " * (widths[index] - _display_width(row[index]))
|
|
174
|
+
for index in range(2)
|
|
175
|
+
]
|
|
176
|
+
print(" ".join([*cells, row[2]]), file=stream)
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _print(value: dict, output: str, stream: TextIO) -> None:
|
|
180
|
+
if output == "json":
|
|
181
|
+
print(json.dumps(value, separators=(",", ":")), file=stream)
|
|
182
|
+
else:
|
|
183
|
+
for key, item in value.items():
|
|
184
|
+
print(f"{key.upper()}\t{item}", file=stream)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def _expiry(value: int) -> str:
|
|
188
|
+
if value == 0:
|
|
189
|
+
return "never"
|
|
190
|
+
try:
|
|
191
|
+
return (
|
|
192
|
+
datetime.fromtimestamp(value, timezone.utc)
|
|
193
|
+
.astimezone()
|
|
194
|
+
.isoformat(sep=" ", timespec="seconds")
|
|
195
|
+
)
|
|
196
|
+
except (OverflowError, OSError, ValueError):
|
|
197
|
+
return f"{value} (outside date range)"
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def _package_version() -> str:
|
|
201
|
+
try:
|
|
202
|
+
return metadata.version("adxadmin")
|
|
203
|
+
except metadata.PackageNotFoundError:
|
|
204
|
+
return "source"
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
if __name__ == "__main__":
|
|
208
|
+
main()
|
adxadmin/client.py
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
"""Typed boundary over the public ADX administration HTTP API."""
|
|
2
|
+
|
|
3
|
+
import ipaddress
|
|
4
|
+
import re
|
|
5
|
+
import uuid
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from typing import Any
|
|
8
|
+
from urllib.parse import urlsplit
|
|
9
|
+
|
|
10
|
+
import httpx
|
|
11
|
+
from typing_extensions import Self
|
|
12
|
+
|
|
13
|
+
from .errors import ApiError, InvalidInput
|
|
14
|
+
|
|
15
|
+
KEY_PATH = "/api/admin/v1/keys"
|
|
16
|
+
KEY_ID = re.compile(r"^[0-9a-fA-F]{64}$")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass
|
|
20
|
+
class ClientOptions:
|
|
21
|
+
endpoint: str
|
|
22
|
+
token: str
|
|
23
|
+
timeout_seconds: float = 30.0
|
|
24
|
+
ca_file: str | None = None
|
|
25
|
+
allow_loopback_http: bool = False
|
|
26
|
+
verify_tls: bool = False
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class AdminClient:
|
|
30
|
+
def __init__(
|
|
31
|
+
self,
|
|
32
|
+
options: ClientOptions,
|
|
33
|
+
*,
|
|
34
|
+
transport: httpx.BaseTransport | None = None,
|
|
35
|
+
) -> None:
|
|
36
|
+
self._endpoint = _validate_endpoint(options.endpoint, options.allow_loopback_http)
|
|
37
|
+
_validate_secret(options.token, "administrator API Key")
|
|
38
|
+
if options.timeout_seconds <= 0:
|
|
39
|
+
raise InvalidInput("request timeout must be positive")
|
|
40
|
+
self._token = options.token
|
|
41
|
+
self._client = httpx.Client(
|
|
42
|
+
base_url=self._endpoint,
|
|
43
|
+
timeout=options.timeout_seconds,
|
|
44
|
+
verify=options.ca_file or options.verify_tls,
|
|
45
|
+
follow_redirects=False,
|
|
46
|
+
transport=transport,
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
def __enter__(self) -> Self:
|
|
50
|
+
return self
|
|
51
|
+
|
|
52
|
+
def __exit__(self, *_unused: object) -> None:
|
|
53
|
+
self.close()
|
|
54
|
+
|
|
55
|
+
def close(self) -> None:
|
|
56
|
+
self._client.close()
|
|
57
|
+
|
|
58
|
+
def create_key(self, tenant: str, expires_at: int = 0) -> dict[str, Any]:
|
|
59
|
+
if (
|
|
60
|
+
not tenant.strip()
|
|
61
|
+
or len(tenant) > 256
|
|
62
|
+
or any(ord(character) < 32 or ord(character) == 127 for character in tenant)
|
|
63
|
+
):
|
|
64
|
+
raise InvalidInput("tenant must be nonempty, bounded and contain no controls")
|
|
65
|
+
if expires_at < 0:
|
|
66
|
+
raise InvalidInput("expiry must be a Unix timestamp or zero")
|
|
67
|
+
response = self._request(
|
|
68
|
+
"POST",
|
|
69
|
+
KEY_PATH,
|
|
70
|
+
json={
|
|
71
|
+
"tenantId": tenant,
|
|
72
|
+
"expiresAtUnixSeconds": expires_at,
|
|
73
|
+
},
|
|
74
|
+
)
|
|
75
|
+
value = self._json(response, 201)
|
|
76
|
+
key = _metadata(value.get("key"))
|
|
77
|
+
if key["tenantId"] != tenant:
|
|
78
|
+
raise InvalidInput("create response tenant does not match the request")
|
|
79
|
+
secret = value.get("apiKey")
|
|
80
|
+
if not isinstance(secret, str):
|
|
81
|
+
raise InvalidInput("server returned an invalid API Key secret")
|
|
82
|
+
_validate_secret(secret, "server API Key")
|
|
83
|
+
return {"key": key, "apiKey": secret}
|
|
84
|
+
|
|
85
|
+
def list_keys(
|
|
86
|
+
self,
|
|
87
|
+
*,
|
|
88
|
+
tenant: str | None = None,
|
|
89
|
+
page_size: int = 100,
|
|
90
|
+
page_token: str | None = None,
|
|
91
|
+
) -> dict[str, Any]:
|
|
92
|
+
if not 1 <= page_size <= 1000:
|
|
93
|
+
raise InvalidInput("page size must be between 1 and 1000")
|
|
94
|
+
parameters: dict[str, str | int] = {"pageSize": page_size}
|
|
95
|
+
if tenant:
|
|
96
|
+
parameters["tenantId"] = tenant
|
|
97
|
+
if page_token:
|
|
98
|
+
parameters["pageToken"] = page_token
|
|
99
|
+
value = self._json(self._request("GET", KEY_PATH, params=parameters), 200)
|
|
100
|
+
items = value.get("items")
|
|
101
|
+
next_page_token = value.get("nextPageToken")
|
|
102
|
+
if not isinstance(items, list) or not isinstance(next_page_token, str):
|
|
103
|
+
raise InvalidInput("server returned an invalid Key page")
|
|
104
|
+
metadata = [_metadata(item) for item in items]
|
|
105
|
+
if tenant and any(item["tenantId"] != tenant for item in metadata):
|
|
106
|
+
raise InvalidInput("list response contains another tenant")
|
|
107
|
+
return {"items": metadata, "nextPageToken": next_page_token}
|
|
108
|
+
|
|
109
|
+
def revoke_key(self, key_id: str) -> None:
|
|
110
|
+
if not KEY_ID.fullmatch(key_id):
|
|
111
|
+
raise InvalidInput("Key ID must be a 64-character hexadecimal digest")
|
|
112
|
+
self._expect(self._request("DELETE", f"{KEY_PATH}/{key_id}"), 204)
|
|
113
|
+
|
|
114
|
+
def _request(self, method: str, path: str, **kwargs: Any) -> httpx.Response:
|
|
115
|
+
headers = {
|
|
116
|
+
"Authorization": f"Bearer {self._token}",
|
|
117
|
+
"X-Request-ID": str(uuid.uuid4()),
|
|
118
|
+
}
|
|
119
|
+
try:
|
|
120
|
+
return self._client.request(method, path, headers=headers, **kwargs)
|
|
121
|
+
except httpx.HTTPError as error:
|
|
122
|
+
raise InvalidInput(f"HTTP request failed: {error}") from error
|
|
123
|
+
|
|
124
|
+
@staticmethod
|
|
125
|
+
def _expect(response: httpx.Response, status: int) -> None:
|
|
126
|
+
if response.status_code != status:
|
|
127
|
+
raise _api_error(response)
|
|
128
|
+
|
|
129
|
+
@classmethod
|
|
130
|
+
def _json(cls, response: httpx.Response, status: int) -> dict[str, Any]:
|
|
131
|
+
cls._expect(response, status)
|
|
132
|
+
try:
|
|
133
|
+
value = response.json()
|
|
134
|
+
except ValueError as error:
|
|
135
|
+
raise InvalidInput("server returned invalid JSON") from error
|
|
136
|
+
if not isinstance(value, dict):
|
|
137
|
+
raise InvalidInput("server returned invalid JSON")
|
|
138
|
+
return value
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _validate_endpoint(endpoint: str, allow_loopback_http: bool) -> str:
|
|
142
|
+
parsed = urlsplit(endpoint)
|
|
143
|
+
endpoint_origin_invalid = (
|
|
144
|
+
not parsed.hostname
|
|
145
|
+
or parsed.username
|
|
146
|
+
or parsed.password
|
|
147
|
+
or parsed.query
|
|
148
|
+
or parsed.fragment
|
|
149
|
+
or parsed.path not in ("", "/")
|
|
150
|
+
)
|
|
151
|
+
if endpoint_origin_invalid:
|
|
152
|
+
raise InvalidInput("endpoint must be an origin URL without credentials, path, query or fragment")
|
|
153
|
+
if parsed.scheme == "https":
|
|
154
|
+
return endpoint.rstrip("/")
|
|
155
|
+
if parsed.scheme == "http" and allow_loopback_http and _is_loopback(parsed.hostname):
|
|
156
|
+
return endpoint.rstrip("/")
|
|
157
|
+
if parsed.scheme == "http":
|
|
158
|
+
raise InvalidInput("plaintext endpoint is permitted only for loopback with --allow-loopback-http")
|
|
159
|
+
raise InvalidInput("endpoint must use https")
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _is_loopback(host: str) -> bool:
|
|
163
|
+
if host.lower() == "localhost":
|
|
164
|
+
return True
|
|
165
|
+
try:
|
|
166
|
+
return ipaddress.ip_address(host).is_loopback
|
|
167
|
+
except ValueError:
|
|
168
|
+
return False
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _metadata(value: object) -> dict[str, Any]:
|
|
172
|
+
if not isinstance(value, dict):
|
|
173
|
+
raise InvalidInput("server returned invalid Key metadata")
|
|
174
|
+
key_id = value.get("id")
|
|
175
|
+
tenant = value.get("tenantId")
|
|
176
|
+
expires_at = value.get("expiresAtUnixSeconds")
|
|
177
|
+
key_metadata_invalid = (
|
|
178
|
+
not isinstance(key_id, str)
|
|
179
|
+
or not KEY_ID.fullmatch(key_id)
|
|
180
|
+
or not isinstance(tenant, str)
|
|
181
|
+
or not tenant.strip()
|
|
182
|
+
or len(tenant) > 256
|
|
183
|
+
or any(ord(character) < 32 or ord(character) == 127 for character in tenant)
|
|
184
|
+
or not isinstance(expires_at, int)
|
|
185
|
+
or isinstance(expires_at, bool)
|
|
186
|
+
or expires_at < 0
|
|
187
|
+
)
|
|
188
|
+
if key_metadata_invalid:
|
|
189
|
+
raise InvalidInput("server returned invalid Key metadata")
|
|
190
|
+
return {
|
|
191
|
+
"id": key_id,
|
|
192
|
+
"tenantId": tenant,
|
|
193
|
+
"expiresAtUnixSeconds": expires_at,
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _validate_secret(secret: str, kind: str) -> None:
|
|
198
|
+
if not 32 <= len(secret) <= 512 or any(ord(character) < 33 or ord(character) == 127 for character in secret):
|
|
199
|
+
raise InvalidInput(f"{kind} must contain 32..512 non-whitespace characters")
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _api_error(response: httpx.Response) -> ApiError:
|
|
203
|
+
try:
|
|
204
|
+
body = response.json()
|
|
205
|
+
except ValueError:
|
|
206
|
+
body = {}
|
|
207
|
+
if not isinstance(body, dict):
|
|
208
|
+
body = {}
|
|
209
|
+
detail = body.get("error")
|
|
210
|
+
if not isinstance(detail, dict):
|
|
211
|
+
detail = {}
|
|
212
|
+
request_id = detail.get("requestId") or response.headers.get("x-request-id") or "unknown"
|
|
213
|
+
return ApiError(
|
|
214
|
+
response.status_code,
|
|
215
|
+
str(body.get("message") or "request failed"),
|
|
216
|
+
code=str(detail.get("code") or "UNKNOWN"),
|
|
217
|
+
retry=str(detail.get("retry") or "UNKNOWN"),
|
|
218
|
+
outcome=str(detail.get("outcome") or "UNKNOWN"),
|
|
219
|
+
request_id=str(request_id),
|
|
220
|
+
)
|
adxadmin/credentials.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""Read and write administrator credentials without silent permission widening."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import stat
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from .errors import InvalidInput
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def read_token(path: Path) -> str:
|
|
11
|
+
metadata = path.stat()
|
|
12
|
+
if os.name == "posix" and stat.S_IMODE(metadata.st_mode) & 0o077:
|
|
13
|
+
raise InvalidInput(
|
|
14
|
+
f"administrator Key file {path} must have mode 0600 or stricter"
|
|
15
|
+
)
|
|
16
|
+
token = path.read_text(encoding="utf-8").strip()
|
|
17
|
+
_validate_secret(token, "administrator API Key")
|
|
18
|
+
return token
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def write_secret(path: Path, secret: str) -> None:
|
|
22
|
+
_validate_secret(secret, "API Key")
|
|
23
|
+
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
24
|
+
descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
|
25
|
+
try:
|
|
26
|
+
with os.fdopen(descriptor, "w", encoding="utf-8") as stream:
|
|
27
|
+
stream.write(secret)
|
|
28
|
+
stream.write("\n")
|
|
29
|
+
stream.flush()
|
|
30
|
+
os.fsync(stream.fileno())
|
|
31
|
+
except BaseException:
|
|
32
|
+
try:
|
|
33
|
+
os.close(descriptor)
|
|
34
|
+
except OSError:
|
|
35
|
+
pass
|
|
36
|
+
raise
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _validate_secret(secret: str, kind: str) -> None:
|
|
40
|
+
if not 32 <= len(secret) <= 512 or any(
|
|
41
|
+
ord(character) < 33 or ord(character) == 127 for character in secret
|
|
42
|
+
):
|
|
43
|
+
raise InvalidInput(f"{kind} must contain 32..512 non-whitespace characters")
|
adxadmin/errors.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Stable client-side administration errors."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class AdminError(Exception):
|
|
5
|
+
"""Base error for failures reported by ``adxadmin``."""
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class InvalidInput(AdminError):
|
|
9
|
+
"""A local argument, endpoint or credential is invalid."""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class ApiError(AdminError):
|
|
13
|
+
"""A structured non-success response returned by ADX."""
|
|
14
|
+
|
|
15
|
+
def __init__(
|
|
16
|
+
self,
|
|
17
|
+
status: int,
|
|
18
|
+
message: str,
|
|
19
|
+
*,
|
|
20
|
+
code: str = "UNKNOWN",
|
|
21
|
+
retry: str = "UNKNOWN",
|
|
22
|
+
outcome: str = "UNKNOWN",
|
|
23
|
+
request_id: str = "unknown",
|
|
24
|
+
) -> None:
|
|
25
|
+
self.status = status
|
|
26
|
+
self.message = message
|
|
27
|
+
self.code = code
|
|
28
|
+
self.retry = retry
|
|
29
|
+
self.outcome = outcome
|
|
30
|
+
self.request_id = request_id
|
|
31
|
+
super().__init__(
|
|
32
|
+
f"ADX returned HTTP {status}: {message} "
|
|
33
|
+
f"[code={code}, retry={retry}, outcome={outcome}, request_id={request_id}]"
|
|
34
|
+
)
|
adxadmin/py.typed
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: adxadmin
|
|
3
|
+
Version: 0.1.0rc1
|
|
4
|
+
Summary: Remote administration client for Agent DX
|
|
5
|
+
License-Expression: Apache-2.0
|
|
6
|
+
Project-URL: Repository, https://gitcode.com/openJiuwen/agent-dx
|
|
7
|
+
Project-URL: Documentation, https://gitcode.com/openJiuwen/agent-dx/blob/refactor/docs/deployment/adxadmin.md
|
|
8
|
+
Classifier: Development Status :: 3 - Alpha
|
|
9
|
+
Classifier: Environment :: Console
|
|
10
|
+
Classifier: Operating System :: OS Independent
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Requires-Python: >=3.10
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
License-File: LICENSE
|
|
20
|
+
Requires-Dist: httpx<1,>=0.24
|
|
21
|
+
Requires-Dist: typing-extensions<5,>=4
|
|
22
|
+
Dynamic: license-file
|
|
23
|
+
|
|
24
|
+
# adxadmin
|
|
25
|
+
|
|
26
|
+
`adxadmin` manages an ADX cluster through its public HTTPS administration API.
|
|
27
|
+
|
|
28
|
+
```sh
|
|
29
|
+
pipx install ./adxadmin-0.1.0rc1-py3-none-any.whl
|
|
30
|
+
adxadmin key create --tenant team-a
|
|
31
|
+
adxadmin key list --tenant team-a
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
HTTPS certificate and hostname verification is skipped by default; HTTPS and
|
|
35
|
+
administrator API Key authentication are still required for remote endpoints.
|
|
36
|
+
Pass `--verify-tls` to trust system CAs, or `--ca` to enable verification with a
|
|
37
|
+
PEM CA file.
|
|
38
|
+
|
|
39
|
+
Table output aligns columns by display width. Key expiration is shown as a
|
|
40
|
+
local date and time with a UTC offset (or `never`). JSON output and
|
|
41
|
+
`--expires-at` retain Unix seconds for automation.
|
|
42
|
+
|
|
43
|
+
See the
|
|
44
|
+
[administration guide](https://gitcode.com/openJiuwen/agent-dx/blob/refactor/docs/deployment/adxadmin.md)
|
|
45
|
+
for connection, credential, output and retry semantics.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
adxadmin/__init__.py,sha256=kweBbYCIwYyorhB2WNf-5DDaJ8Djv-CrjqvqDSh5UQE,40
|
|
2
|
+
adxadmin/cli.py,sha256=4B-E-iD2dF8bQKMrZ4BZ_KSc7VpcA0N9Pyd_Eca7RrM,6868
|
|
3
|
+
adxadmin/client.py,sha256=ueEoFGmKpwD0VlkAEe0NKNeVAb1N7oktatBqGk2yF54,7769
|
|
4
|
+
adxadmin/credentials.py,sha256=C20Hy3EeJNAzN6Aklu9l6FtwtXouGpU9rT8R5fgvvYI,1372
|
|
5
|
+
adxadmin/errors.py,sha256=N6YKYJafWA9mBBDkK9eetYSZRVeCCVnzSqxUfpUhfls,921
|
|
6
|
+
adxadmin/py.typed,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
|
|
7
|
+
adxadmin-0.1.0rc1.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
|
|
8
|
+
adxadmin-0.1.0rc1.dist-info/METADATA,sha256=dBhlZ__5I389kuLotwCbLcvBnpcRsqsK5v1eiW0k_AQ,1762
|
|
9
|
+
adxadmin-0.1.0rc1.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
|
|
10
|
+
adxadmin-0.1.0rc1.dist-info/entry_points.txt,sha256=HKGkh3wFb1DTPNZ_yYvlf-KdzGISPrIpev-xGILdkjA,47
|
|
11
|
+
adxadmin-0.1.0rc1.dist-info/top_level.txt,sha256=TRt21FpaqixQzlaeKjBCo67h75BX-5k8CAmqrd3waR4,9
|
|
12
|
+
adxadmin-0.1.0rc1.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.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
adxadmin
|