ermes-cli 1.3.0__tar.gz → 1.4.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 (76) hide show
  1. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/PKG-INFO +14 -8
  2. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/README.md +11 -6
  3. ermes_cli-1.4.0/ermes_cli/__init__.py +1 -0
  4. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/ermes_cli/auth0.py +1 -1
  5. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/ermes_cli/client.py +15 -10
  6. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/ermes_cli/commands/auth_cmds.py +6 -7
  7. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/ermes_cli/config.py +7 -8
  8. ermes_cli-1.4.0/ermes_cli/keyring_store.py +181 -0
  9. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/ermes_cli/main.py +9 -4
  10. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/pyproject.toml +6 -2
  11. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/tests/conftest.py +5 -34
  12. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/tests/test_auth_cmds.py +20 -11
  13. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/tests/test_commands/test_projects.py +2 -2
  14. ermes_cli-1.4.0/tests/test_connection_errors.py +40 -0
  15. ermes_cli-1.4.0/tests/test_keyring_store.py +169 -0
  16. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/tests/test_write_mode.py +4 -4
  17. ermes_cli-1.3.0/ermes_cli/__init__.py +0 -1
  18. ermes_cli-1.3.0/ermes_cli/keyring_store.py +0 -145
  19. ermes_cli-1.3.0/tests/test_keyring_store.py +0 -185
  20. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/.gitignore +0 -0
  21. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/ermes_cli/admin_api.py +0 -0
  22. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/ermes_cli/commands/__init__.py +0 -0
  23. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/ermes_cli/commands/campaigns.py +0 -0
  24. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/ermes_cli/commands/config_cmd.py +0 -0
  25. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/ermes_cli/commands/data_paths.py +0 -0
  26. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/ermes_cli/commands/export.py +0 -0
  27. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/ermes_cli/commands/ingest.py +0 -0
  28. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/ermes_cli/commands/journeys.py +0 -0
  29. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/ermes_cli/commands/keys.py +0 -0
  30. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/ermes_cli/commands/lists.py +0 -0
  31. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/ermes_cli/commands/metrics.py +0 -0
  32. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/ermes_cli/commands/projects.py +0 -0
  33. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/ermes_cli/commands/providers.py +0 -0
  34. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/ermes_cli/commands/skill.py +0 -0
  35. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/ermes_cli/commands/subscriptions.py +0 -0
  36. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/ermes_cli/commands/tags.py +0 -0
  37. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/ermes_cli/commands/templates.py +0 -0
  38. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/ermes_cli/commands/users.py +0 -0
  39. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/ermes_cli/commands/write_cmds.py +0 -0
  40. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/ermes_cli/errors.py +0 -0
  41. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/ermes_cli/export_utils.py +0 -0
  42. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/ermes_cli/output.py +0 -0
  43. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/ermes_cli/rules.py +0 -0
  44. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/ermes_cli/skill/SKILL.md +0 -0
  45. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/ermes_cli/update.py +0 -0
  46. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/ermes_cli/write_mode.py +0 -0
  47. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/scripts/install-cli.sh +0 -0
  48. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/tests/__init__.py +0 -0
  49. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/tests/test_admin_api.py +0 -0
  50. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/tests/test_auth0.py +0 -0
  51. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/tests/test_client.py +0 -0
  52. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/tests/test_commands/__init__.py +0 -0
  53. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/tests/test_commands/test_campaigns.py +0 -0
  54. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/tests/test_commands/test_data_paths.py +0 -0
  55. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/tests/test_commands/test_export.py +0 -0
  56. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/tests/test_commands/test_ingest.py +0 -0
  57. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/tests/test_commands/test_journeys.py +0 -0
  58. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/tests/test_commands/test_keys.py +0 -0
  59. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/tests/test_commands/test_lists.py +0 -0
  60. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/tests/test_commands/test_metrics.py +0 -0
  61. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/tests/test_commands/test_projects_list.py +0 -0
  62. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/tests/test_commands/test_providers.py +0 -0
  63. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/tests/test_commands/test_subscriptions.py +0 -0
  64. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/tests/test_commands/test_tags.py +0 -0
  65. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/tests/test_commands/test_templates.py +0 -0
  66. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/tests/test_commands/test_users.py +0 -0
  67. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/tests/test_config.py +0 -0
  68. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/tests/test_export_utils.py +0 -0
  69. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/tests/test_output.py +0 -0
  70. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/tests/test_projects_config.py +0 -0
  71. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/tests/test_rules.py +0 -0
  72. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/tests/test_skill_command.py +0 -0
  73. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/tests/test_update.py +0 -0
  74. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/tests/test_version.py +0 -0
  75. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/tests/test_whoami.py +0 -0
  76. {ermes_cli-1.3.0 → ermes_cli-1.4.0}/tests/test_write_cmds.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: ermes-cli
