rb-credentials 0.7.2__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.
- rb_credentials/__init__.py +161 -0
- rb_credentials/py.typed +0 -0
- rb_credentials/status.py +125 -0
- rb_credentials/store.py +334 -0
- rb_credentials-0.7.2.dist-info/METADATA +76 -0
- rb_credentials-0.7.2.dist-info/RECORD +8 -0
- rb_credentials-0.7.2.dist-info/WHEEL +4 -0
- rb_credentials-0.7.2.dist-info/licenses/LICENSE +21 -0
|
@@ -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
|
rb_credentials/py.typed
ADDED
|
File without changes
|
rb_credentials/status.py
ADDED
|
@@ -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
|
rb_credentials/store.py
ADDED
|
@@ -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,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,8 @@
|
|
|
1
|
+
rb_credentials/__init__.py,sha256=m6ye8tHvwIynbmj4v06P73aJvM4DLu2_6dHip4e9AKc,5581
|
|
2
|
+
rb_credentials/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
3
|
+
rb_credentials/status.py,sha256=DuhfxHZzF_0gF4A-qc64EzajKmYNHEz_A-aAYSmrOCM,4011
|
|
4
|
+
rb_credentials/store.py,sha256=oC2dAX7C7dKP6Dc5B2tJXWpfFSz1wpowQLAWcGfMJS0,15247
|
|
5
|
+
rb_credentials-0.7.2.dist-info/METADATA,sha256=lu3r-y2yvLaqrYy3e8ZWHeGTMokjyp_DkpK4eGnLqmM,2283
|
|
6
|
+
rb_credentials-0.7.2.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
7
|
+
rb_credentials-0.7.2.dist-info/licenses/LICENSE,sha256=5GzRg5WDp2lrQTiJlcB9JSzPewiy-E-P7YMKt9idbV4,1071
|
|
8
|
+
rb_credentials-0.7.2.dist-info/RECORD,,
|
|
@@ -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.
|