tickwire-cli 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.
Files changed (35) hide show
  1. tickwire_cli-0.1.0/LICENSE +21 -0
  2. tickwire_cli-0.1.0/PKG-INFO +93 -0
  3. tickwire_cli-0.1.0/README.md +62 -0
  4. tickwire_cli-0.1.0/pyproject.toml +51 -0
  5. tickwire_cli-0.1.0/setup.cfg +4 -0
  6. tickwire_cli-0.1.0/tests/test_against_controlplane.py +283 -0
  7. tickwire_cli-0.1.0/tests/test_credentials.py +90 -0
  8. tickwire_cli-0.1.0/tests/test_login.py +94 -0
  9. tickwire_cli-0.1.0/tests/test_logs.py +373 -0
  10. tickwire_cli-0.1.0/tests/test_packaging.py +49 -0
  11. tickwire_cli-0.1.0/tests/test_readme.py +37 -0
  12. tickwire_cli-0.1.0/tests/test_review_regressions.py +97 -0
  13. tickwire_cli-0.1.0/tests/test_sandbox_create.py +59 -0
  14. tickwire_cli-0.1.0/tests/test_trade.py +155 -0
  15. tickwire_cli-0.1.0/tickwire_cli/__init__.py +4 -0
  16. tickwire_cli-0.1.0/tickwire_cli/__main__.py +14 -0
  17. tickwire_cli-0.1.0/tickwire_cli/_version.py +1 -0
  18. tickwire_cli-0.1.0/tickwire_cli/app.py +174 -0
  19. tickwire_cli-0.1.0/tickwire_cli/commands/__init__.py +11 -0
  20. tickwire_cli-0.1.0/tickwire_cli/commands/accounts.py +51 -0
  21. tickwire_cli-0.1.0/tickwire_cli/commands/login.py +81 -0
  22. tickwire_cli-0.1.0/tickwire_cli/commands/logs.py +272 -0
  23. tickwire_cli-0.1.0/tickwire_cli/commands/sandbox.py +74 -0
  24. tickwire_cli-0.1.0/tickwire_cli/commands/trade.py +153 -0
  25. tickwire_cli-0.1.0/tickwire_cli/commands/trigger.py +44 -0
  26. tickwire_cli-0.1.0/tickwire_cli/commands/webhooks_listen.py +112 -0
  27. tickwire_cli-0.1.0/tickwire_cli/credentials.py +259 -0
  28. tickwire_cli-0.1.0/tickwire_cli/errors.py +6 -0
  29. tickwire_cli-0.1.0/tickwire_cli/output.py +96 -0
  30. tickwire_cli-0.1.0/tickwire_cli.egg-info/PKG-INFO +93 -0
  31. tickwire_cli-0.1.0/tickwire_cli.egg-info/SOURCES.txt +33 -0
  32. tickwire_cli-0.1.0/tickwire_cli.egg-info/dependency_links.txt +1 -0
  33. tickwire_cli-0.1.0/tickwire_cli.egg-info/entry_points.txt +2 -0
  34. tickwire_cli-0.1.0/tickwire_cli.egg-info/requires.txt +8 -0
  35. tickwire_cli-0.1.0/tickwire_cli.egg-info/top_level.txt +1 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Tickwire
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,93 @@
1
+ Metadata-Version: 2.4
2
+ Name: tickwire-cli
3
+ Version: 0.1.0
4
+ Summary: Tickwire CLI: sign in, create a sandbox, list accounts, trade with a reason and a truthful outcome, and forward webhooks to localhost, for the Tickwire MT4/MT5 cloud API.
5
+ Author-email: Tickwire <hello@tickwire.io>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://tickwire.io/
8
+ Project-URL: Documentation, https://tickwire.io/docs/cli/
9
+ Project-URL: Changelog, https://tickwire.io/docs/changelog/
10
+ Keywords: metatrader,mt4,mt5,trading,api,cli,webhooks
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Environment :: Console
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Office/Business :: Financial :: Investment
21
+ Requires-Python: >=3.11
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Requires-Dist: tickwire<0.2,>=0.1.0
25
+ Requires-Dist: httpx<1,>=0.27
26
+ Provides-Extra: keyring
27
+ Requires-Dist: keyring<26,>=24; extra == "keyring"
28
+ Provides-Extra: dev
29
+ Requires-Dist: pytest>=8.0; extra == "dev"
30
+ Dynamic: license-file
31
+
32
+ # tickwire-cli
33
+
34
+ The `tickwire` command for the Tickwire MT4/MT5 cloud API, built on the
35
+ [`tickwire` Python SDK](https://tickwire.io/docs/sdk-python/).
36
+
37
+ **Not published yet.** `pip install tickwire-cli` won't find it. Install from source, from the
38
+ repository root (the SDK first, because the CLI needs it):
39
+
40
+ ```sh
41
+ pip install ./sdk/python ./cli
42
+ ```
43
+
44
+ Once it is published:
45
+
46
+ ```sh
47
+ pip install tickwire-cli # or "tickwire-cli[keyring]" to keep keys in the OS keychain
48
+ ```
49
+
50
+ Python 3.11 or newer. MIT licensed.
51
+
52
+ ## Quick start
53
+
54
+ A free sandbox (no sign-in, no card) against the public API:
55
+
56
+ ```sh
57
+ export TICKWIRE_SANDBOX_URL=https://api.tickwire.io
58
+ tickwire sandbox create # one simulated MT5 account; the key is stored, never printed
59
+ tickwire --sandbox accounts list
60
+ tickwire --sandbox trade open <account-id> --side buy --symbol EURUSD --volume 0.01 --reason "test"
61
+ ```
62
+
63
+ With your own API key:
64
+
65
+ ```sh
66
+ export TICKWIRE_API_URL=https://api.tickwire.io
67
+ tickwire login # hidden prompt; the key is checked, then stored
68
+ tickwire accounts list
69
+ tickwire listen --forward-to http://localhost:3000/webhooks
70
+ tickwire trigger trade.outcome
71
+ tickwire logs tail -f --status errors # your request log, new calls as they happen
72
+ ```
73
+
74
+ The sandbox key from `sandbox create` is restricted: it can manage accounts,
75
+ trade and read, but not use webhooks (`listen`, `trigger`). For those, use your
76
+ own key, or a sandbox key made from it (`POST /v1/sandbox/keys`) with
77
+ `tickwire login --sandbox`.
78
+
79
+ ## Commands
80
+
81
+ - `login`: the key comes from a hidden prompt or stdin, never from an argument, and is never
82
+ printed. It is stored in the OS keychain or in a `0600` file.
83
+ - `trade open|close`: `--reason` is mandatory and an `Idempotency-Key` is sent automatically.
84
+ The result is `applied`, `no_change`, `rejected`, `held` or `unknown` (exit codes 0, 0, 3,
85
+ 4, 5). An `unknown` result is never retried.
86
+ - `listen --forward-to`: events are signed by the server, verified by the CLI, then forwarded
87
+ byte for byte.
88
+ - `logs tail`: your request log, oldest first, `--follow` for new calls. Redacted bodies of
89
+ failed calls only with `--bodies`, and only when the API returns them to your key. Waits for
90
+ `Retry-After` on `429`.
91
+ - `--json` works with every command.
92
+
93
+ Full documentation: [tickwire.io/docs/cli](https://tickwire.io/docs/cli/).
@@ -0,0 +1,62 @@
1
+ # tickwire-cli
2
+
3
+ The `tickwire` command for the Tickwire MT4/MT5 cloud API, built on the
4
+ [`tickwire` Python SDK](https://tickwire.io/docs/sdk-python/).
5
+
6
+ **Not published yet.** `pip install tickwire-cli` won't find it. Install from source, from the
7
+ repository root (the SDK first, because the CLI needs it):
8
+
9
+ ```sh
10
+ pip install ./sdk/python ./cli
11
+ ```
12
+
13
+ Once it is published:
14
+
15
+ ```sh
16
+ pip install tickwire-cli # or "tickwire-cli[keyring]" to keep keys in the OS keychain
17
+ ```
18
+
19
+ Python 3.11 or newer. MIT licensed.
20
+
21
+ ## Quick start
22
+
23
+ A free sandbox (no sign-in, no card) against the public API:
24
+
25
+ ```sh
26
+ export TICKWIRE_SANDBOX_URL=https://api.tickwire.io
27
+ tickwire sandbox create # one simulated MT5 account; the key is stored, never printed
28
+ tickwire --sandbox accounts list
29
+ tickwire --sandbox trade open <account-id> --side buy --symbol EURUSD --volume 0.01 --reason "test"
30
+ ```
31
+
32
+ With your own API key:
33
+
34
+ ```sh
35
+ export TICKWIRE_API_URL=https://api.tickwire.io
36
+ tickwire login # hidden prompt; the key is checked, then stored
37
+ tickwire accounts list
38
+ tickwire listen --forward-to http://localhost:3000/webhooks
39
+ tickwire trigger trade.outcome
40
+ tickwire logs tail -f --status errors # your request log, new calls as they happen
41
+ ```
42
+
43
+ The sandbox key from `sandbox create` is restricted: it can manage accounts,
44
+ trade and read, but not use webhooks (`listen`, `trigger`). For those, use your
45
+ own key, or a sandbox key made from it (`POST /v1/sandbox/keys`) with
46
+ `tickwire login --sandbox`.
47
+
48
+ ## Commands
49
+
50
+ - `login`: the key comes from a hidden prompt or stdin, never from an argument, and is never
51
+ printed. It is stored in the OS keychain or in a `0600` file.
52
+ - `trade open|close`: `--reason` is mandatory and an `Idempotency-Key` is sent automatically.
53
+ The result is `applied`, `no_change`, `rejected`, `held` or `unknown` (exit codes 0, 0, 3,
54
+ 4, 5). An `unknown` result is never retried.
55
+ - `listen --forward-to`: events are signed by the server, verified by the CLI, then forwarded
56
+ byte for byte.
57
+ - `logs tail`: your request log, oldest first, `--follow` for new calls. Redacted bodies of
58
+ failed calls only with `--bodies`, and only when the API returns them to your key. Waits for
59
+ `Retry-After` on `429`.
60
+ - `--json` works with every command.
61
+
62
+ Full documentation: [tickwire.io/docs/cli](https://tickwire.io/docs/cli/).
@@ -0,0 +1,51 @@
1
+ [project]
2
+ name = "tickwire-cli"
3
+ version = "0.1.0"
4
+ description = "Tickwire CLI: sign in, create a sandbox, list accounts, trade with a reason and a truthful outcome, and forward webhooks to localhost, for the Tickwire MT4/MT5 cloud API."
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ requires-python = ">=3.11"
9
+ authors = [{ name = "Tickwire", email = "hello@tickwire.io" }]
10
+ keywords = ["metatrader", "mt4", "mt5", "trading", "api", "cli", "webhooks"]
11
+ classifiers = [
12
+ "Development Status :: 3 - Alpha",
13
+ "Environment :: Console",
14
+ "Intended Audience :: Developers",
15
+ "Operating System :: OS Independent",
16
+ "Programming Language :: Python :: 3",
17
+ "Programming Language :: Python :: 3 :: Only",
18
+ "Programming Language :: Python :: 3.11",
19
+ "Programming Language :: Python :: 3.12",
20
+ "Programming Language :: Python :: 3.13",
21
+ "Topic :: Office/Business :: Financial :: Investment",
22
+ ]
23
+ dependencies = [
24
+ # The Tickwire Python SDK (sdk/python in this repository).
25
+ "tickwire>=0.1.0,<0.2",
26
+ "httpx>=0.27,<1",
27
+ ]
28
+
29
+ [project.optional-dependencies]
30
+ # Store the key in the OS keychain instead of a 0600 file.
31
+ keyring = ["keyring>=24,<26"]
32
+ dev = ["pytest>=8.0"]
33
+
34
+ [project.scripts]
35
+ tickwire = "tickwire_cli.__main__:main"
36
+
37
+ [project.urls]
38
+ Homepage = "https://tickwire.io/"
39
+ Documentation = "https://tickwire.io/docs/cli/"
40
+ Changelog = "https://tickwire.io/docs/changelog/"
41
+
42
+ [build-system]
43
+ requires = ["setuptools>=77"]
44
+ build-backend = "setuptools.build_meta"
45
+
46
+ [tool.setuptools.packages.find]
47
+ where = ["."]
48
+ include = ["tickwire_cli*"]
49
+
50
+ [tool.pytest.ini_options]
51
+ testpaths = ["tests"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,283 @@
1
+ """The CLI against the real control plane, in-process: accounts, trigger, and
2
+ ``listen`` forwarding events signed by the server and verified by the CLI.
3
+
4
+ Skipped when the control plane is not installed (CI installs it with
5
+ requirements-ci.txt). The gateway's ``/v1`` mapping is reproduced by
6
+ :class:`Gateway` (public ``/v1/<x>`` is served by the control plane at ``/<x>``,
7
+ except the routers it mounts under ``/v1`` itself).
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import json
12
+
13
+ import httpx
14
+ import pytest
15
+
16
+ pytest.importorskip("tickwire_controlplane.app")
17
+
18
+ from fastapi.testclient import TestClient # noqa: E402
19
+ from tickwire_controlplane import sandbox as sb # noqa: E402
20
+ from tickwire_controlplane.app import create_app # noqa: E402
21
+ from tickwire_controlplane.store import InMemoryStore # noqa: E402
22
+
23
+ from tickwire import verify_standard_webhook, verify_webhook # noqa: E402
24
+
25
+ API = "https://api.tickwire.test"
26
+ NATIVE_V1 = {"agent", "agent-audit", "agent-keys", "agent-kill-switches", "execution", "pretrade-holds",
27
+ "pretrade-hooks", "sandbox", "connected-apps"}
28
+
29
+
30
+ class Gateway:
31
+ def __init__(self, app) -> None:
32
+ self.tc = TestClient(app)
33
+ self.after: dict[str, callable] = {}
34
+ self.transport = httpx.MockTransport(self.handle)
35
+
36
+ def handle(self, request: httpx.Request) -> httpx.Response:
37
+ path = request.url.path
38
+ parts = path.split("/")
39
+ if path.startswith("/v1/") and parts[2] not in NATIVE_V1:
40
+ path = path[3:]
41
+ headers = {k: v for k, v in request.headers.items() if k.lower() not in ("host", "content-length")}
42
+ r = self.tc.request(request.method, path, params=request.url.params, headers=headers,
43
+ content=request.read())
44
+ hook = self.after.get(f"{request.method} {path}")
45
+ if hook:
46
+ hook()
47
+ return httpx.Response(r.status_code, headers={"content-type": r.headers.get("content-type", "")},
48
+ content=r.content)
49
+
50
+
51
+ @pytest.fixture
52
+ def stack():
53
+ store = InMemoryStore()
54
+ app = create_app(store)
55
+ return store, app, Gateway(app)
56
+
57
+
58
+ @pytest.fixture
59
+ def sandbox_env(stack):
60
+ store, _, _ = stack
61
+ t = sb.create_sandbox_tenant(store)
62
+ key = sb.issue_sandbox_key(store, t.id).secret
63
+ return t, {"TICKWIRE_API_KEY": key, "TICKWIRE_API_URL": API}
64
+
65
+
66
+ @pytest.fixture
67
+ def live_env(stack):
68
+ store, _, _ = stack
69
+ t = store.create_tenant("live-org", balance_cents=10_000)
70
+ return t, {"TICKWIRE_API_KEY": store.issue_full_key(t.id).secret, "TICKWIRE_API_URL": API}
71
+
72
+
73
+ class Local:
74
+ """The developer's local webhook handler."""
75
+
76
+ def __init__(self, status: int = 200) -> None:
77
+ self.got: list[tuple[dict, bytes]] = []
78
+ self.status = status
79
+ self.transport = httpx.MockTransport(self.handle)
80
+
81
+ def handle(self, request: httpx.Request) -> httpx.Response:
82
+ self.got.append((dict(request.headers), request.read()))
83
+ return httpx.Response(self.status)
84
+
85
+
86
+ def test_accounts_list_and_get(cli, stack, live_env):
87
+ store, _, gw = stack
88
+ tenant, env = live_env
89
+ a = store.create_account(tenant.id, platform="mt4", server="Demo-Server", login=123456, password="pw")
90
+ res = cli("accounts", "list", "--json", transport=gw.transport, extra_env=env)
91
+ assert res.code == 0 and [x["id"] for x in res.json] == [a.id]
92
+ assert "pw" not in res.out
93
+ res = cli("accounts", "get", a.id, transport=gw.transport, extra_env=env)
94
+ assert res.code == 0 and a.id in res.out and "mt4" in res.out
95
+ res = cli("accounts", "get", "nope", "--json", transport=gw.transport, extra_env=env)
96
+ assert res.code == 1 and res.json["status"] == 404
97
+
98
+
99
+ def test_listen_forwards_verified_events(cli, stack, sandbox_env):
100
+ store, app, gw = stack
101
+ tenant, env = sandbox_env
102
+ # an event published after the listener starts (as `tickwire trigger` would)
103
+ gw.after["POST /webhook-listeners"] = lambda: app.state.events.publish(
104
+ tenant.id, "account.state_changed", {"account_id": "a1", "state": "DEPLOYED", "password": "hunter2"})
105
+ local = Local()
106
+ res = cli("listen", "--forward-to", "http://localhost:3000/hooks", "--once", "--json",
107
+ transport=gw.transport, forward_transport=local.transport, extra_env=env)
108
+ assert res.code == 0, res.out + res.err
109
+ ready, delivered = res.lines
110
+ assert ready["ready"] is True and ready["secret"].startswith("whsec_")
111
+ assert delivered["forwarded"] is True and delivered["status"] == 200
112
+ assert len(local.got) == 1
113
+ headers, body = local.got[0]
114
+ event = verify_webhook(ready["secret"], headers, body) # the local app's view
115
+ verify_standard_webhook(ready["secret"], headers, body)
116
+ assert event["type"] == "account.state_changed" and event["data"]["state"] == "DEPLOYED"
117
+ assert "hunter2" not in body.decode()
118
+ assert headers["x-tickwire-listener"] == ready["listener"]
119
+
120
+
121
+ def test_listen_filters_and_reports_handler_status(cli, stack, sandbox_env):
122
+ store, app, gw = stack
123
+ tenant, env = sandbox_env
124
+
125
+ def publish():
126
+ app.state.events.publish(tenant.id, "webhook.test", {"x": 1})
127
+ app.state.events.publish(tenant.id, "account.state_changed", {"account_id": "a1"})
128
+ gw.after["POST /webhook-listeners"] = publish
129
+ local = Local(status=500)
130
+ res = cli("listen", "--forward-to", "http://127.0.0.1:9/h", "--events", "account.*", "--once",
131
+ transport=gw.transport, forward_transport=local.transport, extra_env=env)
132
+ assert res.code == 0
133
+ assert len(local.got) == 1 and b"account.state_changed" in local.got[0][1]
134
+ assert "[500]" in res.out
135
+
136
+
137
+ def test_listen_refuses_to_forward_a_tampered_event(cli, stack, sandbox_env):
138
+ store, app, gw = stack
139
+ tenant, env = sandbox_env
140
+ gw.after["POST /webhook-listeners"] = lambda: app.state.events.publish(tenant.id, "webhook.test", {"x": 1})
141
+ inner = gw.transport
142
+
143
+ def tamper(request: httpx.Request) -> httpx.Response:
144
+ r = inner.handle_request(request)
145
+ if "/events" in request.url.path:
146
+ page = json.loads(r.read())
147
+ for ev in page["events"]:
148
+ ev["body"] = ev["body"].replace('"x":1', '"x":2')
149
+ return httpx.Response(200, json=page)
150
+ return r
151
+ local = Local()
152
+ res = cli("listen", "--forward-to", "http://localhost:3000/h", "--once", "--json",
153
+ transport=httpx.MockTransport(tamper), forward_transport=local.transport, extra_env=env)
154
+ assert res.code == 1 and local.got == []
155
+ assert res.lines[-1]["error"] == "signature_invalid"
156
+
157
+
158
+ def test_listen_unreachable_handler_is_reported_not_retried(cli, stack, sandbox_env):
159
+ store, app, gw = stack
160
+ tenant, env = sandbox_env
161
+ gw.after["POST /webhook-listeners"] = lambda: app.state.events.publish(tenant.id, "webhook.test", {})
162
+ calls = []
163
+
164
+ def refuse(request):
165
+ calls.append(1)
166
+ raise httpx.ConnectError("refused", request=request)
167
+ res = cli("listen", "--forward-to", "http://localhost:3000/h", "--once", "--json",
168
+ transport=gw.transport, forward_transport=httpx.MockTransport(refuse), extra_env=env)
169
+ assert res.code == 0 and len(calls) == 1 and res.lines[-1]["forwarded"] is False
170
+
171
+
172
+ def test_trigger_then_listen(cli, stack, sandbox_env):
173
+ store, app, gw = stack
174
+ tenant, env = sandbox_env
175
+ res = cli("trigger", "trade.outcome", "--json", transport=gw.transport, extra_env=env)
176
+ assert res.code == 0 and res.json["test"] is True and res.json["sandbox"] is True
177
+ listed = cli("trigger", "--list", "--json", transport=gw.transport, extra_env=env)
178
+ assert "trade.outcome" in [t["type"] for t in listed.json]
179
+
180
+
181
+ def test_trigger_on_live_is_webhook_test_only(cli, stack, live_env):
182
+ _, _, gw = stack
183
+ _, env = live_env
184
+ res = cli("trigger", "trade.outcome", "--json", transport=gw.transport, extra_env=env)
185
+ assert res.code == 1 and res.json["error"] == "webhook_trigger_sandbox_only"
186
+ assert cli("trigger", "webhook.test", transport=gw.transport, extra_env=env).code == 0
187
+
188
+
189
+ def test_restricted_sandbox_key_cannot_listen(cli, stack):
190
+ store, _, gw = stack
191
+ t = sb.create_sandbox_tenant(store)
192
+ env = {"TICKWIRE_API_KEY": sb.issue_sandbox_key(store, t.id, restricted=True).secret, "TICKWIRE_API_URL": API}
193
+ res = cli("listen", "--forward-to", "http://localhost:1/h", "--once", "--json", transport=gw.transport,
194
+ extra_env=env)
195
+ assert res.code == 1 and res.json["error"] == "sandbox_key_restricted"
196
+
197
+
198
+ def test_listen_across_a_control_plane_restart_says_reset_and_loses_nothing_new(cli, stack, sandbox_env):
199
+ """Regression: after a restart, events were skipped silently when the new head had
200
+ already passed the old cursor."""
201
+ store, app, gw = stack
202
+ tenant, env = sandbox_env
203
+
204
+ def restart():
205
+ app2 = create_app(store) # same data, fresh event bus (seq from 1)
206
+ gw.tc = TestClient(app2)
207
+ for i in range(7):
208
+ app2.state.events.publish(tenant.id, "webhook.test", {"i": i})
209
+ for _ in range(5): # the old head is at >= 5
210
+ app.state.events.publish(tenant.id, "webhook.test", {})
211
+ gw.after["POST /webhook-listeners"] = restart
212
+ local = Local()
213
+ res = cli("listen", "--forward-to", "http://localhost:3000/h", "--once", "--json",
214
+ transport=gw.transport, forward_transport=local.transport, extra_env=env)
215
+ assert res.code == 0, res.err
216
+ assert len(local.got) == 7 and "restarted" in res.err
217
+
218
+
219
+ def test_bad_forward_url(cli, sandbox_env):
220
+ _, env = sandbox_env
221
+ assert cli("listen", "--forward-to", "localhost:3000", extra_env=env).code == 2
222
+
223
+
224
+ def _log_record(tenant_id: str, n: int, status: int = 200, **kw) -> dict:
225
+ d = {"id": f"req_{n:010d}", "tenant_id": tenant_id, "request_id": f"rid{n}", "key_id": "key_1",
226
+ "kind": "http", "method": "GET", "path": "/users/current/accounts/a1/positions",
227
+ "route": "/users/current/accounts/{accountId}/positions", "account_id": "a1", "status": status,
228
+ "error_code": None, "latency_ms": 5, "api_version": "2026-09-25", "rate_bucket": "key",
229
+ "outcome": "completed"}
230
+ d.update(kw)
231
+ return d
232
+
233
+
234
+ def test_logs_tail_against_the_real_request_log_api(cli, stack, live_env):
235
+ from tickwire_controlplane.request_log_db import RequestLogRepo
236
+ store, app, gw = stack
237
+ tenant, env = live_env
238
+ repo = app.state.request_logs = RequestLogRepo("sqlite://")
239
+ repo.ingest([_log_record(tenant.id, n) for n in range(1, 206)]
240
+ + [_log_record(tenant.id, 206, 422, method="POST", path="/v1/execution/accounts/a1/trade",
241
+ error_code="validation_error",
242
+ request_excerpt='{"volume":0,"password":"[REDACTED]"}',
243
+ response_excerpt='{"error":"validation_error"}'),
244
+ _log_record("someone-else", 207, 500)], tier_of=lambda t: "paid")
245
+ res = cli("logs", "tail", "-n", "210", "--json", transport=gw.transport, extra_env=env)
246
+ assert res.code == 0, res.err
247
+ ids = [r["id"] for r in res.lines]
248
+ assert len(ids) == 206 and ids[0] == "req_0000000001" and ids[-1] == "req_0000000206" # paged, oldest first
249
+ assert all("requestBody" not in r for r in res.lines)
250
+ res = cli("logs", "tail", "--status", "errors", "--bodies", "--json", transport=gw.transport, extra_env=env)
251
+ assert res.code == 0 and len(res.lines) == 1
252
+ assert res.lines[0]["requestBody"] == '{"volume":0,"password":"[REDACTED]"}'
253
+ # a read-only key sees the metadata, never the excerpts
254
+ ro = store.create_readonly_key(tenant.id, name="ro", scope="all", account_ids=[])
255
+ res = cli("logs", "tail", "--status", "errors", "--bodies", "--json", transport=gw.transport,
256
+ extra_env={**env, "TICKWIRE_API_KEY": ro.secret})
257
+ assert res.code == 0 and len(res.lines) == 1
258
+ assert "requestBody" not in res.lines[0] and res.lines[0]["excerptsHidden"] is True
259
+ assert "bodies are not shown" in res.err and "volume" not in res.out
260
+
261
+
262
+ def test_forged_request_log_cursor_never_crosses_organisations(stack, live_env):
263
+ """The cursor is plain base64 ``rl:<seq>`` (not signed), so anyone can forge one. It only
264
+ moves the position (``seq < n``); the organisation always comes from the credential."""
265
+ import base64
266
+
267
+ from tickwire_controlplane.request_log_db import RequestLogRepo
268
+ store, app, gw = stack
269
+ tenant, env = live_env
270
+ other = store.create_tenant("other-org")
271
+ repo = app.state.request_logs = RequestLogRepo("sqlite://")
272
+ repo.ingest([_log_record(tenant.id, 1), _log_record(tenant.id, 2)]
273
+ + [_log_record(other.id, n, 500) for n in range(3, 13)], tier_of=lambda t: "paid")
274
+ head = {"X-API-Key": env["TICKWIRE_API_KEY"]}
275
+ with httpx.Client(transport=gw.transport, base_url=API) as http:
276
+ for seq in (1, 3, 8, 13, 10**9):
277
+ forged = base64.urlsafe_b64encode(f"rl:{seq}".encode()).decode().rstrip("=")
278
+ r = http.get("/v1/request-logs", params={"cursor": forged, "limit": 200}, headers=head)
279
+ assert r.status_code == 200
280
+ ids = {row["id"] for row in r.json()["data"]}
281
+ assert ids <= {"req_0000000001", "req_0000000002"}, (seq, ids)
282
+ for oid in (f"req_{n:010d}" for n in range(3, 13)):
283
+ assert http.get(f"/v1/request-logs/{oid}", headers=head).status_code == 404
@@ -0,0 +1,90 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import os
5
+ import stat
6
+
7
+ import pytest
8
+ from conftest import FakeKeyring
9
+
10
+ from tickwire_cli.credentials import (
11
+ KEYRING_SERVICE,
12
+ CredentialError,
13
+ CredentialStore,
14
+ config_dir,
15
+ key_hint,
16
+ )
17
+
18
+ KEY = "tw_live_" + "c3" * 16
19
+
20
+
21
+ def _mode(p) -> int:
22
+ return stat.S_IMODE(os.stat(p).st_mode)
23
+
24
+
25
+ @pytest.mark.skipif(os.name == "nt", reason="POSIX modes")
26
+ def test_file_storage_is_0600_in_a_0700_dir(store):
27
+ os.umask(0o022)
28
+ p = store.save("default", KEY, api_url="https://x", sandbox=False)
29
+ assert p.storage == "file"
30
+ assert _mode(store.dir) == 0o700
31
+ assert _mode(store.dir / "credentials.json") == 0o600
32
+ assert store.key("default") == KEY
33
+ # the config never holds the key
34
+ cfg = (store.dir / "config.json").read_text()
35
+ assert KEY not in cfg and json.loads(cfg)["profiles"]["default"]["key_hint"] == key_hint(KEY)
36
+
37
+
38
+ @pytest.mark.skipif(os.name == "nt", reason="POSIX modes")
39
+ def test_readable_credentials_file_is_refused(store):
40
+ store.save("default", KEY, api_url="https://x", sandbox=False)
41
+ os.chmod(store.dir / "credentials.json", 0o644)
42
+ with pytest.raises(CredentialError, match="chmod 600"):
43
+ store.key("default")
44
+
45
+
46
+ def test_keyring_is_used_when_available(env):
47
+ kr = FakeKeyring()
48
+ s = CredentialStore(env=env, keyring_module=kr)
49
+ p = s.save("sandbox", KEY, api_url="https://x", sandbox=True)
50
+ assert p.storage == "keyring" and kr.data[(KEYRING_SERVICE, "sandbox")] == KEY
51
+ assert not (s.dir / "credentials.json").exists()
52
+ assert s.key("sandbox") == KEY
53
+ assert s.delete("sandbox") and kr.data == {} and s.profile("sandbox") is None
54
+
55
+
56
+ def test_no_keyring_flag_uses_the_file(env):
57
+ kr = FakeKeyring()
58
+ s = CredentialStore(env=env, keyring_module=kr)
59
+ assert s.save("default", KEY, api_url="https://x", sandbox=False, use_keyring=False).storage == "file"
60
+ assert kr.data == {}
61
+
62
+
63
+ def test_broken_keyring_falls_back_to_the_file(env):
64
+ class Locked(FakeKeyring):
65
+ def set_password(self, *a):
66
+ raise RuntimeError("locked")
67
+ s = CredentialStore(env=env, keyring_module=Locked())
68
+ assert s.save("default", KEY, api_url="https://x", sandbox=False).storage == "file"
69
+ assert s.key("default") == KEY
70
+
71
+
72
+ def test_moving_from_file_to_keyring_removes_the_file_copy(env):
73
+ s = CredentialStore(env=env, keyring_module=None)
74
+ s.save("default", KEY, api_url="https://x", sandbox=False)
75
+ s2 = CredentialStore(env=env, keyring_module=FakeKeyring())
76
+ s2.save("default", KEY, api_url="https://x", sandbox=False)
77
+ assert KEY not in (s2.dir / "credentials.json").read_text()
78
+
79
+
80
+ def test_key_hint_never_reveals_the_key():
81
+ assert key_hint(KEY) == "tw_…c3c3"
82
+ # keys issued before the rename to tw_ still get a hint
83
+ assert key_hint("fxs_live_" + "c3" * 16) == "fxs_…c3c3"
84
+ assert key_hint("twsk_" + "d" * 30).startswith("twsk_…")
85
+ assert key_hint("short") == "…"
86
+
87
+
88
+ def test_config_dir_resolution(tmp_path):
89
+ assert config_dir({"TICKWIRE_CONFIG_DIR": str(tmp_path)}) == tmp_path
90
+ assert config_dir({"XDG_CONFIG_HOME": str(tmp_path)}) == tmp_path / "tickwire"