3
- Version: 1.3.0
3
+ Version: 1.4.0
4
4
  Summary: CLI-first access to Ermes marketing automation with Auth0 multi-project auth.
5
5
  Project-URL: Homepage, https://ermes.publinker.com
6
6
  Project-URL: Repository, https://github.com/Martech-DM/ermes
@@ -14,8 +14,9 @@ Classifier: Programming Language :: Python :: 3
14
14
  Classifier: Programming Language :: Python :: 3 :: Only
15
15
  Classifier: Topic :: Communications :: Email
16
16
  Requires-Python: >=3.10
17
+ Requires-Dist: cryptography<49,>=42.0; sys_platform == 'darwin' and platform_machine == 'x86_64'
18
+ Requires-Dist: cryptography>=42.0; sys_platform != 'darwin' or platform_machine != 'x86_64'
17
19
  Requires-Dist: httpx>=0.28
18
- Requires-Dist: keyring>=24.0
19
20
  Requires-Dist: pyyaml>=6.0
20
21
  Requires-Dist: requests>=2.31
21
22
  Requires-Dist: rich>=14.0
@@ -31,7 +32,9 @@ Description-Content-Type: text/markdown
31
32
 
32
33
  This package gives Ermes operators a CLI surface for explicit-project API reads and guarded writes.
33
34
 
34
- Version 1.2.0. It adds `ermes skill install` (DEV-2329). 1.1.0 removed the `ermes-mcp`
35
+ Version 1.4.0. It moves Auth0 tokens off the OS keychain into an encrypted 0600 file,
36
+ `~/.ermes/ermes-cli-token.json` (DEV-2392); run `ermes login` once after upgrading.
37
+ 1.2.0 added `ermes skill install` (DEV-2329). 1.1.0 removed the `ermes-mcp`
35
38
  compatibility server that 1.0.0 shipped (DEV-2326); a machine that registered it must drop that
36
39
  registration (e.g. `claude mcp remove ermes`).
37
40
 
@@ -101,7 +104,7 @@ one JSON document.
101
104
  `pipx install ermes-cli`) upgrades itself. `pipx upgrade` keeps the old venv if pip fails, so a
102
105
  failed upgrade never leaves you without a CLI. Editable checkouts (`git pull`), git or local-dir
103
106
  installs, non-pipx environments and an `ermes` that is not the venv pipx manages get the manual
104
- command instead of a prompt. Keychain tokens and `~/.ermes` are untouched.
107
+ command instead of a prompt. `~/.ermes` (tokens and projects) is untouched.
105
108
 
106
109
  ## Auth — Auth0 device login (recommended)
107
110
 
@@ -111,7 +114,7 @@ ermes projects list # show cached projects; keys stay masked
111
114
  ermes use <project-name-or-id> # interactive active-project selection
112
115
  ermes whoami # local selection only; not API liveness
113
116
  ermes projects refresh # re-sync after admins add you to new projects
114
- ermes logout # delete Keychain tokens + projects.yml
117
+ ermes logout # delete the token file + projects.yml
115
118
  ```
116
119
 
117
120
  `ermes login` runs an Auth0 Device Authorization Flow (RFC 8628) against the
@@ -128,9 +131,12 @@ authenticated user is your Auth0 identity). After authentication:
128
131
  admin account (revoked when you are removed from the project). Keys from the old
129
132
  `cli-managed-<hostname>` scheme are ignored.
130
133
 
131
- Auth0 tokens live in the OS keychain (`ermes-cli` service). On a headless box with no keyring
132
- backend they fall back to `~/.ermes/auth0-tokens.json` (chmod 600). Per-project `sk_` keys live
133
- in `~/.ermes/projects.yml`.
134
+ Auth0 tokens live in `~/.ermes/ermes-cli-token.json` (chmod 600), encrypted with a key derived
135
+ from this machine's id and your OS user, so a copied file is useless elsewhere. It is not the OS
136
+ keychain on purpose: macOS re-prompts "python3.x wants to use your confidential information" after
137
+ every Python upgrade, and Linux secret-service can pop an unlock dialog. **Upgrading from a version
138
+ below 1.4.0? Run `ermes login` once**; the old keychain item is never read (reading is what
139
+ prompts). Per-project `sk_` keys live in `~/.ermes/projects.yml`.
134
140
 
135
141
  For interactive work, `ermes use <project-name-or-id>` persists the active project. For every script
136
142
  or agent command, pin scope without changing that shared default:
@@ -2,7 +2,9 @@
2
2
 
3
3
  This package gives Ermes operators a CLI surface for explicit-project API reads and guarded writes.
4
4
 
5
- Version 1.2.0. It adds `ermes skill install` (DEV-2329). 1.1.0 removed the `ermes-mcp`
5
+ Version 1.4.0. It moves Auth0 tokens off the OS keychain into an encrypted 0600 file,
6
+ `~/.ermes/ermes-cli-token.json` (DEV-2392); run `ermes login` once after upgrading.
7
+ 1.2.0 added `ermes skill install` (DEV-2329). 1.1.0 removed the `ermes-mcp`
6
8
  compatibility server that 1.0.0 shipped (DEV-2326); a machine that registered it must drop that
7
9
  registration (e.g. `claude mcp remove ermes`).
8
10
 
@@ -72,7 +74,7 @@ one JSON document.
72
74
  `pipx install ermes-cli`) upgrades itself. `pipx upgrade` keeps the old venv if pip fails, so a
73
75
  failed upgrade never leaves you without a CLI. Editable checkouts (`git pull`), git or local-dir
74
76
  installs, non-pipx environments and an `ermes` that is not the venv pipx manages get the manual
75
- command instead of a prompt. Keychain tokens and `~/.ermes` are untouched.
77
+ command instead of a prompt. `~/.ermes` (tokens and projects) is untouched.
76
78
 
77
79
  ## Auth — Auth0 device login (recommended)
78
80
 
@@ -82,7 +84,7 @@ ermes projects list # show cached projects; keys stay masked
82
84
  ermes use <project-name-or-id> # interactive active-project selection
83
85
  ermes whoami # local selection only; not API liveness
84
86
  ermes projects refresh # re-sync after admins add you to new projects
85
- ermes logout # delete Keychain tokens + projects.yml
87
+ ermes logout # delete the token file + projects.yml
86
88
  ```
