dpapi-config 0.1.0__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.
- dpapi_config-0.1.0/LICENSE +21 -0
- dpapi_config-0.1.0/PKG-INFO +162 -0
- dpapi_config-0.1.0/README.md +145 -0
- dpapi_config-0.1.0/dpapi_config/__init__.py +298 -0
- dpapi_config-0.1.0/dpapi_config.egg-info/PKG-INFO +162 -0
- dpapi_config-0.1.0/dpapi_config.egg-info/SOURCES.txt +9 -0
- dpapi_config-0.1.0/dpapi_config.egg-info/dependency_links.txt +1 -0
- dpapi_config-0.1.0/dpapi_config.egg-info/top_level.txt +1 -0
- dpapi_config-0.1.0/pyproject.toml +28 -0
- dpapi_config-0.1.0/setup.cfg +4 -0
- dpapi_config-0.1.0/tests/test_dpapi_config.py +155 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 suimajian
|
|
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,162 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: dpapi-config
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Encrypt selected fields of a JSON config file with Windows DPAPI
|
|
5
|
+
Author: suimajian
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/suimajian/dpapi-config
|
|
8
|
+
Keywords: dpapi,windows,config,secrets,encryption
|
|
9
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
10
|
+
Classifier: Operating System :: Microsoft :: Windows
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Topic :: Security :: Cryptography
|
|
13
|
+
Requires-Python: >=3.9
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
License-File: LICENSE
|
|
16
|
+
Dynamic: license-file
|
|
17
|
+
|
|
18
|
+
# dpapi-config
|
|
19
|
+
|
|
20
|
+
Encrypt just the secrets in a JSON config file, with Windows DPAPI, and keep the
|
|
21
|
+
file readable by everything else.
|
|
22
|
+
|
|
23
|
+
```json
|
|
24
|
+
{
|
|
25
|
+
"password": "dpapi:AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAA...",
|
|
26
|
+
"ai": { "api_key": "dpapi:AQAAANCMnd8BFdERjHoAwE..." },
|
|
27
|
+
"theme": "dark"
|
|
28
|
+
}
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
No master password, no key file, no extra dependency — DPAPI derives the key from
|
|
32
|
+
the logged-in Windows account, so there is nothing to store and nothing to leak
|
|
33
|
+
alongside the config.
|
|
34
|
+
|
|
35
|
+
## Install
|
|
36
|
+
|
|
37
|
+
Not on PyPI yet — `pip install dpapi-config` will 404 until 0.1.0 is published.
|
|
38
|
+
Install from the repository instead:
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
pip install git+https://github.com/suimajian/dpapi-config
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
The release workflow already builds the sdist and wheel (they are attached to the
|
|
45
|
+
[releases](https://github.com/suimajian/dpapi-config/releases)); the publish step
|
|
46
|
+
is waiting for credentials, so nothing has been uploaded to the index.
|
|
47
|
+
|
|
48
|
+
## Why this exists
|
|
49
|
+
|
|
50
|
+
Most Python apps that need to remember a password put it in JSON in plaintext, or
|
|
51
|
+
invent a "key file" next to it (which is the same secret, one indirection away).
|
|
52
|
+
On Windows the OS already provides the right primitive. This package wraps it in
|
|
53
|
+
the two behaviours that actually matter:
|
|
54
|
+
|
|
55
|
+
**Encrypt in place.** Each configured field is replaced by `"dpapi:<base64>"`, so
|
|
56
|
+
the file is still one JSON document. Anything that reads the config keeps working;
|
|
57
|
+
only the values you listed become opaque.
|
|
58
|
+
|
|
59
|
+
**Fail closed.** If DPAPI is not available, `protect()` raises
|
|
60
|
+
`CredentialError` — it never returns the input. The first version of this code
|
|
61
|
+
returned the plaintext on failure, which meant a machine without DPAPI silently
|
|
62
|
+
wrote passwords to disk while the UI said "encrypted". Refusing to write is the
|
|
63
|
+
only safe behaviour.
|
|
64
|
+
|
|
65
|
+
## Platform
|
|
66
|
+
|
|
67
|
+
Windows only for encryption. The module imports fine everywhere, `available()`
|
|
68
|
+
returns `False` elsewhere, and the read path still works on a plaintext file —
|
|
69
|
+
but the encryption functions (`protect`, `encrypt_config`, `save`) raise
|
|
70
|
+
`CredentialError` rather than writing secrets in the clear.
|
|
71
|
+
|
|
72
|
+
## Use
|
|
73
|
+
|
|
74
|
+
```python
|
|
75
|
+
from dpapi_config import load, save
|
|
76
|
+
|
|
77
|
+
PATHS = (("password",), ("ai", "api_key"))
|
|
78
|
+
PLACEHOLDERS = ("", "sk-") # "not filled in yet" values, never encrypted
|
|
79
|
+
|
|
80
|
+
cfg = load("config.json", PATHS, PLACEHOLDERS) # plaintext in memory
|
|
81
|
+
cfg["ai"]["api_key"] = "sk-new"
|
|
82
|
+
save("config.json", cfg, PATHS, PLACEHOLDERS) # ciphertext on disk
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
`load()` does **not** write, by default. Pass `migrate=True` to encrypt a file that
|
|
86
|
+
still holds plaintext — the first read then rewrites it in place:
|
|
87
|
+
|
|
88
|
+
```python
|
|
89
|
+
cfg = load("config.json", PATHS, PLACEHOLDERS, migrate=True)
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
The migration is one-way: older builds that do not know about `dpapi:` envelopes
|
|
93
|
+
will read the file as if the secret were missing, so ship both changes together.
|
|
94
|
+
If the file cannot be rewritten (read-only media, a directory the user cannot
|
|
95
|
+
write to), `load` emits a `RuntimeWarning` and returns the decrypted values —
|
|
96
|
+
reading never fails because writing did.
|
|
97
|
+
|
|
98
|
+
Everything else the package does is mechanical: `encrypt_config` /
|
|
99
|
+
`decrypt_config` operate on a dict you already loaded, `protect` / `unprotect`
|
|
100
|
+
work on single strings.
|
|
101
|
+
|
|
102
|
+
## Semantics worth knowing
|
|
103
|
+
|
|
104
|
+
| Situation | Behaviour |
|
|
105
|
+
| --- | --- |
|
|
106
|
+
| DPAPI unavailable, writing a config with secrets | `CredentialError`, nothing written |
|
|
107
|
+
| DPAPI unavailable, reading an encrypted value | `CredentialError` (ask the user again) |
|
|
108
|
+
| Ciphertext from a different Windows user or machine | `CredentialError` |
|
|
109
|
+
| Secret field holds a non-string (`"password": 12345`) | `CredentialError` — never silently written in the clear |
|
|
110
|
+
| Secret field is `null` (not filled in yet) | left as `null`, not encrypted, save succeeds |
|
|
111
|
+
| Value is a placeholder (`""`, `"sk-"`, …) | left as-is, not encrypted |
|
|
112
|
+
| Path does not exist in the config | skipped |
|
|
113
|
+
| Path goes through a list (`servers[0].token`) | not supported; list indices are not walked |
|
|
114
|
+
| `load()` on a plaintext file | returns values, writes nothing unless `migrate=True` |
|
|
115
|
+
| `migrate=True` on a read-only file | `RuntimeWarning`, values still returned |
|
|
116
|
+
| Save interrupted | temp file removed, old config untouched, data is `fsync`ed before the rename |
|
|
117
|
+
|
|
118
|
+
The file permissions are whatever the process creates — this module does not
|
|
119
|
+
tighten the ACL to the current user. If the config lives somewhere other than the
|
|
120
|
+
user's own profile, do that yourself (`icacls` or `SetFileSecurity`).
|
|
121
|
+
|
|
122
|
+
## Scope and non-goals
|
|
123
|
+
|
|
124
|
+
Deliberately not in this package, so you know what you are getting:
|
|
125
|
+
|
|
126
|
+
- **No ACL tightening.** The file keeps whatever permissions the process creates.
|
|
127
|
+
Putting a config in a shared location and relying on this module to protect it
|
|
128
|
+
will not work — use `icacls` / `SetFileSecurity` for that.
|
|
129
|
+
- **No keychain or credential-manager backend.** It is DPAPI, nothing else; the
|
|
130
|
+
ciphertext is only readable by the same Windows user on the same machine.
|
|
131
|
+
- **No encryption of non-string values.** A number, list or dict where a secret is
|
|
132
|
+
expected raises `CredentialError` instead of being written in the clear. `null`
|
|
133
|
+
is the one exception: it means "not filled in yet" and is left alone.
|
|
134
|
+
- **No list traversal.** `servers[0].token` is not a supported path; keep secrets
|
|
135
|
+
as direct string keys.
|
|
136
|
+
- **Not portable.** Encryption raises off Windows; reading a plaintext config
|
|
137
|
+
still works there, but this is not a cross-platform secrets store.
|
|
138
|
+
|
|
139
|
+
## Status
|
|
140
|
+
|
|
141
|
+
0.1.0 — not on PyPI yet. A tag (`v*`) builds sdist + wheel and uploads them as a
|
|
142
|
+
workflow artifact; the publish step only runs when a `PYPI_API_TOKEN` repository
|
|
143
|
+
secret exists, so nothing is published by accident.
|
|
144
|
+
|
|
145
|
+
## Tests
|
|
146
|
+
|
|
147
|
+
```bash
|
|
148
|
+
python -m pytest -q
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
The DPAPI cases are skipped on non-Windows, so the same suite runs in CI on both
|
|
152
|
+
Ubuntu and Windows:
|
|
153
|
+
|
|
154
|
+
```yaml
|
|
155
|
+
strategy:
|
|
156
|
+
matrix:
|
|
157
|
+
os: [ubuntu-latest, windows-latest]
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
## Licence
|
|
161
|
+
|
|
162
|
+
MIT.
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
# dpapi-config
|
|
2
|
+
|
|
3
|
+
Encrypt just the secrets in a JSON config file, with Windows DPAPI, and keep the
|
|
4
|
+
file readable by everything else.
|
|
5
|
+
|
|
6
|
+
```json
|
|
7
|
+
{
|
|
8
|
+
"password": "dpapi:AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAA...",
|
|
9
|
+
"ai": { "api_key": "dpapi:AQAAANCMnd8BFdERjHoAwE..." },
|
|
10
|
+
"theme": "dark"
|
|
11
|
+
}
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
No master password, no key file, no extra dependency — DPAPI derives the key from
|
|
15
|
+
the logged-in Windows account, so there is nothing to store and nothing to leak
|
|
16
|
+
alongside the config.
|
|
17
|
+
|
|
18
|
+
## Install
|
|
19
|
+
|
|
20
|
+
Not on PyPI yet — `pip install dpapi-config` will 404 until 0.1.0 is published.
|
|
21
|
+
Install from the repository instead:
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
pip install git+https://github.com/suimajian/dpapi-config
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
The release workflow already builds the sdist and wheel (they are attached to the
|
|
28
|
+
[releases](https://github.com/suimajian/dpapi-config/releases)); the publish step
|
|
29
|
+
is waiting for credentials, so nothing has been uploaded to the index.
|
|
30
|
+
|
|
31
|
+
## Why this exists
|
|
32
|
+
|
|
33
|
+
Most Python apps that need to remember a password put it in JSON in plaintext, or
|
|
34
|
+
invent a "key file" next to it (which is the same secret, one indirection away).
|
|
35
|
+
On Windows the OS already provides the right primitive. This package wraps it in
|
|
36
|
+
the two behaviours that actually matter:
|
|
37
|
+
|
|
38
|
+
**Encrypt in place.** Each configured field is replaced by `"dpapi:<base64>"`, so
|
|
39
|
+
the file is still one JSON document. Anything that reads the config keeps working;
|
|
40
|
+
only the values you listed become opaque.
|
|
41
|
+
|
|
42
|
+
**Fail closed.** If DPAPI is not available, `protect()` raises
|
|
43
|
+
`CredentialError` — it never returns the input. The first version of this code
|
|
44
|
+
returned the plaintext on failure, which meant a machine without DPAPI silently
|
|
45
|
+
wrote passwords to disk while the UI said "encrypted". Refusing to write is the
|
|
46
|
+
only safe behaviour.
|
|
47
|
+
|
|
48
|
+
## Platform
|
|
49
|
+
|
|
50
|
+
Windows only for encryption. The module imports fine everywhere, `available()`
|
|
51
|
+
returns `False` elsewhere, and the read path still works on a plaintext file —
|
|
52
|
+
but the encryption functions (`protect`, `encrypt_config`, `save`) raise
|
|
53
|
+
`CredentialError` rather than writing secrets in the clear.
|
|
54
|
+
|
|
55
|
+
## Use
|
|
56
|
+
|
|
57
|
+
```python
|
|
58
|
+
from dpapi_config import load, save
|
|
59
|
+
|
|
60
|
+
PATHS = (("password",), ("ai", "api_key"))
|
|
61
|
+
PLACEHOLDERS = ("", "sk-") # "not filled in yet" values, never encrypted
|
|
62
|
+
|
|
63
|
+
cfg = load("config.json", PATHS, PLACEHOLDERS) # plaintext in memory
|
|
64
|
+
cfg["ai"]["api_key"] = "sk-new"
|
|
65
|
+
save("config.json", cfg, PATHS, PLACEHOLDERS) # ciphertext on disk
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
`load()` does **not** write, by default. Pass `migrate=True` to encrypt a file that
|
|
69
|
+
still holds plaintext — the first read then rewrites it in place:
|
|
70
|
+
|
|
71
|
+
```python
|
|
72
|
+
cfg = load("config.json", PATHS, PLACEHOLDERS, migrate=True)
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
The migration is one-way: older builds that do not know about `dpapi:` envelopes
|
|
76
|
+
will read the file as if the secret were missing, so ship both changes together.
|
|
77
|
+
If the file cannot be rewritten (read-only media, a directory the user cannot
|
|
78
|
+
write to), `load` emits a `RuntimeWarning` and returns the decrypted values —
|
|
79
|
+
reading never fails because writing did.
|
|
80
|
+
|
|
81
|
+
Everything else the package does is mechanical: `encrypt_config` /
|
|
82
|
+
`decrypt_config` operate on a dict you already loaded, `protect` / `unprotect`
|
|
83
|
+
work on single strings.
|
|
84
|
+
|
|
85
|
+
## Semantics worth knowing
|
|
86
|
+
|
|
87
|
+
| Situation | Behaviour |
|
|
88
|
+
| --- | --- |
|
|
89
|
+
| DPAPI unavailable, writing a config with secrets | `CredentialError`, nothing written |
|
|
90
|
+
| DPAPI unavailable, reading an encrypted value | `CredentialError` (ask the user again) |
|
|
91
|
+
| Ciphertext from a different Windows user or machine | `CredentialError` |
|
|
92
|
+
| Secret field holds a non-string (`"password": 12345`) | `CredentialError` — never silently written in the clear |
|
|
93
|
+
| Secret field is `null` (not filled in yet) | left as `null`, not encrypted, save succeeds |
|
|
94
|
+
| Value is a placeholder (`""`, `"sk-"`, …) | left as-is, not encrypted |
|
|
95
|
+
| Path does not exist in the config | skipped |
|
|
96
|
+
| Path goes through a list (`servers[0].token`) | not supported; list indices are not walked |
|
|
97
|
+
| `load()` on a plaintext file | returns values, writes nothing unless `migrate=True` |
|
|
98
|
+
| `migrate=True` on a read-only file | `RuntimeWarning`, values still returned |
|
|
99
|
+
| Save interrupted | temp file removed, old config untouched, data is `fsync`ed before the rename |
|
|
100
|
+
|
|
101
|
+
The file permissions are whatever the process creates — this module does not
|
|
102
|
+
tighten the ACL to the current user. If the config lives somewhere other than the
|
|
103
|
+
user's own profile, do that yourself (`icacls` or `SetFileSecurity`).
|
|
104
|
+
|
|
105
|
+
## Scope and non-goals
|
|
106
|
+
|
|
107
|
+
Deliberately not in this package, so you know what you are getting:
|
|
108
|
+
|
|
109
|
+
- **No ACL tightening.** The file keeps whatever permissions the process creates.
|
|
110
|
+
Putting a config in a shared location and relying on this module to protect it
|
|
111
|
+
will not work — use `icacls` / `SetFileSecurity` for that.
|
|
112
|
+
- **No keychain or credential-manager backend.** It is DPAPI, nothing else; the
|
|
113
|
+
ciphertext is only readable by the same Windows user on the same machine.
|
|
114
|
+
- **No encryption of non-string values.** A number, list or dict where a secret is
|
|
115
|
+
expected raises `CredentialError` instead of being written in the clear. `null`
|
|
116
|
+
is the one exception: it means "not filled in yet" and is left alone.
|
|
117
|
+
- **No list traversal.** `servers[0].token` is not a supported path; keep secrets
|
|
118
|
+
as direct string keys.
|
|
119
|
+
- **Not portable.** Encryption raises off Windows; reading a plaintext config
|
|
120
|
+
still works there, but this is not a cross-platform secrets store.
|
|
121
|
+
|
|
122
|
+
## Status
|
|
123
|
+
|
|
124
|
+
0.1.0 — not on PyPI yet. A tag (`v*`) builds sdist + wheel and uploads them as a
|
|
125
|
+
workflow artifact; the publish step only runs when a `PYPI_API_TOKEN` repository
|
|
126
|
+
secret exists, so nothing is published by accident.
|
|
127
|
+
|
|
128
|
+
## Tests
|
|
129
|
+
|
|
130
|
+
```bash
|
|
131
|
+
python -m pytest -q
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
The DPAPI cases are skipped on non-Windows, so the same suite runs in CI on both
|
|
135
|
+
Ubuntu and Windows:
|
|
136
|
+
|
|
137
|
+
```yaml
|
|
138
|
+
strategy:
|
|
139
|
+
matrix:
|
|
140
|
+
os: [ubuntu-latest, windows-latest]
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
## Licence
|
|
144
|
+
|
|
145
|
+
MIT.
|
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
"""Encrypt selected fields of a JSON config file with Windows DPAPI.
|
|
2
|
+
|
|
3
|
+
The ciphertext is stored in place as ``"dpapi:<base64>"``, so the file stays a
|
|
4
|
+
plain JSON document that other tools can still read. Values that are already
|
|
5
|
+
encrypted are left alone, and plaintext secrets are migrated on first load.
|
|
6
|
+
|
|
7
|
+
Design rules (all deliberate):
|
|
8
|
+
|
|
9
|
+
* **Per-user, per-machine.** DPAPI keys are tied to the Windows account and the
|
|
10
|
+
machine. Move the file to another machine and :func:`unprotect` raises
|
|
11
|
+
:class:`CredentialError`; the caller should ask for the secret again.
|
|
12
|
+
* **Fail closed.** If DPAPI is unavailable, :func:`protect` raises instead of
|
|
13
|
+
returning the input. A silent fallback would write plaintext while the UI and
|
|
14
|
+
the docs claim everything is encrypted.
|
|
15
|
+
* **Atomic writes.** :func:`save` writes a temporary file and renames it, so an
|
|
16
|
+
interrupted save cannot leave a half-written config behind.
|
|
17
|
+
|
|
18
|
+
Example::
|
|
19
|
+
|
|
20
|
+
from dpapi_config import load, save
|
|
21
|
+
|
|
22
|
+
PATHS = (("password",), ("ai", "api_key"))
|
|
23
|
+
|
|
24
|
+
cfg = load("config.json", PATHS) # plaintext in memory, ciphertext on disk
|
|
25
|
+
cfg["ai"]["api_key"] = "sk-new"
|
|
26
|
+
save("config.json", cfg, PATHS) # encrypts the fields listed in PATHS
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
from __future__ import annotations
|
|
30
|
+
|
|
31
|
+
import base64
|
|
32
|
+
import ctypes
|
|
33
|
+
import json
|
|
34
|
+
import os
|
|
35
|
+
import tempfile
|
|
36
|
+
import warnings
|
|
37
|
+
from ctypes import wintypes
|
|
38
|
+
from typing import Any, Iterable, Sequence
|
|
39
|
+
|
|
40
|
+
__all__ = [
|
|
41
|
+
"PREFIX",
|
|
42
|
+
"CredentialError",
|
|
43
|
+
"available",
|
|
44
|
+
"is_protected",
|
|
45
|
+
"protect",
|
|
46
|
+
"unprotect",
|
|
47
|
+
"encrypt_config",
|
|
48
|
+
"decrypt_config",
|
|
49
|
+
"load",
|
|
50
|
+
"save",
|
|
51
|
+
]
|
|
52
|
+
|
|
53
|
+
PREFIX = "dpapi:"
|
|
54
|
+
|
|
55
|
+
Path_ = Sequence[str]
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class CredentialError(RuntimeError):
|
|
59
|
+
"""The ciphertext cannot be opened (different user, different machine, or corrupt)."""
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class _BLOB(ctypes.Structure):
|
|
63
|
+
_fields_ = [("cbData", wintypes.DWORD), ("pbData", ctypes.POINTER(ctypes.c_char))]
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _load_libs():
|
|
67
|
+
if os.name != "nt":
|
|
68
|
+
return None, None
|
|
69
|
+
try:
|
|
70
|
+
crypt32 = ctypes.WinDLL("crypt32", use_last_error=True)
|
|
71
|
+
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
|
|
72
|
+
except (AttributeError, OSError):
|
|
73
|
+
return None, None
|
|
74
|
+
crypt32.CryptProtectData.restype = wintypes.BOOL
|
|
75
|
+
crypt32.CryptProtectData.argtypes = [
|
|
76
|
+
ctypes.POINTER(_BLOB), wintypes.LPCWSTR, ctypes.POINTER(_BLOB),
|
|
77
|
+
ctypes.c_void_p, ctypes.c_void_p, wintypes.DWORD, ctypes.POINTER(_BLOB),
|
|
78
|
+
]
|
|
79
|
+
crypt32.CryptUnprotectData.restype = wintypes.BOOL
|
|
80
|
+
crypt32.CryptUnprotectData.argtypes = [
|
|
81
|
+
ctypes.POINTER(_BLOB), ctypes.POINTER(wintypes.LPWSTR), ctypes.POINTER(_BLOB),
|
|
82
|
+
ctypes.c_void_p, ctypes.c_void_p, wintypes.DWORD, ctypes.POINTER(_BLOB),
|
|
83
|
+
]
|
|
84
|
+
kernel32.LocalFree.restype = ctypes.c_void_p
|
|
85
|
+
kernel32.LocalFree.argtypes = [ctypes.c_void_p]
|
|
86
|
+
return crypt32, kernel32
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
_crypt32, _kernel32 = _load_libs()
|
|
90
|
+
|
|
91
|
+
#: Do not show any DPAPI UI prompts.
|
|
92
|
+
_UI_FORBIDDEN = 0x1
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def available() -> bool:
|
|
96
|
+
"""True when DPAPI can be used on this platform."""
|
|
97
|
+
return _crypt32 is not None
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def is_protected(value: Any) -> bool:
|
|
101
|
+
"""True when *value* looks like a ``dpapi:`` envelope."""
|
|
102
|
+
return isinstance(value, str) and value.startswith(PREFIX)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _blob(data: bytes):
|
|
106
|
+
buf = ctypes.create_string_buffer(data, len(data))
|
|
107
|
+
return _BLOB(len(data), ctypes.cast(buf, ctypes.POINTER(ctypes.c_char))), buf
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def protect(text: str) -> str:
|
|
111
|
+
"""Encrypt one value and return its ``dpapi:`` envelope.
|
|
112
|
+
|
|
113
|
+
Raises :class:`CredentialError` when DPAPI is unavailable. Never returns the
|
|
114
|
+
input unchanged: a silent fallback is how plaintext ends up on disk while
|
|
115
|
+
everything else says "encrypted".
|
|
116
|
+
"""
|
|
117
|
+
if not available():
|
|
118
|
+
raise CredentialError(
|
|
119
|
+
"Windows DPAPI is not available (crypt32 could not be loaded); "
|
|
120
|
+
"refusing to write the value in plaintext."
|
|
121
|
+
)
|
|
122
|
+
data_in, _keep = _blob(text.encode("utf-8"))
|
|
123
|
+
data_out = _BLOB()
|
|
124
|
+
ok = _crypt32.CryptProtectData(
|
|
125
|
+
ctypes.byref(data_in), None, None, None, None, _UI_FORBIDDEN,
|
|
126
|
+
ctypes.byref(data_out),
|
|
127
|
+
)
|
|
128
|
+
if not ok:
|
|
129
|
+
raise CredentialError(f"CryptProtectData failed, error {ctypes.get_last_error()}")
|
|
130
|
+
try:
|
|
131
|
+
raw = ctypes.string_at(data_out.pbData, data_out.cbData)
|
|
132
|
+
finally:
|
|
133
|
+
_kernel32.LocalFree(ctypes.cast(data_out.pbData, ctypes.c_void_p))
|
|
134
|
+
return PREFIX + base64.b64encode(raw).decode("ascii")
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def unprotect(value: str) -> str:
|
|
138
|
+
"""Decrypt a ``dpapi:`` envelope. Plain values are returned unchanged."""
|
|
139
|
+
if not is_protected(value):
|
|
140
|
+
return value
|
|
141
|
+
if not available():
|
|
142
|
+
raise CredentialError("This is a Windows DPAPI envelope; the current platform cannot open it.")
|
|
143
|
+
try:
|
|
144
|
+
raw_blob = base64.b64decode(value[len(PREFIX):], validate=True)
|
|
145
|
+
except Exception as e: # noqa: BLE001 - anything undecodable counts as corrupt
|
|
146
|
+
raise CredentialError(f"envelope payload is not valid base64: {e}") from e
|
|
147
|
+
data_in, _keep = _blob(raw_blob)
|
|
148
|
+
data_out = _BLOB()
|
|
149
|
+
ok = _crypt32.CryptUnprotectData(
|
|
150
|
+
ctypes.byref(data_in), None, None, None, None, _UI_FORBIDDEN,
|
|
151
|
+
ctypes.byref(data_out),
|
|
152
|
+
)
|
|
153
|
+
if not ok:
|
|
154
|
+
raise CredentialError(
|
|
155
|
+
"DPAPI decryption failed (usually a different Windows user or machine); "
|
|
156
|
+
"ask the user to enter the secret again."
|
|
157
|
+
)
|
|
158
|
+
try:
|
|
159
|
+
raw = ctypes.string_at(data_out.pbData, data_out.cbData)
|
|
160
|
+
finally:
|
|
161
|
+
_kernel32.LocalFree(ctypes.cast(data_out.pbData, ctypes.c_void_p))
|
|
162
|
+
return raw.decode("utf-8")
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _walk(cfg: dict, paths: Iterable[Path_]):
|
|
166
|
+
"""Yield ``(parent dict, key, value)`` for every existing path in *paths*."""
|
|
167
|
+
for path in paths:
|
|
168
|
+
if not path:
|
|
169
|
+
continue
|
|
170
|
+
node: Any = cfg
|
|
171
|
+
for key in path[:-1]:
|
|
172
|
+
if not isinstance(node, dict):
|
|
173
|
+
node = None
|
|
174
|
+
break
|
|
175
|
+
node = node.get(key)
|
|
176
|
+
if isinstance(node, dict) and path[-1] in node:
|
|
177
|
+
yield node, path[-1], node[path[-1]]
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def decrypt_config(cfg: dict, paths: Iterable[Path_]) -> dict:
|
|
181
|
+
"""Decrypt in place and return the same dict."""
|
|
182
|
+
for parent, key, value in _walk(cfg, paths):
|
|
183
|
+
if is_protected(value):
|
|
184
|
+
parent[key] = unprotect(value)
|
|
185
|
+
return cfg
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def encrypt_config(cfg: dict, paths: Iterable[Path_], placeholders: Iterable[str] = ()) -> dict:
|
|
189
|
+
"""Encrypt in place and return the same dict. Placeholder values are skipped.
|
|
190
|
+
|
|
191
|
+
``None`` is skipped as well: in a config it means "not filled in yet", and
|
|
192
|
+
raising on it would make the whole save fail for a form the user has not
|
|
193
|
+
completed. Everything else that is not a string (``"password": 12345``) raises
|
|
194
|
+
instead of being left alone: silently skipping would write that value to disk
|
|
195
|
+
in the clear, which is the one thing this module promises not to do.
|
|
196
|
+
"""
|
|
197
|
+
skip = set(placeholders)
|
|
198
|
+
for parent, key, value in _walk(cfg, paths):
|
|
199
|
+
if value is None:
|
|
200
|
+
continue
|
|
201
|
+
if not isinstance(value, str):
|
|
202
|
+
raise CredentialError(
|
|
203
|
+
f"field {key!r} must hold a string to be encrypted; got "
|
|
204
|
+
f"{type(value).__name__}. Convert it before saving, or drop it from "
|
|
205
|
+
f"the paths list if it is not actually a secret."
|
|
206
|
+
)
|
|
207
|
+
if value not in skip and not is_protected(value):
|
|
208
|
+
parent[key] = protect(value)
|
|
209
|
+
return cfg
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _needs_migration(cfg: dict, paths: Iterable[Path_], placeholders: Iterable[str]) -> bool:
|
|
213
|
+
skip = set(placeholders)
|
|
214
|
+
return any(
|
|
215
|
+
isinstance(value, str) and value not in skip and not is_protected(value)
|
|
216
|
+
for _, _, value in _walk(cfg, paths)
|
|
217
|
+
)
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def load(path: str | os.PathLike[str], paths: Iterable[Path_],
|
|
221
|
+
placeholders: Iterable[str] = (), *, migrate: bool = False) -> dict:
|
|
222
|
+
"""Read *path* and return a dict with decrypted values.
|
|
223
|
+
|
|
224
|
+
``migrate=True`` encrypts plaintext secrets found on disk and writes the file
|
|
225
|
+
back, so a config written by an older build becomes encrypted after one read.
|
|
226
|
+
It is off by default: reading should not write. A read-only config (Program
|
|
227
|
+
Files, a network share, a signed image) still loads, and a failed migration is
|
|
228
|
+
reported as a warning rather than turning ``load`` into an error.
|
|
229
|
+
|
|
230
|
+
The migration is one-way: older builds cannot read ``dpapi:`` values.
|
|
231
|
+
"""
|
|
232
|
+
paths = tuple(paths)
|
|
233
|
+
with open(path, "r", encoding="utf-8") as f:
|
|
234
|
+
cfg = json.load(f)
|
|
235
|
+
if not isinstance(cfg, dict):
|
|
236
|
+
raise CredentialError(f"{path} does not contain a JSON object")
|
|
237
|
+
needs_migration = migrate and _needs_migration(cfg, paths, placeholders)
|
|
238
|
+
decrypt_config(cfg, paths)
|
|
239
|
+
if needs_migration and available():
|
|
240
|
+
try:
|
|
241
|
+
save(path, cfg, paths, placeholders)
|
|
242
|
+
except OSError as exc:
|
|
243
|
+
warnings.warn(
|
|
244
|
+
f"could not encrypt {path} in place ({exc}); continuing with the "
|
|
245
|
+
f"decrypted values in memory",
|
|
246
|
+
RuntimeWarning,
|
|
247
|
+
stacklevel=2,
|
|
248
|
+
)
|
|
249
|
+
return cfg
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def save(path: str | os.PathLike[str], cfg: dict, paths: Iterable[Path_],
|
|
253
|
+
placeholders: Iterable[str] = ()) -> None:
|
|
254
|
+
"""Write *cfg* to *path* with the sensitive fields encrypted.
|
|
255
|
+
|
|
256
|
+
Fail closed: when DPAPI is unavailable and the config holds secrets, this
|
|
257
|
+
raises instead of writing plaintext. The write itself is atomic
|
|
258
|
+
(``mkstemp`` + :func:`os.replace`), so a crash cannot truncate the file.
|
|
259
|
+
"""
|
|
260
|
+
paths = tuple(paths)
|
|
261
|
+
if not available() and _needs_migration(cfg, paths, placeholders):
|
|
262
|
+
raise CredentialError(
|
|
263
|
+
"Windows DPAPI is not available, so the secrets in this config cannot be "
|
|
264
|
+
"encrypted; refusing to write them to disk."
|
|
265
|
+
)
|
|
266
|
+
disk = encrypt_config(json.loads(json.dumps(cfg)), paths, placeholders)
|
|
267
|
+
parent = os.path.dirname(os.path.abspath(path))
|
|
268
|
+
fd, tmp = tempfile.mkstemp(dir=parent, prefix=".config-", suffix=".tmp")
|
|
269
|
+
try:
|
|
270
|
+
with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as f:
|
|
271
|
+
json.dump(disk, f, indent=4, ensure_ascii=False)
|
|
272
|
+
f.write("\n")
|
|
273
|
+
f.flush()
|
|
274
|
+
# Without fsync the rename can land before the data does, and a power
|
|
275
|
+
# cut leaves the new name pointing at a truncated file.
|
|
276
|
+
os.fsync(f.fileno())
|
|
277
|
+
os.replace(tmp, path)
|
|
278
|
+
_fsync_directory(parent)
|
|
279
|
+
except BaseException:
|
|
280
|
+
try:
|
|
281
|
+
os.unlink(tmp)
|
|
282
|
+
except OSError:
|
|
283
|
+
pass
|
|
284
|
+
raise
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def _fsync_directory(directory: str) -> None:
|
|
288
|
+
"""Flush the directory entry so the rename itself survives a power loss."""
|
|
289
|
+
try:
|
|
290
|
+
fd = os.open(directory, os.O_RDONLY)
|
|
291
|
+
except OSError:
|
|
292
|
+
return # not supported on Windows; best effort
|
|
293
|
+
try:
|
|
294
|
+
os.fsync(fd)
|
|
295
|
+
except OSError:
|
|
296
|
+
pass
|
|
297
|
+
finally:
|
|
298
|
+
os.close(fd)
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: dpapi-config
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Encrypt selected fields of a JSON config file with Windows DPAPI
|
|
5
|
+
Author: suimajian
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/suimajian/dpapi-config
|
|
8
|
+
Keywords: dpapi,windows,config,secrets,encryption
|
|
9
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
10
|
+
Classifier: Operating System :: Microsoft :: Windows
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Topic :: Security :: Cryptography
|
|
13
|
+
Requires-Python: >=3.9
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
License-File: LICENSE
|
|
16
|
+
Dynamic: license-file
|
|
17
|
+
|
|
18
|
+
# dpapi-config
|
|
19
|
+
|
|
20
|
+
Encrypt just the secrets in a JSON config file, with Windows DPAPI, and keep the
|
|
21
|
+
file readable by everything else.
|
|
22
|
+
|
|
23
|
+
```json
|
|
24
|
+
{
|
|
25
|
+
"password": "dpapi:AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAA...",
|
|
26
|
+
"ai": { "api_key": "dpapi:AQAAANCMnd8BFdERjHoAwE..." },
|
|
27
|
+
"theme": "dark"
|
|
28
|
+
}
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
No master password, no key file, no extra dependency — DPAPI derives the key from
|
|
32
|
+
the logged-in Windows account, so there is nothing to store and nothing to leak
|
|
33
|
+
alongside the config.
|
|
34
|
+
|
|
35
|
+
## Install
|
|
36
|
+
|
|
37
|
+
Not on PyPI yet — `pip install dpapi-config` will 404 until 0.1.0 is published.
|
|
38
|
+
Install from the repository instead:
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
pip install git+https://github.com/suimajian/dpapi-config
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
The release workflow already builds the sdist and wheel (they are attached to the
|
|
45
|
+
[releases](https://github.com/suimajian/dpapi-config/releases)); the publish step
|
|
46
|
+
is waiting for credentials, so nothing has been uploaded to the index.
|
|
47
|
+
|
|
48
|
+
## Why this exists
|
|
49
|
+
|
|
50
|
+
Most Python apps that need to remember a password put it in JSON in plaintext, or
|
|
51
|
+
invent a "key file" next to it (which is the same secret, one indirection away).
|
|
52
|
+
On Windows the OS already provides the right primitive. This package wraps it in
|
|
53
|
+
the two behaviours that actually matter:
|
|
54
|
+
|
|
55
|
+
**Encrypt in place.** Each configured field is replaced by `"dpapi:<base64>"`, so
|
|
56
|
+
the file is still one JSON document. Anything that reads the config keeps working;
|
|
57
|
+
only the values you listed become opaque.
|
|
58
|
+
|
|
59
|
+
**Fail closed.** If DPAPI is not available, `protect()` raises
|
|
60
|
+
`CredentialError` — it never returns the input. The first version of this code
|
|
61
|
+
returned the plaintext on failure, which meant a machine without DPAPI silently
|
|
62
|
+
wrote passwords to disk while the UI said "encrypted". Refusing to write is the
|
|
63
|
+
only safe behaviour.
|
|
64
|
+
|
|
65
|
+
## Platform
|
|
66
|
+
|
|
67
|
+
Windows only for encryption. The module imports fine everywhere, `available()`
|
|
68
|
+
returns `False` elsewhere, and the read path still works on a plaintext file —
|
|
69
|
+
but the encryption functions (`protect`, `encrypt_config`, `save`) raise
|
|
70
|
+
`CredentialError` rather than writing secrets in the clear.
|
|
71
|
+
|
|
72
|
+
## Use
|
|
73
|
+
|
|
74
|
+
```python
|
|
75
|
+
from dpapi_config import load, save
|
|
76
|
+
|
|
77
|
+
PATHS = (("password",), ("ai", "api_key"))
|
|
78
|
+
PLACEHOLDERS = ("", "sk-") # "not filled in yet" values, never encrypted
|
|
79
|
+
|
|
80
|
+
cfg = load("config.json", PATHS, PLACEHOLDERS) # plaintext in memory
|
|
81
|
+
cfg["ai"]["api_key"] = "sk-new"
|
|
82
|
+
save("config.json", cfg, PATHS, PLACEHOLDERS) # ciphertext on disk
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
`load()` does **not** write, by default. Pass `migrate=True` to encrypt a file that
|
|
86
|
+
still holds plaintext — the first read then rewrites it in place:
|
|
87
|
+
|
|
88
|
+
```python
|
|
89
|
+
cfg = load("config.json", PATHS, PLACEHOLDERS, migrate=True)
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
The migration is one-way: older builds that do not know about `dpapi:` envelopes
|
|
93
|
+
will read the file as if the secret were missing, so ship both changes together.
|
|
94
|
+
If the file cannot be rewritten (read-only media, a directory the user cannot
|
|
95
|
+
write to), `load` emits a `RuntimeWarning` and returns the decrypted values —
|
|
96
|
+
reading never fails because writing did.
|
|
97
|
+
|
|
98
|
+
Everything else the package does is mechanical: `encrypt_config` /
|
|
99
|
+
`decrypt_config` operate on a dict you already loaded, `protect` / `unprotect`
|
|
100
|
+
work on single strings.
|
|
101
|
+
|
|
102
|
+
## Semantics worth knowing
|
|
103
|
+
|
|
104
|
+
| Situation | Behaviour |
|
|
105
|
+
| --- | --- |
|
|
106
|
+
| DPAPI unavailable, writing a config with secrets | `CredentialError`, nothing written |
|
|
107
|
+
| DPAPI unavailable, reading an encrypted value | `CredentialError` (ask the user again) |
|
|
108
|
+
| Ciphertext from a different Windows user or machine | `CredentialError` |
|
|
109
|
+
| Secret field holds a non-string (`"password": 12345`) | `CredentialError` — never silently written in the clear |
|
|
110
|
+
| Secret field is `null` (not filled in yet) | left as `null`, not encrypted, save succeeds |
|
|
111
|
+
| Value is a placeholder (`""`, `"sk-"`, …) | left as-is, not encrypted |
|
|
112
|
+
| Path does not exist in the config | skipped |
|
|
113
|
+
| Path goes through a list (`servers[0].token`) | not supported; list indices are not walked |
|
|
114
|
+
| `load()` on a plaintext file | returns values, writes nothing unless `migrate=True` |
|
|
115
|
+
| `migrate=True` on a read-only file | `RuntimeWarning`, values still returned |
|
|
116
|
+
| Save interrupted | temp file removed, old config untouched, data is `fsync`ed before the rename |
|
|
117
|
+
|
|
118
|
+
The file permissions are whatever the process creates — this module does not
|
|
119
|
+
tighten the ACL to the current user. If the config lives somewhere other than the
|
|
120
|
+
user's own profile, do that yourself (`icacls` or `SetFileSecurity`).
|
|
121
|
+
|
|
122
|
+
## Scope and non-goals
|
|
123
|
+
|
|
124
|
+
Deliberately not in this package, so you know what you are getting:
|
|
125
|
+
|
|
126
|
+
- **No ACL tightening.** The file keeps whatever permissions the process creates.
|
|
127
|
+
Putting a config in a shared location and relying on this module to protect it
|
|
128
|
+
will not work — use `icacls` / `SetFileSecurity` for that.
|
|
129
|
+
- **No keychain or credential-manager backend.** It is DPAPI, nothing else; the
|
|
130
|
+
ciphertext is only readable by the same Windows user on the same machine.
|
|
131
|
+
- **No encryption of non-string values.** A number, list or dict where a secret is
|
|
132
|
+
expected raises `CredentialError` instead of being written in the clear. `null`
|
|
133
|
+
is the one exception: it means "not filled in yet" and is left alone.
|
|
134
|
+
- **No list traversal.** `servers[0].token` is not a supported path; keep secrets
|
|
135
|
+
as direct string keys.
|
|
136
|
+
- **Not portable.** Encryption raises off Windows; reading a plaintext config
|
|
137
|
+
still works there, but this is not a cross-platform secrets store.
|
|
138
|
+
|
|
139
|
+
## Status
|
|
140
|
+
|
|
141
|
+
0.1.0 — not on PyPI yet. A tag (`v*`) builds sdist + wheel and uploads them as a
|
|
142
|
+
workflow artifact; the publish step only runs when a `PYPI_API_TOKEN` repository
|
|
143
|
+
secret exists, so nothing is published by accident.
|
|
144
|
+
|
|
145
|
+
## Tests
|
|
146
|
+
|
|
147
|
+
```bash
|
|
148
|
+
python -m pytest -q
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
The DPAPI cases are skipped on non-Windows, so the same suite runs in CI on both
|
|
152
|
+
Ubuntu and Windows:
|
|
153
|
+
|
|
154
|
+
```yaml
|
|
155
|
+
strategy:
|
|
156
|
+
matrix:
|
|
157
|
+
os: [ubuntu-latest, windows-latest]
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
## Licence
|
|
161
|
+
|
|
162
|
+
MIT.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
dpapi_config
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "dpapi-config"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Encrypt selected fields of a JSON config file with Windows DPAPI"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = { text = "MIT" }
|
|
12
|
+
authors = [{ name = "suimajian" }]
|
|
13
|
+
keywords = ["dpapi", "windows", "config", "secrets", "encryption"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"License :: OSI Approved :: MIT License",
|
|
16
|
+
"Operating System :: Microsoft :: Windows",
|
|
17
|
+
"Programming Language :: Python :: 3",
|
|
18
|
+
"Topic :: Security :: Cryptography",
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
[project.urls]
|
|
22
|
+
Homepage = "https://github.com/suimajian/dpapi-config"
|
|
23
|
+
|
|
24
|
+
[tool.setuptools]
|
|
25
|
+
packages = ["dpapi_config"]
|
|
26
|
+
|
|
27
|
+
[tool.pytest.ini_options]
|
|
28
|
+
testpaths = ["tests"]
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
|
|
6
|
+
import pytest
|
|
7
|
+
|
|
8
|
+
from dpapi_config import (
|
|
9
|
+
CredentialError,
|
|
10
|
+
available,
|
|
11
|
+
decrypt_config,
|
|
12
|
+
encrypt_config,
|
|
13
|
+
is_protected,
|
|
14
|
+
load,
|
|
15
|
+
protect,
|
|
16
|
+
save,
|
|
17
|
+
unprotect,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
PATHS = (("password",), ("ai", "api_key"))
|
|
21
|
+
PLACEHOLDERS = ("", "sk-")
|
|
22
|
+
|
|
23
|
+
win_only = pytest.mark.skipif(not available(), reason="Windows DPAPI not available")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@win_only
|
|
27
|
+
def test_roundtrip():
|
|
28
|
+
env = protect("hunter2")
|
|
29
|
+
assert env.startswith("dpapi:")
|
|
30
|
+
assert unprotect(env) == "hunter2"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@win_only
|
|
34
|
+
def test_ciphertext_differs_per_call():
|
|
35
|
+
# DPAPI salts each call; identical plaintext must not produce identical bytes.
|
|
36
|
+
assert protect("same") != protect("same")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def test_plain_value_is_returned_unchanged():
|
|
40
|
+
assert unprotect("not encrypted") == "not encrypted"
|
|
41
|
+
assert not is_protected("not encrypted")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def test_is_protected():
|
|
45
|
+
assert is_protected("dpapi:AAAA")
|
|
46
|
+
assert not is_protected("DPAPI:AAAA")
|
|
47
|
+
assert not is_protected(None)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def test_unprotect_rejects_bad_base64():
|
|
51
|
+
with pytest.raises(CredentialError):
|
|
52
|
+
unprotect("dpapi:not base64!!")
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@win_only
|
|
56
|
+
def test_config_encrypt_decrypt_roundtrip():
|
|
57
|
+
cfg = {"password": "pw", "ai": {"api_key": "sk-live"}, "other": "keep"}
|
|
58
|
+
encrypt_config(cfg, PATHS)
|
|
59
|
+
assert is_protected(cfg["password"])
|
|
60
|
+
assert is_protected(cfg["ai"]["api_key"])
|
|
61
|
+
assert cfg["other"] == "keep"
|
|
62
|
+
|
|
63
|
+
decrypt_config(cfg, PATHS)
|
|
64
|
+
assert cfg == {"password": "pw", "ai": {"api_key": "sk-live"}, "other": "keep"}
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
@win_only
|
|
68
|
+
def test_placeholders_are_not_encrypted():
|
|
69
|
+
cfg = {"password": "", "ai": {"api_key": "sk-"}}
|
|
70
|
+
encrypt_config(cfg, PATHS, PLACEHOLDERS)
|
|
71
|
+
assert cfg["password"] == ""
|
|
72
|
+
assert cfg["ai"]["api_key"] == "sk-"
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
@win_only
|
|
76
|
+
def test_missing_paths_are_skipped():
|
|
77
|
+
cfg = {"ai": {"nope": "x"}}
|
|
78
|
+
encrypt_config(cfg, (("ai", "api_key"), ("missing", "deep", "key")))
|
|
79
|
+
assert cfg == {"ai": {"nope": "x"}}
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
@win_only
|
|
83
|
+
def test_save_and_load_persist_ciphertext(tmp_path):
|
|
84
|
+
path = tmp_path / "config.json"
|
|
85
|
+
save(path, {"password": "pw", "ai": {"api_key": "sk-live"}}, PATHS, PLACEHOLDERS)
|
|
86
|
+
|
|
87
|
+
raw = json.loads(path.read_text(encoding="utf-8"))
|
|
88
|
+
assert raw["password"].startswith("dpapi:")
|
|
89
|
+
assert raw["ai"]["api_key"].startswith("dpapi:")
|
|
90
|
+
|
|
91
|
+
assert load(path, PATHS, PLACEHOLDERS) == {"password": "pw", "ai": {"api_key": "sk-live"}}
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
@win_only
|
|
95
|
+
def test_load_migrates_plaintext_in_place_when_asked(tmp_path):
|
|
96
|
+
path = tmp_path / "config.json"
|
|
97
|
+
path.write_text(json.dumps({"password": "legacy"}), encoding="utf-8")
|
|
98
|
+
|
|
99
|
+
assert load(path, PATHS, migrate=True)["password"] == "legacy"
|
|
100
|
+
assert json.loads(path.read_text(encoding="utf-8"))["password"].startswith("dpapi:")
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
@win_only
|
|
104
|
+
def test_load_does_not_write_by_default(tmp_path):
|
|
105
|
+
path = tmp_path / "config.json"
|
|
106
|
+
path.write_text(json.dumps({"password": "legacy"}), encoding="utf-8")
|
|
107
|
+
before = path.stat().st_mtime_ns
|
|
108
|
+
|
|
109
|
+
assert load(path, PATHS)["password"] == "legacy"
|
|
110
|
+
assert path.stat().st_mtime_ns == before
|
|
111
|
+
assert json.loads(path.read_text(encoding="utf-8"))["password"] == "legacy"
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
@win_only
|
|
115
|
+
def test_load_survives_a_read_only_file(tmp_path):
|
|
116
|
+
"""A read-only config must still load when migration was requested."""
|
|
117
|
+
path = tmp_path / "config.json"
|
|
118
|
+
path.write_text(json.dumps({"password": "legacy"}), encoding="utf-8")
|
|
119
|
+
os.chmod(path, 0o444)
|
|
120
|
+
try:
|
|
121
|
+
with pytest.warns(RuntimeWarning):
|
|
122
|
+
cfg = load(path, PATHS, migrate=True)
|
|
123
|
+
assert cfg["password"] == "legacy"
|
|
124
|
+
finally:
|
|
125
|
+
os.chmod(path, 0o666)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def test_non_string_secret_raises_instead_of_writing_plaintext(tmp_path):
|
|
129
|
+
path = tmp_path / "config.json"
|
|
130
|
+
with pytest.raises(CredentialError):
|
|
131
|
+
save(path, {"password": 12345}, PATHS)
|
|
132
|
+
assert not path.exists(), "nothing may be written when a secret cannot be encrypted"
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
@win_only
|
|
136
|
+
def test_save_is_atomic_and_leaves_no_temp_files(tmp_path):
|
|
137
|
+
path = tmp_path / "config.json"
|
|
138
|
+
save(path, {"password": "pw"}, PATHS)
|
|
139
|
+
save(path, {"password": "pw2"}, PATHS)
|
|
140
|
+
assert sorted(p.name for p in tmp_path.iterdir()) == ["config.json"]
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def test_load_rejects_non_object(tmp_path):
|
|
144
|
+
path = tmp_path / "config.json"
|
|
145
|
+
path.write_text("[1, 2, 3]", encoding="utf-8")
|
|
146
|
+
with pytest.raises(CredentialError):
|
|
147
|
+
load(path, PATHS)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def test_null_secret_is_left_as_null(tmp_path):
|
|
151
|
+
"""``null`` means "not filled in yet": save must not fail, and must not encrypt."""
|
|
152
|
+
path = tmp_path / "config.json"
|
|
153
|
+
save(path, {"user": "me", "password": None}, PATHS)
|
|
154
|
+
assert json.loads(path.read_text(encoding="utf-8"))["password"] is None
|
|
155
|
+
assert load(path, PATHS)["password"] is None
|