confsync-client 0.1.0__tar.gz → 0.2.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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: confsync-client
3
- Version: 0.1.0
3
+ Version: 0.2.0
4
4
  Summary: Client library and CLI for confsync — pull/push encrypted config documents
5
5
  Requires-Python: >=3.11
6
6
  Requires-Dist: httpx>=0.27
@@ -9,7 +9,7 @@ Typical usage from another project (e.g. flexgate):
9
9
  """
10
10
  from __future__ import annotations
11
11
 
12
- __version__ = "0.1.0"
12
+ __version__ = "0.2.0"
13
13
 
14
14
  from confsync.core import ConfsyncClient, ConfsyncError
15
15
  from confsync.credentials import load_client, login
@@ -0,0 +1,296 @@
1
+ """confsync client CLI: login / push / pull / list / history / help."""
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
+ HELP_TOPICS = {
19
+ "auth": """\
20
+ confsync help: auth — logging in
21
+
22
+ confsync login --server https://confsync.example.com [--api-key KEY]
23
+
24
+ Credentials are saved to ~/.confsync/credentials.json (mode 0600) and shared
25
+ by every tool that imports confsync. Override the path with
26
+ $CONFSYNC_CREDENTIALS. Re-login anytime; logout = delete the file.
27
+
28
+ Two kinds of credentials are accepted:
29
+
30
+ 1. API key (cs_...) Create one in the web UI under /keys. Shown once;
31
+ only its hash is stored server-side.
32
+ 2. Gitea access token If the server has Gitea configured, paste a token
33
+ from Gitea (Settings -> Applications -> Access
34
+ Tokens, scope read:user is enough). The server
35
+ verifies it against your Gitea (cached ~5 min) and
36
+ maps it to the confsync user with the same login.
37
+
38
+ Requires client >= 0.2.0 for Gitea tokens (older clients insist on cs_ keys).\
39
+ """,
40
+
41
+ "upgrade": """\
42
+ confsync help: upgrade — upgrading client and server
43
+
44
+ Client:
45
+ CLI users pip install -U confsync-client
46
+ (or: uv tool upgrade confsync-client)
47
+ Embedded apps put confsync-client>=0.2.0 in your app's dependencies
48
+ After upgrading nothing else changes: credentials file and REST API are
49
+ stable across versions — no re-login needed.
50
+
51
+ Compatibility matrix:
52
+ client 0.1.x <-> server 0.2.x works (API unchanged)
53
+ Gitea-token login needs client >= 0.2.0 AND server >= 0.2.0
54
+
55
+ Check what the server runs:
56
+ curl https://<server>/api/v1/version
57
+
58
+ Server upgrade (Docker): see MIGRATION.md in the confsync repository —
59
+ backup (confsync-server backup), update code, docker compose up -d --build,
60
+ verify /api/v1/version. DB schema migrations apply automatically on start.\
61
+ """,
62
+
63
+ "api": """\
64
+ confsync help: api — REST reference (all under /api/v1)
65
+
66
+ Auth: Authorization: Bearer <cs_-key or Gitea access token>
67
+
68
+ GET /version public server version
69
+ GET /whoami verify the credential
70
+ GET /documents list documents
71
+ GET /documents/{app}/{name} pull -> {content, version, ...}
72
+ PUT /documents/{app}/{name} push body: {"content": "..."}
73
+ DELETE /documents/{app}/{name} delete (removes history too)
74
+ GET /documents/{app}/{name}/history version list
75
+ GET /documents/{app}/{name}/history/{version} fetch old version
76
+
77
+ Limits: 4 MB per document; last 20 versions kept. Python shortcut:
78
+
79
+ from confsync import load_client
80
+ with load_client() as c:
81
+ c.push(app="myapp", name="config.yaml", content=text)
82
+ text = c.pull(app="myapp", name="config.yaml")\
83
+ """,
84
+
85
+ "server": """\
86
+ confsync help: server — deployment pointers
87
+
88
+ The server is a small Starlette app, deployed with docker compose behind an
89
+ nginx TLS proxy. Everything lives in deploy/ of the confsync repository:
90
+
91
+ cd deploy && docker compose up -d --build
92
+
93
+ Main env vars (deploy/.env):
94
+ CONFSYNC_EXTERNAL_URL public https URL (OAuth callbacks)
95
+ CONFSYNC_GITHUB_CLIENT_ID/SECRET GitHub OAuth (web UI login)
96
+ CONFSYNC_GITEA_URL/CLIENT_ID/SECRET self-hosted Gitea login (optional)
97
+ CONFSYNC_ALLOWED_USERS comma-separated login allowlist
98
+ CONFSYNC_MASTER_KEY base64 AES key (else auto-generated in /data)
99
+
100
+ State (the confsync-data volume, /data in the container):
101
+ server.db SQLite; documents stored AES-256-GCM encrypted
102
+ master.key server-side encryption key (0600) — losing it loses all docs
103
+
104
+ First user to log in becomes admin. Hot backup before upgrades:
105
+ confsync-server backup\
106
+ """,
107
+
108
+ "troubleshooting": """\
109
+ confsync help: troubleshooting
110
+
111
+ "no credentials at ..." not logged in — run confsync login
112
+ 401 invalid or revoked API key wrong key, or it was revoked in the web UI
113
+ 401 Gitea rejected the access token
114
+ token revoked/expired in Gitea; the server
115
+ caches verifications for ~5 min
116
+ 403 ... not on the allowlist admin must add your login under /admin
117
+ "refusing plaintext http ..." the server must be https (localhost excepted
118
+ for tests) — put it behind a TLS proxy
119
+ "cannot reach <server>" network/DNS/TLS problem; confsync never uses
120
+ $HTTP(S)_PROXY, check direct connectivity
121
+ push 413 document exceeds the 4 MB limit
122
+
123
+ Server-side: docker logs confsync-server; version via
124
+ curl https://<server>/api/v1/version; backups via confsync-server backup.\
125
+ """,
126
+ }
127
+
128
+ HELP_OVERVIEW = f"""\
129
+ confsync {__version__} — sync config documents with a confsync server
130
+
131
+ Quick start:
132
+ confsync login --server https://confsync.example.com # cs_ key or Gitea token
133
+ confsync push --app myapp --name config.yaml --file path/to/file
134
+ confsync pull --app myapp --name config.yaml # to stdout
135
+ confsync list
136
+
137
+ Commands: login, push, pull, list, history, delete, help
138
+
139
+ Topics (confsync help <topic>):
140
+ auth logging in: API keys and Gitea access tokens
141
+ upgrade upgrading client/server and compatibility notes
142
+ api REST API reference
143
+ server server deployment pointers (Docker, env, data)
144
+ troubleshooting common errors and fixes\
145
+ """
146
+
147
+
148
+ def cmd_help(args: argparse.Namespace) -> None:
149
+ topic = args.topic
150
+ if topic is None:
151
+ print(HELP_OVERVIEW)
152
+ return
153
+ text = HELP_TOPICS.get(topic)
154
+ if text is None:
155
+ _fail(f"unknown help topic: {topic!r}\n"
156
+ f"available: {', '.join(HELP_TOPICS)}")
157
+ print(text)
158
+
159
+
160
+ def _client_or_die():
161
+ try:
162
+ return load_client()
163
+ except ConfsyncError as exc:
164
+ _fail(str(exc))
165
+
166
+
167
+ def cmd_login(args: argparse.Namespace) -> None:
168
+ api_key = args.api_key
169
+ if not api_key:
170
+ print(f"Create an API key in the web UI ({args.server}/keys), or use a "
171
+ "Gitea access token if the server has Gitea configured.")
172
+ api_key = getpass.getpass("API key / Gitea token: ").strip()
173
+ try:
174
+ with login(args.server, api_key) as client:
175
+ who = client.whoami()
176
+ except ConfsyncError as exc:
177
+ _fail(str(exc))
178
+ print(f"Logged in as {who['login']} @ {args.server}")
179
+ print(f"Credentials saved to {get_credentials_path()}")
180
+
181
+
182
+ def cmd_push(args: argparse.Namespace) -> None:
183
+ try:
184
+ with open(args.file, encoding="utf-8") as f:
185
+ content = f.read()
186
+ except OSError as exc:
187
+ _fail(f"cannot read {args.file}: {exc}")
188
+ with _client_or_die() as client:
189
+ try:
190
+ version = client.push(args.app, args.name, content)
191
+ except ConfsyncError as exc:
192
+ _fail(str(exc))
193
+ print(f"pushed {args.app}/{args.name} → v{version}")
194
+
195
+
196
+ def cmd_pull(args: argparse.Namespace) -> None:
197
+ with _client_or_die() as client:
198
+ try:
199
+ content = client.pull(args.app, args.name, version=args.version)
200
+ except ConfsyncError as exc:
201
+ _fail(str(exc))
202
+ if args.file:
203
+ with open(args.file, "w", encoding="utf-8") as f:
204
+ f.write(content)
205
+ print(f"wrote {args.app}/{args.name} → {args.file}")
206
+ else:
207
+ sys.stdout.write(content)
208
+
209
+
210
+ def cmd_list(args: argparse.Namespace) -> None:
211
+ with _client_or_die() as client:
212
+ try:
213
+ docs = client.list()
214
+ except ConfsyncError as exc:
215
+ _fail(str(exc))
216
+ if not docs:
217
+ print("no documents")
218
+ return
219
+ for d in docs:
220
+ print(f"{d['app']}/{d['name']} v{d['version']} {d['size']}B")
221
+
222
+
223
+ def cmd_history(args: argparse.Namespace) -> None:
224
+ with _client_or_die() as client:
225
+ try:
226
+ rows = client.history(args.app, args.name)
227
+ except ConfsyncError as exc:
228
+ _fail(str(exc))
229
+ if not rows:
230
+ print("no history")
231
+ return
232
+ for r in rows:
233
+ print(f"v{r['version']} {r['size']}B saved {r['saved_at']:.0f}")
234
+
235
+
236
+ def cmd_delete(args: argparse.Namespace) -> None:
237
+ with _client_or_die() as client:
238
+ try:
239
+ client.delete(args.app, args.name)
240
+ except ConfsyncError as exc:
241
+ _fail(str(exc))
242
+ print(f"deleted {args.app}/{args.name}")
243
+
244
+
245
+ def main() -> None:
246
+ parser = argparse.ArgumentParser(
247
+ prog="confsync",
248
+ description="confsync client — sync config documents with a confsync server",
249
+ )
250
+ parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
251
+ sub = parser.add_subparsers(dest="group")
252
+
253
+ p = sub.add_parser("login", help="Save server URL + API key (shared credentials)")
254
+ p.add_argument("--server", required=True, help="e.g. https://confsync.example.com")
255
+ p.add_argument("--api-key", help="API key (cs_...); prompted if omitted")
256
+
257
+ p = sub.add_parser("push", help="Upload a file as a document")
258
+ p.add_argument("--app", required=True)
259
+ p.add_argument("--name", required=True)
260
+ p.add_argument("--file", required=True)
261
+
262
+ p = sub.add_parser("pull", help="Download a document (stdout or --file)")
263
+ p.add_argument("--app", required=True)
264
+ p.add_argument("--name", required=True)
265
+ p.add_argument("--file", help="Write to this path instead of stdout")
266
+ p.add_argument("--version", type=int, help="Pull a history version instead of latest")
267
+
268
+ sub.add_parser("list", help="List my documents")
269
+
270
+ p = sub.add_parser("history", help="List a document's version history")
271
+ p.add_argument("--app", required=True)
272
+ p.add_argument("--name", required=True)
273
+
274
+ p = sub.add_parser("delete", help="Delete a document and its history")
275
+ p.add_argument("--app", required=True)
276
+ p.add_argument("--name", required=True)
277
+
278
+ hlp = sub.add_parser("help", help="Show help topics and how-tos")
279
+ hlp.add_argument("topic", nargs="?",
280
+ help=f"one of: {', '.join(HELP_TOPICS)}")
281
+
282
+ args = parser.parse_args()
283
+ handlers = {
284
+ "login": cmd_login, "push": cmd_push, "pull": cmd_pull,
285
+ "list": cmd_list, "history": cmd_history, "delete": cmd_delete,
286
+ "help": cmd_help,
287
+ }
288
+ handler = handlers.get(args.group or "")
289
+ if handler is None:
290
+ parser.print_help()
291
+ sys.exit(0)
292
+ handler(args)
293
+
294
+
295
+ if __name__ == "__main__":
296
+ main()
@@ -25,10 +25,12 @@ def login(server_url: str, api_key: str, *, verify: bool = True) -> ConfsyncClie
25
25
  """Validate and persist credentials; returns a ready client.
