harpocrate 0.8.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.
Files changed (49) hide show
  1. harpocrate-0.8.0/.gitignore +234 -0
  2. harpocrate-0.8.0/CHANGELOG.md +100 -0
  3. harpocrate-0.8.0/LICENSE +21 -0
  4. harpocrate-0.8.0/PKG-INFO +176 -0
  5. harpocrate-0.8.0/README.md +135 -0
  6. harpocrate-0.8.0/harpocrate/__init__.py +54 -0
  7. harpocrate-0.8.0/harpocrate/cache.py +73 -0
  8. harpocrate-0.8.0/harpocrate/cli.py +193 -0
  9. harpocrate-0.8.0/harpocrate/client.py +553 -0
  10. harpocrate-0.8.0/harpocrate/connect.py +213 -0
  11. harpocrate-0.8.0/harpocrate/crypto/__init__.py +7 -0
  12. harpocrate-0.8.0/harpocrate/crypto/aes_gcm.py +72 -0
  13. harpocrate-0.8.0/harpocrate/exceptions.py +77 -0
  14. harpocrate-0.8.0/harpocrate/generators/__init__.py +77 -0
  15. harpocrate-0.8.0/harpocrate/generators/bcrypt_password_gen.py +48 -0
  16. harpocrate-0.8.0/harpocrate/generators/bytes_gen.py +37 -0
  17. harpocrate-0.8.0/harpocrate/generators/passphrase_gen.py +68 -0
  18. harpocrate-0.8.0/harpocrate/generators/random_gen.py +62 -0
  19. harpocrate-0.8.0/harpocrate/generators/rsa_keypair_gen.py +70 -0
  20. harpocrate-0.8.0/harpocrate/generators/ssh_keypair_gen.py +67 -0
  21. harpocrate-0.8.0/harpocrate/generators/template_gen.py +80 -0
  22. harpocrate-0.8.0/harpocrate/generators/tls_certificate_gen.py +110 -0
  23. harpocrate-0.8.0/harpocrate/generators/uuid_gen.py +64 -0
  24. harpocrate-0.8.0/harpocrate/generators/wordlists/en.txt +550 -0
  25. harpocrate-0.8.0/harpocrate/generators/wordlists/fr.txt +325 -0
  26. harpocrate-0.8.0/harpocrate/http.py +192 -0
  27. harpocrate-0.8.0/harpocrate/models/__init__.py +16 -0
  28. harpocrate-0.8.0/harpocrate/models/secret.py +87 -0
  29. harpocrate-0.8.0/harpocrate/models/secret_type.py +73 -0
  30. harpocrate-0.8.0/harpocrate/models/wallet.py +58 -0
  31. harpocrate-0.8.0/harpocrate/py.typed +0 -0
  32. harpocrate-0.8.0/harpocrate/rotation.py +104 -0
  33. harpocrate-0.8.0/harpocrate/token.py +223 -0
  34. harpocrate-0.8.0/pyproject.toml +87 -0
  35. harpocrate-0.8.0/tests/conftest.py +58 -0
  36. harpocrate-0.8.0/tests/e2e/__init__.py +1 -0
  37. harpocrate-0.8.0/tests/test_rotation.py +190 -0
  38. harpocrate-0.8.0/tests/unit/__init__.py +1 -0
  39. harpocrate-0.8.0/tests/unit/test_cache.py +102 -0
  40. harpocrate-0.8.0/tests/unit/test_client.py +351 -0
  41. harpocrate-0.8.0/tests/unit/test_connect.py +165 -0
  42. harpocrate-0.8.0/tests/unit/test_create_with_type.py +89 -0
  43. harpocrate-0.8.0/tests/unit/test_crypto.py +116 -0
  44. harpocrate-0.8.0/tests/unit/test_generators.py +509 -0
  45. harpocrate-0.8.0/tests/unit/test_http_path_kwarg_collision.py +144 -0
  46. harpocrate-0.8.0/tests/unit/test_http_split_token.py +120 -0
  47. harpocrate-0.8.0/tests/unit/test_pathstyle_lookup.py +167 -0
  48. harpocrate-0.8.0/tests/unit/test_token.py +252 -0
  49. harpocrate-0.8.0/tests/unit/test_types_client.py +129 -0
