cli-login 0.1.0__py3-none-any.whl

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.
cli_login/testing.py ADDED
@@ -0,0 +1,258 @@
1
+ """Fakes for specs: a provider, a store and a clock with no network, Keychain or credentials."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import json
7
+
8
+ from .errors import AuthError
9
+ from .target import Target
10
+
11
+ ISSUER = "https://idp.example.test/pool-1"
12
+ CLIENT_ID = "client-1"
13
+
14
+
15
+ def make_target(**overrides) -> Target:
16
+ values = {
17
+ "issuer": ISSUER,
18
+ "client_id": CLIENT_ID,
19
+ "oauth_domain": "https://auth.example.test",
20
+ "token_endpoint": "https://auth.example.test/oauth2/token",
21
+ "api_endpoint": "https://api.example.test/graphql",
22
+ "key": "key-1",
23
+ "namespace": "example-product",
24
+ "callback_uri": "http://127.0.0.1:5182/oauth/callback",
25
+ }
26
+ values.update(overrides)
27
+ return Target(**values)
28
+
29
+
30
+ def make_id_token(now, *, subject="person-1", issuer=ISSUER, audience=CLIENT_ID, token_use="id", lifetime=3600):
31
+ claims = {
32
+ "iss": issuer,
33
+ "aud": audience,
34
+ "sub": subject,
35
+ "token_use": token_use,
36
+ "exp": now + lifetime,
37
+ "email": "person@example.test",
38
+ }
39
+
40
+ def encode(value):
41
+ return base64.urlsafe_b64encode(json.dumps(value).encode()).decode().rstrip("=")
42
+
43
+ return encode({"alg": "RS256"}) + "." + encode(claims) + ".fixture-signature"
44
+
45
+
46
+ class FakeClock:
47
+ def __init__(self, now=1000.0):
48
+ self.now = now
49
+
50
+ def __call__(self):
51
+ return self.now
52
+
53
+ def advance(self, seconds):
54
+ self.now += seconds
55
+
56
+
57
+ class FakeStore:
58
+ def __init__(self):
59
+ self.data = {}
60
+ self.locked = False
61
+
62
+ def _check(self):
63
+ if self.locked:
64
+ raise AuthError("Unable to read OS secure credential storage; unlock it and retry.")
65
+
66
+ def get(self, key):
67
+ self._check()
68
+ return self.data.get(key)
69
+
70
+ def set(self, key, value):
71
+ self._check()
72
+ self.data[key] = value
73
+
74
+ def delete(self, key):
75
+ self._check()
76
+ self.data.pop(key, None)
77
+
78
+
79
+ class FakeProvider:
80
+ """Answers the token and revoke endpoints; `failure` is raised by the next token call."""
81
+
82
+ def __init__(self, clock, *, subject="person-1"):
83
+ self.clock = clock
84
+ self.subject = subject
85
+ self.calls = []
86
+ self.failure = None
87
+ self.revocation_failure = False
88
+ self.issuer = ISSUER
89
+
90
+ def post(self, url, fields):
91
+ self.calls.append((url, fields))
92
+ if url.endswith("/oauth2/revoke"):
93
+ if self.revocation_failure:
94
+ raise AuthError("Provider temporarily unavailable; retry later.")
95
+ return {}
96
+ if self.failure:
97
+ raise self.failure
98
+ return {
99
+ "id_token": make_id_token(self.clock(), subject=self.subject, issuer=self.issuer),
100
+ "refresh_token": "refresh-secret-" + str(len(self.calls)),
101
+ "expires_in": 3600,
102
+ }
103
+
104
+
105
+ class FakeKeyctl:
106
+ """An in-memory kernel keyring with the same methods as ``Keyctl``. ``blocked`` mimics a seccomp profile."""
107
+
108
+ def __init__(self, *, blocked=None, persistent=True):
109
+ import errno
110
+
111
+ self.errno = errno
112
+ self.blocked = blocked # an errno, e.g. EPERM, raised by every call
113
+ self.persistent = persistent
114
+ self.keys = {} # (ring, description) -> (id, payload)
115
+ self.ids = {}
116
+ self.next_id = 100
117
+
118
+ def _guard(self):
119
+ if self.blocked:
120
+ raise OSError(self.blocked, "blocked")
121
+
122
+ def user_keyring(self):
123
+ self._guard()
124
+ return 1
125
+
126
+ def persistent_keyring(self):
127
+ self._guard()
128
+ if not self.persistent:
129
+ raise OSError(95, "no persistent keyrings")
130
+ return 2
131
+
132
+ def add_key(self, ring, description, payload):
133
+ self._guard()
134
+ existing = self.keys.get((ring, description))
135
+ key_id = existing[0] if existing else self.next_id
136
+ if not existing:
137
+ self.next_id += 1
138
+ self.keys[(ring, description)] = (key_id, bytes(payload))
139
+ self.ids[key_id] = (ring, description)
140
+ return key_id
141
+
142
+ def search(self, ring, description):
143
+ self._guard()
144
+ if (ring, description) not in self.keys:
145
+ raise OSError(126, "no key") # ENOKEY on Linux
146
+ return self.keys[(ring, description)][0]
147
+
148
+ def read(self, key):
149
+ self._guard()
150
+ return self.keys[self.ids[key]][1]
151
+
152
+ def unlink(self, key, ring):
153
+ self._guard()
154
+ self.keys.pop(self.ids.pop(key))
155
+
156
+
157
+ class FakeCredentialManager:
158
+ """In-memory Credential Manager with the real 2,560-byte blob limit and optional crash injection."""
159
+
160
+ def __init__(self, *, fail_after_writes=None, broken=False):
161
+ self.items = {}
162
+ self.writes = 0
163
+ self.fail_after_writes = fail_after_writes # raise on the write after this many succeeded
164
+ self.broken = broken
165
+
166
+ def _guard(self):
167
+ if self.broken:
168
+ raise OSError(5, "access denied")
169
+
170
+ def write(self, target, blob, user):
171
+ self._guard()
172
+ if len(blob) > 2560:
173
+ raise OSError(1783, "blob too large")
174
+ if self.fail_after_writes is not None and self.writes >= self.fail_after_writes:
175
+ raise OSError(1, "simulated crash")
176
+ self.writes += 1
177
+ self.items[target] = bytes(blob)
178
+
179
+ def read(self, target):
180
+ self._guard()
181
+ return self.items.get(target)
182
+
183
+ def delete(self, target):
184
+ self._guard()
185
+ self.items.pop(target, None)
186
+
187
+ def enumerate(self, prefix):
188
+ self._guard()
189
+ return [t for t in list(self.items) if t.startswith(prefix)]
190
+
191
+
192
+ class FakeSecretStorage:
193
+ """A stand-in for the ``secretstorage`` module: a default collection that can be locked or missing."""
194
+
195
+ class exceptions:
196
+ class SecretStorageException(Exception):
197
+ pass
198
+
199
+ class SecretServiceNotAvailableException(SecretStorageException):
200
+ pass
201
+
202
+ class LockedException(SecretStorageException):
203
+ pass
204
+
205
+ class _Item:
206
+ def __init__(self, collection, attributes, secret):
207
+ self.collection, self.attributes, self.secret = collection, attributes, secret
208
+
209
+ def get_secret(self):
210
+ return self.secret
211
+
212
+ def delete(self):
213
+ self.collection.items.remove(self)
214
+
215
+ class _Collection:
216
+ def __init__(self, owner):
217
+ self.owner, self.items = owner, []
218
+
219
+ def is_locked(self):
220
+ return self.owner.locked
221
+
222
+ def create_item(self, label, attributes, secret, replace=False, content_type="text/plain"):
223
+ if replace:
224
+ self.items = [i for i in self.items if i.attributes != attributes]
225
+ self.owner.labels.append(label)
226
+ item = FakeSecretStorage._Item(self, dict(attributes), secret)
227
+ self.items.append(item)
228
+ return item
229
+
230
+ def search_items(self, attributes):
231
+ return iter([i for i in self.items if i.attributes == attributes])
232
+
233
+ class _Connection:
234
+ def close(self):
235
+ pass
236
+
237
+ def __init__(self, *, locked=False, no_bus=False):
238
+ self.locked, self.no_bus, self.labels = locked, no_bus, []
239
+ self.collection = self._Collection(self)
240
+
241
+ def dbus_init(self):
242
+ if self.no_bus:
243
+ raise self.exceptions.SecretServiceNotAvailableException("raw bus failure naming secret-value")
244
+ return self._Connection()
245
+
246
+ def get_default_collection(self, connection):
247
+ return self.collection
248
+
249
+
250
+ def skip_or_fail(name: str, reason: str) -> None:
251
+ """Skip a real-backend spec, unless CI requires that backend (ANTHUS_REQUIRE_REAL lists its name)."""
252
+ import os
253
+
254
+ import pytest
255
+
256
+ if name in os.environ.get("ANTHUS_REQUIRE_REAL", "").split(","):
257
+ pytest.fail(f"{name} is required in this run but unavailable: {reason}")
258
+ pytest.skip(f"{name} unavailable: {reason}")
@@ -0,0 +1,104 @@
1
+ Metadata-Version: 2.5
2
+ Name: cli-login
3
+ Version: 0.1.0
4
+ Summary: One CLI login for every Anthus product: PKCE sign-in, remote approval, secure storage and renewal.
5
+ Author: Anthus AI
6
+ License: MIT
7
+ License-File: LICENSE
8
+ Requires-Python: >=3.10
9
+ Provides-Extra: dev
10
+ Requires-Dist: behave>=1.2.6; extra == 'dev'
11
+ Requires-Dist: pytest>=8; extra == 'dev'
12
+ Requires-Dist: ruff>=0.6; extra == 'dev'
13
+ Provides-Extra: linux
14
+ Requires-Dist: secretstorage>=3.3; (sys_platform == 'linux') and extra == 'linux'
15
+ Description-Content-Type: text/markdown
16
+
17
+ # cli-login
18
+
19
+ One CLI login for every Anthus product, without long-lived keys.
20
+
21
+ - **Sign in on this machine or from another device.** `login --remote` prints a URL and a short matching code; you
22
+ approve on your phone or laptop, and the waiting CLI receives its own renewable session. No access key, pasted
23
+ code or token passes through chat.
24
+ - **Secure storage, never plain text.** macOS Keychain, Linux Secret Service, the Linux kernel keyring, a
25
+ memory-only agent for cloud machines, or Windows Credential Manager.
26
+ - **Renewal and honest logout.** Sessions renew with the refresh token. Logout revokes it, and says so when it
27
+ could not.
28
+ - **A broker per deployment.** A small Lambda function and DynamoDB table that hands one authorization code to the
29
+ one CLI that asked for it, and never holds a token.
30
+
31
+ ## Install
32
+
33
+ ```bash
34
+ pip install cli-login
35
+ pip install "cli-login[linux]" # adds Secret Service support on Linux
36
+ ```
37
+
38
+ Requires Python 3.10 or newer.
39
+
40
+ ## Where sessions are stored
41
+
42
+ Sessions live only in a secure store, tried in this order. There is no plaintext fallback: if nothing is
43
+ usable, the tool fails with the exact steps to fix it.
44
+
45
+ | Platform | Store (in order) | Lasts |
46
+ | --- | --- | --- |
47
+ | macOS | Keychain (service name = the product namespace, so existing sessions keep working) | until logout |
48
+ | Linux | 1. Secret Service (D-Bus), needs `pip install "cli-login[linux]"` and an unlocked keyring; 2. kernel keyring; 3. the memory agent | keyring: until logout; kernel keyring: until reboot, or the persistent keyring's expiry (3 days from last use by default); agent: until it stops |
49
+ | Windows | Credential Manager (`<namespace>/<key>`; values over 2,560 bytes are chunked) | until logout |
50
+
51
+ The memory agent is not available on Windows in this version. Set `CLI_LOGIN_STORE` to `keychain`,
52
+ `secret-service`, `kernel-keyring`, `agent` or `credential-manager` to choose a store explicitly (for operators
53
+ and tests). Any other value is refused.
54
+
55
+ ### Cloud machines and containers
56
+
57
+ A cloud machine usually has no desktop keyring, and Docker's default seccomp profile blocks the kernel keyring
58
+ calls. Start the memory agent once per product, then sign in again:
59
+
60
+ ```bash
61
+ python -m cli_login.stores.agent serve --namespace <product-namespace> --background
62
+ python -m cli_login.stores.agent status --namespace <product-namespace>
63
+ python -m cli_login.stores.agent stop --namespace <product-namespace>
64
+ ```
65
+
66
+ A product mounts the same functions (`stores.agent.serve`, `start_background`, `status`, `stop`, `main`) under
67
+ its own CLI name, such as `<product> auth agent`. The agent holds sessions in memory only, behind a 0600 Unix
68
+ socket in a 0700 directory under the product's state directory (`~/.config/cli-login/<namespace>/agent`,
69
+ or the socket named by `CLI_LOGIN_AGENT_SOCKET`, which must sit in a private directory and be short
70
+ enough for a Unix socket). It checks the caller's user id on every connection, disables core dumps, and keeps
71
+ nothing on disk. After it stops, or the machine restarts, sign in again. Processes of the same user can use it,
72
+ as with ssh-agent.
73
+
74
+ ### Recovering from each failure
75
+
76
+ - **"No Secret Service is reachable"**: no D-Bus session or keyring daemon. On a server, use the memory agent.
77
+ - **"Secret Service keyring is locked"**: unlock it by signing in to the desktop session, then retry.
78
+ - **"cli-login[linux]"**: the optional dependency is missing; `pip install "cli-login[linux]"`.
79
+ - **"kernel keyring is unavailable"**: the kernel or container blocks `add_key`/`keyctl`. Use the memory agent,
80
+ or run the container with a seccomp profile that allows them.
81
+ - **"The memory agent is not running"**: run the `serve` command shown in the message, then sign in again.
82
+ - **Agent socket refused**: the directory or socket is not owned by you or not private; fix the mode (0700) or
83
+ remove the stale path and restart the agent.
84
+ - **"The stored session is damaged"** (Windows): run the login command again to replace it.
85
+ - **Credential Manager errors on Windows**: sign in to Windows normally (not a restricted service account) and
86
+ retry.
87
+
88
+ Status: see [docs/design.md](docs/design.md).
89
+
90
+ ## Releasing (maintainers)
91
+
92
+ Pushing to `main` (a pull request from `develop`) runs python-semantic-release on the conventional commits:
93
+ `feat:` and `fix:` (or a breaking change) bump the version in `pyproject.toml`, tag `vX.Y.Z` and create a GitHub
94
+ release; other commits release nothing. The `pypi` job then builds the sdist and wheel and publishes them with
95
+ OIDC trusted publishing, so no PyPI token is stored anywhere. Publishing needs a PyPI trusted publisher, registered
96
+ by the PyPI account owner: project `cli-login`, owner `AnthusAI`, repository `cli-login`, workflow
97
+ `release.yml`, environment `pypi`. The workflow's `pypi` environment must also exist in the repository settings.
98
+
99
+ The library targets Cognito user pools with the authorization-code flow and PKCE. Each product supplies its own
100
+ issuer, client and endpoints; this repository holds none.
101
+
102
+ ## License
103
+
104
+ MIT
@@ -0,0 +1,23 @@
1
+ cli_login/__init__.py,sha256=9nG3qR-QqY5eSevoqA1ZsG_6kcictSeR2UwLIu8PiEc,110
2
+ cli_login/errors.py,sha256=hMZPo-6gR6YaAViUQnyLjAIBiy_sXVQiqIwQ8Kn6pW4,986
3
+ cli_login/locks.py,sha256=z8cqSqaHpPqV3FK6a5K1A1TBgALK68MytlmfseheAfQ,3145
4
+ cli_login/oauth.py,sha256=gv7hUqOHRo3ERm9PgPeoRiw_gpJp5Qhdi_QcUpR5kIU,5661
5
+ cli_login/remote.py,sha256=EHWCSC2IRVMEDVPnz8AGh5l0XZOkj7_OcMNuJd9SPs4,10678
6
+ cli_login/session.py,sha256=dODDrg8gHrslo2rrk3O8plNB2kTQgSwNw3JbWlCvr_M,9008
7
+ cli_login/target.py,sha256=cd9GMeoE19BwoFGY3tN2ESsuD2Ozq_LvMkWA8kjpuLo,3994
8
+ cli_login/testing.py,sha256=-hY2DmC6z1t6vYFpDTs8zQYXPZdCTx4-sz82qFpjRZ8,7831
9
+ cli_login/broker/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
10
+ cli_login/broker/handler.py,sha256=sAKqvClfeOKhv9m_ed1oa3rKad2olN454i4xdFfjkvk,15013
11
+ cli_login/broker/pages.py,sha256=4VoJ23tWFzZcHKWyW0RjG_Wic8clJ2R5FYoasKZ5mv8,9183
12
+ cli_login/broker/throttle.py,sha256=KsRlvKurMltGVvciYH1VETOc9WpdCWIFHXmzg1_K5PQ,835
13
+ cli_login/broker/transactions.py,sha256=Zk4DfSc-P7K6d9NhypPW-UI4-DTs5ect_sJM0O4mojg,7999
14
+ cli_login/stores/__init__.py,sha256=xTrwCJ7gL_Uv0jqnAAL1DsZCYWRKAKNXDKmzpvn4yvY,4382
15
+ cli_login/stores/agent.py,sha256=dNZXHZlac_tffi0HKBC6eIn8qPB6q9XQwkeLCRwfCyQ,18324
16
+ cli_login/stores/kernel_keyring.py,sha256=NYuk9hu8mQdf-74u9fjpN7iWBbeGItVhXAeP2vTHMsQ,7689
17
+ cli_login/stores/macos.py,sha256=VGkaqTXvmpRkplLVNwqH_zEi6OuA5xt-EAUH71bwMV0,7693
18
+ cli_login/stores/secret_service.py,sha256=4-cGflAb0uynIXvJA4dl0BlD2MqSYbkeCgf2iGVX8Io,4098
19
+ cli_login/stores/windows.py,sha256=nmd4P_1UDkRwH71Sham2lsteNLF41CejIYUIHGa1Jgw,8932
20
+ cli_login-0.1.0.dist-info/METADATA,sha256=OFLG_s-OhmwMFwbCY9jrxPnj-x5fkE-fOVw-cJkg43U,5550
21
+ cli_login-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
22
+ cli_login-0.1.0.dist-info/licenses/LICENSE,sha256=lwi5rYQU2i8v8ETJW7EUitz-SwIu2CbVNivaF1If6wo,1076
23
+ cli_login-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Anthus AI Solutions
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.