confsync-client 0.1.0__tar.gz

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.
@@ -0,0 +1,7 @@
1
+ __pycache__/
2
+ *.pyc
3
+ .venv/
4
+ dist/
5
+ *.egg-info/
6
+ .env
7
+ .pytest_cache/
@@ -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,5 @@
1
+ # confsync-client
2
+
3
+ Client library and CLI for [confsync](https://github.com/Agony5757/confsync) — pull/push encrypted config documents.
4
+
5
+ See the repository root README for full documentation.
@@ -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__"]
@@ -0,0 +1,3 @@
1
+ from confsync.cli import main
2
+
3
+ main()
@@ -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()
@@ -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"]
@@ -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,25 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "confsync-client"
7
+ dynamic = ["version"]
8
+ description = "Client library and CLI for confsync — pull/push encrypted config documents"
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ dependencies = [
12
+ "httpx>=0.27",
13
+ ]
14
+
15
+ [project.optional-dependencies]
16
+ dev = ["pytest>=8"]
17
+
18
+ [project.scripts]
19
+ confsync = "confsync.cli:main"
20
+
21
+ [tool.hatch.version]
22
+ path = "confsync/__init__.py"
23
+
24
+ [tool.hatch.build.targets.wheel]
25
+ packages = ["confsync"]
@@ -0,0 +1,88 @@
1
+ import json
2
+
3
+ import httpx
4
+ import pytest
5
+
6
+ from confsync import ConfsyncClient, ConfsyncError, load_client, login
7
+ from confsync.core import validate_server_url
8
+
9
+
10
+ def test_validate_server_url():
11
+ assert validate_server_url("https://conf.example.com/") == "https://conf.example.com"
12
+ assert validate_server_url("http://localhost:8930") == "http://localhost:8930"
13
+ assert validate_server_url("http://127.0.0.1:8930") == "http://127.0.0.1:8930"
14
+ with pytest.raises(ConfsyncError):
15
+ validate_server_url("http://conf.example.com") # plaintext remote
16
+ with pytest.raises(ConfsyncError):
17
+ validate_server_url("not-a-url")
18
+
19
+
20
+ def test_credentials_roundtrip(tmp_path, monkeypatch):
21
+ creds = tmp_path / "credentials.json"
22
+ monkeypatch.setenv("CONFSYNC_CREDENTIALS", str(creds))
23
+ client = login("https://conf.example.com", "cs_" + "a" * 48, verify=False)
24
+ client.close()
25
+ assert creds.exists()
26
+ import stat as stat_mod
27
+ assert stat_mod.S_IMODE(creds.stat().st_mode) == 0o600
28
+
29
+ loaded = load_client()
30
+ assert loaded.server_url == "https://conf.example.com"
31
+ loaded.close()
32
+
33
+
34
+ def test_load_client_missing(tmp_path, monkeypatch):
35
+ monkeypatch.setenv("CONFSYNC_CREDENTIALS", str(tmp_path / "nope.json"))
36
+ with pytest.raises(ConfsyncError):
37
+ load_client()
38
+
39
+
40
+ def test_login_rejects_bad_key_format(tmp_path, monkeypatch):
41
+ monkeypatch.setenv("CONFSYNC_CREDENTIALS", str(tmp_path / "c.json"))
42
+ with pytest.raises(ConfsyncError):
43
+ login("https://conf.example.com", "not-a-cs-key", verify=False)
44
+
45
+
46
+ def _mock_app(request: httpx.Request) -> httpx.Response:
47
+ """Tiny in-memory confsync server for client tests."""
48
+ if request.headers.get("Authorization") != "Bearer cs_good":
49
+ return httpx.Response(401, json={"error": "invalid or revoked API key"})
50
+ store = _mock_app.store
51
+ if request.url.path == "/api/v1/whoami":
52
+ return httpx.Response(200, json={"login": "alice", "name": "Alice"})
53
+ if request.method == "PUT":
54
+ body = json.loads(request.content)
55
+ parts = request.url.path.split("/", 4) # /api/v1/documents/app/name
56
+ store[parts[3] + "/" + parts[4]] = body["content"]
57
+ return httpx.Response(200, json={"version": 1})
58
+ if request.method == "GET" and request.url.path.startswith("/api/v1/documents/"):
59
+ parts = request.url.path.split("/", 4)
60
+ key = parts[3] + "/" + parts[4]
61
+ if key not in store:
62
+ return httpx.Response(404, json={"error": "not found"})
63
+ return httpx.Response(200, json={"version": 1, "content": store[key]})
64
+ return httpx.Response(404, json={"error": "unknown"})
65
+
66
+
67
+ _mock_app.store = {}
68
+
69
+
70
+ def _mock_client() -> ConfsyncClient:
71
+ return ConfsyncClient("https://conf.example.com", "cs_good",
72
+ transport=httpx.MockTransport(_mock_app))
73
+
74
+
75
+ def test_client_push_pull_against_mock():
76
+ with _mock_client() as c:
77
+ assert c.whoami()["login"] == "alice"
78
+ assert c.push("app", "cfg.yaml", "a: 1") == 1
79
+ assert c.pull("app", "cfg.yaml") == "a: 1"
80
+ with pytest.raises(ConfsyncError):
81
+ c.pull("app", "missing")
82
+
83
+
84
+ def test_client_auth_error():
85
+ with ConfsyncClient("https://conf.example.com", "cs_bad",
86
+ transport=httpx.MockTransport(_mock_app)) as c:
87
+ with pytest.raises(ConfsyncError, match="invalid or revoked"):
88
+ c.whoami()