keychain-cli 0.1.1__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.
@@ -0,0 +1,78 @@
1
+ """The Keychain access layer behind one narrow seam.
2
+
3
+ Commands depend on ``SecretStore`` and never on the Security framework directly, so every
4
+ command can be unit-tested against an in-memory fake (constitution VI). The only production
5
+ implementation is ``keychain_cli.keychain.store.SecurityFrameworkStore``; import it lazily
6
+ so that a non-macOS run fails at the platform check before any framework loads.
7
+
8
+ This module deliberately imports no ``ctypes`` code.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from typing import Protocol
14
+
15
+ from keychain_cli.errors import KeychainError as StoreError
16
+ from keychain_cli.names import Namespace
17
+ from keychain_cli.secret import SecretValue
18
+
19
+ __all__ = [
20
+ "AlreadyExists",
21
+ "Namespace",
22
+ "NotFound",
23
+ "SecretStore",
24
+ "StoreError",
25
+ ]
26
+
27
+
28
+ class AlreadyExists(Exception):
29
+ """The variable already holds a value. Commands decide whether to overwrite."""
30
+
31
+
32
+ class NotFound(Exception):
33
+ """The namespace or variable does not exist."""
34
+
35
+
36
+ class SecretStore(Protocol):
37
+ """Everything the tool ever asks of the Keychain.
38
+
39
+ List operations request attributes only and never secret data. Errors from the
40
+ underlying store are raised as ``StoreError`` carrying the OS status and OS message,
41
+ never a value.
42
+ """
43
+
44
+ def list_namespaces(self) -> list[Namespace]:
45
+ """All namespaces that hold at least one variable, sorted by ``key``."""
46
+ ...
47
+
48
+ def list_variables(self, namespace: Namespace) -> list[str]:
49
+ """Sorted variable names. Raises ``NotFound`` if the namespace holds none."""
50
+ ...
51
+
52
+ def exists(self, namespace: Namespace, name: str) -> bool:
53
+ """Whether the variable holds a value. Reads no secret data."""
54
+ ...
55
+
56
+ def get(self, namespace: Namespace, name: str) -> SecretValue:
57
+ """One value. Raises ``NotFound``."""
58
+ ...
59
+
60
+ def get_all(self, namespace: Namespace) -> dict[str, SecretValue]:
61
+ """Every variable in the namespace. Raises ``NotFound`` if there are none."""
62
+ ...
63
+
64
+ def add(self, namespace: Namespace, name: str, value: SecretValue) -> None:
65
+ """Store a new variable. Raises ``AlreadyExists``; never overwrites."""
66
+ ...
67
+
68
+ def update(self, namespace: Namespace, name: str, value: SecretValue) -> None:
69
+ """Replace an existing value. Raises ``NotFound``."""
70
+ ...
71
+
72
+ def delete_variable(self, namespace: Namespace, name: str) -> None:
73
+ """Remove one variable. Raises ``NotFound``."""
74
+ ...
75
+
76
+ def delete_namespace(self, namespace: Namespace) -> int:
77
+ """Remove every variable in the namespace. Returns the count; raises ``NotFound`` if 0."""
78
+ ...
@@ -0,0 +1,186 @@
1
+ """CoreFoundation bindings: just enough to build a query dictionary and read a result.
2
+
3
+ Every object created here is released by the ``CFObjects`` context manager that created
4
+ it. Objects returned by the Security framework are owned by the caller and released with
5
+ ``release`` after their contents have been copied into Python values.
6
+
7
+ Reference: ``specs/001-keychain-secret-manager/research/keychain-probe.py``.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import ctypes
13
+ from collections.abc import Iterable, Sequence
14
+ from types import TracebackType
15
+ from typing import Self
16
+
17
+ _CF_PATH = "/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation"
18
+ CF = ctypes.CDLL(_CF_PATH)
19
+
20
+ CFTypeRef = ctypes.c_void_p
21
+ CFIndex = ctypes.c_long
22
+ _UTF8 = 0x08000100
23
+ _SINT32 = 3
24
+
25
+ CF.CFStringCreateWithCString.restype = CFTypeRef
26
+ CF.CFStringCreateWithCString.argtypes = [CFTypeRef, ctypes.c_char_p, ctypes.c_uint32]
27
+ CF.CFDataCreate.restype = CFTypeRef
28
+ CF.CFDataCreate.argtypes = [CFTypeRef, ctypes.c_char_p, CFIndex]
29
+ CF.CFNumberCreate.restype = CFTypeRef
30
+ CF.CFNumberCreate.argtypes = [CFTypeRef, CFIndex, ctypes.c_void_p]
31
+ CF.CFDictionaryCreate.restype = CFTypeRef
32
+ CF.CFDictionaryCreate.argtypes = [
33
+ CFTypeRef,
34
+ ctypes.POINTER(CFTypeRef),
35
+ ctypes.POINTER(CFTypeRef),
36
+ CFIndex,
37
+ ctypes.c_void_p,
38
+ ctypes.c_void_p,
39
+ ]
40
+ CF.CFArrayCreate.restype = CFTypeRef
41
+ CF.CFArrayCreate.argtypes = [CFTypeRef, ctypes.POINTER(CFTypeRef), CFIndex, ctypes.c_void_p]
42
+ CF.CFRelease.restype = None
43
+ CF.CFRelease.argtypes = [CFTypeRef]
44
+ CF.CFArrayGetCount.restype = CFIndex
45
+ CF.CFArrayGetCount.argtypes = [CFTypeRef]
46
+ CF.CFArrayGetValueAtIndex.restype = CFTypeRef
47
+ CF.CFArrayGetValueAtIndex.argtypes = [CFTypeRef, CFIndex]
48
+ CF.CFDictionaryGetValue.restype = CFTypeRef
49
+ CF.CFDictionaryGetValue.argtypes = [CFTypeRef, CFTypeRef]
50
+ CF.CFGetTypeID.restype = ctypes.c_ulong
51
+ CF.CFGetTypeID.argtypes = [CFTypeRef]
52
+ CF.CFStringGetTypeID.restype = ctypes.c_ulong
53
+ CF.CFDataGetTypeID.restype = ctypes.c_ulong
54
+ CF.CFArrayGetTypeID.restype = ctypes.c_ulong
55
+ CF.CFDictionaryGetTypeID.restype = ctypes.c_ulong
56
+ CF.CFStringGetLength.restype = CFIndex
57
+ CF.CFStringGetLength.argtypes = [CFTypeRef]
58
+ CF.CFStringGetCString.restype = ctypes.c_bool
59
+ CF.CFStringGetCString.argtypes = [CFTypeRef, ctypes.c_char_p, CFIndex, ctypes.c_uint32]
60
+ CF.CFDataGetLength.restype = CFIndex
61
+ CF.CFDataGetLength.argtypes = [CFTypeRef]
62
+ CF.CFDataGetBytePtr.restype = ctypes.POINTER(ctypes.c_ubyte)
63
+ CF.CFDataGetBytePtr.argtypes = [CFTypeRef]
64
+
65
+ _KEY_CALLBACKS = ctypes.addressof(ctypes.c_char.in_dll(CF, "kCFTypeDictionaryKeyCallBacks"))
66
+ _VALUE_CALLBACKS = ctypes.addressof(ctypes.c_char.in_dll(CF, "kCFTypeDictionaryValueCallBacks"))
67
+ _ARRAY_CALLBACKS = ctypes.addressof(ctypes.c_char.in_dll(CF, "kCFTypeArrayCallBacks"))
68
+
69
+
70
+ def ptr(ref: int | ctypes.c_void_p | None) -> int:
71
+ """Normalize a ctypes pointer or raw address to an int address."""
72
+ if ref is None:
73
+ return 0
74
+ if isinstance(ref, ctypes.c_void_p):
75
+ return ref.value or 0
76
+ return ref
77
+
78
+
79
+ BOOLEAN_TRUE = ptr(CFTypeRef.in_dll(CF, "kCFBooleanTrue"))
80
+
81
+
82
+ def release(ref: int) -> None:
83
+ """Release an object owned by the caller."""
84
+ if ref:
85
+ CF.CFRelease(ref)
86
+
87
+
88
+ class CFObjects:
89
+ """Create CoreFoundation objects and release all of them on exit.
90
+
91
+ ``CFDictionaryCreate`` and ``CFArrayCreate`` retain their members, so releasing the
92
+ members and the container together is correct.
93
+ """
94
+
95
+ def __init__(self) -> None:
96
+ self._owned: list[int] = []
97
+
98
+ def __enter__(self) -> Self:
99
+ return self
100
+
101
+ def __exit__(
102
+ self,
103
+ exc_type: type[BaseException] | None,
104
+ exc: BaseException | None,
105
+ tb: TracebackType | None,
106
+ ) -> None:
107
+ for ref in reversed(self._owned):
108
+ release(ref)
109
+ self._owned.clear()
110
+
111
+ def _own(self, ref: int | None) -> int:
112
+ address = ptr(ref)
113
+ if not address:
114
+ msg = "CoreFoundation returned a null object"
115
+ raise MemoryError(msg)
116
+ self._owned.append(address)
117
+ return address
118
+
119
+ def string(self, text: str) -> int:
120
+ return self._own(CF.CFStringCreateWithCString(None, text.encode("utf-8"), _UTF8))
121
+
122
+ def data(self, raw: bytes) -> int:
123
+ return self._own(CF.CFDataCreate(None, raw, len(raw)))
124
+
125
+ def number32(self, value: int) -> int:
126
+ boxed = ctypes.c_int32(value)
127
+ return self._own(CF.CFNumberCreate(None, _SINT32, ctypes.byref(boxed)))
128
+
129
+ def dictionary(self, pairs: Sequence[tuple[int, int]]) -> int:
130
+ count = len(pairs)
131
+ keys = (CFTypeRef * count)(*[k for k, _ in pairs])
132
+ values = (CFTypeRef * count)(*[v for _, v in pairs])
133
+ return self._own(
134
+ CF.CFDictionaryCreate(None, keys, values, count, _KEY_CALLBACKS, _VALUE_CALLBACKS)
135
+ )
136
+
137
+ def array(self, items: Iterable[int]) -> int:
138
+ members = list(items)
139
+ buffer = (CFTypeRef * len(members))(*members)
140
+ return self._own(CF.CFArrayCreate(None, buffer, len(members), _ARRAY_CALLBACKS))
141
+
142
+
143
+ def is_array(ref: int) -> bool:
144
+ return bool(CF.CFGetTypeID(ref) == CF.CFArrayGetTypeID())
145
+
146
+
147
+ def is_dictionary(ref: int) -> bool:
148
+ return bool(CF.CFGetTypeID(ref) == CF.CFDictionaryGetTypeID())
149
+
150
+
151
+ def is_data(ref: int) -> bool:
152
+ return bool(CF.CFGetTypeID(ref) == CF.CFDataGetTypeID())
153
+
154
+
155
+ def is_string(ref: int) -> bool:
156
+ return bool(CF.CFGetTypeID(ref) == CF.CFStringGetTypeID())
157
+
158
+
159
+ def array_items(ref: int) -> list[int]:
160
+ """Addresses of an array's members. Not retained; valid while ``ref`` lives."""
161
+ count = CF.CFArrayGetCount(ref)
162
+ return [ptr(CF.CFArrayGetValueAtIndex(ref, index)) for index in range(count)]
163
+
164
+
165
+ def dict_get(ref: int, key: int) -> int:
166
+ """Address of a dictionary value, or 0 when the key is absent. Not retained."""
167
+ return ptr(CF.CFDictionaryGetValue(ref, key))
168
+
169
+
170
+ def to_str(ref: int) -> str:
171
+ """Copy a CFString into a Python str."""
172
+ length = CF.CFStringGetLength(ref)
173
+ buffer = ctypes.create_string_buffer(length * 4 + 1)
174
+ if not CF.CFStringGetCString(ref, buffer, len(buffer), _UTF8):
175
+ msg = "CFString could not be converted to UTF-8"
176
+ raise ValueError(msg)
177
+ return buffer.value.decode("utf-8")
178
+
179
+
180
+ def to_bytes(ref: int) -> bytes:
181
+ """Copy CFData into Python bytes."""
182
+ length = CF.CFDataGetLength(ref)
183
+ if length == 0:
184
+ return b""
185
+ pointer = CF.CFDataGetBytePtr(ref)
186
+ return bytes(pointer[:length])
@@ -0,0 +1,131 @@
1
+ """Security framework bindings: item CRUD, keychain files, and status text.
2
+
3
+ No function here takes or returns a Python secret; values travel as CFData addresses built
4
+ by ``_cf.CFObjects``. Nothing here spawns a process or touches ``argv``.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import ctypes
10
+
11
+ from keychain_cli.keychain import _cf
12
+
13
+ _SEC_PATH = "/System/Library/Frameworks/Security.framework/Security"
14
+ SEC = ctypes.CDLL(_SEC_PATH)
15
+
16
+ OSStatus = ctypes.c_int32
17
+ CFTypeRef = _cf.CFTypeRef
18
+
19
+ SEC.SecItemAdd.restype = OSStatus
20
+ SEC.SecItemAdd.argtypes = [CFTypeRef, ctypes.POINTER(CFTypeRef)]
21
+ SEC.SecItemCopyMatching.restype = OSStatus
22
+ SEC.SecItemCopyMatching.argtypes = [CFTypeRef, ctypes.POINTER(CFTypeRef)]
23
+ SEC.SecItemUpdate.restype = OSStatus
24
+ SEC.SecItemUpdate.argtypes = [CFTypeRef, CFTypeRef]
25
+ SEC.SecItemDelete.restype = OSStatus
26
+ SEC.SecItemDelete.argtypes = [CFTypeRef]
27
+ SEC.SecKeychainCreate.restype = OSStatus
28
+ SEC.SecKeychainCreate.argtypes = [
29
+ ctypes.c_char_p,
30
+ ctypes.c_uint32,
31
+ ctypes.c_void_p,
32
+ ctypes.c_bool,
33
+ CFTypeRef,
34
+ ctypes.POINTER(CFTypeRef),
35
+ ]
36
+ SEC.SecKeychainOpen.restype = OSStatus
37
+ SEC.SecKeychainOpen.argtypes = [ctypes.c_char_p, ctypes.POINTER(CFTypeRef)]
38
+ SEC.SecKeychainDelete.restype = OSStatus
39
+ SEC.SecKeychainDelete.argtypes = [CFTypeRef]
40
+ SEC.SecCopyErrorMessageString.restype = CFTypeRef
41
+ SEC.SecCopyErrorMessageString.argtypes = [OSStatus, ctypes.c_void_p]
42
+
43
+ # Status codes the store maps to specific outcomes. Everything else is a StoreError.
44
+ ERR_DUPLICATE = -25299
45
+ ERR_NOT_FOUND = -25300
46
+ ERR_INTERACTION_NOT_ALLOWED = -25308
47
+ ERR_AUTH_FAILED = -25293
48
+ ERR_USER_CANCELED = -128
49
+
50
+ # Ownership stamp: FourCharCode 'kccl'. Only items carrying it are visible to the tool.
51
+ CREATOR_STAMP = 0x6B63636C
52
+ SERVICE_PREFIX = "keychain-cli:"
53
+
54
+
55
+ def _constant(name: str) -> int:
56
+ return _cf.ptr(CFTypeRef.in_dll(SEC, name))
57
+
58
+
59
+ class Keys:
60
+ """Addresses of the ``kSec*`` CFString constants used in queries."""
61
+
62
+ CLASS = _constant("kSecClass")
63
+ CLASS_GENERIC_PASSWORD = _constant("kSecClassGenericPassword")
64
+ ATTR_SERVICE = _constant("kSecAttrService")
65
+ ATTR_ACCOUNT = _constant("kSecAttrAccount")
66
+ ATTR_CREATOR = _constant("kSecAttrCreator")
67
+ ATTR_GENERIC = _constant("kSecAttrGeneric")
68
+ ATTR_LABEL = _constant("kSecAttrLabel")
69
+ VALUE_DATA = _constant("kSecValueData")
70
+ RETURN_ATTRIBUTES = _constant("kSecReturnAttributes")
71
+ RETURN_DATA = _constant("kSecReturnData")
72
+ MATCH_LIMIT = _constant("kSecMatchLimit")
73
+ MATCH_LIMIT_ALL = _constant("kSecMatchLimitAll")
74
+ USE_KEYCHAIN = _constant("kSecUseKeychain")
75
+ MATCH_SEARCH_LIST = _constant("kSecMatchSearchList")
76
+
77
+
78
+ def status_message(status: int) -> str:
79
+ """The OS description of a status code. Never contains item data."""
80
+ ref = _cf.ptr(SEC.SecCopyErrorMessageString(status, None))
81
+ if not ref:
82
+ return "unknown Security framework error"
83
+ try:
84
+ return _cf.to_str(ref)
85
+ finally:
86
+ _cf.release(ref)
87
+
88
+
89
+ def item_add(attributes: int) -> int:
90
+ """Add one item. Returns the OS status; ``ERR_DUPLICATE`` if it already exists."""
91
+ return int(SEC.SecItemAdd(attributes, None))
92
+
93
+
94
+ def item_copy_matching(query: int) -> tuple[int, int]:
95
+ """Run a query. Returns ``(status, result_address)``; the caller releases the result."""
96
+ result = CFTypeRef()
97
+ status = int(SEC.SecItemCopyMatching(query, ctypes.byref(result)))
98
+ return status, _cf.ptr(result)
99
+
100
+
101
+ def item_update(query: int, changes: int) -> int:
102
+ """Apply ``changes`` to the item matching ``query``. Returns the OS status."""
103
+ return int(SEC.SecItemUpdate(query, changes))
104
+
105
+
106
+ def item_delete(query: int) -> int:
107
+ """Delete the item(s) matching ``query``. Returns the OS status."""
108
+ return int(SEC.SecItemDelete(query))
109
+
110
+
111
+ def keychain_create(path: str, password: bytes) -> tuple[int, int]:
112
+ """Create a keychain file. Returns ``(status, handle)``. Never prompts."""
113
+ handle = CFTypeRef()
114
+ status = int(
115
+ SEC.SecKeychainCreate(
116
+ path.encode("utf-8"), len(password), password, False, None, ctypes.byref(handle)
117
+ )
118
+ )
119
+ return status, _cf.ptr(handle)
120
+
121
+
122
+ def keychain_open(path: str) -> tuple[int, int]:
123
+ """Open an existing keychain file. Returns ``(status, handle)``."""
124
+ handle = CFTypeRef()
125
+ status = int(SEC.SecKeychainOpen(path.encode("utf-8"), ctypes.byref(handle)))
126
+ return status, _cf.ptr(handle)
127
+
128
+
129
+ def keychain_delete(handle: int) -> int:
130
+ """Delete a keychain file and release the handle."""
131
+ return int(SEC.SecKeychainDelete(handle))
@@ -0,0 +1,239 @@
1
+ """``SecretStore`` on the macOS Keychain via the Security framework.
2
+
3
+ Item layout (data-model.md, "KeychainItem"):
4
+
5
+ kSecClass generic password
6
+ kSecAttrService "keychain-cli:<namespace key>" exact-match grouping key
7
+ kSecAttrAccount variable name case-sensitive
8
+ kSecAttrCreator 0x6B63636C ('kccl') ownership stamp, enumeration key
9
+ kSecAttrGeneric namespace display name (UTF-8) first-given casing
10
+ kSecAttrLabel "keychain-cli: <Display>/<VAR>" for Keychain Access only
11
+ kSecValueData the secret requested only by get/get_all
12
+
13
+ Every query carries the creator stamp, so items the tool did not create are invisible to
14
+ it. List operations ask for attributes only and never for data.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import os
20
+ from collections.abc import Sequence
21
+ from pathlib import Path
22
+ from types import TracebackType
23
+ from typing import Self
24
+
25
+ from keychain_cli.keychain import AlreadyExists, NotFound, StoreError, _cf, _sec
26
+ from keychain_cli.keychain._sec import Keys
27
+ from keychain_cli.names import Namespace
28
+ from keychain_cli.secret import SecretValue
29
+
30
+ KeychainHandle = int
31
+
32
+ _Pairs = list[tuple[int, int]]
33
+
34
+
35
+ class SecurityFrameworkStore:
36
+ """Production store. Pass ``keychain`` to target a specific keychain file (tests)."""
37
+
38
+ def __init__(self, keychain: KeychainHandle | None = None) -> None:
39
+ self._keychain = keychain
40
+
41
+ # ---- listing (attributes only) -------------------------------------------------
42
+
43
+ def list_namespaces(self) -> list[Namespace]:
44
+ rows = self._match_attributes(namespace=None, name=None)
45
+ seen: dict[str, Namespace] = {}
46
+ for service, _account, display in rows:
47
+ key = service[len(_sec.SERVICE_PREFIX) :]
48
+ seen.setdefault(key, Namespace(key=key, display=display or key))
49
+ return [seen[key] for key in sorted(seen)]
50
+
51
+ def list_variables(self, namespace: Namespace) -> list[str]:
52
+ rows = self._match_attributes(namespace=namespace, name=None)
53
+ if not rows:
54
+ raise NotFound(namespace.display)
55
+ return sorted(account for _service, account, _display in rows)
56
+
57
+ def exists(self, namespace: Namespace, name: str) -> bool:
58
+ return bool(self._match_attributes(namespace=namespace, name=name))
59
+
60
+ # ---- reading values ----------------------------------------------------------
61
+
62
+ def get(self, namespace: Namespace, name: str) -> SecretValue:
63
+ with _cf.CFObjects() as cf:
64
+ query = self._query(cf, namespace=namespace, name=name)
65
+ query.append((Keys.RETURN_DATA, _cf.BOOLEAN_TRUE))
66
+ status, result = _sec.item_copy_matching(cf.dictionary(query))
67
+ if status == _sec.ERR_NOT_FOUND:
68
+ raise NotFound(name)
69
+ _raise_unless_ok(status)
70
+ try:
71
+ if not _cf.is_data(result):
72
+ raise StoreError(status, "unexpected result type from SecItemCopyMatching")
73
+ return SecretValue(_cf.to_bytes(result))
74
+ finally:
75
+ _cf.release(result)
76
+
77
+ def get_all(self, namespace: Namespace) -> dict[str, SecretValue]:
78
+ # One attribute query for the names, then one data query per variable. The file-based
79
+ # keychain rejects kSecReturnData combined with kSecMatchLimitAll (errSecParam, -50).
80
+ names = self.list_variables(namespace)
81
+ return {name: self.get(namespace, name) for name in names}
82
+
83
+ # ---- writing -----------------------------------------------------------------
84
+
85
+ def add(self, namespace: Namespace, name: str, value: SecretValue) -> None:
86
+ display = self._existing_display(namespace) or namespace.display
87
+ with _cf.CFObjects() as cf:
88
+ attributes: _Pairs = [
89
+ (Keys.CLASS, Keys.CLASS_GENERIC_PASSWORD),
90
+ (Keys.ATTR_SERVICE, cf.string(_service(namespace))),
91
+ (Keys.ATTR_ACCOUNT, cf.string(name)),
92
+ (Keys.ATTR_CREATOR, cf.number32(_sec.CREATOR_STAMP)),
93
+ (Keys.ATTR_GENERIC, cf.data(display.encode("utf-8"))),
94
+ (Keys.ATTR_LABEL, cf.string(f"keychain-cli: {display}/{name}")),
95
+ (Keys.VALUE_DATA, cf.data(value.data)),
96
+ ]
97
+ if self._keychain is not None:
98
+ attributes.append((Keys.USE_KEYCHAIN, self._keychain))
99
+ status = _sec.item_add(cf.dictionary(attributes))
100
+ if status == _sec.ERR_DUPLICATE:
101
+ raise AlreadyExists(name)
102
+ _raise_unless_ok(status)
103
+
104
+ def update(self, namespace: Namespace, name: str, value: SecretValue) -> None:
105
+ with _cf.CFObjects() as cf:
106
+ query = self._query(cf, namespace=namespace, name=name)
107
+ changes: _Pairs = [(Keys.VALUE_DATA, cf.data(value.data))]
108
+ status = _sec.item_update(cf.dictionary(query), cf.dictionary(changes))
109
+ if status == _sec.ERR_NOT_FOUND:
110
+ raise NotFound(name)
111
+ _raise_unless_ok(status)
112
+
113
+ # ---- deleting ----------------------------------------------------------------
114
+
115
+ def delete_variable(self, namespace: Namespace, name: str) -> None:
116
+ with _cf.CFObjects() as cf:
117
+ query = self._query(cf, namespace=namespace, name=name)
118
+ status = _sec.item_delete(cf.dictionary(query))
119
+ if status == _sec.ERR_NOT_FOUND:
120
+ raise NotFound(name)
121
+ _raise_unless_ok(status)
122
+
123
+ def delete_namespace(self, namespace: Namespace) -> int:
124
+ count = len(self.list_variables(namespace))
125
+ with _cf.CFObjects() as cf:
126
+ query = self._query(cf, namespace=namespace, name=None)
127
+ query.append((Keys.MATCH_LIMIT, Keys.MATCH_LIMIT_ALL))
128
+ status = _sec.item_delete(cf.dictionary(query))
129
+ if status == _sec.ERR_NOT_FOUND:
130
+ raise NotFound(namespace.display)
131
+ _raise_unless_ok(status)
132
+ return count
133
+
134
+ # ---- internals ---------------------------------------------------------------
135
+
136
+ def _query(self, cf: _cf.CFObjects, *, namespace: Namespace | None, name: str | None) -> _Pairs:
137
+ """The base query every read and delete uses: class, stamp, optional scope."""
138
+ pairs: _Pairs = [
139
+ (Keys.CLASS, Keys.CLASS_GENERIC_PASSWORD),
140
+ (Keys.ATTR_CREATOR, cf.number32(_sec.CREATOR_STAMP)),
141
+ ]
142
+ if namespace is not None:
143
+ pairs.append((Keys.ATTR_SERVICE, cf.string(_service(namespace))))
144
+ if name is not None:
145
+ pairs.append((Keys.ATTR_ACCOUNT, cf.string(name)))
146
+ if self._keychain is not None:
147
+ pairs.append((Keys.MATCH_SEARCH_LIST, cf.array([self._keychain])))
148
+ return pairs
149
+
150
+ def _match_attributes(
151
+ self, *, namespace: Namespace | None, name: str | None
152
+ ) -> list[tuple[str, str, str]]:
153
+ """Attribute-only query. Returns ``(service, account, display)`` rows, never data."""
154
+ with _cf.CFObjects() as cf:
155
+ query = self._query(cf, namespace=namespace, name=name)
156
+ query.append((Keys.MATCH_LIMIT, Keys.MATCH_LIMIT_ALL))
157
+ query.append((Keys.RETURN_ATTRIBUTES, _cf.BOOLEAN_TRUE))
158
+ status, result = _sec.item_copy_matching(cf.dictionary(query))
159
+ if status == _sec.ERR_NOT_FOUND:
160
+ return []
161
+ _raise_unless_ok(status)
162
+ try:
163
+ rows: list[tuple[str, str, str]] = []
164
+ for item in _iter_dicts(result):
165
+ service = _cf.dict_get(item, Keys.ATTR_SERVICE)
166
+ account = _cf.dict_get(item, Keys.ATTR_ACCOUNT)
167
+ generic = _cf.dict_get(item, Keys.ATTR_GENERIC)
168
+ if not (service and account):
169
+ continue
170
+ display = _cf.to_bytes(generic).decode("utf-8", errors="replace") if generic else ""
171
+ rows.append((_cf.to_str(service), _cf.to_str(account), display))
172
+ return rows
173
+ finally:
174
+ _cf.release(result)
175
+
176
+ def _existing_display(self, namespace: Namespace) -> str | None:
177
+ rows = self._match_attributes(namespace=namespace, name=None)
178
+ for _service, _account, display in rows:
179
+ if display:
180
+ return display
181
+ return None
182
+
183
+
184
+ def _service(namespace: Namespace) -> str:
185
+ return _sec.SERVICE_PREFIX + namespace.key
186
+
187
+
188
+ def _iter_dicts(result: int) -> Sequence[int]:
189
+ if not result:
190
+ return []
191
+ if _cf.is_array(result):
192
+ return [item for item in _cf.array_items(result) if _cf.is_dictionary(item)]
193
+ if _cf.is_dictionary(result):
194
+ return [result]
195
+ return []
196
+
197
+
198
+ def _raise_unless_ok(status: int) -> None:
199
+ if status != 0:
200
+ raise StoreError(status, _sec.status_message(status))
201
+
202
+
203
+ # ---- keychain files (integration tests and the test-keychain override) -------------
204
+
205
+
206
+ class TemporaryKeychain:
207
+ """Create a throwaway keychain file and delete it on exit.
208
+
209
+ Used only by the integration test suite so tests never touch the login keychain. The
210
+ unlock password is random and discarded; nothing about it is a secret worth keeping.
211
+ """
212
+
213
+ def __init__(self, directory: Path) -> None:
214
+ self.path = directory / "keychain-cli-test.keychain-db"
215
+ self.handle: KeychainHandle = 0
216
+
217
+ def __enter__(self) -> Self:
218
+ status, handle = _sec.keychain_create(str(self.path), os.urandom(24).hex().encode())
219
+ _raise_unless_ok(status)
220
+ self.handle = handle
221
+ return self
222
+
223
+ def __exit__(
224
+ self,
225
+ exc_type: type[BaseException] | None,
226
+ exc: BaseException | None,
227
+ tb: TracebackType | None,
228
+ ) -> None:
229
+ if self.handle:
230
+ _sec.keychain_delete(self.handle)
231
+ self.handle = 0
232
+ self.path.unlink(missing_ok=True)
233
+
234
+
235
+ def open_keychain(path: Path) -> KeychainHandle:
236
+ """Open an existing keychain file. Used for ``KEYCHAIN_CLI_TEST_KEYCHAIN``."""
237
+ status, handle = _sec.keychain_open(str(path))
238
+ _raise_unless_ok(status)
239
+ return handle