mimiry 0.2.1__tar.gz → 0.2.2__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 (27) hide show
  1. {mimiry-0.2.1 → mimiry-0.2.2}/PKG-INFO +2 -2
  2. {mimiry-0.2.1 → mimiry-0.2.2}/README.md +1 -1
  3. {mimiry-0.2.1 → mimiry-0.2.2}/pyproject.toml +1 -1
  4. {mimiry-0.2.1 → mimiry-0.2.2}/src/Mimiry.egg-info/PKG-INFO +2 -2
  5. {mimiry-0.2.1 → mimiry-0.2.2}/src/Mimiry.egg-info/SOURCES.txt +3 -1
  6. mimiry-0.2.2/src/mimiry/_config.py +177 -0
  7. {mimiry-0.2.1 → mimiry-0.2.2}/src/mimiry/_setup.py +19 -16
  8. mimiry-0.2.2/tests/test_config.py +105 -0
  9. mimiry-0.2.2/tests/test_setup.py +264 -0
  10. mimiry-0.2.1/src/mimiry/_config.py +0 -58
  11. {mimiry-0.2.1 → mimiry-0.2.2}/setup.cfg +0 -0
  12. {mimiry-0.2.1 → mimiry-0.2.2}/src/Mimiry.egg-info/dependency_links.txt +0 -0
  13. {mimiry-0.2.1 → mimiry-0.2.2}/src/Mimiry.egg-info/entry_points.txt +0 -0
  14. {mimiry-0.2.1 → mimiry-0.2.2}/src/Mimiry.egg-info/requires.txt +0 -0
  15. {mimiry-0.2.1 → mimiry-0.2.2}/src/Mimiry.egg-info/top_level.txt +0 -0
  16. {mimiry-0.2.1 → mimiry-0.2.2}/src/mimiry/__init__.py +0 -0
  17. {mimiry-0.2.1 → mimiry-0.2.2}/src/mimiry/__main__.py +0 -0
  18. {mimiry-0.2.1 → mimiry-0.2.2}/src/mimiry/_auth.py +0 -0
  19. {mimiry-0.2.1 → mimiry-0.2.2}/src/mimiry/_cli.py +0 -0
  20. {mimiry-0.2.1 → mimiry-0.2.2}/src/mimiry/_client.py +0 -0
  21. {mimiry-0.2.1 → mimiry-0.2.2}/src/mimiry/_serialization.py +0 -0
  22. {mimiry-0.2.1 → mimiry-0.2.2}/src/mimiry/_session.py +0 -0
  23. {mimiry-0.2.1 → mimiry-0.2.2}/src/mimiry/_ssh.py +0 -0
  24. {mimiry-0.2.1 → mimiry-0.2.2}/src/mimiry/exceptions.py +0 -0
  25. {mimiry-0.2.1 → mimiry-0.2.2}/src/mimiry/function.py +0 -0
  26. {mimiry-0.2.1 → mimiry-0.2.2}/src/mimiry/image.py +0 -0
  27. {mimiry-0.2.1 → mimiry-0.2.2}/src/mimiry/run.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: Mimiry
3
- Version: 0.2.1
3
+ Version: 0.2.2
4
4
  Summary: Python SDK for serverless compute
5
5
  Author-email: Oliver <oliversorensen39@gmail.com>
6
6
  License: Proprietary
@@ -40,7 +40,7 @@ pip install -e .
40
40
 
41
41
  ## Auth
42
42
 