87
89
 
88
90
  `ermes login` runs an Auth0 Device Authorization Flow (RFC 8628) against the
@@ -99,9 +101,12 @@ authenticated user is your Auth0 identity). After authentication:
99
101
  admin account (revoked when you are removed from the project). Keys from the old
100
102
  `cli-managed-<hostname>` scheme are ignored.
101
103
 
102
- Auth0 tokens live in the OS keychain (`ermes-cli` service). On a headless box with no keyring
103
- backend they fall back to `~/.ermes/auth0-tokens.json` (chmod 600). Per-project `sk_` keys live
104
- in `~/.ermes/projects.yml`.
104
+ Auth0 tokens live in `~/.ermes/ermes-cli-token.json` (chmod 600), encrypted with a key derived
105
+ from this machine's id and your OS user, so a copied file is useless elsewhere. It is not the OS
106
+ keychain on purpose: macOS re-prompts "python3.x wants to use your confidential information" after
107
+ every Python upgrade, and Linux secret-service can pop an unlock dialog. **Upgrading from a version
108
+ below 1.4.0? Run `ermes login` once**; the old keychain item is never read (reading is what
109
+ prompts). Per-project `sk_` keys live in `~/.ermes/projects.yml`.
105
110
 
106
111
  For interactive work, `ermes use <project-name-or-id>` persists the active project. For every script
107
112
  or agent command, pin scope without changing that shared default:
@@ -0,0 +1 @@
1
+ __version__ = "1.4.0"
@@ -12,7 +12,7 @@ Three operations:
12
12
  access token (Auth0 rotates the refresh token; we carry the old one
13
13
  forward if the response omits a new one).
14
14
 