26
26
 
27
27
  With verify=True (default) the key is checked against the server first.
28
+ The key may be a confsync API key (``cs_…``) or, when the server has
29
+ Gitea configured, a Gitea access token.
28
30
  """
29
31
  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
+ if not api_key.strip():
33
+ raise ConfsyncError("empty API key/token")
32
34
  client = ConfsyncClient(server_url, api_key)
33
35
  if verify:
34
36
  client.whoami() # raises ConfsyncError on a bad key
@@ -0,0 +1,52 @@
1
+ """CLI `confsync help [topic]` — offline help docs."""
2
+ import sys
3
+
4
+ import pytest
5
+
6
+ from confsync import cli
7
+ from confsync.cli import HELP_OVERVIEW, HELP_TOPICS
8
+
9
+
10
+ def _run(argv, monkeypatch):
11
+ monkeypatch.setattr(sys, "argv", ["confsync"] + argv)
12
+ cli.main()
13
+
14
+
15
+ def test_help_overview(monkeypatch, capsys):
16
+ _run(["help"], monkeypatch)
17
+ out = capsys.readouterr().out
18
+ assert "Quick start" in out
19
+ assert "confsync login" in out
20
+ for topic in HELP_TOPICS:
21
+ assert topic in out
22
+
23
+
24
+ def test_help_every_topic(monkeypatch, capsys):
25
+ for topic, text in HELP_TOPICS.items():
26
+ _run(["help", topic], monkeypatch)
27
+ out = capsys.readouterr().out
28
+ assert text.splitlines()[0] in out
29
+
30
+
31
+ def test_help_auth_mentions_both_credential_kinds():
32
+ assert "cs_" in HELP_TOPICS["auth"]
33
+ assert "Gitea access token" in HELP_TOPICS["auth"]
34
+
35
+
36
+ def test_help_upgrade_mentions_compatibility():
37
+ assert "0.2.0" in HELP_TOPICS["upgrade"]
38
+ assert "/api/v1/version" in HELP_TOPICS["upgrade"]
39
+
40
+
41
+ def test_help_unknown_topic_fails_with_list(monkeypatch, capsys):
42
+ with pytest.raises(SystemExit) as exc:
43
+ _run(["help", "nope"], monkeypatch)
44
+ assert exc.value.code == 1
45
+ err = capsys.readouterr().err
46
+ assert "unknown help topic" in err
47
+ assert ", ".join(HELP_TOPICS) in err
48
+
49
+
50
+ def test_overview_lists_commands():
51
+ for cmd in ("login", "push", "pull", "list", "history", "delete"):
52
+ assert cmd in HELP_OVERVIEW
@@ -37,10 +37,20 @@ def test_load_client_missing(tmp_path, monkeypatch):
37
37
  load_client()
38
38
 
39
39
 
40
- def test_login_rejects_bad_key_format(tmp_path, monkeypatch):
40
+ def test_login_accepts_gitea_token(tmp_path, monkeypatch):
41
+ # non-cs_ credentials are fine: the server (whoami) decides whether it is
42
+ # a valid confsync API key or a Gitea access token.
43
+ creds = tmp_path / "c.json"
44
+ monkeypatch.setenv("CONFSYNC_CREDENTIALS", str(creds))
45
+ client = login("https://conf.example.com", "gt-e2e-token", verify=False)
46
+ client.close()
47
+ assert json.loads(creds.read_text())["api_key"] == "gt-e2e-token"
48
+
49
+
50
+ def test_login_rejects_empty_key(tmp_path, monkeypatch):
41
51
  monkeypatch.setenv("CONFSYNC_CREDENTIALS", str(tmp_path / "c.json"))
42
52
  with pytest.raises(ConfsyncError):
43
- login("https://conf.example.com", "not-a-cs-key", verify=False)
53
+ login("https://conf.example.com", " ", verify=False)
44
54
 
45
55
 
46
56
  def _mock_app(request: httpx.Request) -> httpx.Response:
@@ -1,148 +0,0 @@
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()