@@ -0,0 +1,234 @@
1
+ # Claude Code memory (local only)
2
+ .claude/
3
+
4
+ # Byte-compiled / optimized / DLL files
5
+ __pycache__/
6
+ *.py[codz]
7
+ *$py.class
8
+
9
+ # C extensions
10
+ *.so
11
+
12
+ # Distribution / packaging
13
+ .Python
14
+ build/
15
+ develop-eggs/
16
+ dist/
17
+ downloads/
18
+ eggs/
19
+ .eggs/
20
+ lib/
21
+ lib64/
22
+ !cli-bash/lib/
23
+ !frontend/src/lib/
24
+ parts/
25
+ sdist/
26
+ var/
27
+ wheels/
28
+ share/python-wheels/
29
+ *.egg-info/
30
+ .installed.cfg
31
+ *.egg
32
+ MANIFEST
33
+
34
+ # PyInstaller
35
+ # Usually these files are written by a python script from a template
36
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
37
+ *.manifest
38
+ *.spec
39
+
40
+ # Installer logs
41
+ pip-log.txt
42
+ pip-delete-this-directory.txt
43
+
44
+ # Unit test / coverage reports
45
+ htmlcov/
46
+ .tox/
47
+ .nox/
48
+ .coverage
49
+ .coverage.*
50
+ .cache
51
+ nosetests.xml
52
+ coverage.xml
53
+ *.cover
54
+ *.py.cover
55
+ .hypothesis/
56
+ .pytest_cache/
57
+ cover/
58
+
59
+ # Translations
60
+ *.mo
61
+ *.pot
62
+
63
+ # Django stuff:
64
+ *.log
65
+ local_settings.py
66
+ db.sqlite3
67
+ db.sqlite3-journal
68
+
69
+ # Flask stuff:
70
+ instance/
71
+ .webassets-cache
72
+
73
+ # Scrapy stuff:
74
+ .scrapy
75
+
76
+ # Sphinx documentation
77
+ docs/_build/
78
+
79
+ # PyBuilder
80
+ .pybuilder/
81
+ target/
82
+
83
+ # Jupyter Notebook
84
+ .ipynb_checkpoints
85
+
86
+ # IPython
87
+ profile_default/
88
+ ipython_config.py
89
+
90
+ # pyenv
91
+ # For a library or package, you might want to ignore these files since the code is
92
+ # intended to run in multiple environments; otherwise, check them in:
93
+ # .python-version
94
+
95
+ # pipenv
96
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
97
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
98
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
99
+ # install all needed dependencies.
100
+ # Pipfile.lock
101
+
102
+ # UV
103
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
104
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
105
+ # commonly ignored for libraries.
106
+ # uv.lock
107
+
108
+ # poetry
109
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
110
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
111
+ # commonly ignored for libraries.
112
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
113
+ # poetry.lock
114
+ # poetry.toml
115
+
116
+ # pdm
117
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
118
+ # pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
119
+ # https://pdm-project.org/en/latest/usage/project/#working-with-version-control
120
+ # pdm.lock
121
+ # pdm.toml
122
+ .pdm-python
123
+ .pdm-build/
124
+
125
+ # pixi
126
+ # Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
127
+ # pixi.lock
128
+ # Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
129
+ # in the .venv directory. It is recommended not to include this directory in version control.
130
+ .pixi
131
+
132
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
133
+ __pypackages__/
134
+
135
+ # Celery stuff
136
+ celerybeat-schedule
137
+ celerybeat.pid
138
+
139
+ # Redis
140
+ *.rdb
141
+ *.aof
142
+ *.pid
143
+
144
+ # RabbitMQ
145
+ mnesia/
146
+ rabbitmq/
147
+ rabbitmq-data/
148
+
149
+ # ActiveMQ
150
+ activemq-data/
151
+
152
+ # SageMath parsed files
153
+ *.sage.py
154
+
155
+ # Environments
156
+ .env
157
+ .env.test
158
+ .env.local
159
+ .envrc
160
+
161
+ # Données runtime (volumes Docker bind-mountés)
162
+ /data/
163
+ .venv
164
+ env/
165
+ venv/
166
+ ENV/
167
+ env.bak/
168
+ venv.bak/
169
+
170
+ # Spyder project settings
171
+ .spyderproject
172
+ .spyproject
173
+
174
+ # Rope project settings
175
+ .ropeproject
176
+
177
+ # mkdocs documentation
178
+ /site
179
+
180
+ # mypy
181
+ .mypy_cache/
182
+ .dmypy.json
183
+ dmypy.json
184
+
185
+ # Pyre type checker
186
+ .pyre/
187
+
188
+ # pytype static type analyzer
189
+ .pytype/
190
+
191
+ # Cython debug symbols
192
+ cython_debug/
193
+
194
+ # PyCharm
195
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
196
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
197
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
198
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
199
+ # .idea/
200
+
201
+ # Abstra
202
+ # Abstra is an AI-powered process automation framework.
203
+ # Ignore directories containing user credentials, local state, and settings.
204
+ # Learn more at https://abstra.io/docs
205
+ .abstra/
206
+
207
+ # Visual Studio Code
208
+ # Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
209
+ # that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
210
+ # and can be added to the global gitignore or merged into this file. However, if you prefer,
211
+ # you could uncomment the following to ignore the entire vscode folder
212
+ # .vscode/
213
+ # Temporary file for partial code execution
214
+ tempCodeRunnerFile.py
215
+
216
+ # Ruff stuff:
217
+ .ruff_cache/
218
+
219
+ # PyPI configuration file
220
+ .pypirc
221
+
222
+ # Marimo
223
+ marimo/_static/
224
+ marimo/_lsp/
225
+ __marimo__/
226
+
227
+ # Streamlit
228
+ .streamlit/secrets.toml
229
+ frontend/node_modules/
230
+ frontend/dist/
231
+
232
+ # Wiki = dépôt séparé (gaelgael5/harpocrate.wiki). Un clone local ici ne doit pas
233
+ # être ajouté : un gitlink sans .gitmodules casse actions/checkout (2026-10-20).
234
+ /harpocrate.wiki/
@@ -0,0 +1,100 @@
1
+ # Changelog
2
+
3
+ ## 0.8.0 — 2026-10-03
4
+
5
+ ### Nouveau — assistant « Se connecter avec Harpocrate » (`harpocrate.connect`)
6
+
7
+ Une application déclarée dans le registre d'une instance Harpocrate obtient une API key
8
+ sur un wallet choisi par l'utilisateur, sans copier-coller de token, et sans que
9
+ Harpocrate voie jamais la `dkey` de la clé :
10
+
11
+ - `connect.start(base_url, client_id, redirect_uri, permissions, ttl_days=None)` —
12
+ génère PKCE S256 et une paire de clés éphémère P-256, dépose la demande (PAR) et rend
13
+ `(browser_url, ConnectState)` ;
14
+ - `connect.finish(pending, code=..., state=...)` — vérifie le `state` (CSRF), échange le
15
+ code (une seule fois), ouvre le scellé JWE ECDH-ES / A256GCM avec la clé privée
16
+ éphémère et rend un `ConnectResult(token, api_key_id, wallet_id)`.
17
+
18
+ `ConnectState` contient le `code_verifier` et la clé privée éphémère : à garder côté
19
+ serveur entre la redirection et le retour (`to_dict` / `from_dict`), jamais dans un
20
+ cookie lisible ni dans l'URL. Ni `ConnectState` ni `ConnectResult` n'affichent leurs
21
+ secrets dans `repr`.
22
+
23
+ - `harpocrate.token.with_decryption_key(token, dkey_b64)` — inverse de
24
+ `truncate_token_for_transport` : réinsère la dkey dans un token signé sans elle.
25
+ - Nouvelle exception `ConnectError` (attribut `error_code`).
26
+
27
+ ### Distribution
28
+
29
+ - Première version publiée sur PyPI (`pip install harpocrate`, `uv add harpocrate`),
30
+ par la CI GitHub Actions en Trusted Publishing — voir `RELEASING.md`. PyPI devient le
31
+ canal officiel ; le téléchargement du wheel depuis une instance Harpocrate sera retiré.
32
+ - Le paquet déclare ses types (`py.typed`) et sa licence en expression SPDX.
33
+
34
+ ### Dépendances
35
+
36
+ - `joserfc>=1.7` (descellement JWE ; pas de primitive cryptographique maison).
37
+
38
+ ## 0.7.0 — 2026-05-17
39
+
40
+ ### Security — split-token client-side
41
+
42
+ **La `decryption_key` ne transite plus jamais sur le canal HTTP.**
43
+
44
+ Le `VaultHttpClient` tronque maintenant le token API key à l'instanciation :
45
+ le segment `dkey` (43 chars base64url) est remplacé par un placeholder constant
46
+ avant la première requête. La vraie `dkey` reste en RAM côté client, parsée par
47
+ `VaultClient` pour le déchiffrement local des `encrypted_wallet_key`.
48
+
49
+ Le HMAC du token ne couvre pas le segment `dkey` (cf.
50
+ `backend/app/core/api_key_token.py:103-112`), donc la troncature est
51
+ transparente pour la validation serveur.
52
+
53
+ - **Avant 0.7.0** : le SDK envoyait le token complet `hrpv_1_id_exp_perms_auth_dkey_hmac`
54
+ dans le header `Authorization`. La dkey transitait sur TLS et était parsée
55
+ côté serveur (jamais utilisée par un handler, mais présente en mémoire).
56
+ - **À partir de 0.7.0** : le SDK envoie `hrpv_1_id_exp_perms_auth_<placeholder43>_hmac`.
57
+ Un serveur compromis qui logue le header `Authorization` ne récupère plus la dkey.
58
+
59
+ ### Nouvelles API publiques
60
+
61
+ - `harpocrate.token.truncate_token_for_transport(token: str) -> str` —
62
+ helper exposé pour les intégrations qui construisent leurs propres clients
63
+ HTTP. Lève `InvalidTokenError` si le token est mal formé.
64
+
65
+ ### Breaking changes
66
+
67
+ - `VaultHttpClient(base_url, token=...)` **valide maintenant le format du
68
+ token au boot**. Un token de fixtures de test sans le format `hrpv_*`
69
+ complet (8 segments, longueurs fixes) lève `InvalidTokenError`. Mettez à
70
+ jour vos fixtures de test pour utiliser un token réel ou utilisez
71
+ `unittest.mock.patch("harpocrate.client.parse_token")` + `patch("harpocrate.client.VaultHttpClient")`
72
+ pour tester un client mocké de bout en bout (cf. `tests/test_rotation.py`).
73
+
74
+ ### Tests
75
+
76
+ - Suite de tests `tests/unit/test_http_split_token.py` qui intercepte
77
+ `httpx.request` et vérifie que la `dkey` n'apparaît jamais dans le header
78
+ `Authorization` envoyé (GET, POST, PUT, PATCH, DELETE).
79
+ - 8 nouveaux tests unitaires pour `truncate_token_for_transport`.
80
+ - Suite totale : 140 tests verts.
81
+
82
+ ### Migration depuis 0.6.x
83
+
84
+ Pour les utilisateurs du SDK :
85
+ - **Aucun changement de code requis** : `VaultClient(token=..., base_url=...)`
86
+ fonctionne à l'identique. Le token complet est toujours accepté en entrée,
87
+ la troncature est interne.
88
+ - Si vous instanciez directement `VaultHttpClient` avec un token de test
89
+ (`"hrpv_test"`, `"hrpv_x"`...), remplacez-le par un token au bon format
90
+ (cf. `tests/unit/test_http_split_token.py` pour un exemple).
91
+
92
+ Les autres SDK officiels (TypeScript, JavaScript, Go, Rust, C#) n'ont **pas
93
+ encore** ce changement — ils enverront toujours le token complet jusqu'à leur
94
+ prochaine version.
95
+
96
+ ---
97
+
98
+ ## 0.6.0 — antérieur
99
+
100
+ (historique non documenté dans ce CHANGELOG ; voir `git log` pour les détails).
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 black beard
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,176 @@
1
+ Metadata-Version: 2.5
2
+ Name: harpocrate
3
+ Version: 0.8.0
4
+ Summary: Client Python zero-knowledge pour le coffre de secrets Harpocrate : chiffrement côté client, le serveur ne voit jamais une valeur
5
+ Project-URL: Homepage, https://github.com/gaelgael5/harpocrate
6
+ Project-URL: Source, https://github.com/gaelgael5/harpocrate/tree/main/sdk-python
7
+ Project-URL: Changelog, https://github.com/gaelgael5/harpocrate/blob/main/sdk-python/CHANGELOG.md
8
+ Project-URL: Issues, https://github.com/gaelgael5/harpocrate/issues
9
+ Author: gaelgael5
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: encryption,harpocrate,secrets,vault,zero-knowledge
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Intended Audience :: System Administrators
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3 :: Only
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Topic :: Security :: Cryptography
24
+ Classifier: Typing :: Typed
25
+ Requires-Python: >=3.10
26
+ Requires-Dist: argon2-cffi>=23
27
+ Requires-Dist: bcrypt>=4.1
28
+ Requires-Dist: cachetools>=5.3
29
+ Requires-Dist: click>=8.1
30
+ Requires-Dist: cryptography>=42
31
+ Requires-Dist: httpx>=0.27
32
+ Requires-Dist: joserfc>=1.7
33
+ Requires-Dist: pydantic>=2.6
34
+ Provides-Extra: dev
35
+ Requires-Dist: mypy>=1.9; extra == 'dev'
36
+ Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
37
+ Requires-Dist: pytest>=8.0; extra == 'dev'
38
+ Requires-Dist: ruff>=0.3; extra == 'dev'
39
+ Requires-Dist: types-cachetools>=5.3; extra == 'dev'
40
+ Description-Content-Type: text/markdown
41
+
42
+ # Harpocrate SDK Python
43
+
44
+ Client Python zero-knowledge pour Harpocrate Vault.
45
+
46
+ ## Installation
47
+
48
+ Depuis [PyPI](https://pypi.org/project/harpocrate/) :
49
+
50
+ ```bash
51
+ pip install harpocrate
52
+ # ou
53
+ uv add harpocrate
54
+ ```
55
+
56
+ Python 3.10 ou plus récent.
57
+
58
+ ## Usage rapide
59
+
60
+ ```python
61
+ from harpocrate import VaultClient
62
+
63
+ client = VaultClient(
64
+ token="hrpv_1_...",
65
+ base_url="https://vault.yoops.org",
66
+ )
67
+
68
+ # Lire un secret
69
+ value = client.secrets.get("ANTHROPIC_API_KEY")
70
+
71
+ # Lister les secrets
72
+ for secret in client.secrets.list().secrets:
73
+ print(secret.name, "placeholder" if secret.is_placeholder else "valued")
74
+
75
+ # Peupler tous les placeholders
76
+ results = client.secrets.populate_all()
77
+ for r in results:
78
+ print(r.name, "OK" if r.success else r.error)
79
+ ```
80
+
81
+ ## Détection de rotation (LOT_22, ≥ 0.5.0)
82
+
83
+ Quand un secret est rotaté côté Harpocrate, l'application qui consomme ce
84
+ secret détecte typiquement l'expiration via une réponse 401 de l'API tierce
85
+ (Anthropic, OpenAI, etc.). Le SDK fournit un mécanisme déclaratif pour gérer
86
+ ce cas :
87
+
88
+ ```python
89
+ from harpocrate import VaultClient
90
+
91
+ client = VaultClient(token="hrpv_...", base_url="https://vault.yoops.org")
92
+
93
+ # 1. Enregistrer un callback pour un secret nommé
94
+ @client.on_auth_error("anthropic_api_key")
95
+ async def on_anthropic_rotated(new_value: str) -> None:
96
+ anthropic_client.api_key = new_value
97
+
98
+ # 2. Filet de sécurité : callback pour TOUS les secrets
99
+ @client.on_any_auth_error
100
+ async def log_any_rotation(name: str, new_value: str) -> None:
101
+ logger.warning("secret rotated: %s", name)
102
+
103
+ # 3. Quand l'app détecte un 401 sur un appel utilisant le secret :
104
+ async def call_anthropic(prompt: str) -> str:
105
+ key = client.secrets.get("anthropic_api_key")
106
+ try:
107
+ return await anthropic.complete(prompt, api_key=key)
108
+ except anthropic.AuthenticationError:
109
+ # Le SDK refait un GET forcé, déchiffre, appelle les callbacks
110
+ new_key = await client.notify_auth_error("anthropic_api_key")
111
+ return await anthropic.complete(prompt, api_key=new_key)
112
+ ```
113
+
114
+ ### Context manager (sucre syntaxique)
115
+
116
+ ```python
117
+ async with client.using_secret("anthropic_api_key") as get_value:
118
+ key = await get_value()
119
+ try:
120
+ return await anthropic.complete(prompt, api_key=key)
121
+ except anthropic.AuthenticationError:
122
+ key = await get_value(retry=True) # force_refresh + callbacks
123
+ return await anthropic.complete(prompt, api_key=key)
124
+ ```
125
+
126
+ ### Force refresh ponctuel
127
+
128
+ ```python
129
+ # Invalide le cache wallet_key local et refait un GET
130
+ new_value = client.secrets.get("anthropic_api_key", force_refresh=True)
131
+ ```
132
+
133
+ ### Exceptions
134
+
135
+ - `SecretRefreshFailed` : le refresh a échoué (secret supprimé, API key révoquée)
136
+
137
+ ## Se connecter avec Harpocrate (≥ 0.8.0)
138
+
139
+ Pour qu'une application obtienne une API key sans copier-coller : l'application doit
140
+ être déclarée par un admin Harpocrate (registre des applications, URL de retour exacte).
141
+
142
+ ```python
143
+ from harpocrate import connect
144
+
145
+ # Backend de l'application, au clic sur « Connecter » :
146
+ browser_url, pending = connect.start(
147
+ base_url="https://vault.example",
148
+ client_id="ragflow",
149
+ redirect_uri="https://rag.example/harpocrate/callback",
150
+ permissions=0x01, # read
151
+ ttl_days=90,
152
+ )
153
+ session["harpocrate_connect"] = pending.to_dict() # côté serveur uniquement
154
+ # → rediriger le navigateur vers browser_url
155
+
156
+ # Sur redirect_uri :
157
+ if "error" in request.args: # access_denied : l'utilisateur a refusé
158
+ ...
159
+ pending = connect.ConnectState.from_dict(session.pop("harpocrate_connect"))
160
+ result = connect.finish(pending, code=request.args["code"], state=request.args["state"])
161
+ # result.token : API key complète, à chiffrer au repos ; result.wallet_id, result.api_key_id
162
+ ```
163
+
164
+ Le code de retour vaut 60 s et ne s'échange qu'une fois ; la demande vaut 15 min.
165
+
166
+ ## CLI harpocrate-gen
167
+
168
+ ```bash
169
+ export HARPOCRATE_TOKEN=hrpv_1_...
170
+ export HARPOCRATE_URL=https://vault.yoops.org
171
+
172
+ harpocrate-gen list
173
+ harpocrate-gen get --name ANTHROPIC_API_KEY
174
+ harpocrate-gen populate --name DB_PASSWORD
175
+ harpocrate-gen populate-all
176
+ ```
@@ -0,0 +1,135 @@
1
+ # Harpocrate SDK Python
2
+
3
+ Client Python zero-knowledge pour Harpocrate Vault.
4
+
5
+ ## Installation
6
+
7
+ Depuis [PyPI](https://pypi.org/project/harpocrate/) :
8
+
9
+ ```bash
10
+ pip install harpocrate
11
+ # ou
12
+ uv add harpocrate
13
+ ```
14
+
15
+ Python 3.10 ou plus récent.
16
+
17
+ ## Usage rapide
18
+
19
+ ```python
20
+ from harpocrate import VaultClient
21
+
22
+ client = VaultClient(
23
+ token="hrpv_1_...",
24
+ base_url="https://vault.yoops.org",
25
+ )
26
+
27
+ # Lire un secret
28
+ value = client.secrets.get("ANTHROPIC_API_KEY")
29
+
30
+ # Lister les secrets
31
+ for secret in client.secrets.list().secrets:
32
+ print(secret.name, "placeholder" if secret.is_placeholder else "valued")
33
+
34
+ # Peupler tous les placeholders
35
+ results = client.secrets.populate_all()
36
+ for r in results:
37
+ print(r.name, "OK" if r.success else r.error)
38
+ ```
39
+
40
+ ## Détection de rotation (LOT_22, ≥ 0.5.0)
41
+
42
+ Quand un secret est rotaté côté Harpocrate, l'application qui consomme ce
43
+ secret détecte typiquement l'expiration via une réponse 401 de l'API tierce
44
+ (Anthropic, OpenAI, etc.). Le SDK fournit un mécanisme déclaratif pour gérer
45
+ ce cas :
46
+
47
+ ```python
48
+ from harpocrate import VaultClient
49
+
50
+ client = VaultClient(token="hrpv_...", base_url="https://vault.yoops.org")
51
+
52
+ # 1. Enregistrer un callback pour un secret nommé
53
+ @client.on_auth_error("anthropic_api_key")
54
+ async def on_anthropic_rotated(new_value: str) -> None:
55
+ anthropic_client.api_key = new_value
56
+
57
+ # 2. Filet de sécurité : callback pour TOUS les secrets
58
+ @client.on_any_auth_error
59
+ async def log_any_rotation(name: str, new_value: str) -> None:
60
+ logger.warning("secret rotated: %s", name)
61
+
62
+ # 3. Quand l'app détecte un 401 sur un appel utilisant le secret :
63
+ async def call_anthropic(prompt: str) -> str:
64
+ key = client.secrets.get("anthropic_api_key")
65
+ try:
66
+ return await anthropic.complete(prompt, api_key=key)
67
+ except anthropic.AuthenticationError:
68
+ # Le SDK refait un GET forcé, déchiffre, appelle les callbacks
69
+ new_key = await client.notify_auth_error("anthropic_api_key")
70
+ return await anthropic.complete(prompt, api_key=new_key)
71
+ ```
72
+
73
+ ### Context manager (sucre syntaxique)
74
+
75
+ ```python
76
+ async with client.using_secret("anthropic_api_key") as get_value:
77
+ key = await get_value()
78
+ try:
79
+ return await anthropic.complete(prompt, api_key=key)
80
+ except anthropic.AuthenticationError:
81
+ key = await get_value(retry=True) # force_refresh + callbacks
82
+ return await anthropic.complete(prompt, api_key=key)
83
+ ```
84
+
85
+ ### Force refresh ponctuel
86
+
87
+ ```python
88
+ # Invalide le cache wallet_key local et refait un GET
89
+ new_value = client.secrets.get("anthropic_api_key", force_refresh=True)
90
+ ```
91
+
92
+ ### Exceptions
93
+
94
+ - `SecretRefreshFailed` : le refresh a échoué (secret supprimé, API key révoquée)
95
+
96
+ ## Se connecter avec Harpocrate (≥ 0.8.0)
97
+
98
+ Pour qu'une application obtienne une API key sans copier-coller : l'application doit
99
+ être déclarée par un admin Harpocrate (registre des applications, URL de retour exacte).
100
+
101
+ ```python
102
+ from harpocrate import connect
103
+
104
+ # Backend de l'application, au clic sur « Connecter » :
105
+ browser_url, pending = connect.start(
106
+ base_url="https://vault.example",
107
+ client_id="ragflow",
108
+ redirect_uri="https://rag.example/harpocrate/callback",
109
+ permissions=0x01, # read
110
+ ttl_days=90,
111
+ )
112
+ session["harpocrate_connect"] = pending.to_dict() # côté serveur uniquement
113
+ # → rediriger le navigateur vers browser_url
114
+
115
+ # Sur redirect_uri :
116
+ if "error" in request.args: # access_denied : l'utilisateur a refusé
117
+ ...
118
+ pending = connect.ConnectState.from_dict(session.pop("harpocrate_connect"))
119
+ result = connect.finish(pending, code=request.args["code"], state=request.args["state"])
120
+ # result.token : API key complète, à chiffrer au repos ; result.wallet_id, result.api_key_id
121
+ ```
122
+
123
+ Le code de retour vaut 60 s et ne s'échange qu'une fois ; la demande vaut 15 min.
124
+
125
+ ## CLI harpocrate-gen
126
+
127
+ ```bash
128
+ export HARPOCRATE_TOKEN=hrpv_1_...
129
+ export HARPOCRATE_URL=https://vault.yoops.org
130
+
131
+ harpocrate-gen list
132
+ harpocrate-gen get --name ANTHROPIC_API_KEY
133
+ harpocrate-gen populate --name DB_PASSWORD
134
+ harpocrate-gen populate-all
135
+ ```