43
- Running jobs requires a Mimiry account. The SDK authenticates with SSH-JWT — the same SSH key you register on your account at the [Mimiry portal](https://softlaunch.mimiry.com). The fastest way to get set up is the interactive wizard, which generates a key (if needed), walks you through registering it in the portal, writes `MIMIRY_SSH_KEY` to your shell profile, and verifies the connection:
43
+ Running jobs requires a Mimiry account. The SDK authenticates with SSH-JWT — the same SSH key you register on your account at the [Mimiry portal](https://softlaunch.mimiry.com). The fastest way to get set up is the interactive wizard, which generates a key (if needed), walks you through registering it in the portal, saves the key path to `~/.config/mimiry/config.toml` so the SDK works right away (and in every future shell, no restart needed), and verifies the connection. It also exports `MIMIRY_SSH_KEY` to your shell profile for `curl`/shell use:
44
44
 
45
45
  ```bash
46
46
  mimiry setup # alias: mimiry init
@@ -19,7 +19,7 @@ pip install -e .
19
19
 
20
20
  ## Auth
21
21
 
22
- Running jobs requires a Mimiry account. The SDK authenticates with SSH-JWT — the same SSH key you register on your account at the [Mimiry portal](https://softlaunch.mimiry.com). The fastest way to get set up is the interactive wizard, which generates a key (if needed), walks you through registering it in the portal, writes `MIMIRY_SSH_KEY` to your shell profile, and verifies the connection:
22
+ Running jobs requires a Mimiry account. The SDK authenticates with SSH-JWT — the same SSH key you register on your account at the [Mimiry portal](https://softlaunch.mimiry.com). The fastest way to get set up is the interactive wizard, which generates a key (if needed), walks you through registering it in the portal, saves the key path to `~/.config/mimiry/config.toml` so the SDK works right away (and in every future shell, no restart needed), and verifies the connection. It also exports `MIMIRY_SSH_KEY` to your shell profile for `curl`/shell use:
23
23
 
24
24
  ```bash
25
25
  mimiry setup # alias: mimiry init
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "Mimiry"
7
- version = "0.2.1"
7
+ version = "0.2.2"
8
8
  description = "Python SDK for serverless compute"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: Mimiry
3
- Version: 0.2.1
3
+ Version: 0.2.2
4
4
  Summary: Python SDK for serverless compute
5
5
  Author-email: Oliver <oliversorensen39@gmail.com>
6
6
  License: Proprietary
@@ -40,7 +40,7 @@ pip install -e .
40
40
 
41
41
  ## Auth
42
42
 
43
- Running jobs requires a Mimiry account. The SDK authenticates with SSH-JWT — the same SSH key you register on your account at the [Mimiry portal](https://softlaunch.mimiry.com). The fastest way to get set up is the interactive wizard, which generates a key (if needed), walks you through registering it in the portal, writes `MIMIRY_SSH_KEY` to your shell profile, and verifies the connection:
43
+ Running jobs requires a Mimiry account. The SDK authenticates with SSH-JWT — the same SSH key you register on your account at the [Mimiry portal](https://softlaunch.mimiry.com). The fastest way to get set up is the interactive wizard, which generates a key (if needed), walks you through registering it in the portal, saves the key path to `~/.config/mimiry/config.toml` so the SDK works right away (and in every future shell, no restart needed), and verifies the connection. It also exports `MIMIRY_SSH_KEY` to your shell profile for `curl`/shell use:
44
44
 
45
45
  ```bash
46
46
  mimiry setup # alias: mimiry init
@@ -19,4 +19,6 @@ src/mimiry/_ssh.py
19
19
  src/mimiry/exceptions.py
20
20
  src/mimiry/function.py
21
21
  src/mimiry/image.py
22
- src/mimiry/run.py
22
+ src/mimiry/run.py
23
+ tests/test_config.py
24
+ tests/test_setup.py
@@ -0,0 +1,177 @@
1
+ """Process-global SDK configuration. Holds auth + API base URL.
2
+
3
+ Key-path resolution precedence (highest first):
4
+
5
+ 1. an explicit ``mimiry.configure(ssh_key_path=...)`` call or the ``--ssh-key``
6
+ CLI flag
7
+ 2. the ``MIMIRY_SSH_KEY`` environment variable
8
+ 3. the on-disk config file written by ``mimiry setup``
9
+ (``$XDG_CONFIG_HOME/mimiry/config.toml``, default ``~/.config/mimiry/config.toml``)
10
+
11
+ The config file stores **only the path** to the SSH key — never the key
12
+ material itself, and never a token. That keeps the file low-sensitivity: the
13
+ real secret stays in ``~/.ssh/mimiry`` behind its own ``0600`` perms. We still
14
+ write the config ``0600`` and refuse to read it if it's group/other-writable,
15
+ since a writable config would be a key-redirection injection vector.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import os
21
+ import stat
22
+ import tempfile
23
+ from dataclasses import dataclass, field
24
+ from pathlib import Path
25
+
26
+ DEFAULT_API_BASE = "https://softlaunch.mimiry.com"
27
+ DEFAULT_TIMEOUT_SECONDS = 1800 # 30 min — must accommodate ~2 min cold start + work
28
+
29
+ # Group/other WRITABLE bits. We reject a config carrying these on read: an
30
+ # attacker who can write the file could repoint the SDK at a key they control.
31
+ # Readability is *not* checked — the file holds only a path, which isn't secret.
32
+ _INSECURE_WRITE_BITS = stat.S_IWGRP | stat.S_IWOTH # 0o022
33
+
34
+
35
+ @dataclass
36
+ class Config:
37
+ ssh_key_path: Path | None = None
38
+ api_base: str = DEFAULT_API_BASE
39
+ timeout_seconds: int = DEFAULT_TIMEOUT_SECONDS
40
+ poll_interval_seconds: float = 5.0
41
+ # Tighter than state polling — the marker-emission → auto_terminate window is
42
+ # only the wrapper's tail sleep (~20s), so we need ~2s cadence to catch it reliably.
43
+ log_poll_interval_seconds: float = 2.0
44
+ extras: dict = field(default_factory=dict)
45
+
46
+
47
+ _config = Config()
48
+
49
+
50
+ # ────────────────────────── on-disk config file ──────────────────────────
51
+
52
+
53
+ def config_path() -> Path:
54
+ """Path to the persisted config file (honours ``$XDG_CONFIG_HOME``)."""
55
+ base = os.environ.get("XDG_CONFIG_HOME")
56
+ root = Path(base).expanduser() if base else Path.home() / ".config"
57
+ return root / "mimiry" / "config.toml"
58
+
59
+
60
+ def save_key_path(ssh_key_path: str | Path, path: Path | None = None) -> Path:
61
+ """Persist the SSH key *path* (never key material) to a ``0600`` config file.
62
+
63
+ The write is atomic — content goes to a temp file in the same directory and
64
+ is ``os.replace``-d into place — so a crash mid-write can't leave a
65
+ truncated config behind. The containing directory is created ``0700``.
66
+ """
67
+ cfg_path = path or config_path()
68
+ cfg_path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
69
+
70
+ key_str = str(Path(ssh_key_path).expanduser())
71
+ # TOML-escape backslashes/quotes (defensive — WSL paths are POSIX, but a
72
+ # Windows-style path could carry backslashes).
73
+ escaped = key_str.replace("\\", "\\\\").replace('"', '\\"')
74
+ body = (
75
+ "# Mimiry SDK config — written by `mimiry setup`.\n"
76
+ "# Holds only the path to your SSH key, never the key itself.\n"
77
+ f'ssh_key_path = "{escaped}"\n'
78
+ )
79
+
80
+ fd, tmp_name = tempfile.mkstemp(dir=str(cfg_path.parent), prefix=".config-", suffix=".tmp")
81
+ tmp = Path(tmp_name)
82
+ try:
83
+ os.fchmod(fd, 0o600)
84
+ with os.fdopen(fd, "w") as fh:
85
+ fh.write(body)
86
+ fh.flush()
87
+ os.fsync(fh.fileno())
88
+ os.replace(tmp, cfg_path) # atomic on POSIX
89
+ except BaseException:
90
+ tmp.unlink(missing_ok=True)
91
+ raise
92
+ return cfg_path
93
+
94
+
95
+ def read_key_path(path: Path | None = None) -> Path | None:
96
+ """Return the key path stored in the config file, or ``None`` if absent.
97
+
98
+ Raises ``PermissionError`` if the file is group/other-writable, since a
99
+ writable config is a key-redirection injection vector.
100
+ """
101
+ cfg_path = path or config_path()
102
+ try:
103
+ st = cfg_path.stat()
104
+ except FileNotFoundError:
105
+ return None
106
+ if st.st_mode & _INSECURE_WRITE_BITS:
107
+ raise PermissionError(
108
+ f"{cfg_path} is writable by group/other ({oct(stat.S_IMODE(st.st_mode))}); "
109
+ f"refusing to trust it. Fix with: chmod 600 {cfg_path}"
110
+ )
111
+ value = _load_toml(cfg_path.read_text()).get("ssh_key_path")
112
+ return Path(value).expanduser() if value else None
113
+
114
+
115
+ def _load_toml(text: str) -> dict:
116
+ """Parse the config file, preferring stdlib ``tomllib`` (Python 3.11+)."""
117
+ try:
118
+ import tomllib
119
+ except ModuleNotFoundError: # Python 3.10 — no stdlib TOML parser
120
+ return _parse_simple_toml(text)
121
+ return tomllib.loads(text)
122
+
123
+
124
+ def _parse_simple_toml(text: str) -> dict:
125
+ """Minimal fallback for Python 3.10: top-level ``key = "value"`` scalars only.
126
+
127
+ Sufficient for our schema (a single string key). Not a general TOML parser.
128
+ """
129
+ result: dict[str, str] = {}
130
+ for raw in text.splitlines():
131
+ line = raw.split("#", 1)[0].strip()
132
+ if not line or "=" not in line:
133
+ continue
134
+ key, _, value = line.partition("=")
135
+ value = value.strip()
136
+ if len(value) >= 2 and value[0] == value[-1] and value[0] in ("'", '"'):
137
+ value = value[1:-1].replace('\\"', '"').replace("\\\\", "\\")
138
+ result[key.strip()] = value
139
+ return result
140
+
141
+
142
+ # ────────────────────────── public configuration API ──────────────────────────
143
+
144
+
145
+ def configure(
146
+ ssh_key_path: str | Path | None = None,
147
+ api_base: str | None = None,
148
+ timeout_seconds: int | None = None,
149
+ poll_interval_seconds: float | None = None,
150
+ ) -> Config:
151
+ """Set SDK-wide configuration. Any argument left as ``None`` is unchanged."""
152
+ if ssh_key_path is not None:
153
+ _config.ssh_key_path = Path(ssh_key_path).expanduser()
154
+ if api_base is not None:
155
+ _config.api_base = api_base.rstrip("/")
156
+ if timeout_seconds is not None:
157
+ _config.timeout_seconds = timeout_seconds
158
+ if poll_interval_seconds is not None:
159
+ _config.poll_interval_seconds = poll_interval_seconds
160
+ return _config
161
+
162
+
163
+ def get_config() -> Config:
164
+ """Return the active configuration, resolving the key path on first read.
165
+
166
+ Precedence: an explicit ``configure()`` call (already on ``_config``) wins;
167
+ otherwise ``MIMIRY_SSH_KEY``; otherwise the on-disk config file.
168
+ """
169
+ if _config.ssh_key_path is None:
170
+ env_key = os.environ.get("MIMIRY_SSH_KEY")
171
+ if env_key:
172
+ _config.ssh_key_path = Path(env_key).expanduser()
173
+ else:
174
+ _config.ssh_key_path = read_key_path() # may stay None
175
+ if "MIMIRY_API_BASE" in os.environ:
176
+ _config.api_base = os.environ["MIMIRY_API_BASE"].rstrip("/")
177
+ return _config
@@ -4,9 +4,10 @@ A one-time interactive wizard for Mimiry's SSH-JWT auth (there is no API-key
4
4
  flow). The wizard:
5
5
 
6
6
  1. Generates an ed25519 key at ``~/.ssh/mimiry`` if one doesn't already exist.
7
- 2. Shows the public key and opens the portal so the user can register it
8
- (there is no key-registration API — registration is manual in the portal).
9
- 3. Writes ``MIMIRY_SSH_KEY`` to the user's shell rc file (with confirmation).
7
+ 2. Shows the public key so the user can register it in the portal (there is no
8
+ key-registration API — registration is manual).
9
+ 3. Saves the key path to the SDK config file so the SDK works immediately, and
10
+ also exports ``MIMIRY_SSH_KEY`` to the user's shell rc for shell/curl use.
10
11
  4. Runs a balance check to verify the whole chain end-to-end.
11
12
 
12
13
  Everything here is deliberately dependency-free (stdlib only) and degrades
@@ -19,12 +20,11 @@ from __future__ import annotations
19
20
  import os
20
21
  import subprocess
21
22
  import sys
22
- import webbrowser
23
23
  from pathlib import Path
24
24
 
25
25
  from mimiry._auth import get_token
26
26
  from mimiry._client import MimiryClient
27
- from mimiry._config import DEFAULT_API_BASE
27
+ from mimiry._config import DEFAULT_API_BASE, save_key_path
28
28
 
29
29
  DEFAULT_KEY_PATH = Path("~/.ssh/mimiry").expanduser()
30
30
 
@@ -103,12 +103,10 @@ def _register_key(pub_path: Path, api_base: str) -> None:
103
103
  print(" (Mimiry has no key-registration API yet — this step is manual.)")
104
104
 
105
105
  if _is_interactive():
106
- if _confirm("\n Open the portal in your browser now?", default=True):
107
- try:
108
- webbrowser.open(portal_url)
109
- except Exception:
110
- pass # headless / no browser — the URL is printed above anyway
111
- _prompt("\n Press Enter once the key is registered to continue...")
106
+ # Note: we intentionally do not auto-open a browser. `webbrowser.open`
107
+ # shells out to xdg-open on Linux/WSL, which errors noisily (or hangs)
108
+ # when no opener is installed. The URL above is copy-pasteable.
109
+ _prompt("\n Open the URL above, then press Enter once the key is registered...")
112
110
 
113
111
 
114
112
  # ────────────────────────── step 3: write shell rc ──────────────────────────
@@ -150,8 +148,8 @@ def _write_rc(key_path: Path) -> None:
150
148
  needs_nl = existing and not existing.endswith("\n")
151
149
  with rc_path.open("a") as fh:
152
150
  fh.write(("\n" if needs_nl else "") + f"\n{_RC_MARKER}\n{export_line}\n")
153
- print(f" Wrote MIMIRY_SSH_KEY to {rc_path}.")
154
- print(f" Restart your shell or run: source {rc_path}")
151
+ print(f" Also exported MIMIRY_SSH_KEY in {rc_path} (for shell/curl use).")
152
+ print(" That activates in new shells — no restart needed for the SDK itself.")
155
153
 
156
154
 
157
155
  # ────────────────────────── step 4: verify ──────────────────────────
@@ -195,10 +193,15 @@ def run_setup_wizard(
195
193
  _step(2, "Register your key in the portal")
196
194
  _register_key(pub, api_base)
197
195
 
198
- _step(3, "Persist MIMIRY_SSH_KEY")
199
- # Make the key visible to this process so the verification step works even
200
- # before the user reloads their shell.
196
+ _step(3, "Save configuration")
197
+ # Primary mechanism: write the key path to the SDK config file. The SDK
198
+ # reads this directly, so it works in *this* shell and every future one
199
+ # without a restart. (Make it visible to this process too, for the verify
200
+ # step below.)
201
201
  os.environ["MIMIRY_SSH_KEY"] = str(priv)
202
+ cfg_file = save_key_path(priv)
203
+ print(f" Saved key path to {cfg_file} (chmod 600) — the SDK uses this immediately.")
204
+ # Secondary convenience: export the env var for shell/curl workflows too.
202
205
  _write_rc(priv)
203
206
 
204
207
  _step(4, "Verify")
@@ -0,0 +1,105 @@
1
+ """Tests for SDK config persistence + key-path resolution precedence."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import stat
7
+ from pathlib import Path
8
+
9
+ import pytest
10
+
11
+ import mimiry._config as cfg_mod
12
+ from mimiry._config import (
13
+ Config,
14
+ _parse_simple_toml,
15
+ config_path,
16
+ get_config,
17
+ read_key_path,
18
+ save_key_path,
19
+ )
20
+
21
+
22
+ @pytest.fixture(autouse=True)
23
+ def isolate_config(tmp_path, monkeypatch):
24
+ """Point XDG at a tmp dir and reset the process-global config per test."""
25
+ monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path / "xdg"))
26
+ monkeypatch.delenv("MIMIRY_SSH_KEY", raising=False)
27
+ monkeypatch.delenv("MIMIRY_API_BASE", raising=False)
28
+ # Reset the module-global Config so cached state doesn't leak across tests.
29
+ monkeypatch.setattr(cfg_mod, "_config", Config())
30
+ yield
31
+
32
+
33
+ def test_config_path_honours_xdg(tmp_path):
34
+ assert config_path() == tmp_path / "xdg" / "mimiry" / "config.toml"
35
+
36
+
37
+ def test_save_creates_secure_file_and_dir():
38
+ written = save_key_path("~/.ssh/mimiry")
39
+ assert written.is_file()
40
+ # File is 0600, parent dir is 0700.
41
+ assert stat.S_IMODE(written.stat().st_mode) == 0o600
42
+ assert stat.S_IMODE(written.parent.stat().st_mode) == 0o700
43
+ # Stores the expanded path, not key material.
44
+ text = written.read_text()
45
+ assert str(Path("~/.ssh/mimiry").expanduser()) in text
46
+ assert "PRIVATE KEY" not in text
47
+
48
+
49
+ def test_save_then_read_round_trips():
50
+ save_key_path("/home/olive/.ssh/mimiry")
51
+ assert read_key_path() == Path("/home/olive/.ssh/mimiry")
52
+
53
+
54
+ def test_read_missing_returns_none():
55
+ assert read_key_path() is None
56
+
57
+
58
+ def test_read_rejects_group_or_other_writable():
59
+ written = save_key_path("/home/olive/.ssh/mimiry")
60
+ # Make it group+other writable — the injection vector we guard against.
61
+ written.chmod(0o666)
62
+ with pytest.raises(PermissionError, match="writable by group/other"):
63
+ read_key_path()
64
+
65
+
66
+ def test_world_readable_is_allowed():
67
+ """A path isn't secret; only writability is rejected."""
68
+ written = save_key_path("/home/olive/.ssh/mimiry")
69
+ written.chmod(0o644) # readable by all, writable by none-but-owner
70
+ assert read_key_path() == Path("/home/olive/.ssh/mimiry")
71
+
72
+
73
+ def test_precedence_explicit_beats_env_and_file(monkeypatch):
74
+ save_key_path("/from/file")
75
+ monkeypatch.setenv("MIMIRY_SSH_KEY", "/from/env")
76
+ cfg_mod.configure(ssh_key_path="/from/arg")
77
+ assert get_config().ssh_key_path == Path("/from/arg")
78
+
79
+
80
+ def test_precedence_env_beats_file(monkeypatch):
81
+ save_key_path("/from/file")
82
+ monkeypatch.setenv("MIMIRY_SSH_KEY", "/from/env")
83
+ assert get_config().ssh_key_path == Path("/from/env")
84
+
85
+
86
+ def test_precedence_file_used_when_no_env_or_explicit():
87
+ save_key_path("/from/file")
88
+ assert get_config().ssh_key_path == Path("/from/file")
89
+
90
+
91
+ def test_get_config_none_when_nothing_set():
92
+ assert get_config().ssh_key_path is None
93
+
94
+
95
+ def test_simple_toml_parser_fallback():
96
+ text = (
97
+ "# a comment\n"
98
+ '\n'
99
+ 'ssh_key_path = "/home/olive/.ssh/mimiry" # trailing\n'
100
+ )
101
+ assert _parse_simple_toml(text)["ssh_key_path"] == "/home/olive/.ssh/mimiry"
102
+
103
+
104
+ def test_simple_toml_parser_unescapes():
105
+ assert _parse_simple_toml(r'ssh_key_path = "C:\\Users\\olive"')["ssh_key_path"] == r"C:\Users\olive"
@@ -0,0 +1,264 @@
1
+ """Tests for the interactive setup wizard (``mimiry setup`` / ``mimiry init``).
2
+
3
+ All external effects are mocked: ``ssh-keygen`` is never invoked for real, no
4
+ network call is made, and the user's real home / rc files are never touched.
5
+ Prompts are driven by monkeypatching ``_setup._prompt`` / ``_setup._confirm``
6
+ or by feeding ``input`` via ``monkeypatch.setattr('builtins.input', ...)``.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import subprocess
12
+ from pathlib import Path
13
+
14
+ import pytest
15
+
16
+ import mimiry._setup as setup
17
+
18
+
19
+ # ────────────────────────── prompt helpers ──────────────────────────
20
+
21
+
22
+ def test_prompt_returns_default_on_eof(monkeypatch):
23
+ def boom(_msg):
24
+ raise EOFError
25
+
26
+ monkeypatch.setattr("builtins.input", boom)
27
+ assert setup._prompt("anything? ", default="fallback") == "fallback"
28
+
29
+
30
+ def test_prompt_strips_and_falls_back_to_default_on_empty(monkeypatch):
31
+ monkeypatch.setattr("builtins.input", lambda _msg: " ")
32
+ assert setup._prompt("q? ", default="d") == "d"
33
+ monkeypatch.setattr("builtins.input", lambda _msg: " hello ")
34
+ assert setup._prompt("q? ", default="d") == "hello"
35
+
36
+
37
+ @pytest.mark.parametrize(
38
+ ("answer", "default", "expected"),
39
+ [
40
+ ("", True, True), # empty → default
41
+ ("", False, False),
42
+ ("y", False, True),
43
+ ("yes", False, True),
44
+ ("n", True, False),
45
+ ("nope", True, False), # anything not in {y,yes} is False
46
+ ],
47
+ )
48
+ def test_confirm(monkeypatch, answer, default, expected):
49
+ monkeypatch.setattr(setup, "_prompt", lambda _msg: answer)
50
+ assert setup._confirm("ok?", default=default) is expected
51
+
52
+
53
+ # ────────────────────────── _ensure_key ──────────────────────────
54
+
55
+
56
+ def _fake_run_factory(record):
57
+ """Return a fake ``subprocess.run`` that records calls and fakes ssh-keygen.
58
+
59
+ For ``ssh-keygen -y`` (derive pubkey) it writes a dummy line to the passed
60
+ ``stdout`` file handle; for keypair generation it creates the priv/pub files.
61
+ """
62
+
63
+ def fake_run(cmd, *args, **kwargs):
64
+ record.append(cmd)
65
+ if "-y" in cmd: # derive public key from private key → stdout
66
+ kwargs["stdout"].write("ssh-ed25519 AAAAfake derived\n")
67
+ elif "-t" in cmd: # generate a new keypair at -f <path>
68
+ target = Path(cmd[cmd.index("-f") + 1])
69
+ target.write_text("PRIVATE\n")
70
+ Path(f"{target}.pub").write_text("ssh-ed25519 AAAAfake mimiry\n")
71
+ return subprocess.CompletedProcess(cmd, 0)
72
+
73
+ return fake_run
74
+
75
+
76
+ def test_ensure_key_generates_when_missing(tmp_path, monkeypatch, capsys):
77
+ calls: list = []
78
+ monkeypatch.setattr(setup.subprocess, "run", _fake_run_factory(calls))
79
+ key = tmp_path / "subdir" / "mimiry"
80
+
81
+ result = setup._ensure_key(key)
82
+
83
+ assert result == key
84
+ assert key.is_file() and Path(f"{key}.pub").is_file()
85
+ # Parent dir created with 0700.
86
+ assert (key.parent.stat().st_mode & 0o777) == 0o700
87
+ # ssh-keygen was asked for an ed25519 key at the right path.
88
+ assert calls and calls[0][:3] == ["ssh-keygen", "-t", "ed25519"]
89
+ assert str(key) in calls[0]
90
+
91
+
92
+ def test_ensure_key_uses_existing_keypair_without_regenerating(tmp_path, monkeypatch):
93
+ calls: list = []
94
+ monkeypatch.setattr(setup.subprocess, "run", _fake_run_factory(calls))
95
+ key = tmp_path / "mimiry"
96
+ key.write_text("PRIVATE\n")
97
+ Path(f"{key}.pub").write_text("ssh-ed25519 AAAA existing\n")
98
+
99
+ assert setup._ensure_key(key) == key
100
+ assert calls == [] # no ssh-keygen invocation at all
101
+
102
+
103
+ def test_ensure_key_derives_missing_pub_from_existing_priv(tmp_path, monkeypatch):
104
+ calls: list = []
105
+ monkeypatch.setattr(setup.subprocess, "run", _fake_run_factory(calls))
106
+ key = tmp_path / "mimiry"
107
+ key.write_text("PRIVATE\n") # priv present, .pub absent
108
+
109
+ setup._ensure_key(key)
110
+
111
+ pub = Path(f"{key}.pub")
112
+ assert pub.is_file()
113
+ assert pub.read_text() == "ssh-ed25519 AAAAfake derived\n"
114
+ # Used the "-y" derive path, not a full keygen.
115
+ assert calls and "-y" in calls[0]
116
+
117
+
118
+ # ────────────────────────── _detect_rc ──────────────────────────
119
+
120
+
121
+ @pytest.mark.parametrize(
122
+ ("shell", "rc_name", "needle"),
123
+ [
124
+ ("/usr/bin/zsh", ".zshrc", "export MIMIRY_SSH_KEY="),
125
+ ("/usr/bin/bash", ".bashrc", "export MIMIRY_SSH_KEY="),
126
+ ("/usr/bin/fish", "config.fish", "set -x MIMIRY_SSH_KEY "),
127
+ ("", ".bashrc", "export MIMIRY_SSH_KEY="), # unknown → bash default
128
+ ],
129
+ )
130
+ def test_detect_rc(monkeypatch, tmp_path, shell, rc_name, needle):
131
+ monkeypatch.setenv("SHELL", shell)
132
+ monkeypatch.setattr(setup.Path, "home", classmethod(lambda cls: tmp_path))
133
+ rc_path, template = setup._detect_rc()
134
+ assert rc_path.name == rc_name
135
+ assert needle in template
136
+
137
+
138
+ # ────────────────────────── _write_rc ──────────────────────────
139
+
140
+
141
+ @pytest.fixture
142
+ def home(tmp_path, monkeypatch):
143
+ """Point ``Path.home()`` at a tmp dir and default the shell to bash."""
144
+ monkeypatch.setattr(setup.Path, "home", classmethod(lambda cls: tmp_path))
145
+ monkeypatch.setenv("SHELL", "/bin/bash")
146
+ return tmp_path
147
+
148
+
149
+ def test_write_rc_appends_export_with_marker(home, monkeypatch):
150
+ monkeypatch.setattr(setup, "_confirm", lambda *a, **k: True)
151
+ key = Path("/home/olive/.ssh/mimiry")
152
+
153
+ setup._write_rc(key)
154
+
155
+ rc = (home / ".bashrc").read_text()
156
+ assert setup._RC_MARKER in rc
157
+ assert f"export MIMIRY_SSH_KEY={key}" in rc
158
+
159
+
160
+ def test_write_rc_is_idempotent_when_line_present(home, monkeypatch):
161
+ key = Path("/home/olive/.ssh/mimiry")
162
+ rc = home / ".bashrc"
163
+ rc.write_text(f"export MIMIRY_SSH_KEY={key}\n")
164
+ # Should not even ask to confirm — fail loudly if it does.
165
+ monkeypatch.setattr(setup, "_confirm", lambda *a, **k: pytest.fail("should not prompt"))
166
+
167
+ setup._write_rc(key)
168
+
169
+ # Unchanged — no duplicate marker line added.
170
+ assert rc.read_text() == f"export MIMIRY_SSH_KEY={key}\n"
171
+
172
+
173
+ def test_write_rc_respects_decline(home, monkeypatch):
174
+ monkeypatch.setattr(setup, "_confirm", lambda *a, **k: False)
175
+ rc = home / ".bashrc"
176
+ rc.write_text("# pre-existing\n")
177
+
178
+ setup._write_rc(Path("/home/olive/.ssh/mimiry"))
179
+
180
+ assert "MIMIRY_SSH_KEY" not in rc.read_text()
181
+
182
+
183
+ def test_write_rc_warns_on_conflicting_value_and_can_skip(home, monkeypatch):
184
+ rc = home / ".bashrc"
185
+ rc.write_text("export MIMIRY_SSH_KEY=/old/key\n")
186
+ # First _confirm = "append anyway?" → decline, so nothing else happens.
187
+ monkeypatch.setattr(setup, "_confirm", lambda *a, **k: False)
188
+
189
+ setup._write_rc(Path("/new/key"))
190
+
191
+ assert "/new/key" not in rc.read_text()
192
+ assert "/old/key" in rc.read_text()
193
+
194
+
195
+ # ────────────────────────── _verify ──────────────────────────
196
+
197
+
198
+ class _FakeClient:
199
+ def __init__(self, balance):
200
+ self._balance = balance
201
+
202
+ def __enter__(self):
203
+ return self
204
+
205
+ def __exit__(self, *exc):
206
+ return False
207
+
208
+ def get_balance(self):
209
+ return self._balance
210
+
211
+
212
+ def test_verify_success(monkeypatch, capsys):
213
+ monkeypatch.setattr(setup, "get_token", lambda key, base: "tok")
214
+ monkeypatch.setattr(setup, "MimiryClient", lambda tok: _FakeClient({"balance": 42, "currency": "EUR"}))
215
+
216
+ assert setup._verify(Path("/k"), "https://api") is True
217
+ out = capsys.readouterr().out
218
+ assert "42 EUR" in out
219
+
220
+
221
+ def test_verify_failure_returns_false_with_guidance(monkeypatch, capsys):
222
+ def boom(_key, _base):
223
+ raise RuntimeError("key not registered")
224
+
225
+ monkeypatch.setattr(setup, "get_token", boom)
226
+
227
+ assert setup._verify(Path("/k"), "https://api") is False
228
+ out = capsys.readouterr().out
229
+ assert "Balance check failed" in out
230
+ assert "register" in out.lower()
231
+
232
+
233
+ # ────────────────────────── run_setup_wizard orchestration ──────────────────────────
234
+
235
+
236
+ def test_run_setup_wizard_success(monkeypatch, tmp_path):
237
+ """End-to-end happy path with every side-effecting step stubbed."""
238
+ priv = tmp_path / "mimiry"
239
+ priv.write_text("PRIVATE\n")
240
+ Path(f"{priv}.pub").write_text("ssh-ed25519 AAAA mimiry\n")
241
+
242
+ monkeypatch.setattr(setup, "_ensure_key", lambda kp: priv)
243
+ monkeypatch.setattr(setup, "_register_key", lambda pub, base: None)
244
+ monkeypatch.setattr(setup, "save_key_path", lambda p: tmp_path / "config.toml")
245
+ monkeypatch.setattr(setup, "_write_rc", lambda p: None)
246
+ monkeypatch.setattr(setup, "_verify", lambda p, b: True)
247
+ monkeypatch.delenv("MIMIRY_SSH_KEY", raising=False)
248
+
249
+ code = setup.run_setup_wizard(ssh_key_path=priv, api_base="https://api")
250
+
251
+ assert code == 0
252
+ # The wizard exports the key for the current process (used by verify).
253
+ assert setup.os.environ["MIMIRY_SSH_KEY"] == str(priv)
254
+
255
+
256
+ def test_run_setup_wizard_returns_1_when_verify_fails(monkeypatch, tmp_path):
257
+ priv = tmp_path / "mimiry"
258
+ monkeypatch.setattr(setup, "_ensure_key", lambda kp: priv)
259
+ monkeypatch.setattr(setup, "_register_key", lambda pub, base: None)
260
+ monkeypatch.setattr(setup, "save_key_path", lambda p: tmp_path / "config.toml")
261
+ monkeypatch.setattr(setup, "_write_rc", lambda p: None)
262
+ monkeypatch.setattr(setup, "_verify", lambda p, b: False)
263
+
264
+ assert setup.run_setup_wizard(ssh_key_path=priv, api_base="https://api") == 1
@@ -1,58 +0,0 @@
1
- """Process-global SDK configuration. Holds auth + API base URL.
2
-
3
- Users either set MIMIRY_SSH_KEY env var or call ``mimiry.configure(ssh_key_path=...)``
4
- once. Subsequent calls override.
5
- """
6
-
7
- from __future__ import annotations
8
-
9
- import os
10
- from dataclasses import dataclass, field
11
- from pathlib import Path
12
-
13
- DEFAULT_API_BASE = "https://softlaunch.mimiry.com"
14
- DEFAULT_TIMEOUT_SECONDS = 1800 # 30 min — must accommodate ~2 min cold start + work
15
-
16
-
17
- @dataclass
18
- class Config:
19
- ssh_key_path: Path | None = None
20
- api_base: str = DEFAULT_API_BASE
21
- timeout_seconds: int = DEFAULT_TIMEOUT_SECONDS
22
- poll_interval_seconds: float = 5.0
23
- # Tighter than state polling — the marker-emission → auto_terminate window is
24
- # only the wrapper's tail sleep (~20s), so we need ~2s cadence to catch it reliably.
25
- log_poll_interval_seconds: float = 2.0
26
- extras: dict = field(default_factory=dict)
27
-
28
-
29
- _config = Config()
30
-
31
-
32
- def configure(
33
- ssh_key_path: str | Path | None = None,
34
- api_base: str | None = None,
35
- timeout_seconds: int | None = None,
36
- poll_interval_seconds: float | None = None,
37
- ) -> Config:
38
- """Set SDK-wide configuration. Any argument left as ``None`` is unchanged."""
39
- if ssh_key_path is not None:
40
- _config.ssh_key_path = Path(ssh_key_path).expanduser()
41
- if api_base is not None:
42
- _config.api_base = api_base.rstrip("/")
43
- if timeout_seconds is not None:
44
- _config.timeout_seconds = timeout_seconds
45
- if poll_interval_seconds is not None:
46
- _config.poll_interval_seconds = poll_interval_seconds
47
- return _config
48
-
49
-
50
- def get_config() -> Config:
51
- """Return the active configuration. Auto-bootstraps from env vars on first read."""
52
- if _config.ssh_key_path is None:
53
- env_key = os.environ.get("MIMIRY_SSH_KEY")
54
- if env_key:
55
- _config.ssh_key_path = Path(env_key).expanduser()
56
- if "MIMIRY_API_BASE" in os.environ:
57
- _config.api_base = os.environ["MIMIRY_API_BASE"].rstrip("/")
58
- return _config
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes