rb-credentials 0.7.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.
- rb_credentials-0.7.2/.gitignore +10 -0
- rb_credentials-0.7.2/LICENSE +21 -0
- rb_credentials-0.7.2/PKG-INFO +76 -0
- rb_credentials-0.7.2/README.md +63 -0
- rb_credentials-0.7.2/pyproject.toml +82 -0
- rb_credentials-0.7.2/src/rb_credentials/__init__.py +161 -0
- rb_credentials-0.7.2/src/rb_credentials/py.typed +0 -0
- rb_credentials-0.7.2/src/rb_credentials/status.py +125 -0
- rb_credentials-0.7.2/src/rb_credentials/store.py +334 -0
- rb_credentials-0.7.2/tests/test_credentials.py +79 -0
- rb_credentials-0.7.2/tests/test_status.py +68 -0
- rb_credentials-0.7.2/tests/test_store.py +277 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Roman Bolandau
|
|
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,76 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: rb-credentials
|
|
3
|
+
Version: 0.7.2
|
|
4
|
+
Summary: Resolve named credentials without storing or printing secrets: the environment knows addresses, the package knows names.
|
|
5
|
+
Author: Roman Bolandau
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Requires-Python: >=3.11
|
|
9
|
+
Requires-Dist: pydantic<3,>=2.10
|
|
10
|
+
Provides-Extra: keyring
|
|
11
|
+
Requires-Dist: keyring>=25.0; extra == 'keyring'
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
|
|
14
|
+
# rb-credentials
|
|
15
|
+
|
|
16
|
+
Resolve named credentials without storing, logging or printing secrets.
|
|
17
|
+
|
|
18
|
+
The package knows credential names; the environment knows addresses. You map a
|
|
19
|
+
name such as `github` to an address such as an environment variable or a
|
|
20
|
+
keychain entry, and the package resolves it to a `Credential` whose token is a
|
|
21
|
+
`SecretStr`. No address is hard-coded, and nothing is written to disk.
|
|
22
|
+
|
|
23
|
+
## Install
|
|
24
|
+
|
|
25
|
+
```sh
|
|
26
|
+
uv add rb-credentials
|
|
27
|
+
uv add "rb-credentials[keyring]"
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
## Use
|
|
31
|
+
|
|
32
|
+
```python
|
|
33
|
+
from rb_credentials import providers_for, resolve_credential
|
|
34
|
+
|
|
35
|
+
providers = providers_for({"github": "env:GITHUB_TOKEN"})
|
|
36
|
+
credential = resolve_credential(*providers, name="github")
|
|
37
|
+
token = credential.token.get_secret_value()
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Addresses:
|
|
41
|
+
|
|
42
|
+
- `env:NAME` reads the environment variable `NAME`.
|
|
43
|
+
- `keyring:service/account` reads the OS keychain through the optional
|
|
44
|
+
`keyring` extra. Without the extra the lookup returns nothing; there is no
|
|
45
|
+
plaintext fallback.
|
|
46
|
+
|
|
47
|
+
Provide your own source with `CallableCredentials`, or implement
|
|
48
|
+
`CredentialProvider`:
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
from rb_credentials import CallableCredentials, providers_for, resolve_credential
|
|
52
|
+
|
|
53
|
+
providers = (*providers_for({}), CallableCredentials(lambda name: vault.read(name)))
|
|
54
|
+
credential = resolve_credential(*providers, name="github")
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
A missing credential raises `CredentialsUnavailable` with the credential name
|
|
58
|
+
and never with a value. Pass a `Credential` or a ready client into your
|
|
59
|
+
operations; do not read the environment inside them.
|
|
60
|
+
|
|
61
|
+
## Rules
|
|
62
|
+
|
|
63
|
+
- Secrets stay in `SecretStr`, never in `str`, arguments, results or logs.
|
|
64
|
+
- Expiry is explicit: `credential.is_expired()` and `expires_at`.
|
|
65
|
+
- No storage, no caching, no plaintext file.
|
|
66
|
+
|
|
67
|
+
## Develop
|
|
68
|
+
|
|
69
|
+
```sh
|
|
70
|
+
uv sync
|
|
71
|
+
uv run poe check
|
|
72
|
+
uv build
|
|
73
|
+
uvx --from 'twine>=6,<7' twine check dist/*
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
The library version is independent of any project that depends on it.
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
# rb-credentials
|
|
2
|
+
|
|
3
|
+
Resolve named credentials without storing, logging or printing secrets.
|
|
4
|
+
|
|
5
|
+
The package knows credential names; the environment knows addresses. You map a
|
|
6
|
+
name such as `github` to an address such as an environment variable or a
|
|
7
|
+
keychain entry, and the package resolves it to a `Credential` whose token is a
|
|
8
|
+
`SecretStr`. No address is hard-coded, and nothing is written to disk.
|
|
9
|
+
|
|
10
|
+
## Install
|
|
11
|
+
|
|
12
|
+
```sh
|
|
13
|
+
uv add rb-credentials
|
|
14
|
+
uv add "rb-credentials[keyring]"
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## Use
|
|
18
|
+
|
|
19
|
+
```python
|
|
20
|
+
from rb_credentials import providers_for, resolve_credential
|
|
21
|
+
|
|
22
|
+
providers = providers_for({"github": "env:GITHUB_TOKEN"})
|
|
23
|
+
credential = resolve_credential(*providers, name="github")
|
|
24
|
+
token = credential.token.get_secret_value()
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
Addresses:
|
|
28
|
+
|
|
29
|
+
- `env:NAME` reads the environment variable `NAME`.
|
|
30
|
+
- `keyring:service/account` reads the OS keychain through the optional
|
|
31
|
+
`keyring` extra. Without the extra the lookup returns nothing; there is no
|
|
32
|
+
plaintext fallback.
|
|
33
|
+
|
|
34
|
+
Provide your own source with `CallableCredentials`, or implement
|
|
35
|
+
`CredentialProvider`:
|
|
36
|
+
|
|
37
|
+
```python
|
|
38
|
+
from rb_credentials import CallableCredentials, providers_for, resolve_credential
|
|
39
|
+
|
|
40
|
+
providers = (*providers_for({}), CallableCredentials(lambda name: vault.read(name)))
|
|
41
|
+
credential = resolve_credential(*providers, name="github")
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
A missing credential raises `CredentialsUnavailable` with the credential name
|
|
45
|
+
and never with a value. Pass a `Credential` or a ready client into your
|
|
46
|
+
operations; do not read the environment inside them.
|
|
47
|
+
|
|
48
|
+
## Rules
|
|
49
|
+
|
|
50
|
+
- Secrets stay in `SecretStr`, never in `str`, arguments, results or logs.
|
|
51
|
+
- Expiry is explicit: `credential.is_expired()` and `expires_at`.
|
|
52
|
+
- No storage, no caching, no plaintext file.
|
|
53
|
+
|
|
54
|
+
## Develop
|
|
55
|
+
|
|
56
|
+
```sh
|
|
57
|
+
uv sync
|
|
58
|
+
uv run poe check
|
|
59
|
+
uv build
|
|
60
|
+
uvx --from 'twine>=6,<7' twine check dist/*
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
The library version is independent of any project that depends on it.
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "rb-credentials"
|
|
3
|
+
# Version comes from the git tag vX.Y.Z (uv-dynamic-versioning) — never add `version =`.
|
|
4
|
+
dynamic = ["version"]
|
|
5
|
+
description = "Resolve named credentials without storing or printing secrets: the environment knows addresses, the package knows names."
|
|
6
|
+
readme = "README.md"
|
|
7
|
+
license = "MIT"
|
|
8
|
+
license-files = ["LICENSE"]
|
|
9
|
+
requires-python = ">=3.11"
|
|
10
|
+
authors = [{ name = "Roman Bolandau" }]
|
|
11
|
+
dependencies = ["pydantic>=2.10,<3"]
|
|
12
|
+
|
|
13
|
+
[project.optional-dependencies]
|
|
14
|
+
keyring = ["keyring>=25.0"]
|
|
15
|
+
|
|
16
|
+
[tool.rb.install]
|
|
17
|
+
homeserver = [] # library: nobody runs it
|
|
18
|
+
mac = false
|
|
19
|
+
|
|
20
|
+
[build-system]
|
|
21
|
+
requires = ["hatchling", "uv-dynamic-versioning"]
|
|
22
|
+
build-backend = "hatchling.build"
|
|
23
|
+
|
|
24
|
+
[tool.hatch.version]
|
|
25
|
+
source = "uv-dynamic-versioning"
|
|
26
|
+
|
|
27
|
+
[tool.uv-dynamic-versioning]
|
|
28
|
+
vcs = "git"
|
|
29
|
+
style = "pep440"
|
|
30
|
+
fallback-version = "0.0.0"
|
|
31
|
+
|
|
32
|
+
[tool.uv]
|
|
33
|
+
cache-keys = [{ file = "pyproject.toml" }, { git = { commit = true, tags = true } }]
|
|
34
|
+
|
|
35
|
+
[tool.hatch.build.targets.sdist]
|
|
36
|
+
# What a release must not carry: the agent's own files, the forge configs and the dev tooling.
|
|
37
|
+
exclude = [
|
|
38
|
+
"/.agents",
|
|
39
|
+
"/.claude",
|
|
40
|
+
"/.claude-plugin",
|
|
41
|
+
"/.gitea",
|
|
42
|
+
"/.github",
|
|
43
|
+
"/docs",
|
|
44
|
+
"/scripts",
|
|
45
|
+
"/uv.lock",
|
|
46
|
+
"/AGENTS.md",
|
|
47
|
+
"/CLAUDE.md",
|
|
48
|
+
"/CODING_STANDARDS.md",
|
|
49
|
+
"/CONTEXT.md",
|
|
50
|
+
"/.copier-answers.yml",
|
|
51
|
+
"^\\.gitignore$",
|
|
52
|
+
"/.gitleaks.toml",
|
|
53
|
+
]
|
|
54
|
+
|
|
55
|
+
[tool.hatch.build.targets.wheel]
|
|
56
|
+
packages = ["src/rb_credentials"]
|
|
57
|
+
|
|
58
|
+
[dependency-groups]
|
|
59
|
+
dev = ["pytest>=8.0", "pytest-cov>=5.0", "ruff>=0.6", "ty", "keyring>=25.0"] # keyring: the optional extra, for ty and the tests
|
|
60
|
+
|
|
61
|
+
[tool.pytest.ini_options]
|
|
62
|
+
testpaths = ["tests"]
|
|
63
|
+
addopts = "--cov --cov-report=term-missing:skip-covered"
|
|
64
|
+
|
|
65
|
+
[tool.coverage.run]
|
|
66
|
+
source = ["src"]
|
|
67
|
+
|
|
68
|
+
[tool.coverage.report]
|
|
69
|
+
fail_under = 85
|
|
70
|
+
show_missing = true
|
|
71
|
+
|
|
72
|
+
[tool.ty.terminal]
|
|
73
|
+
error-on-warning = false
|
|
74
|
+
|
|
75
|
+
[tool.ruff]
|
|
76
|
+
line-length = 120
|
|
77
|
+
|
|
78
|
+
[tool.ruff.lint]
|
|
79
|
+
select = ["E4", "E7", "E9", "F", "I", "UP", "B", "SIM", "RUF", "S", "T20"]
|
|
80
|
+
|
|
81
|
+
[tool.ruff.lint.per-file-ignores]
|
|
82
|
+
"tests/*" = ["S101", "S105", "S106"] # fake secrets are the point of the tests
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
"""Resolve named credentials without storing, logging or printing secrets.
|
|
2
|
+
|
|
3
|
+
The package knows credential names; the environment knows addresses. A caller
|
|
4
|
+
maps a name such as ``github`` to an address such as an environment variable or
|
|
5
|
+
a keychain entry and passes that mapping in. No address is hard-coded here, and
|
|
6
|
+
nothing in this module writes a secret anywhere.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import importlib
|
|
12
|
+
import os
|
|
13
|
+
from collections.abc import Callable, Mapping
|
|
14
|
+
from datetime import UTC, datetime, timedelta
|
|
15
|
+
from typing import Protocol, runtime_checkable
|
|
16
|
+
|
|
17
|
+
from pydantic import BaseModel, ConfigDict, SecretStr, field_validator
|
|
18
|
+
|
|
19
|
+
__all__ = [
|
|
20
|
+
"CallableCredentials",
|
|
21
|
+
"Credential",
|
|
22
|
+
"CredentialProvider",
|
|
23
|
+
"CredentialsUnavailable",
|
|
24
|
+
"EnvironmentCredentials",
|
|
25
|
+
"KeyringCredentials",
|
|
26
|
+
"Store",
|
|
27
|
+
"StoreUnavailable",
|
|
28
|
+
"parse_address",
|
|
29
|
+
"providers_for",
|
|
30
|
+
"resolve_credential",
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class CredentialsUnavailable(Exception):
|
|
35
|
+
"""No provider produced a usable credential for the requested name."""
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class StoreUnavailable(Exception):
|
|
39
|
+
"""The OS credential store is missing (no `keyring` extra) or refused the operation."""
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class Credential(BaseModel):
|
|
43
|
+
"""A secret value with an optional expiry and scopes."""
|
|
44
|
+
|
|
45
|
+
model_config = ConfigDict(extra="forbid")
|
|
46
|
+
|
|
47
|
+
name: str
|
|
48
|
+
token: SecretStr
|
|
49
|
+
expires_at: datetime | None = None
|
|
50
|
+
scopes: tuple[str, ...] = ()
|
|
51
|
+
|
|
52
|
+
@field_validator("token")
|
|
53
|
+
@classmethod
|
|
54
|
+
def _not_blank(cls, value: SecretStr) -> SecretStr:
|
|
55
|
+
if not value.get_secret_value().strip():
|
|
56
|
+
raise ValueError("credential token must not be blank")
|
|
57
|
+
return value
|
|
58
|
+
|
|
59
|
+
def is_expired(self, *, now: datetime | None = None, leeway: timedelta = timedelta(0)) -> bool:
|
|
60
|
+
"""Report whether the credential has expired, with optional leeway."""
|
|
61
|
+
if self.expires_at is None:
|
|
62
|
+
return False
|
|
63
|
+
return self.expires_at <= (now or datetime.now(UTC)) + leeway
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@runtime_checkable
|
|
67
|
+
class CredentialProvider(Protocol):
|
|
68
|
+
"""Read one credential by name, or return None when this provider has none."""
|
|
69
|
+
|
|
70
|
+
def resolve(self, name: str) -> Credential | None: ...
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class EnvironmentCredentials:
|
|
74
|
+
"""Read addresses from a mapping of credential name to environment variable."""
|
|
75
|
+
|
|
76
|
+
def __init__(self, mapping: Mapping[str, str], environ: Mapping[str, str] | None = None) -> None:
|
|
77
|
+
self.mapping = dict(mapping)
|
|
78
|
+
self.environ = os.environ if environ is None else environ
|
|
79
|
+
|
|
80
|
+
def resolve(self, name: str) -> Credential | None:
|
|
81
|
+
variable = self.mapping.get(name)
|
|
82
|
+
if variable is None:
|
|
83
|
+
return None
|
|
84
|
+
raw = self.environ.get(variable)
|
|
85
|
+
if not raw:
|
|
86
|
+
return None
|
|
87
|
+
return Credential(name=name, token=raw)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class CallableCredentials:
|
|
91
|
+
"""Adapt any reader function to the provider protocol."""
|
|
92
|
+
|
|
93
|
+
def __init__(self, reader: Callable[[str], str | None]) -> None:
|
|
94
|
+
self.reader = reader
|
|
95
|
+
|
|
96
|
+
def resolve(self, name: str) -> Credential | None:
|
|
97
|
+
raw = self.reader(name)
|
|
98
|
+
return Credential(name=name, token=raw) if raw else None
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class KeyringCredentials:
|
|
102
|
+
"""Read addresses like ``service/account`` from the OS keychain.
|
|
103
|
+
|
|
104
|
+
The keychain backend comes from the optional ``keyring`` extra. Without it,
|
|
105
|
+
every lookup returns None instead of falling back to a plaintext file.
|
|
106
|
+
"""
|
|
107
|
+
|
|
108
|
+
def __init__(self, mapping: Mapping[str, str]) -> None:
|
|
109
|
+
self.mapping = dict(mapping)
|
|
110
|
+
|
|
111
|
+
def resolve(self, name: str) -> Credential | None:
|
|
112
|
+
address = self.mapping.get(name)
|
|
113
|
+
if address is None or "/" not in address:
|
|
114
|
+
return None
|
|
115
|
+
service, _, account = address.partition("/")
|
|
116
|
+
try:
|
|
117
|
+
keyring = importlib.import_module("keyring")
|
|
118
|
+
except ModuleNotFoundError:
|
|
119
|
+
return None
|
|
120
|
+
try:
|
|
121
|
+
raw = keyring.get_password(service, account)
|
|
122
|
+
except Exception:
|
|
123
|
+
return None
|
|
124
|
+
return Credential(name=name, token=raw) if raw else None
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def parse_address(address: str) -> tuple[str, str, str | None]:
|
|
128
|
+
"""Split ``env:NAME`` or ``keyring:service/account`` into its parts."""
|
|
129
|
+
scheme, _, value = address.partition(":")
|
|
130
|
+
if scheme == "env" and value:
|
|
131
|
+
return ("env", value, None)
|
|
132
|
+
if scheme == "keyring":
|
|
133
|
+
service, _, account = value.partition("/")
|
|
134
|
+
if service and account:
|
|
135
|
+
return ("keyring", service, account)
|
|
136
|
+
raise ValueError(f"Unsupported credential address scheme: {scheme or 'missing'}")
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def providers_for(mapping: Mapping[str, str]) -> tuple[CredentialProvider, ...]:
|
|
140
|
+
"""Build providers from a name-to-address mapping owned by the caller."""
|
|
141
|
+
environment: dict[str, str] = {}
|
|
142
|
+
keychain: dict[str, str] = {}
|
|
143
|
+
for name, address in mapping.items():
|
|
144
|
+
scheme, first, second = parse_address(address)
|
|
145
|
+
if scheme == "env":
|
|
146
|
+
environment[name] = first
|
|
147
|
+
else:
|
|
148
|
+
keychain[name] = f"{first}/{second}"
|
|
149
|
+
return (EnvironmentCredentials(environment), KeyringCredentials(keychain))
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def resolve_credential(*providers: CredentialProvider, name: str) -> Credential:
|
|
153
|
+
"""Return the first credential a provider offers, or raise without a value."""
|
|
154
|
+
for provider in providers:
|
|
155
|
+
credential = provider.resolve(name)
|
|
156
|
+
if credential is not None:
|
|
157
|
+
return credential
|
|
158
|
+
raise CredentialsUnavailable(f"No credential is configured for {name!r}. Ask the environment owner to map it.")
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
from .store import Store # noqa: E402 — needs the errors above; keeps `import rb_credentials` cheap
|
|
File without changes
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
"""The `<cli> auth status [--check] --json` envelope (tools `docs/standard-release.md` §8), one implementation.
|
|
2
|
+
|
|
3
|
+
A package finds its credential and probes its service; this module owns the shape they all report in, so two tools
|
|
4
|
+
cannot disagree on it: codes 0/3, the same nine keys per `credentials[]` record, the same vocabulary of statuses.
|
|
5
|
+
Credential values never arrive here — `scrub` is handed them only to erase them from a message.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from collections.abc import Sequence
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from datetime import UTC, datetime
|
|
13
|
+
from typing import Literal
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"EXIT_OK",
|
|
17
|
+
"EXIT_PROBLEM",
|
|
18
|
+
"Health",
|
|
19
|
+
"HealthStatus",
|
|
20
|
+
"Quota",
|
|
21
|
+
"entry",
|
|
22
|
+
"exit_code",
|
|
23
|
+
"is_problem",
|
|
24
|
+
"iso",
|
|
25
|
+
"problems",
|
|
26
|
+
"report",
|
|
27
|
+
"scrub",
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
EXIT_OK = 0
|
|
31
|
+
EXIT_PROBLEM = 3
|
|
32
|
+
HEALTHY = frozenset({"ok", "unchecked"})
|
|
33
|
+
# A problem even for an optional provider: a credential is there but wrong.
|
|
34
|
+
ALWAYS_PROBLEMS = frozenset({"invalid", "expired"})
|
|
35
|
+
|
|
36
|
+
HealthStatus = Literal["ok", "invalid", "expired", "quota_exhausted", "unreachable"]
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass(frozen=True)
|
|
40
|
+
class Quota:
|
|
41
|
+
remaining: int | None = None
|
|
42
|
+
limit: int | None = None
|
|
43
|
+
unit: str = "requests"
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass(frozen=True)
|
|
47
|
+
class Health:
|
|
48
|
+
"""Result of a provider's live check. Never put a credential value in `message`."""
|
|
49
|
+
|
|
50
|
+
status: HealthStatus = "ok"
|
|
51
|
+
expires_at: datetime | None = None
|
|
52
|
+
quota: Quota | None = None
|
|
53
|
+
message: str | None = None
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def scrub(message: str | None, secrets: Sequence[str | None]) -> str | None:
|
|
57
|
+
"""`message` with every secret replaced by `***`."""
|
|
58
|
+
if message is None:
|
|
59
|
+
return None
|
|
60
|
+
for secret in secrets:
|
|
61
|
+
if secret:
|
|
62
|
+
message = message.replace(secret, "***")
|
|
63
|
+
return message
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def iso(moment: datetime | None) -> str | None:
|
|
67
|
+
return moment.astimezone(UTC).replace(microsecond=0).isoformat().replace("+00:00", "Z") if moment else None
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def entry(
|
|
71
|
+
name: str,
|
|
72
|
+
*,
|
|
73
|
+
required: bool = True,
|
|
74
|
+
fields: Sequence[str] = (),
|
|
75
|
+
source: str = "missing",
|
|
76
|
+
source_ref: str | None = None,
|
|
77
|
+
status: str = "missing",
|
|
78
|
+
expires_at: datetime | None = None,
|
|
79
|
+
quota: Quota | None = None,
|
|
80
|
+
message: str | None = None,
|
|
81
|
+
) -> dict:
|
|
82
|
+
"""One `credentials[]` record — all nine keys, in one order for every tool.
|
|
83
|
+
|
|
84
|
+
`name` is the whole record name, `<provider>` or `<provider>:<target>`; a package with per-target credentials
|
|
85
|
+
enumerates its own targets and calls this once per target. `fields` are the declared credential fields, in the
|
|
86
|
+
declared order, never "what happened to be found": that would differ between two machines.
|
|
87
|
+
"""
|
|
88
|
+
return {
|
|
89
|
+
"provider": name,
|
|
90
|
+
"required": required,
|
|
91
|
+
"fields": list(fields),
|
|
92
|
+
"source": source,
|
|
93
|
+
"source_ref": source_ref,
|
|
94
|
+
"status": status,
|
|
95
|
+
"expires_at": iso(expires_at),
|
|
96
|
+
"quota": vars(quota) if quota else None,
|
|
97
|
+
"message": message,
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def report(tool: str, version: str, entries: list[dict]) -> dict:
|
|
102
|
+
"""The envelope: which tool, which version, when, and the records. The command adds `ok` and the exit-3 error."""
|
|
103
|
+
return {
|
|
104
|
+
"tool": tool,
|
|
105
|
+
"version": version,
|
|
106
|
+
"checked_at": iso(datetime.now(UTC)),
|
|
107
|
+
"credentials": entries,
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def is_problem(record: dict) -> bool:
|
|
112
|
+
"""Whether a record fails `auth status`: invalid/expired always, anything not ok/unchecked if required."""
|
|
113
|
+
if record["status"] in ALWAYS_PROBLEMS:
|
|
114
|
+
return True
|
|
115
|
+
return record["required"] and record["status"] not in HEALTHY
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def problems(report: dict) -> dict[str, str]:
|
|
119
|
+
"""Provider → status for every record that fails; the payload of the command's exit-3 error."""
|
|
120
|
+
return {record["provider"]: record["status"] for record in report["credentials"] if is_problem(record)}
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def exit_code(report: dict) -> int:
|
|
124
|
+
"""`EXIT_PROBLEM` when any record fails, `EXIT_OK` otherwise."""
|
|
125
|
+
return EXIT_PROBLEM if problems(report) else EXIT_OK
|
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
"""The credential store: multi-field credentials in the OS keychain, environment variables where no keychain exists.
|
|
2
|
+
|
|
3
|
+
A package owns a namespace (its command name) and asks the store about a provider: `openai`, a deploy target
|
|
4
|
+
`example.com`, a profile name. One credential is a small dict of named fields stored as one JSON blob per provider:
|
|
5
|
+
a single `api_key`, or session cookies, or a host's username and password — the store does not care.
|
|
6
|
+
|
|
7
|
+
Addresses stay with the caller: the store never hard-codes a variable name, a keychain service or a secret. The
|
|
8
|
+
conventions it does implement are the ones every tool of the family shares:
|
|
9
|
+
|
|
10
|
+
- keychain service `<namespace>:<provider>`, indexed per namespace so `auth status` can list what is stored
|
|
11
|
+
(`keyring` cannot enumerate);
|
|
12
|
+
- environment variable `<NAMESPACE>_<PROVIDER>_<FIELD>`, which wins field-by-field over the keychain;
|
|
13
|
+
- read-only access to another tool's namespace (`shared_namespaces`), never a write.
|
|
14
|
+
|
|
15
|
+
A machine without a secret service (headless Linux, a container) is not an error: reads fall back to the
|
|
16
|
+
environment, and `backend()` reports the absence for `doctor`.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import json
|
|
22
|
+
import logging
|
|
23
|
+
import os
|
|
24
|
+
import re
|
|
25
|
+
from collections.abc import Mapping
|
|
26
|
+
|
|
27
|
+
from . import CredentialsUnavailable, StoreUnavailable
|
|
28
|
+
|
|
29
|
+
__all__ = ["Store"]
|
|
30
|
+
|
|
31
|
+
# keyring is an optional extra: a caller that only reads environment variables never imports it.
|
|
32
|
+
log = logging.getLogger(__name__)
|
|
33
|
+
|
|
34
|
+
_INDEX_USER = "__stored_credentials__"
|
|
35
|
+
_DEFAULT_FIELD = "api_key"
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _keyring():
|
|
39
|
+
"""The keyring backend, or None when the extra is not installed / no backend works."""
|
|
40
|
+
try:
|
|
41
|
+
import keyring
|
|
42
|
+
import keyring.errors
|
|
43
|
+
from keyring.backends import fail
|
|
44
|
+
except ImportError: # the `keyring` extra is not installed: env vars only
|
|
45
|
+
return None
|
|
46
|
+
if isinstance(keyring.get_keyring(), fail.Keyring):
|
|
47
|
+
return None
|
|
48
|
+
return keyring
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class Store:
|
|
52
|
+
"""Credentials of one package: namespace for the keychain and the environment names."""
|
|
53
|
+
|
|
54
|
+
def __init__(
|
|
55
|
+
self,
|
|
56
|
+
namespace: str,
|
|
57
|
+
*,
|
|
58
|
+
shared_namespaces: tuple[str, ...] = (),
|
|
59
|
+
keyring: object | None = None,
|
|
60
|
+
bare_field: str | None = None,
|
|
61
|
+
) -> None:
|
|
62
|
+
self.namespace = namespace
|
|
63
|
+
self.shared_namespaces = tuple(shared_namespaces)
|
|
64
|
+
# A keychain entry written by an older release may be one raw string rather than a JSON bag:
|
|
65
|
+
# with `bare_field`, such an entry is read as that field's value (e.g. "password").
|
|
66
|
+
self.bare_field = bare_field
|
|
67
|
+
# An injected backend (a test double, another keyring module) wins over the default one.
|
|
68
|
+
self._injected_keyring = keyring
|
|
69
|
+
self._keychain_problem: str | None = None
|
|
70
|
+
self._warned_missing = False
|
|
71
|
+
|
|
72
|
+
# --- names the store builds -------------------------------------------------
|
|
73
|
+
|
|
74
|
+
def service_name(self, provider: str) -> str:
|
|
75
|
+
return f"{self.namespace}:{provider}"
|
|
76
|
+
|
|
77
|
+
def env_var_name(self, provider: str, field: str) -> str:
|
|
78
|
+
return re.sub(r"[^A-Z0-9]", "_", f"{self.namespace}_{provider}_{field}".upper())
|
|
79
|
+
|
|
80
|
+
def _namespaces(self) -> tuple[str, ...]:
|
|
81
|
+
return (self.namespace, *self.shared_namespaces)
|
|
82
|
+
|
|
83
|
+
@property
|
|
84
|
+
def _keyring(self):
|
|
85
|
+
return self._injected_keyring if self._injected_keyring is not None else _keyring()
|
|
86
|
+
|
|
87
|
+
@property
|
|
88
|
+
def unavailable_reason(self) -> str | None:
|
|
89
|
+
"""Why the keychain could not be read, or None: `doctor` and `auth status` report it."""
|
|
90
|
+
return self._keychain_problem
|
|
91
|
+
|
|
92
|
+
# --- the stored set ---------------------------------------------------------
|
|
93
|
+
|
|
94
|
+
def backend(self) -> str | None:
|
|
95
|
+
"""Name of the active keyring backend, or None when only the environment can supply secrets."""
|
|
96
|
+
keyring = self._keyring
|
|
97
|
+
if keyring is None or not hasattr(keyring, "get_keyring"):
|
|
98
|
+
return None
|
|
99
|
+
backend = keyring.get_keyring()
|
|
100
|
+
return f"{type(backend).__module__}.{type(backend).__name__}"
|
|
101
|
+
|
|
102
|
+
def stored(self, provider: str, namespace: str | None = None) -> dict[str, str]:
|
|
103
|
+
"""The fields stored in the keychain for one provider in one namespace (empty when absent)."""
|
|
104
|
+
keyring = self._keyring
|
|
105
|
+
if keyring is None:
|
|
106
|
+
return {}
|
|
107
|
+
try:
|
|
108
|
+
raw = keyring.get_password(self.service_name_for(provider, namespace or self.namespace), provider)
|
|
109
|
+
except keyring.errors.KeyringError as exc:
|
|
110
|
+
if self._keychain_problem is None:
|
|
111
|
+
self._keychain_problem = str(exc)
|
|
112
|
+
log.debug("OS credential store unavailable (%s); using environment variables only", exc)
|
|
113
|
+
return {}
|
|
114
|
+
if not raw:
|
|
115
|
+
return {}
|
|
116
|
+
try:
|
|
117
|
+
parsed = json.loads(raw)
|
|
118
|
+
except json.JSONDecodeError:
|
|
119
|
+
parsed = None
|
|
120
|
+
if isinstance(parsed, dict):
|
|
121
|
+
return parsed
|
|
122
|
+
if parsed is not None:
|
|
123
|
+
log.debug("stored credential for '%s' is JSON but not an object; ignoring it", provider)
|
|
124
|
+
return {}
|
|
125
|
+
if self.bare_field is not None:
|
|
126
|
+
# A single value from an older release: one field, no bag.
|
|
127
|
+
return {self.bare_field: raw}
|
|
128
|
+
log.debug("stored credential for '%s' is not valid JSON; ignoring it", provider)
|
|
129
|
+
return {}
|
|
130
|
+
|
|
131
|
+
def service_name_for(self, provider: str, namespace: str) -> str:
|
|
132
|
+
return f"{namespace}:{provider}"
|
|
133
|
+
|
|
134
|
+
def stored_names(self) -> list[str]:
|
|
135
|
+
"""Names of the providers stored in this namespace's keychain (environment-only ones are not listed)."""
|
|
136
|
+
keyring = self._keyring
|
|
137
|
+
if keyring is None:
|
|
138
|
+
return []
|
|
139
|
+
try:
|
|
140
|
+
raw = keyring.get_password(self.namespace, _INDEX_USER)
|
|
141
|
+
except keyring.errors.KeyringError:
|
|
142
|
+
return []
|
|
143
|
+
if not raw:
|
|
144
|
+
return []
|
|
145
|
+
try:
|
|
146
|
+
names = json.loads(raw)
|
|
147
|
+
except json.JSONDecodeError:
|
|
148
|
+
log.debug("the stored-credentials index of '%s' is not valid JSON; ignoring it", self.namespace)
|
|
149
|
+
return []
|
|
150
|
+
return sorted(names)
|
|
151
|
+
|
|
152
|
+
def _update_index(self, provider: str, *, present: bool) -> None:
|
|
153
|
+
keyring = self._keyring
|
|
154
|
+
if keyring is None:
|
|
155
|
+
return
|
|
156
|
+
names = set(self.stored_names())
|
|
157
|
+
names = names | {provider} if present else names - {provider}
|
|
158
|
+
try:
|
|
159
|
+
keyring.set_password(self.namespace, _INDEX_USER, json.dumps(sorted(names)))
|
|
160
|
+
except keyring.errors.KeyringError as exc: # the credential itself is stored; only listing suffers
|
|
161
|
+
log.debug("could not update the stored-credentials index (%s)", exc)
|
|
162
|
+
|
|
163
|
+
# --- reading ----------------------------------------------------------------
|
|
164
|
+
|
|
165
|
+
def read_from_env(self, provider: str, fields: list[str]) -> dict[str, str]:
|
|
166
|
+
"""Whichever of `fields` are set in the environment for this provider."""
|
|
167
|
+
result: dict[str, str] = {}
|
|
168
|
+
for field in fields:
|
|
169
|
+
value = os.environ.get(self.env_var_name(provider, field))
|
|
170
|
+
if value is not None:
|
|
171
|
+
result[field] = value
|
|
172
|
+
return result
|
|
173
|
+
|
|
174
|
+
def get(
|
|
175
|
+
self,
|
|
176
|
+
provider: str,
|
|
177
|
+
*,
|
|
178
|
+
env_fields: list[str] | None = None,
|
|
179
|
+
legacy_env: Mapping[str, str] | None = None,
|
|
180
|
+
legacy_env_first: bool = False,
|
|
181
|
+
) -> dict[str, str] | None:
|
|
182
|
+
"""The whole credential of a provider: stored fields merged with the environment (env wins per field)."""
|
|
183
|
+
stored = self.stored(provider)
|
|
184
|
+
fields = env_fields or list(stored) or [_DEFAULT_FIELD]
|
|
185
|
+
located = self.locate(provider, fields, legacy_env=legacy_env, legacy_env_first=legacy_env_first)
|
|
186
|
+
merged = {**stored, **{field: value for field, (value, _, _) in located.items()}}
|
|
187
|
+
return merged or None
|
|
188
|
+
|
|
189
|
+
def locate(
|
|
190
|
+
self,
|
|
191
|
+
provider: str,
|
|
192
|
+
fields: list[str],
|
|
193
|
+
*,
|
|
194
|
+
legacy_env: Mapping[str, str] | None = None,
|
|
195
|
+
legacy_env_first: bool = False,
|
|
196
|
+
) -> dict[str, tuple[str, str, str]]:
|
|
197
|
+
"""Per present field: (value, source "env"|"keychain", where: the variable name or the service).
|
|
198
|
+
|
|
199
|
+
Order per field, first hit wins: own env var, each shared namespace's env var, the keychain (own namespace
|
|
200
|
+
first, then shared), then the legacy variable — or right after the env vars with `legacy_env_first`.
|
|
201
|
+
For `auth status`, which reports the source and never the value.
|
|
202
|
+
"""
|
|
203
|
+
legacy = dict(legacy_env or {})
|
|
204
|
+
namespaces = self._namespaces()
|
|
205
|
+
stored = {
|
|
206
|
+
ns: (self.stored(provider) if ns == self.namespace else self.stored(provider, ns)) for ns in namespaces
|
|
207
|
+
}
|
|
208
|
+
located: dict[str, tuple[str, str, str]] = {}
|
|
209
|
+
for field in fields:
|
|
210
|
+
env_names = [re.sub(r"[^A-Z0-9]", "_", f"{ns}_{provider}_{field}".upper()) for ns in namespaces]
|
|
211
|
+
legacy_names = [legacy[field]] if field in legacy else []
|
|
212
|
+
env_first = env_names + legacy_names if legacy_env_first else env_names
|
|
213
|
+
for name in env_first:
|
|
214
|
+
if (value := os.environ.get(name)) is not None:
|
|
215
|
+
located[field] = (value, "env", name)
|
|
216
|
+
break
|
|
217
|
+
else:
|
|
218
|
+
for ns in namespaces:
|
|
219
|
+
if field in stored[ns]:
|
|
220
|
+
located[field] = (stored[ns][field], "keychain", self.service_name_for(provider, ns))
|
|
221
|
+
break
|
|
222
|
+
else:
|
|
223
|
+
for name in [] if legacy_env_first else legacy_names:
|
|
224
|
+
if (value := os.environ.get(name)) is not None:
|
|
225
|
+
located[field] = (value, "env", name)
|
|
226
|
+
self._warn_if_missing(provider, [field for field in fields if field not in located])
|
|
227
|
+
return located
|
|
228
|
+
|
|
229
|
+
def _warn_if_missing(self, provider: str, missing: list[str]) -> None:
|
|
230
|
+
if missing and self._keychain_problem is not None and not self._warned_missing:
|
|
231
|
+
self._warned_missing = True
|
|
232
|
+
# DEBUG, not WARNING: a library must not write to the caller's stdout/stderr. The caller reads
|
|
233
|
+
# `unavailable_reason` and decides what to tell the user.
|
|
234
|
+
log.debug(
|
|
235
|
+
"OS credential store unavailable (%s) and %s not set in the environment for '%s'",
|
|
236
|
+
self._keychain_problem,
|
|
237
|
+
", ".join(missing),
|
|
238
|
+
provider,
|
|
239
|
+
)
|
|
240
|
+
|
|
241
|
+
def get_secret(self, provider: str, field: str = _DEFAULT_FIELD) -> str | None:
|
|
242
|
+
"""The common single-secret case: one field, `api_key` by default."""
|
|
243
|
+
credential = self.get(provider, env_fields=[field])
|
|
244
|
+
return credential.get(field) if credential else None
|
|
245
|
+
|
|
246
|
+
def read_secret_from_env(self, provider: str, field: str = _DEFAULT_FIELD) -> str | None:
|
|
247
|
+
return self.read_from_env(provider, [field]).get(field)
|
|
248
|
+
|
|
249
|
+
# --- writing ----------------------------------------------------------------
|
|
250
|
+
|
|
251
|
+
def store(self, provider: str, fields: Mapping[str, str]) -> None:
|
|
252
|
+
"""Write one provider's fields into the keychain and add it to the namespace index."""
|
|
253
|
+
keyring = self._keyring
|
|
254
|
+
if keyring is None:
|
|
255
|
+
raise StoreUnavailable(f"no OS credential store: install the 'keyring' extra to store '{provider}'")
|
|
256
|
+
try:
|
|
257
|
+
keyring.set_password(self.service_name(provider), provider, json.dumps(dict(fields)))
|
|
258
|
+
except keyring.errors.KeyringError as exc:
|
|
259
|
+
raise StoreUnavailable(f"could not store '{provider}': {exc}") from exc
|
|
260
|
+
self._update_index(provider, present=True)
|
|
261
|
+
|
|
262
|
+
def store_secret(self, provider: str, secret: str, field: str = _DEFAULT_FIELD) -> None:
|
|
263
|
+
self.store(provider, {field: secret})
|
|
264
|
+
|
|
265
|
+
def delete(self, provider: str, *, ignore_unavailable: bool = False) -> None:
|
|
266
|
+
"""Remove a provider's credential; deleting an absent one is not an error.
|
|
267
|
+
|
|
268
|
+
`ignore_unavailable`: a machine without a keychain has nothing stored, so there is nothing to delete —
|
|
269
|
+
a package that treats a headless host as "no secrets here" passes True instead of failing the command.
|
|
270
|
+
"""
|
|
271
|
+
keyring = self._keyring
|
|
272
|
+
if keyring is None:
|
|
273
|
+
if ignore_unavailable:
|
|
274
|
+
return
|
|
275
|
+
raise StoreUnavailable(f"no OS credential store: nothing to delete for '{provider}'")
|
|
276
|
+
try:
|
|
277
|
+
keyring.delete_password(self.service_name(provider), provider)
|
|
278
|
+
except keyring.errors.PasswordDeleteError:
|
|
279
|
+
pass
|
|
280
|
+
except keyring.errors.KeyringError as exc:
|
|
281
|
+
if ignore_unavailable:
|
|
282
|
+
log.debug("OS credential store unavailable when deleting '%s' (%s)", provider, exc)
|
|
283
|
+
else:
|
|
284
|
+
raise StoreUnavailable(f"could not delete '{provider}': {exc}") from exc
|
|
285
|
+
self._update_index(provider, present=False)
|
|
286
|
+
|
|
287
|
+
# --- one raw value per slot ---------------------------------------------------
|
|
288
|
+
# Some stores are a single string per (kind, name) — a service-account JSON, one API key — rather than a bag
|
|
289
|
+
# of fields. They share the keychain and the "read once, warn once" state of this store.
|
|
290
|
+
|
|
291
|
+
def get_value(self, kind: str, name: str = "default") -> str | None:
|
|
292
|
+
keyring = self._keyring
|
|
293
|
+
if keyring is None:
|
|
294
|
+
return None
|
|
295
|
+
try:
|
|
296
|
+
value = keyring.get_password(self.service_name(kind), name)
|
|
297
|
+
except keyring.errors.KeyringError as exc:
|
|
298
|
+
if self._keychain_problem is None:
|
|
299
|
+
self._keychain_problem = str(exc)
|
|
300
|
+
log.debug("OS credential store unavailable (%s); using environment variables only", exc)
|
|
301
|
+
return None
|
|
302
|
+
return value or None
|
|
303
|
+
|
|
304
|
+
def set_value(self, kind: str, value: str, name: str = "default") -> None:
|
|
305
|
+
keyring = self._keyring
|
|
306
|
+
if keyring is None:
|
|
307
|
+
raise StoreUnavailable(f"no OS credential store: install the 'keyring' extra to store '{kind}'")
|
|
308
|
+
try:
|
|
309
|
+
keyring.set_password(self.service_name(kind), name, value)
|
|
310
|
+
except keyring.errors.KeyringError as exc:
|
|
311
|
+
raise StoreUnavailable(f"could not store '{kind}': {exc}") from exc
|
|
312
|
+
|
|
313
|
+
def delete_value(self, kind: str, name: str = "default") -> None:
|
|
314
|
+
keyring = self._keyring
|
|
315
|
+
if keyring is None:
|
|
316
|
+
raise StoreUnavailable(f"no OS credential store: nothing to delete for '{kind}'")
|
|
317
|
+
try:
|
|
318
|
+
keyring.delete_password(self.service_name(kind), name)
|
|
319
|
+
except keyring.errors.PasswordDeleteError:
|
|
320
|
+
pass
|
|
321
|
+
except keyring.errors.KeyringError as exc:
|
|
322
|
+
raise StoreUnavailable(f"could not delete '{kind}': {exc}") from exc
|
|
323
|
+
|
|
324
|
+
# --- helpers for the callers -------------------------------------------------
|
|
325
|
+
|
|
326
|
+
def require(self, provider: str, field: str = _DEFAULT_FIELD) -> str:
|
|
327
|
+
"""A secret that must exist: raises `CredentialsUnavailable` naming the provider and the place to set it."""
|
|
328
|
+
value = self.get_secret(provider, field)
|
|
329
|
+
if value is None:
|
|
330
|
+
raise CredentialsUnavailable(
|
|
331
|
+
f"no credential for '{provider}': set {self.env_var_name(provider, field)} "
|
|
332
|
+
f"or store it with `auth login {provider}`"
|
|
333
|
+
)
|
|
334
|
+
return value
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""Guard the credentials protocol without using real secrets."""
|
|
2
|
+
|
|
3
|
+
import importlib.util
|
|
4
|
+
from datetime import UTC, datetime, timedelta
|
|
5
|
+
|
|
6
|
+
import pytest
|
|
7
|
+
|
|
8
|
+
from rb_credentials import (
|
|
9
|
+
CallableCredentials,
|
|
10
|
+
Credential,
|
|
11
|
+
CredentialsUnavailable,
|
|
12
|
+
EnvironmentCredentials,
|
|
13
|
+
KeyringCredentials,
|
|
14
|
+
parse_address,
|
|
15
|
+
providers_for,
|
|
16
|
+
resolve_credential,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def test_environment_provider_reads_the_mapped_variable() -> None:
|
|
21
|
+
provider = EnvironmentCredentials({"api": "API_TOKEN"}, {"API_TOKEN": "value"})
|
|
22
|
+
credential = provider.resolve("api")
|
|
23
|
+
assert credential is not None
|
|
24
|
+
assert credential.token.get_secret_value() == "value"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def test_unknown_name_and_missing_variable_return_none() -> None:
|
|
28
|
+
provider = EnvironmentCredentials({"api": "API_TOKEN"}, {})
|
|
29
|
+
assert provider.resolve("api") is None
|
|
30
|
+
assert provider.resolve("other") is None
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def test_the_first_provider_with_a_value_wins() -> None:
|
|
34
|
+
empty = CallableCredentials(lambda name: None)
|
|
35
|
+
answering = CallableCredentials(lambda name: "second")
|
|
36
|
+
credential = resolve_credential(empty, answering, name="api")
|
|
37
|
+
assert credential.token.get_secret_value() == "second"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def test_missing_credential_names_the_credential_not_a_value() -> None:
|
|
41
|
+
with pytest.raises(CredentialsUnavailable) as failure:
|
|
42
|
+
resolve_credential(CallableCredentials(lambda name: None), name="api")
|
|
43
|
+
assert "api" in str(failure.value)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def test_token_is_masked_and_blank_tokens_are_rejected() -> None:
|
|
47
|
+
credential = Credential(name="api", token="secret-value")
|
|
48
|
+
assert "secret-value" not in repr(credential)
|
|
49
|
+
assert credential.token.get_secret_value() == "secret-value"
|
|
50
|
+
with pytest.raises(ValueError):
|
|
51
|
+
Credential(name="api", token=" ")
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def test_expiry_is_explicit() -> None:
|
|
55
|
+
expired = Credential(name="api", token="value", expires_at=datetime.now(UTC) - timedelta(seconds=1))
|
|
56
|
+
assert expired.is_expired()
|
|
57
|
+
assert not Credential(name="api", token="value").is_expired()
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def test_keyring_without_the_extra_returns_none() -> None:
|
|
61
|
+
provider = KeyringCredentials({"api": "service/account"})
|
|
62
|
+
if importlib.util.find_spec("keyring") is None:
|
|
63
|
+
assert provider.resolve("api") is None
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def test_addresses_are_parsed_by_scheme() -> None:
|
|
67
|
+
assert parse_address("env:API_TOKEN") == ("env", "API_TOKEN", None)
|
|
68
|
+
assert parse_address("keyring:service/account") == ("keyring", "service", "account")
|
|
69
|
+
for address in ("API_TOKEN", "env:", "keyring:service", "vault:path"):
|
|
70
|
+
with pytest.raises(ValueError):
|
|
71
|
+
parse_address(address)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def test_providers_built_from_a_mapping_resolve_by_name(
|
|
75
|
+
monkeypatch: pytest.MonkeyPatch,
|
|
76
|
+
) -> None:
|
|
77
|
+
monkeypatch.setenv("API_TOKEN", "token")
|
|
78
|
+
providers = providers_for({"api": "env:API_TOKEN"})
|
|
79
|
+
assert resolve_credential(*providers, name="api").token.get_secret_value() == "token"
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""The `auth status` envelope: the shape every tool of the family reports in (ADR 0017)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from datetime import UTC, datetime
|
|
6
|
+
|
|
7
|
+
from rb_credentials import status
|
|
8
|
+
|
|
9
|
+
ENTRY_KEYS = ["provider", "required", "fields", "source", "source_ref", "status", "expires_at", "quota", "message"]
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def test_entry_has_the_nine_keys_in_one_order() -> None:
|
|
13
|
+
record = status.entry("demo")
|
|
14
|
+
assert list(record) == ENTRY_KEYS
|
|
15
|
+
assert (record["provider"], record["required"], record["status"], record["source"]) == (
|
|
16
|
+
"demo",
|
|
17
|
+
True,
|
|
18
|
+
"missing",
|
|
19
|
+
"missing",
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def test_fields_are_the_declared_ones_in_declared_order() -> None:
|
|
24
|
+
record = status.entry("yandex", fields=("token", "client_id"), required=False)
|
|
25
|
+
assert (record["fields"], record["required"]) == (["token", "client_id"], False)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def test_expiry_is_utc_z_without_microseconds_and_quota_is_a_plain_dict() -> None:
|
|
29
|
+
moment = datetime(2026, 11, 19, 12, 0, 0, 123456, tzinfo=UTC)
|
|
30
|
+
record = status.entry("demo", expires_at=moment, quota=status.Quota(remaining=5, limit=10))
|
|
31
|
+
assert record["expires_at"] == "2026-11-19T12:00:00Z"
|
|
32
|
+
assert record["quota"] == {"remaining": 5, "limit": 10, "unit": "requests"}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def test_report_carries_tool_version_and_a_utc_timestamp() -> None:
|
|
36
|
+
payload = status.report("dataio", "1.2.3", [status.entry("demo")])
|
|
37
|
+
assert list(payload) == ["tool", "version", "checked_at", "credentials"]
|
|
38
|
+
assert payload["checked_at"].endswith("Z") and "." not in payload["checked_at"]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def test_scrub_erases_every_secret_and_passes_none_through() -> None:
|
|
42
|
+
assert status.scrub("token abc123 refused for abc123", ["abc123", None, ""]) == "token *** refused for ***"
|
|
43
|
+
assert status.scrub(None, ["abc123"]) is None
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def test_problems_are_invalid_always_and_anything_but_ok_unchecked_when_required() -> None:
|
|
47
|
+
payload = status.report(
|
|
48
|
+
"tool",
|
|
49
|
+
"1.0",
|
|
50
|
+
[
|
|
51
|
+
status.entry("bad", required=False, status="invalid"),
|
|
52
|
+
status.entry("gone", required=True, status="missing"),
|
|
53
|
+
status.entry("fine", required=True, status="unchecked"),
|
|
54
|
+
status.entry("optional_gone", required=False, status="missing"),
|
|
55
|
+
],
|
|
56
|
+
)
|
|
57
|
+
assert status.problems(payload) == {"bad": "invalid", "gone": "missing"}
|
|
58
|
+
assert status.exit_code(payload) == status.EXIT_PROBLEM == 3
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def test_no_problem_is_exit_0() -> None:
|
|
62
|
+
payload = status.report("tool", "1.0", [status.entry("fine", status="ok")])
|
|
63
|
+
assert (status.problems(payload), status.exit_code(payload)) == ({}, 0)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def test_health_defaults_to_ok_and_quota_defaults_are_requests() -> None:
|
|
67
|
+
assert status.Health() == status.Health(status="ok", expires_at=None, quota=None, message=None)
|
|
68
|
+
assert status.Quota() == status.Quota(remaining=None, limit=None, unit="requests")
|
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
"""The store: the family's naming conventions, the keychain with its index, and the env-var fallback."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
|
|
7
|
+
import pytest
|
|
8
|
+
|
|
9
|
+
from rb_credentials import CredentialsUnavailable, Store, StoreUnavailable
|
|
10
|
+
from rb_credentials import store as store_module
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class FakeKeyring:
|
|
14
|
+
"""The small part of keyring the store uses, in memory."""
|
|
15
|
+
|
|
16
|
+
class errors: # mirrors keyring.errors
|
|
17
|
+
class KeyringError(Exception): ...
|
|
18
|
+
|
|
19
|
+
class PasswordDeleteError(KeyringError): ...
|
|
20
|
+
|
|
21
|
+
def __init__(self) -> None:
|
|
22
|
+
self.entries: dict[tuple[str, str], str] = {}
|
|
23
|
+
self.fail = False
|
|
24
|
+
|
|
25
|
+
def get_password(self, service: str, user: str) -> str | None:
|
|
26
|
+
if self.fail:
|
|
27
|
+
raise self.errors.KeyringError("no secret service")
|
|
28
|
+
return self.entries.get((service, user))
|
|
29
|
+
|
|
30
|
+
def set_password(self, service: str, user: str, value: str) -> None:
|
|
31
|
+
if self.fail:
|
|
32
|
+
raise self.errors.KeyringError("no secret service")
|
|
33
|
+
self.entries[(service, user)] = value
|
|
34
|
+
|
|
35
|
+
def delete_password(self, service: str, user: str) -> None:
|
|
36
|
+
if self.fail:
|
|
37
|
+
raise self.errors.KeyringError("no secret service")
|
|
38
|
+
if (service, user) not in self.entries:
|
|
39
|
+
raise self.errors.PasswordDeleteError("absent")
|
|
40
|
+
del self.entries[(service, user)]
|
|
41
|
+
|
|
42
|
+
def get_keyring(self) -> object:
|
|
43
|
+
return self
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@pytest.fixture
|
|
47
|
+
def keyring(monkeypatch: pytest.MonkeyPatch) -> FakeKeyring:
|
|
48
|
+
fake = FakeKeyring()
|
|
49
|
+
monkeypatch.setattr(store_module, "_keyring", lambda: fake)
|
|
50
|
+
return fake
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def test_the_family_names() -> None:
|
|
54
|
+
store = Store("serp")
|
|
55
|
+
assert store.service_name("xmlriver") == "serp:xmlriver"
|
|
56
|
+
assert store.env_var_name("xmlriver", "api_key") == "SERP_XMLRIVER_API_KEY"
|
|
57
|
+
assert store.env_var_name("deploy:example.com", "api_key") == "SERP_DEPLOY_EXAMPLE_COM_API_KEY"
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def test_a_stored_secret_round_trips(keyring: FakeKeyring) -> None:
|
|
61
|
+
store = Store("demo")
|
|
62
|
+
store.store_secret("openai", "sk-1")
|
|
63
|
+
assert store.get_secret("openai") == "sk-1"
|
|
64
|
+
assert store.stored_names() == ["openai"]
|
|
65
|
+
store.delete("openai")
|
|
66
|
+
assert store.get_secret("openai") is None
|
|
67
|
+
assert store.stored_names() == []
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def test_env_wins_over_the_keychain_field_by_field(keyring: FakeKeyring, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
71
|
+
store = Store("demo")
|
|
72
|
+
store.store("host", {"user": "u", "password": "p"})
|
|
73
|
+
monkeypatch.setenv("DEMO_HOST_PASSWORD", "rotated")
|
|
74
|
+
credential = store.get("host", env_fields=["user", "password"])
|
|
75
|
+
assert credential == {"user": "u", "password": "rotated"}
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def test_a_multi_field_credential_survives_as_one_blob(keyring: FakeKeyring) -> None:
|
|
79
|
+
store = Store("demo")
|
|
80
|
+
store.store("site", {"cookie": "c", "csrf": "t"})
|
|
81
|
+
assert json.loads(keyring.entries[("demo:site", "site")]) == {"cookie": "c", "csrf": "t"}
|
|
82
|
+
assert store.get("site") == {"cookie": "c", "csrf": "t"}
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def test_locate_names_the_source_without_the_value(keyring: FakeKeyring, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
86
|
+
store = Store("demo")
|
|
87
|
+
store.store_secret("openai", "stored")
|
|
88
|
+
monkeypatch.setenv("DEMO_OTHER_API_KEY", "from-env")
|
|
89
|
+
assert store.locate("openai", ["api_key"])["api_key"] == ("stored", "keychain", "demo:openai")
|
|
90
|
+
assert store.locate("other", ["api_key"])["api_key"] == ("from-env", "env", "DEMO_OTHER_API_KEY")
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def test_a_shared_namespace_is_read_but_never_written(keyring: FakeKeyring) -> None:
|
|
94
|
+
Store("neighbour").store_secret("openai", "theirs")
|
|
95
|
+
store = Store("demo", shared_namespaces=("neighbour",))
|
|
96
|
+
assert store.get_secret("openai") == "theirs"
|
|
97
|
+
assert store.stored_names() == []
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def test_without_a_keyring_the_environment_still_works(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
101
|
+
monkeypatch.setattr(store_module, "_keyring", lambda: None)
|
|
102
|
+
store = Store("demo")
|
|
103
|
+
monkeypatch.setenv("DEMO_OPENAI_API_KEY", "from-env")
|
|
104
|
+
assert store.get_secret("openai") == "from-env"
|
|
105
|
+
assert store.backend() is None
|
|
106
|
+
with pytest.raises(StoreUnavailable):
|
|
107
|
+
store.store_secret("openai", "x")
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def test_require_names_the_variable_to_set(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
111
|
+
monkeypatch.setattr(store_module, "_keyring", lambda: None)
|
|
112
|
+
store = Store("demo")
|
|
113
|
+
with pytest.raises(CredentialsUnavailable) as excinfo:
|
|
114
|
+
store.require("openai")
|
|
115
|
+
assert "DEMO_OPENAI_API_KEY" in str(excinfo.value)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def test_a_broken_keyring_falls_back_to_the_environment(keyring: FakeKeyring, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
119
|
+
keyring.fail = True
|
|
120
|
+
store = Store("demo")
|
|
121
|
+
monkeypatch.setenv("DEMO_OPENAI_API_KEY", "from-env")
|
|
122
|
+
assert store.get_secret("openai") == "from-env"
|
|
123
|
+
assert store.stored_names() == []
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
# --- the name-and-address API that predates the store ---------------------------------
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def test_parse_address_understands_env_and_keyring() -> None:
|
|
130
|
+
from rb_credentials import parse_address
|
|
131
|
+
|
|
132
|
+
assert parse_address("env:OPENAI_KEY") == ("env", "OPENAI_KEY", None)
|
|
133
|
+
assert parse_address("keyring:openai/bob") == ("keyring", "openai", "bob")
|
|
134
|
+
with pytest.raises(ValueError):
|
|
135
|
+
parse_address("file:/tmp/secret")
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def test_providers_resolve_from_the_environment(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
139
|
+
from rb_credentials import providers_for, resolve_credential
|
|
140
|
+
|
|
141
|
+
monkeypatch.setenv("OPENAI_KEY", "sk-env")
|
|
142
|
+
credential = resolve_credential(*providers_for({"openai": "env:OPENAI_KEY"}), name="openai")
|
|
143
|
+
assert credential.token.get_secret_value() == "sk-env"
|
|
144
|
+
assert credential.name == "openai"
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def test_resolve_names_the_missing_credential(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
148
|
+
from rb_credentials import providers_for, resolve_credential
|
|
149
|
+
|
|
150
|
+
monkeypatch.delenv("ABSENT_KEY", raising=False)
|
|
151
|
+
with pytest.raises(CredentialsUnavailable) as excinfo:
|
|
152
|
+
resolve_credential(*providers_for({"absent": "env:ABSENT_KEY"}), name="absent")
|
|
153
|
+
assert "absent" in str(excinfo.value)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def test_a_callable_provider_adapts_any_reader() -> None:
|
|
157
|
+
from rb_credentials import CallableCredentials, resolve_credential
|
|
158
|
+
|
|
159
|
+
provider = CallableCredentials(lambda name: "value" if name == "x" else None)
|
|
160
|
+
assert resolve_credential(provider, name="x").token.get_secret_value() == "value"
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def test_an_expired_credential_says_so() -> None:
|
|
164
|
+
from datetime import UTC, datetime, timedelta
|
|
165
|
+
|
|
166
|
+
from rb_credentials import Credential
|
|
167
|
+
|
|
168
|
+
past = datetime.now(UTC) - timedelta(minutes=1)
|
|
169
|
+
assert Credential(name="a", token="t", expires_at=past).is_expired()
|
|
170
|
+
assert not Credential(name="a", token="t").is_expired()
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def test_a_legacy_variable_is_read_after_the_family_one(monkeypatch: pytest.MonkeyPatch, keyring: FakeKeyring) -> None:
|
|
174
|
+
store = Store("serp")
|
|
175
|
+
monkeypatch.setenv("XMLRIVER_API_KEY", "legacy")
|
|
176
|
+
assert store.get("xmlriver", env_fields=["api_key"], legacy_env={"api_key": "XMLRIVER_API_KEY"}) == {
|
|
177
|
+
"api_key": "legacy"
|
|
178
|
+
}
|
|
179
|
+
monkeypatch.setenv("SERP_XMLRIVER_API_KEY", "family")
|
|
180
|
+
located = store.locate("xmlriver", ["api_key"], legacy_env={"api_key": "XMLRIVER_API_KEY"})
|
|
181
|
+
assert located["api_key"] == ("family", "env", "SERP_XMLRIVER_API_KEY")
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def test_deleting_an_absent_credential_is_not_an_error(keyring: FakeKeyring) -> None:
|
|
185
|
+
Store("demo").delete("never-stored")
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def test_the_backend_is_reported_for_doctor(keyring: FakeKeyring) -> None:
|
|
189
|
+
assert Store("demo").backend()
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def test_a_broken_index_does_not_break_listing(keyring: FakeKeyring) -> None:
|
|
193
|
+
keyring.entries[("demo", "__stored_credentials__")] = "not json"
|
|
194
|
+
assert Store("demo").stored_names() == []
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def test_the_real_keyring_backend_is_detected() -> None:
|
|
198
|
+
"""Without monkeypatching: with the extra installed a backend exists, without it the store says so."""
|
|
199
|
+
backend = store_module._keyring()
|
|
200
|
+
if backend is None:
|
|
201
|
+
assert Store("demo").backend() is None
|
|
202
|
+
else:
|
|
203
|
+
assert Store("demo").backend()
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def test_the_reason_a_keychain_could_not_be_read_is_public(keyring: FakeKeyring) -> None:
|
|
207
|
+
store = Store("demo")
|
|
208
|
+
assert store.unavailable_reason is None
|
|
209
|
+
keyring.fail = True
|
|
210
|
+
store.stored("openai")
|
|
211
|
+
assert "secret service" in (store.unavailable_reason or "")
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def test_one_raw_value_per_slot(keyring: FakeKeyring) -> None:
|
|
215
|
+
store = Store("google-oauth")
|
|
216
|
+
store.set_value("service_account", '{"k": 1}')
|
|
217
|
+
assert store.get_value("service_account") == '{"k": 1}'
|
|
218
|
+
store.set_value("api_key", "key-1", name="psi")
|
|
219
|
+
assert store.get_value("api_key", "psi") == "key-1"
|
|
220
|
+
store.delete_value("service_account")
|
|
221
|
+
assert store.get_value("service_account") is None
|
|
222
|
+
store.delete_value("never-there")
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def test_slot_errors_are_store_unavailable(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
226
|
+
monkeypatch.setattr(store_module, "_keyring", lambda: None)
|
|
227
|
+
store = Store("demo")
|
|
228
|
+
with pytest.raises(StoreUnavailable):
|
|
229
|
+
store.set_value("service_account", "{}")
|
|
230
|
+
with pytest.raises(StoreUnavailable):
|
|
231
|
+
store.delete_value("service_account")
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def test_a_failing_keychain_on_slots(keyring: FakeKeyring) -> None:
|
|
235
|
+
store = Store("demo")
|
|
236
|
+
keyring.fail = True
|
|
237
|
+
assert store.get_value("service_account") is None
|
|
238
|
+
assert store.unavailable_reason
|
|
239
|
+
with pytest.raises(StoreUnavailable):
|
|
240
|
+
store.set_value("service_account", "{}")
|
|
241
|
+
with pytest.raises(StoreUnavailable):
|
|
242
|
+
store.delete_value("service_account")
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def test_an_injected_backend_is_used_instead_of_the_real_one() -> None:
|
|
246
|
+
fake = FakeKeyring()
|
|
247
|
+
store = Store("demo", keyring=fake)
|
|
248
|
+
store.store_secret("openai", "sk-injected")
|
|
249
|
+
assert fake.entries[("demo:openai", "openai")]
|
|
250
|
+
assert store.get_secret("openai") == "sk-injected"
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def test_a_bare_legacy_value_is_read_as_the_named_field(keyring: FakeKeyring) -> None:
|
|
254
|
+
keyring.entries[("hostme:client.ru", "client.ru")] = "s3cret"
|
|
255
|
+
store = Store("hostme", keyring=keyring, bare_field="password")
|
|
256
|
+
assert store.get("client.ru") == {"password": "s3cret"}
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def test_without_bare_field_a_bare_value_is_ignored(keyring: FakeKeyring) -> None:
|
|
260
|
+
keyring.entries[("demo:openai", "openai")] = "raw"
|
|
261
|
+
assert Store("demo", keyring=keyring).get("openai") is None
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def test_deleting_on_a_host_without_a_keychain_can_be_a_no_op(
|
|
265
|
+
keyring: FakeKeyring, monkeypatch: pytest.MonkeyPatch
|
|
266
|
+
) -> None:
|
|
267
|
+
keyring.fail = True
|
|
268
|
+
store = Store("hostme", keyring=keyring)
|
|
269
|
+
with pytest.raises(StoreUnavailable):
|
|
270
|
+
store.delete("client.ru")
|
|
271
|
+
store.delete("client.ru", ignore_unavailable=True)
|
|
272
|
+
|
|
273
|
+
monkeypatch.setattr(store_module, "_keyring", lambda: None)
|
|
274
|
+
without = Store("hostme")
|
|
275
|
+
with pytest.raises(StoreUnavailable):
|
|
276
|
+
without.delete("client.ru")
|
|
277
|
+
without.delete("client.ru", ignore_unavailable=True)
|