15
- All three are pure: no keychain writes. The caller decides what to persist.
15
+ All three are pure: no token-file writes. The caller decides what to persist.
16
16
  """
17
17
 
18
18
  from __future__ import annotations
@@ -50,32 +50,37 @@ class ErmesClient:
50
50
  raise ErmesAPIError(f"{label}: {detail}", status)
51
51
  raise ErmesAPIError(f"Server error: {status}", status)
52
52
 
53
- def get(self, path: str, params: dict | None = None) -> Any:
54
- response = self._client.get(path, params=params)
53
+ def _send(self, method: str, path: str, **kwargs: Any) -> Any:
54
+ try:
55
+ response = getattr(self._client, method)(path, **kwargs)
56
+ except httpx.TransportError as e:
57
+ # Type name + host only: the exception text can echo the Bearer header (DEV-2261).
58
+ url = self._client.base_url
59
+ host = f"{url.host}:{url.port}" if url.port else url.host
60
+ raise ErmesAPIError(f"could not reach {host}: {type(e).__name__}") from None
55
61
  return self._handle_response(response)
56
62
 
63
+ def get(self, path: str, params: dict | None = None) -> Any:
64
+ return self._send("get", path, params=params)
65
+
57
66
  def post(self, path: str, json: dict | None = None, *, read_only: bool = False) -> Any:
58
67
  # read_only: a POST the server treats as a pure read (e.g. template preview),
59
68
  # so the write guard has nothing to protect.
60
69
  if not read_only:
61
70
  assert_writes_allowed("POST", path)
62
- response = self._client.post(path, json=json)
63
- return self._handle_response(response)
71
+ return self._send("post", path, json=json)
64
72
 
65
73
  def patch(self, path: str, json: dict | None = None) -> Any:
66
74
  assert_writes_allowed("PATCH", path)
67
- response = self._client.patch(path, json=json)
68
- return self._handle_response(response)
75
+ return self._send("patch", path, json=json)
69
76
 
70
77
  def put(self, path: str, json: dict | None = None) -> Any:
71
78
  assert_writes_allowed("PUT", path)
72
- response = self._client.put(path, json=json)
73
- return self._handle_response(response)
79
+ return self._send("put", path, json=json)
74
80
 
75
81
  def delete(self, path: str) -> Any:
76
82
  assert_writes_allowed("DELETE", path)
77
- response = self._client.delete(path)
78
- return self._handle_response(response)
83
+ return self._send("delete", path)
79
84
 
80
85
  MAX_PAGES = 500
81
86
 
@@ -5,7 +5,6 @@ from __future__ import annotations
5
5
  import re
6
6
  import socket
7
7
 
8
- import keyring
9
8
  import typer
10
9
  from rich.console import Console
11
10
  from rich.table import Table
@@ -143,7 +142,7 @@ def _ensure_admin_session(
143
142
  ) -> tuple[str, admin_api.ExchangeResult]:
144
143
  """Return `(api_base, exchange_result)` using cached Auth0 tokens.
145
144
 
146
- Loads the keychain bundle, transparently refreshes the Auth0 access token
145
+ Loads the token-file bundle, transparently refreshes the Auth0 access token
147
146
  via the cached refresh_token when it has expired, then exchanges it for an
148
147
  Ermes admin JWT via `/api/cli/exchange`. Exits (code 1) with an actionable
149
148
  message when the user isn't logged in, the refresh token is dead, or the
