confsync-client 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.
- confsync/__init__.py +17 -0
- confsync/__main__.py +3 -0
- confsync/cli.py +148 -0
- confsync/core.py +108 -0
- confsync/credentials.py +59 -0
- confsync_client-0.1.0.dist-info/METADATA +15 -0
- confsync_client-0.1.0.dist-info/RECORD +9 -0
- confsync_client-0.1.0.dist-info/WHEEL +4 -0
- confsync_client-0.1.0.dist-info/entry_points.txt +2 -0
confsync/__init__.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""confsync client — pull/push encrypted config documents.
|
|
2
|
+
|
|
3
|
+
Typical usage from another project (e.g. flexgate):
|
|
4
|
+
|
|
5
|
+
from confsync import load_client
|
|
6
|
+
client = load_client() # shared ~/.confsync credentials
|
|
7
|
+
client.push(app="myapp", name="config.yaml", content=text)
|
|
8
|
+
text = client.pull(app="myapp", name="config.yaml")
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
__version__ = "0.1.0"
|
|
13
|
+
|
|
14
|
+
from confsync.core import ConfsyncClient, ConfsyncError
|
|
15
|
+
from confsync.credentials import load_client, login
|
|
16
|
+
|
|
17
|
+
__all__ = ["ConfsyncClient", "ConfsyncError", "load_client", "login", "__version__"]
|
confsync/__main__.py
ADDED
confsync/cli.py
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
"""confsync client CLI: login / push / pull / list / history."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import getpass
|
|
6
|
+
import sys
|
|
7
|
+
|
|
8
|
+
from confsync import __version__
|
|
9
|
+
from confsync.core import ConfsyncError
|
|
10
|
+
from confsync.credentials import get_credentials_path, load_client, login
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _fail(msg: str) -> None:
|
|
14
|
+
print(f"error: {msg}", file=sys.stderr)
|
|
15
|
+
sys.exit(1)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _client_or_die():
|
|
19
|
+
try:
|
|
20
|
+
return load_client()
|
|
21
|
+
except ConfsyncError as exc:
|
|
22
|
+
_fail(str(exc))
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def cmd_login(args: argparse.Namespace) -> None:
|
|
26
|
+
api_key = args.api_key
|
|
27
|
+
if not api_key:
|
|
28
|
+
print(f"Create an API key in the web UI: {args.server}/keys")
|
|
29
|
+
api_key = getpass.getpass("API key: ").strip()
|
|
30
|
+
try:
|
|
31
|
+
with login(args.server, api_key) as client:
|
|
32
|
+
who = client.whoami()
|
|
33
|
+
except ConfsyncError as exc:
|
|
34
|
+
_fail(str(exc))
|
|
35
|
+
print(f"Logged in as {who['login']} @ {args.server}")
|
|
36
|
+
print(f"Credentials saved to {get_credentials_path()}")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def cmd_push(args: argparse.Namespace) -> None:
|
|
40
|
+
try:
|
|
41
|
+
with open(args.file, encoding="utf-8") as f:
|
|
42
|
+
content = f.read()
|
|
43
|
+
except OSError as exc:
|
|
44
|
+
_fail(f"cannot read {args.file}: {exc}")
|
|
45
|
+
with _client_or_die() as client:
|
|
46
|
+
try:
|
|
47
|
+
version = client.push(args.app, args.name, content)
|
|
48
|
+
except ConfsyncError as exc:
|
|
49
|
+
_fail(str(exc))
|
|
50
|
+
print(f"pushed {args.app}/{args.name} → v{version}")
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def cmd_pull(args: argparse.Namespace) -> None:
|
|
54
|
+
with _client_or_die() as client:
|
|
55
|
+
try:
|
|
56
|
+
content = client.pull(args.app, args.name, version=args.version)
|
|
57
|
+
except ConfsyncError as exc:
|
|
58
|
+
_fail(str(exc))
|
|
59
|
+
if args.file:
|
|
60
|
+
with open(args.file, "w", encoding="utf-8") as f:
|
|
61
|
+
f.write(content)
|
|
62
|
+
print(f"wrote {args.app}/{args.name} → {args.file}")
|
|
63
|
+
else:
|
|
64
|
+
sys.stdout.write(content)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def cmd_list(args: argparse.Namespace) -> None:
|
|
68
|
+
with _client_or_die() as client:
|
|
69
|
+
try:
|
|
70
|
+
docs = client.list()
|
|
71
|
+
except ConfsyncError as exc:
|
|
72
|
+
_fail(str(exc))
|
|
73
|
+
if not docs:
|
|
74
|
+
print("no documents")
|
|
75
|
+
return
|
|
76
|
+
for d in docs:
|
|
77
|
+
print(f"{d['app']}/{d['name']} v{d['version']} {d['size']}B")
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def cmd_history(args: argparse.Namespace) -> None:
|
|
81
|
+
with _client_or_die() as client:
|
|
82
|
+
try:
|
|
83
|
+
rows = client.history(args.app, args.name)
|
|
84
|
+
except ConfsyncError as exc:
|
|
85
|
+
_fail(str(exc))
|
|
86
|
+
if not rows:
|
|
87
|
+
print("no history")
|
|
88
|
+
return
|
|
89
|
+
for r in rows:
|
|
90
|
+
print(f"v{r['version']} {r['size']}B saved {r['saved_at']:.0f}")
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def cmd_delete(args: argparse.Namespace) -> None:
|
|
94
|
+
with _client_or_die() as client:
|
|
95
|
+
try:
|
|
96
|
+
client.delete(args.app, args.name)
|
|
97
|
+
except ConfsyncError as exc:
|
|
98
|
+
_fail(str(exc))
|
|
99
|
+
print(f"deleted {args.app}/{args.name}")
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def main() -> None:
|
|
103
|
+
parser = argparse.ArgumentParser(
|
|
104
|
+
prog="confsync",
|
|
105
|
+
description="confsync client — sync config documents with a confsync server",
|
|
106
|
+
)
|
|
107
|
+
parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
|
|
108
|
+
sub = parser.add_subparsers(dest="group")
|
|
109
|
+
|
|
110
|
+
p = sub.add_parser("login", help="Save server URL + API key (shared credentials)")
|
|
111
|
+
p.add_argument("--server", required=True, help="e.g. https://confsync.example.com")
|
|
112
|
+
p.add_argument("--api-key", help="API key (cs_...); prompted if omitted")
|
|
113
|
+
|
|
114
|
+
p = sub.add_parser("push", help="Upload a file as a document")
|
|
115
|
+
p.add_argument("--app", required=True)
|
|
116
|
+
p.add_argument("--name", required=True)
|
|
117
|
+
p.add_argument("--file", required=True)
|
|
118
|
+
|
|
119
|
+
p = sub.add_parser("pull", help="Download a document (stdout or --file)")
|
|
120
|
+
p.add_argument("--app", required=True)
|
|
121
|
+
p.add_argument("--name", required=True)
|
|
122
|
+
p.add_argument("--file", help="Write to this path instead of stdout")
|
|
123
|
+
p.add_argument("--version", type=int, help="Pull a history version instead of latest")
|
|
124
|
+
|
|
125
|
+
sub.add_parser("list", help="List my documents")
|
|
126
|
+
|
|
127
|
+
p = sub.add_parser("history", help="List a document's version history")
|
|
128
|
+
p.add_argument("--app", required=True)
|
|
129
|
+
p.add_argument("--name", required=True)
|
|
130
|
+
|
|
131
|
+
p = sub.add_parser("delete", help="Delete a document and its history")
|
|
132
|
+
p.add_argument("--app", required=True)
|
|
133
|
+
p.add_argument("--name", required=True)
|
|
134
|
+
|
|
135
|
+
args = parser.parse_args()
|
|
136
|
+
handlers = {
|
|
137
|
+
"login": cmd_login, "push": cmd_push, "pull": cmd_pull,
|
|
138
|
+
"list": cmd_list, "history": cmd_history, "delete": cmd_delete,
|
|
139
|
+
}
|
|
140
|
+
handler = handlers.get(args.group or "")
|
|
141
|
+
if handler is None:
|
|
142
|
+
parser.print_help()
|
|
143
|
+
sys.exit(0)
|
|
144
|
+
handler(args)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
if __name__ == "__main__":
|
|
148
|
+
main()
|
confsync/core.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"""ConfsyncClient — thin synchronous wrapper over the confsync REST API."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from urllib.parse import quote, urlparse
|
|
5
|
+
|
|
6
|
+
import httpx
|
|
7
|
+
|
|
8
|
+
API_BASE = "/api/v1"
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class ConfsyncError(Exception):
|
|
12
|
+
"""Raised on any confsync server error (auth, not-found, network...)."""
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def validate_server_url(server_url: str) -> str:
|
|
16
|
+
"""Require https (plaintext http allowed only for localhost). Returns the
|
|
17
|
+
normalized URL (no trailing slash)."""
|
|
18
|
+
url = server_url.rstrip("/")
|
|
19
|
+
parsed = urlparse(url)
|
|
20
|
+
if parsed.scheme not in ("http", "https") or not parsed.netloc:
|
|
21
|
+
raise ConfsyncError(f"invalid server URL: {server_url!r}")
|
|
22
|
+
host = parsed.hostname or ""
|
|
23
|
+
if parsed.scheme == "http" and host not in ("localhost", "127.0.0.1", "::1"):
|
|
24
|
+
raise ConfsyncError(
|
|
25
|
+
f"refusing plaintext http for non-localhost server: {url}. "
|
|
26
|
+
"Use https (put the server behind a TLS reverse proxy)."
|
|
27
|
+
)
|
|
28
|
+
return url
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class ConfsyncClient:
|
|
32
|
+
def __init__(self, server_url: str, api_key: str, timeout: float = 30.0,
|
|
33
|
+
transport: httpx.BaseTransport | None = None):
|
|
34
|
+
self.server_url = validate_server_url(server_url)
|
|
35
|
+
# trust_env=False: never route through env-configured proxies —
|
|
36
|
+
# deterministic TLS to the configured server, no credential leakage
|
|
37
|
+
# through $ALL_PROXY/$HTTPS_PROXY.
|
|
38
|
+
self._client = httpx.Client(
|
|
39
|
+
base_url=self.server_url + API_BASE,
|
|
40
|
+
headers={"Authorization": f"Bearer {api_key}"},
|
|
41
|
+
timeout=timeout,
|
|
42
|
+
transport=transport,
|
|
43
|
+
trust_env=False,
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
def close(self) -> None:
|
|
47
|
+
self._client.close()
|
|
48
|
+
|
|
49
|
+
def __enter__(self) -> "ConfsyncClient":
|
|
50
|
+
return self
|
|
51
|
+
|
|
52
|
+
def __exit__(self, *exc) -> None:
|
|
53
|
+
self.close()
|
|
54
|
+
|
|
55
|
+
# ── low level ─────────────────────────────────────────────────
|
|
56
|
+
|
|
57
|
+
def _request(self, method: str, path: str, **kwargs) -> dict:
|
|
58
|
+
try:
|
|
59
|
+
resp = self._client.request(method, path, **kwargs)
|
|
60
|
+
except httpx.HTTPError as exc:
|
|
61
|
+
raise ConfsyncError(f"cannot reach {self.server_url}: {exc}") from exc
|
|
62
|
+
try:
|
|
63
|
+
data = resp.json()
|
|
64
|
+
except ValueError:
|
|
65
|
+
raise ConfsyncError(
|
|
66
|
+
f"unexpected response from server (HTTP {resp.status_code}): "
|
|
67
|
+
f"{resp.text[:200]}"
|
|
68
|
+
)
|
|
69
|
+
if resp.status_code >= 400:
|
|
70
|
+
raise ConfsyncError(data.get("error") or f"HTTP {resp.status_code}")
|
|
71
|
+
return data
|
|
72
|
+
|
|
73
|
+
@staticmethod
|
|
74
|
+
def _doc_path(app: str, name: str) -> str:
|
|
75
|
+
return f"/documents/{quote(app, safe='')}/{quote(name, safe='')}"
|
|
76
|
+
|
|
77
|
+
# ── public API ────────────────────────────────────────────────
|
|
78
|
+
|
|
79
|
+
def whoami(self) -> dict:
|
|
80
|
+
"""Verify the API key; returns {"login": ..., "name": ...}."""
|
|
81
|
+
return self._request("GET", "/whoami")
|
|
82
|
+
|
|
83
|
+
def list(self) -> list[dict]:
|
|
84
|
+
"""List my documents: [{app, name, version, updated_at, size}]."""
|
|
85
|
+
return self._request("GET", "/documents")["documents"]
|
|
86
|
+
|
|
87
|
+
def pull(self, app: str, name: str, version: int | None = None) -> str:
|
|
88
|
+
"""Fetch a document's plaintext content (latest or a history version)."""
|
|
89
|
+
path = self._doc_path(app, name)
|
|
90
|
+
if version is not None:
|
|
91
|
+
path += f"/history/{version}"
|
|
92
|
+
return self._request("GET", path)["content"]
|
|
93
|
+
|
|
94
|
+
def pull_meta(self, app: str, name: str) -> dict:
|
|
95
|
+
"""Full document record: {app, name, version, updated_at, content}."""
|
|
96
|
+
return self._request("GET", self._doc_path(app, name))
|
|
97
|
+
|
|
98
|
+
def push(self, app: str, name: str, content: str) -> int:
|
|
99
|
+
"""Store content as a new version; returns the new version number."""
|
|
100
|
+
data = self._request("PUT", self._doc_path(app, name), json={"content": content})
|
|
101
|
+
return int(data["version"])
|
|
102
|
+
|
|
103
|
+
def delete(self, app: str, name: str) -> None:
|
|
104
|
+
self._request("DELETE", self._doc_path(app, name))
|
|
105
|
+
|
|
106
|
+
def history(self, app: str, name: str) -> list[dict]:
|
|
107
|
+
"""[{version, saved_at, size}], newest first."""
|
|
108
|
+
return self._request("GET", self._doc_path(app, name) + "/history")["history"]
|
confsync/credentials.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"""Shared client credentials: ~/.confsync/credentials.json (mode 0600).
|
|
2
|
+
|
|
3
|
+
All apps that embed confsync (flexgate, your other repos, the CLI) read the
|
|
4
|
+
same credentials file, so ``confsync login`` once works everywhere. Override
|
|
5
|
+
the path with CONFSYNC_CREDENTIALS (used by tests).
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
|
|
12
|
+
from confsync.core import ConfsyncClient, ConfsyncError, validate_server_url
|
|
13
|
+
|
|
14
|
+
CREDENTIALS_ENV = "CONFSYNC_CREDENTIALS"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def get_credentials_path() -> str:
|
|
18
|
+
env = os.environ.get(CREDENTIALS_ENV, "").strip()
|
|
19
|
+
if env:
|
|
20
|
+
return env
|
|
21
|
+
return os.path.join(os.path.expanduser("~/.confsync"), "credentials.json")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def login(server_url: str, api_key: str, *, verify: bool = True) -> ConfsyncClient:
|
|
25
|
+
"""Validate and persist credentials; returns a ready client.
|
|
26
|
+
|
|
27
|
+
With verify=True (default) the key is checked against the server first.
|
|
28
|
+
"""
|
|
29
|
+
server_url = validate_server_url(server_url)
|
|
30
|
+
if not api_key.startswith("cs_"):
|
|
31
|
+
raise ConfsyncError("API keys start with 'cs_'; create one in the web UI (/keys).")
|
|
32
|
+
client = ConfsyncClient(server_url, api_key)
|
|
33
|
+
if verify:
|
|
34
|
+
client.whoami() # raises ConfsyncError on a bad key
|
|
35
|
+
|
|
36
|
+
path = get_credentials_path()
|
|
37
|
+
os.makedirs(os.path.dirname(path), exist_ok=True)
|
|
38
|
+
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
|
39
|
+
try:
|
|
40
|
+
os.write(fd, json.dumps({"server_url": server_url, "api_key": api_key},
|
|
41
|
+
indent=2).encode() + b"\n")
|
|
42
|
+
finally:
|
|
43
|
+
os.close(fd)
|
|
44
|
+
return client
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def load_client() -> ConfsyncClient:
|
|
48
|
+
"""Build a client from the shared credentials file."""
|
|
49
|
+
path = get_credentials_path()
|
|
50
|
+
if not os.path.exists(path):
|
|
51
|
+
raise ConfsyncError(
|
|
52
|
+
f"no credentials at {path}. Run: confsync login --server <url>"
|
|
53
|
+
)
|
|
54
|
+
with open(path) as f:
|
|
55
|
+
data = json.load(f)
|
|
56
|
+
try:
|
|
57
|
+
return ConfsyncClient(data["server_url"], data["api_key"])
|
|
58
|
+
except KeyError as exc:
|
|
59
|
+
raise ConfsyncError(f"credentials file {path} is missing {exc}") from exc
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: confsync-client
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Client library and CLI for confsync — pull/push encrypted config documents
|
|
5
|
+
Requires-Python: >=3.11
|
|
6
|
+
Requires-Dist: httpx>=0.27
|
|
7
|
+
Provides-Extra: dev
|
|
8
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
9
|
+
Description-Content-Type: text/markdown
|
|
10
|
+
|
|
11
|
+
# confsync-client
|
|
12
|
+
|
|
13
|
+
Client library and CLI for [confsync](https://github.com/Agony5757/confsync) — pull/push encrypted config documents.
|
|
14
|
+
|
|
15
|
+
See the repository root README for full documentation.
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
confsync/__init__.py,sha256=nu2omLqQyiumKDD9LzG6bk7lMf0v4Qm0iLgLkbFFSiE,609
|
|
2
|
+
confsync/__main__.py,sha256=_Pt03oKLiq6Kux9-oDMsa4SpJbbcAdRIBN5I9bhL09Y,38
|
|
3
|
+
confsync/cli.py,sha256=5vC4knibqRciqRpqSeTnlc6qwiinuc_cnKwCgvaDJi0,4738
|
|
4
|
+
confsync/core.py,sha256=Q2kVOw9LyI8qzfFWVE7rPUW0E7p5A7Ji1UdChn1AMQo,4374
|
|
5
|
+
confsync/credentials.py,sha256=ln7Le8N0cgcK1Q5oB3vZfzncRGDi7cmKn3cj3z4dNB4,2080
|
|
6
|
+
confsync_client-0.1.0.dist-info/METADATA,sha256=Zcy2wfUgKC3ti4CM2fZZFmfgaNMRcl2g_fRk2EcVt40,492
|
|
7
|
+
confsync_client-0.1.0.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
|
|
8
|
+
confsync_client-0.1.0.dist-info/entry_points.txt,sha256=4fcIftaxrxs337pGQevTglaOKm_XJ45h7N_mhy5kLRI,47
|
|
9
|
+
confsync_client-0.1.0.dist-info/RECORD,,
|