@@ -230,7 +229,7 @@ def login(
230
229
 
231
230
  What this does:
232
231
  1. Starts an Auth0 device flow against the shared `dev-hqiwr-re` tenant.
233
- 2. Stores the resulting Auth0 tokens in your OS keychain (`ermes-cli` service).
232
+ 2. Stores the resulting Auth0 tokens encrypted in `~/.ermes/ermes-cli-token.json` (chmod 600).
234
233
  3. Trades the Auth0 access token for an Ermes admin JWT via /api/cli/exchange.
235
234
  4. Calls /api/admin/projects/all to enumerate every project you can see.
236
235
  5. Caches the list in `~/.ermes/projects.yml` (chmod 600).
@@ -250,7 +249,7 @@ def login(
250
249
 
251
250
  bundle.base_url = base_url
252
251
  keyring_store.save(bundle)
253
- console.print("[green]✓[/green] Auth0 tokens stored in OS keychain.")
252
+ console.print("[green]✓[/green] Auth0 tokens stored in ~/.ermes/ermes-cli-token.json (encrypted, 0600).")
254
253
 
255
254
  try:
256
255
  result = admin_api.exchange_auth0_token(
@@ -269,7 +268,7 @@ def login(
269
268
  stored.get("auth0_email") != result.admin_email
270
269
  or str(stored.get("base_url") or "").rstrip("/") != base_url.rstrip("/")
271
270
  ):
272
- # The keyring now holds this admin's tokens; the previous admin's cached
271
+ # The token file now holds this admin's tokens; the previous admin's cached
273
272
  # keys must not outlive the login even if discovery stops early.
274
273
  clear_projects_file()
275
274
  console.print()
@@ -326,8 +325,8 @@ def logout() -> None:
326
325
  console.print("[yellow]Could not revoke the refresh token at Auth0; it expires on its own.[/yellow]")
327
326
  try:
328
327
  keyring_store.clear()
329
- except keyring.errors.KeyringError as exc:
330
- console.print(f"[red]Could not remove the Auth0 tokens from the keyring:[/red] {exc}")
328
+ except OSError as exc:
329
+ console.print(f"[red]Could not remove the Auth0 token file:[/red] {exc}")
331
330
  raise typer.Exit(code=1)
332
331
  finally:
333
332
  clear_projects_file()
@@ -34,6 +34,7 @@ from __future__ import annotations
34
34
  import contextlib
35
35
  import os
36
36
  import sys
37
+ import tempfile
37
38
  from pathlib import Path
38
39
  from typing import Any
39
40
 
@@ -84,17 +85,15 @@ def load_config() -> dict:
84
85
  def _open_private(path: Path):
85
86
  """Write `path` atomically as a fresh 0600 file.
86
87
 
87
- The bytes go to a sibling temp file opened O_EXCL|O_NOFOLLOW (a planted
88
- symlink or stale temp is never followed), then `os.replace` swaps it in: a
89
- reader sees the old file or the new one, never a truncated one, and a
88
+ The bytes go to a uniquely named sibling temp file from `mkstemp` (0600,
89
+ O_EXCL, so a planted symlink is never followed and two concurrent writers
90
+ never share a temp — DEV-2404), then `os.replace` swaps it in: a reader
91
+ sees the old file or the new one, never a truncated one, and a
90
92
  pre-existing wide-mode file or symlink is replaced by a fresh 0600 inode.
91
93
  """
92
- tmp = path.with_name(path.name + ".tmp")
93
- tmp.unlink(missing_ok=True)
94
- fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0), 0o600)
94
+ fd, tmp_name = tempfile.mkstemp(dir=path.parent, prefix=path.name + ".", suffix=".tmp")
95
+ tmp = Path(tmp_name)
95
96
  try:
96
- if hasattr(os, "fchmod"): # absent on Windows < 3.13; the 0o600 at open still applies
97
- os.fchmod(fd, 0o600)
98
97
  f = os.fdopen(fd, "w")
99
98
  except OSError:
100
99
  os.close(fd)
@@ -0,0 +1,181 @@
1
+ """Auth0 token storage: one encrypted JSON file, mode 0600, in `~/.ermes`.
2
+
3
+ Not the OS vault. macOS ties a Keychain item to the exact Python binary that
4
+ wrote it, so every Python upgrade made the next command ask "python3.x wants
5
+ to use your confidential information stored in 'ermes-cli'", and Linux
6
+ secret-service can pop an unlock dialog. A 0600 file is the same trade-off as
7
+ ~/.aws/credentials and gcloud, and never prompts. Tokens an older version left
8
+ in the vault are not read (reading prompts); users run `ermes login` once.
9
+
10
+ The bundle is Fernet-encrypted with a key derived from this machine's id and
11
+ the OS user, so a copy of the file (a backup, a dotfile sync, a leaked
12
+ archive) is useless elsewhere. It does not stop a process running as the same
13
+ user on the same machine; nothing short of an OS vault does. (DEV-2392, same
14
+ design as publinker-cli DEV-2388.)
15
+
16
+ This module ONLY deals with Auth0 tokens. Per-project Ermes API keys live in
17
+ `~/.ermes/projects.yml` (managed by `config.py`).
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import base64
23
+ import functools
24
+ import json
25
+ import os
26
+ import re
27
+ import subprocess # nosec B404
28
+ import sys
29
+ import time
30
+ import uuid
31
+ from dataclasses import asdict, dataclass
32
+ from pathlib import Path
33
+
34
+ from cryptography.fernet import Fernet, InvalidToken
35
+ from cryptography.hazmat.primitives import hashes
36
+ from cryptography.hazmat.primitives.kdf.hkdf import HKDF
37
+
38
+ from ermes_cli.config import _config_dir, _open_private
39
+
40
+ KEYRING_SERVICE = "ermes-cli" # kept: names the token file
41
+
42
+
43
+ def _token_file() -> Path:
44
+ return _config_dir() / f"{KEYRING_SERVICE}-token.json"
45
+
46
+
47
+ def _legacy_plaintext_file() -> Path:
48
+ """Pre-1.4 headless fallback: the bundle in clear text. Never read, always removed."""
49
+ return _config_dir() / "auth0-tokens.json"
50
+
51
+
52
+ @dataclass
53
+ class TokenBundle:
54
+ access_token: str
55
+ refresh_token: str
56
+ id_token: str
57
+ expires_at: int # unix epoch seconds
58
+ base_url: str = "" # the Ermes host these tokens were obtained for (DEV-2261)
59
+
60
+ @classmethod
61
+ def from_token_response(
62
+ cls, body: dict, now: int | None = None
63
+ ) -> TokenBundle:
64
+ """Build a bundle from Auth0's `/oauth/token` response."""
65
+ now = now if now is not None else int(time.time())
66
+ return cls(
67
+ access_token=body["access_token"],
68
+ refresh_token=body.get("refresh_token", ""),
69
+ id_token=body.get("id_token", ""),
70
+ expires_at=now + int(body.get("expires_in", 0)),
71
+ )
72
+
73
+ def is_expired(self, now: int | None = None, leeway: int = 60) -> bool:
74
+ """True if the access token has expired (with `leeway` seconds buffer)."""
75
+ now = now if now is not None else int(time.time())
76
+ return now + leeway >= self.expires_at
77
+
78
+
79
+ @functools.cache
80
+ def _machine_id() -> str:
81
+ """A stable per-machine id; falls back to the MAC address."""
82
+ try:
83
+ if sys.platform == "darwin":
84
+ out = subprocess.run( # nosec B603
85
+ ["/usr/sbin/ioreg", "-rd1", "-c", "IOPlatformExpertDevice"],
86
+ check=False,
87
+ capture_output=True,
88
+ text=True,
89
+ timeout=5,
90
+ ).stdout
91
+ found = re.search(r'"IOPlatformUUID" = "([^"]+)"', out)
92
+ if found:
93
+ return found.group(1)
94
+ elif sys.platform == "win32":
95
+ import winreg
96
+
97
+ with winreg.OpenKey(
98
+ winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Cryptography"
99
+ ) as key:
100
+ return str(winreg.QueryValueEx(key, "MachineGuid")[0])
101
+ else:
102
+ for candidate in ("/etc/machine-id", "/var/lib/dbus/machine-id"):
103
+ try:
104
+ value = Path(candidate).read_text().strip()
105
+ except OSError:
106
+ continue
107
+ if value:
108
+ return value
109
+ except (OSError, subprocess.SubprocessError):
110
+ pass
111
+ return _generated_machine_id()
112
+
113
+
114
+ def _generated_machine_id() -> str:
115
+ """No OS id (slim containers): keep one generated id next to the token.
116
+ `uuid.getnode()` is random per process on a host without a NIC, so a
117
+ token saved under it could never be read back."""
118
+ path = _config_dir() / "machine-id"
119
+ try:
120
+ value = path.read_text().strip()
121
+ except OSError:
122
+ value = ""
123
+ if value:
124
+ return value
125
+ try:
126
+ path.parent.mkdir(parents=True, exist_ok=True)
127
+ value = uuid.uuid4().hex
128
+ with _open_private(path) as f:
129
+ f.write(value)
130
+ return value
131
+ except OSError:
132
+ return str(uuid.getnode()) # read-only home: survives this process only
133
+
134
+
135
+ def _fernet(salt: bytes) -> Fernet:
136
+ user = str(os.getuid()) if hasattr(os, "getuid") else os.environ.get("USERNAME", "")
137
+ key = HKDF(
138
+ algorithm=hashes.SHA256(),
139
+ length=32,
140
+ salt=salt,
141
+ info=b"ermes-cli token v1",
142
+ ).derive(f"{_machine_id()}:{user}".encode())
143
+ return Fernet(base64.urlsafe_b64encode(key))
144
+
145
+
146
+ def save(bundle: TokenBundle) -> None:
147
+ path = _token_file()
148
+ path.parent.mkdir(parents=True, exist_ok=True)
149
+ salt = os.urandom(16)
150
+ token = _fernet(salt).encrypt(json.dumps(asdict(bundle)).encode())
151
+ # _open_private: fresh 0600 inode swapped in atomically, so a pre-existing
152
+ # wide-mode file or symlink never survives a save.
153
+ with _open_private(path) as f:
154
+ json.dump(
155
+ {"v": 1, "salt": base64.urlsafe_b64encode(salt).decode(), "token": token.decode()},
156
+ f,
157
+ )
158
+ try:
159
+ _legacy_plaintext_file().unlink(missing_ok=True)
160
+ except OSError:
161
+ pass # the new bundle is on disk; the legacy file is clear()'s job too
162
+
163
+
164
+ def load() -> TokenBundle | None:
165
+ try:
166
+ envelope = json.loads(_token_file().read_bytes())
167
+ salt = base64.urlsafe_b64decode(envelope["salt"])
168
+ data = _fernet(salt).decrypt(envelope["token"].encode())
169
+ return TokenBundle(**json.loads(data))
170
+ except (OSError, TypeError, KeyError, ValueError, AttributeError, InvalidToken):
171
+ # Corrupted, or copied from another machine/user — treat as logged out.
172
+ # The next login overwrites it.
173
+ return None
174
+
175
+
176
+ def clear() -> None:
177
+ """Remove the stored tokens. Raises `OSError` when the file cannot be
178
+ removed, so `logout` cannot report success while the token is still on
179
+ disk. An absent file is already cleared."""
180
+ _token_file().unlink(missing_ok=True)
181
+ _legacy_plaintext_file().unlink(missing_ok=True)
@@ -4,7 +4,7 @@ from typing import Optional
4
4
  import typer
5
5
  from ermes_cli import __version__
6
6
  from ermes_cli.config import resolve_profile, ConfigError
7
- from ermes_cli.client import ErmesClient
7
+ from ermes_cli.client import ErmesAPIError, ErmesClient
8
8
 
9
9
  app = typer.Typer(
10
10
  name="ermes",
@@ -171,8 +171,9 @@ def whoami(
171
171
  try:
172
172
  project_info = client.get("/")
173
173
  except Exception as e:
174
- # Never echo the exception text: an httpx header error repeats the key verbatim.
175
- typer.echo(f"Connection failed: {type(e).__name__}", err=True)
174
+ # Never echo a raw exception: an httpx header error repeats the key verbatim.
175
+ # ErmesAPIError text is built by the client and is key-free (DEV-2351).
176
+ typer.echo(f"Connection failed: {_safe_error(e)}", err=True)
176
177
  raise typer.Exit(code=1)
177
178
  finally:
178
179
  client.close()
@@ -186,6 +187,10 @@ def whoami(
186
187
  render_detail(result, use_json=state.use_json)
187
188
 
188
189
 
190
+ def _safe_error(e: Exception) -> str:
191
+ return str(e) if isinstance(e, ErmesAPIError) else type(e).__name__
192
+
193
+
189
194
  def _api_check() -> str:
190
195
  """One bounded read with the resolved key; exit 1 so scripts can gate on it.
191
196
 
@@ -196,7 +201,7 @@ def _api_check() -> str:
196
201
  try:
197
202
  client.get("/")
198
203
  except Exception as e: # noqa: BLE001 — any failure is a failed check; never echo the key
199
- typer.echo(f"api_check failed: {type(e).__name__}", err=True)
204
+ typer.echo(f"api_check failed: {_safe_error(e)}", err=True)
200
205
  raise typer.Exit(code=1)
201
206
  return "ok"
202
207
 
@@ -5,7 +5,7 @@ build-backend = "hatchling.build"
5
5
  [project]
6
6
  name = "ermes-cli"
7
7
  # Keep in lockstep with ermes_cli/__init__.py::__version__ — tests/test_version.py fails if they drift.
8
- version = "1.3.0"
8
+ version = "1.4.0"
9
9
  description = "CLI-first access to Ermes marketing automation with Auth0 multi-project auth."
10
10
  readme = "README.md"
11
11
  requires-python = ">=3.10"
@@ -25,7 +25,11 @@ dependencies = [
25
25
  "httpx>=0.28",
26
26
  "rich>=14.0",
27
27
  "pyyaml>=6.0",
28
- "keyring>=24.0",
28
+ # Fernet-encrypts the Auth0 token file (keyring_store.py); no OS vault, no prompts.
29
+ # cryptography>=49 ships no macOS x86_64 wheel (pipx would build from source,
30
+ # needs Rust); Intel Macs stay on the 48.x universal2 line.
31
+ "cryptography>=42.0; sys_platform != 'darwin' or platform_machine != 'x86_64'",
32
+ "cryptography>=42.0,<49; sys_platform == 'darwin' and platform_machine == 'x86_64'",
29
33
  "requests>=2.31",
30
34
  # zoneinfo data — guarantees `projects create --timezone` validation works on
31
35
  # hosts without system tzdata (slim containers, Windows, Lambda). Without it,
@@ -1,7 +1,6 @@
1
- import keyring
2
- import keyring.backend
3
1
  import pytest
4
2
  from typer.testing import CliRunner
3
+
5
4
  from ermes_cli.main import app, state
6
5
 
7
6
 
@@ -27,8 +26,11 @@ def invoke(runner):
27
26
  return runner.invoke(app, *args, **kwargs)
28
27
  return _invoke
29
28
 
30
- @pytest.fixture
29
+ @pytest.fixture(autouse=True)
31
30
  def config_dir(tmp_path, monkeypatch):
31
+ """Every test, not only the ones that ask: a command that reaches
32
+ keyring_store or config unpatched must land in tmp_path, never in the
33
+ developer's real `~/.ermes` (the token file lives there since DEV-2392)."""
32
34
  config_path = tmp_path / ".ermes"
33
35
  monkeypatch.setenv("ERMES_CONFIG_DIR", str(config_path))
34
36
  return config_path
@@ -40,34 +42,3 @@ def _reset_state():
40
42
  state.client = None
41
43
  state.profile_name = None
42
44
  state.use_json = False
43
-
44
-
45
- class InMemoryKeyring(keyring.backend.KeyringBackend):
46
- """Trivial in-memory keyring backend so tests never touch the real OS vault."""
47
-
48
- priority = 1
49
-
50
- def __init__(self):
51
- self._store: dict[tuple[str, str], str] = {}
52
-
53
- def get_password(self, service, username):
54
- return self._store.get((service, username))
55
-
56
- def set_password(self, service, username, password):
57
- self._store[(service, username)] = password
58
-
59
- def delete_password(self, service, username):
60
- try:
61
- del self._store[(service, username)]
62
- except KeyError as exc:
63
- raise keyring.errors.PasswordDeleteError(str(exc)) from exc
64
-
65
-
66
- @pytest.fixture(autouse=True)
67
- def in_memory_keyring():
68
- """Every test, not only test_keyring_store: a command that reaches
69
- keyring_store unpatched must hit this, never the macOS login keychain
70
- (which prompts for the user's password mid-run)."""
71
- backend = InMemoryKeyring()
72
- keyring.set_keyring(backend)
73
- yield backend
@@ -93,15 +93,26 @@ def test_login_rejects_plaintext_base_url(invoke, config_dir):
93
93
  assert result.exit_code == 1 and "https" in result.output
94
94
 
95
95
 
96
- def test_logout_fails_loudly_when_keyring_refuses_delete(invoke, config_dir, monkeypatch):
97
- import keyring
98
-
96
+ def test_logout_fails_loudly_when_the_token_file_refuses_delete(invoke, config_dir, monkeypatch):
99
97
  def refuse():
100
- raise keyring.errors.KeyringError("vault locked")
98
+ raise OSError("permission denied")
101
99
 
102
100
  monkeypatch.setattr(auth_cmds.keyring_store, "clear", refuse)
103
101
  result = invoke(["logout"])
104
- assert result.exit_code == 1 and "vault locked" in result.output
102
+ assert result.exit_code == 1 and "permission denied" in result.output
103
+
104
+
105
+ def test_logout_end_to_end_removes_the_token_file(invoke, config_dir, monkeypatch):
106
+ """No stubs on the store: a real encrypted bundle on disk is gone after `logout`."""
107
+ from ermes_cli import keyring_store
108
+
109
+ keyring_store.save(_fresh_bundle())
110
+ assert (config_dir / "ermes-cli-token.json").exists()
111
+ monkeypatch.setattr(auth_cmds.auth0, "revoke_refresh_token", lambda rt: True)
112
+ result = invoke(["logout"])
113
+ assert result.exit_code == 0, result.output
114
+ assert not (config_dir / "ermes-cli-token.json").exists()
115
+ assert keyring_store.load() is None
105
116
 
106
117
 
107
118
  def _seed_keyless(active=42):
@@ -305,25 +316,23 @@ def test_require_https_rejects_plaintext_userinfo_and_backslashes(url):
305
316
  assert exc.value.exit_code == 1
306
317
 
307
318
 
308
- def test_refresh_projects_rejects_plaintext_base_url_before_touching_the_keyring(
319
+ def test_refresh_projects_rejects_plaintext_base_url_before_touching_the_token_store(
309
320
  invoke, config_dir, monkeypatch
310
321
  ):
311
322
  def _boom():
312
- raise AssertionError("keyring read before the URL was validated")
323
+ raise AssertionError("token store read before the URL was validated")
313
324
 
314
325
  monkeypatch.setattr(auth_cmds.keyring_store, "load", _boom)
315
326
  result = invoke(["projects", "refresh", "--base-url", "http://ermes.example.com"])
316
327
  assert result.exit_code == 1 and "https" in result.output
317
328
 
318
329
 
319
- def test_logout_still_removes_projects_yml_when_keyring_refuses_delete(invoke, config_dir, monkeypatch):
320
- import keyring
321
-
330
+ def test_logout_still_removes_projects_yml_when_the_token_file_refuses_delete(invoke, config_dir, monkeypatch):
322
331
  _seed_keyless()
323
332
  assert get_projects()
324
333
 
325
334
  def refuse():
326
- raise keyring.errors.KeyringError("vault locked")
335
+ raise OSError("permission denied")
327
336
 
328
337
  monkeypatch.setattr(auth_cmds.keyring_store, "clear", refuse)
329
338
  result = invoke(["logout"])
@@ -2,7 +2,7 @@
2
2
 
3
3
  Unlike the other command tests (which exercise client.py over httpx and use
4
4
  pytest-httpx), `projects create` runs entirely through admin_api.py over
5
- `requests`, so we mock with `responses` and stub the keychain bundle.
5
+ `requests`, so we mock with `responses` and stub the token bundle.
6
6
  """
7
7
 
8
8
  from __future__ import annotations
@@ -25,7 +25,7 @@ EXCHANGE_OK = {
25
25
 
26
26
 
27
27
  def _stub_admin_session(monkeypatch):
28
- """Pin the host-derived key name + a non-expired keychain bundle, and mock
28
+ """Pin the host-derived key name + a non-expired token bundle, and mock
29
29
  the Auth0→Ermes exchange so _ensure_admin_session resolves to a JWT."""
30
30
  monkeypatch.setattr("socket.gethostname", lambda: "buildhost")
31
31
  monkeypatch.setattr("ermes_cli.admin_api.socket.gethostname", lambda: "buildhost")