lgpd-guard 0.2.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.
- lgpd_guard-0.2.0/LICENSE +202 -0
- lgpd_guard-0.2.0/PKG-INFO +314 -0
- lgpd_guard-0.2.0/README.md +282 -0
- lgpd_guard-0.2.0/lgpd_guard/__init__.py +24 -0
- lgpd_guard-0.2.0/lgpd_guard/litellm_guardrail.py +210 -0
- lgpd_guard-0.2.0/lgpd_guard/ner.py +158 -0
- lgpd_guard-0.2.0/lgpd_guard/patterns.py +304 -0
- lgpd_guard-0.2.0/lgpd_guard/protector.py +136 -0
- lgpd_guard-0.2.0/lgpd_guard/spacy_names.py +91 -0
- lgpd_guard-0.2.0/lgpd_guard/stream_restorer.py +58 -0
- lgpd_guard-0.2.0/lgpd_guard/validators.py +92 -0
- lgpd_guard-0.2.0/lgpd_guard.egg-info/PKG-INFO +314 -0
- lgpd_guard-0.2.0/lgpd_guard.egg-info/SOURCES.txt +30 -0
- lgpd_guard-0.2.0/lgpd_guard.egg-info/dependency_links.txt +1 -0
- lgpd_guard-0.2.0/lgpd_guard.egg-info/requires.txt +23 -0
- lgpd_guard-0.2.0/lgpd_guard.egg-info/top_level.txt +1 -0
- lgpd_guard-0.2.0/pyproject.toml +36 -0
- lgpd_guard-0.2.0/setup.cfg +4 -0
- lgpd_guard-0.2.0/tests/test_evals.py +15 -0
- lgpd_guard-0.2.0/tests/test_lgpd_guard_and_providers.py +102 -0
- lgpd_guard-0.2.0/tests/test_litellm_guardrail.py +172 -0
- lgpd_guard-0.2.0/tests/test_new_additions.py +297 -0
- lgpd_guard-0.2.0/tests/test_pii.py +285 -0
- lgpd_guard-0.2.0/tests/test_postgres.py +145 -0
- lgpd_guard-0.2.0/tests/test_providers.py +113 -0
- lgpd_guard-0.2.0/tests/test_proxy_config.py +68 -0
- lgpd_guard-0.2.0/tests/test_router_cache_quota.py +177 -0
- lgpd_guard-0.2.0/tests/test_security.py +154 -0
- lgpd_guard-0.2.0/tests/test_streaming.py +111 -0
- lgpd_guard-0.2.0/tests/test_usage_and_api.py +642 -0
- lgpd_guard-0.2.0/tests/test_use_case.py +84 -0
- lgpd_guard-0.2.0/tests/test_xray.py +92 -0
lgpd_guard-0.2.0/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: lgpd-guard
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Reversible masking of Brazilian PII for LLM calls, with streaming restore and a LiteLLM guardrail.
|
|
5
|
+
License-Expression: Apache-2.0
|
|
6
|
+
Keywords: lgpd,pii,llm,brazil,cpf,cnpj,litellm
|
|
7
|
+
Classifier: Development Status :: 4 - Beta
|
|
8
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
9
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
10
|
+
Requires-Python: >=3.11
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Provides-Extra: gateway
|
|
14
|
+
Requires-Dist: fastapi; extra == "gateway"
|
|
15
|
+
Requires-Dist: uvicorn[standard]; extra == "gateway"
|
|
16
|
+
Requires-Dist: httpx; extra == "gateway"
|
|
17
|
+
Requires-Dist: pydantic>=2; extra == "gateway"
|
|
18
|
+
Requires-Dist: psycopg[binary,pool]; extra == "gateway"
|
|
19
|
+
Requires-Dist: pgvector; extra == "gateway"
|
|
20
|
+
Provides-Extra: litellm
|
|
21
|
+
Requires-Dist: litellm[proxy]; extra == "litellm"
|
|
22
|
+
Provides-Extra: spacy
|
|
23
|
+
Requires-Dist: spacy<3.9,>=3.8; extra == "spacy"
|
|
24
|
+
Provides-Extra: bench
|
|
25
|
+
Requires-Dist: spacy<3.9,>=3.8; extra == "bench"
|
|
26
|
+
Requires-Dist: presidio-analyzer==2.2.366; extra == "bench"
|
|
27
|
+
Requires-Dist: tarja==0.12.0; extra == "bench"
|
|
28
|
+
Requires-Dist: pyarrow; extra == "bench"
|
|
29
|
+
Provides-Extra: dev
|
|
30
|
+
Requires-Dist: pytest; extra == "dev"
|
|
31
|
+
Dynamic: license-file
|
|
32
|
+
|
|
33
|
+
# LGPD AI Gateway e `lgpd-guard`
|
|
34
|
+
|
|
35
|
+
> **v0.2.0 (Beta).** A técnica é **pseudonimização** (reversível), não anonimização definitiva, e a
|
|
36
|
+
> detecção em texto livre é parcial: valide com textos do seu domínio antes de usar em produção e veja
|
|
37
|
+
> as [limitações conhecidas](#limitações-conhecidas).
|
|
38
|
+
|
|
39
|
+
Um gateway entre a sua aplicação e os modelos de IA (Gemini, OpenAI, Claude). Ele troca dados
|
|
40
|
+
pessoais brasileiros por etiquetas antes de enviar o texto ao provedor e coloca os valores de volta
|
|
41
|
+
na resposta, inclusive durante o streaming.
|
|
42
|
+
|
|
43
|
+
```text
|
|
44
|
+
Você envia: Cliente: Maria da Silva, CPF 529.982.247-25, quer a 2ª via.
|
|
45
|
+
O provedor recebe: Cliente: <PERSON_1>, CPF <CPF_1>, quer a 2ª via.
|
|
46
|
+
Você recebe: Maria da Silva (CPF 529.982.247-25), sua 2ª via...
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Há duas formas de usar:
|
|
50
|
+
|
|
51
|
+
- **Gateway completo** (FastAPI + PostgreSQL/pgvector), com API no formato da OpenAI.
|
|
52
|
+
- **Pacote `lgpd-guard`**, sem dependências, sozinho ou como guardrail do LiteLLM.
|
|
53
|
+
|
|
54
|
+
## Como funciona
|
|
55
|
+
|
|
56
|
+
```mermaid
|
|
57
|
+
flowchart LR
|
|
58
|
+
A["Sua aplicação"] -->|"chave do gateway"| B["FastAPI"]
|
|
59
|
+
B --> C["1. Mascara dados"]
|
|
60
|
+
C --> D["2. Escolhe o modelo"]
|
|
61
|
+
D -->|"sem dado detectado, 1 mensagem"| E{"3. Cache semântico do tenant"}
|
|
62
|
+
E -->|"achou"| H["6. Restaura e responde"]
|
|
63
|
+
E -->|"não achou"| F["4. Cotas: dia, semana, mês, global"]
|
|
64
|
+
D -->|"com dado detectado"| F
|
|
65
|
+
F --> G["5. Gemini → OpenAI → Claude"]
|
|
66
|
+
G --> H
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
## O que ele detecta
|
|
70
|
+
|
|
71
|
+
| Dado | Como |
|
|
72
|
+
| --- | --- |
|
|
73
|
+
| CPF | Dígitos verificadores, ou logo após "CPF" (mesmo com dígito errado) |
|
|
74
|
+
| CNPJ | Dígitos verificadores; numérico e **alfanumérico** (emitido desde 31/07/2026) |
|
|
75
|
+
| Cartão | Prefixo da bandeira e Luhn |
|
|
76
|
+
| E-mail | Formato |
|
|
77
|
+
| Telefone | DDD válido, ou logo após "Telefone"; números soltos dependem do contexto |
|
|
78
|
+
| CEP | Com hífen, ou logo após "CEP" |
|
|
79
|
+
| RG, CNH, PIS, título de eleitor | Só após o rótulo ("RG: ...") |
|
|
80
|
+
| Conta, agência, placa e IP | Só após o rótulo |
|
|
81
|
+
| Data de nascimento | Só perto de "nascimento" ou "nascido" |
|
|
82
|
+
| Saúde (CNS, CID, diagnósticos) | CNS (15 dígitos, Módulo 11) ou rótulo; CID-10/11 após rótulo; diagnósticos clínicos explícitos |
|
|
83
|
+
| Chave Pix aleatória | UUID perto de palavras como "pix" ou "chave" |
|
|
84
|
+
| Nome | `light`: campos, cargos e apresentações. `spacy`: também nomes soltos |
|
|
85
|
+
| Endereço | Logradouro com inicial maiúscula, ou em minúsculas com número |
|
|
86
|
+
|
|
87
|
+
Um nome completo achado uma vez é mascarado em toda a requisição.
|
|
88
|
+
|
|
89
|
+
### Modo de nomes
|
|
90
|
+
|
|
91
|
+
| `NER_MODE` | Acha | Custo |
|
|
92
|
+
| --- | --- | --- |
|
|
93
|
+
| `off` | Nenhum nome ou endereço | Nenhum |
|
|
94
|
+
| `light` (padrão) | Nomes com contexto | Cerca de 1 ms por página |
|
|
95
|
+
| `spacy` | Também nomes sem contexto | Cerca de 15 ms por página, uns 570 MB de modelo e cerca de 950 MB de RAM |
|
|
96
|
+
| `strict` | Também lugares, pois o modelo confunde sobrenomes (Dias, Luz) com lugares | O mesmo, com mais texto mascarado à toa |
|
|
97
|
+
|
|
98
|
+
No Docker, defina `NER_MODE=spacy` (ou `strict`) e `SPACY_MODEL=pt_core_news_lg` no `.env` e reconstrua.
|
|
99
|
+
Se o modelo faltar, o gateway não inicia. O modelo tem licença própria (CC BY-SA 4.0).
|
|
100
|
+
|
|
101
|
+
Também há:
|
|
102
|
+
|
|
103
|
+
- **Streaming:** restaura etiquetas cortadas entre pedaços (`<CP` + `F_1>`).
|
|
104
|
+
- **Cotas** por dia, semana e mês, por tenant, mais um teto global. Cada chamada reserva o pior caso
|
|
105
|
+
e depois acerta com os **tokens reais** e o preço do modelo que respondeu.
|
|
106
|
+
- **Fallback** entre provedores quando um deles falha.
|
|
107
|
+
- **Auditoria no banco**, só com HMAC-SHA256 separado por tenant. Se não der para gravar, a chamada é
|
|
108
|
+
bloqueada. `POST /v1/audit/search` responde quando um valor foi mascarado, sem guardá-lo.
|
|
109
|
+
- **Cache semântico com validade**, que não mistura perguntas com números ou negações diferentes.
|
|
110
|
+
- **Painel `/xray`**, que mostra o texto mascarado que saiu para o provedor.
|
|
111
|
+
|
|
112
|
+
| Endpoint (sempre do próprio tenant) | Uso |
|
|
113
|
+
| --- | --- |
|
|
114
|
+
| `POST /v1/chat/completions`, `GET /v1/models` | API no formato da OpenAI |
|
|
115
|
+
| `GET /v1/audit`, `POST /v1/audit/search` | Auditoria |
|
|
116
|
+
| `GET /v1/usage` | Gasto por período, em USD |
|
|
117
|
+
| `DELETE /v1/cache` | Apaga o cache do tenant |
|
|
118
|
+
| `GET /health`, `GET /health/ready`, `GET /metrics` | Saúde, prontidão do banco e métricas Prometheus (autenticado) |
|
|
119
|
+
|
|
120
|
+
## Limitações conhecidas
|
|
121
|
+
|
|
122
|
+
**Detecção.** Passam sem máscara:
|
|
123
|
+
|
|
124
|
+
- no modo `light`, nome solto sem partícula nem contexto ("Ana Souza quer cancelar");
|
|
125
|
+
- nome em minúsculas sem contexto (fora de papéis, rótulos, saudações ou apresentações como "meu nome é");
|
|
126
|
+
- documento, conta ou data de nascimento sem rótulo por perto; chave Pix sem contexto;
|
|
127
|
+
- dados de saúde em texto livre fora de diagnósticos explícitos ou condições mapeadas;
|
|
128
|
+
- imagens e arquivos.
|
|
129
|
+
|
|
130
|
+
Os modos `spacy` e `strict` podem marcar palavras comuns como nome e são lentos com textos enormes: até 8 s no corpo
|
|
131
|
+
máximo de 128 mil caracteres, em um PC. Rodam fora do laço principal, uma requisição por vez.
|
|
132
|
+
|
|
133
|
+
**LGPD.** A técnica é **pseudonimização**, não anonimização: é reversível por quem tem o mapa.
|
|
134
|
+
Trate os dados como pessoais. Este projeto não garante conformidade com a LGPD nem substitui
|
|
135
|
+
avaliação jurídica.
|
|
136
|
+
|
|
137
|
+
**Gateway.**
|
|
138
|
+
|
|
139
|
+
- Um dado **não detectado** pode ficar no cache até vencer (7 dias por padrão; `CACHE_ENABLED=false`
|
|
140
|
+
desliga) e vai para a API de embeddings.
|
|
141
|
+
- Os preços embutidos são de 29/11/2026 e podem mudar; chamadas de embeddings ao cache semântico usam o preço de `gemini-embedding-001` na cota.
|
|
142
|
+
Stream interrompido é cobrado por estimativa.
|
|
143
|
+
- A API aceita texto, `response_format` (`text`, `json_object`, `json_schema`) e `tools` (com mascaramento e restauração segura em JSON). Imagens e `n > 1` são **recusados**. Claude que não aceita
|
|
144
|
+
`temperature` é chamado sem ela.
|
|
145
|
+
- Com o banco fora, as chamadas respondem 503 após cerca de 10 s.
|
|
146
|
+
- No Docker, o Nginx gera certificado autoassinado se `./certs/fullchain.pem` e `privkey.pem` não existirem; em produção, monte certificados válidos em `./certs/`, configure `TRUSTED_PROXY_CIDR` se houver balanceador na frente (sem isso, ou em rede bridge sem IP real repassado, os clientes dividem o mesmo IP de origem no container) e agende backups com `python scripts/db_backup.py backup`.
|
|
147
|
+
- Camadas gratuitas de IA podem usar o conteúdo enviado; confira os termos do seu provedor.
|
|
148
|
+
|
|
149
|
+
## Como rodar
|
|
150
|
+
|
|
151
|
+
### Docker
|
|
152
|
+
|
|
153
|
+
```bash
|
|
154
|
+
cp .env.example .env # Windows: copy .env.example .env
|
|
155
|
+
# preencha GATEWAY_API_KEY, AUDIT_HMAC_SECRET e ao menos um provedor
|
|
156
|
+
docker compose up -d --build
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
- Painel: <https://localhost:8443/xray> (cole a `GATEWAY_API_KEY` no topo; a porta `8080` redireciona para HTTPS)
|
|
160
|
+
- Open WebUI: <http://localhost:3000>
|
|
161
|
+
- Documentação da API: <https://localhost:8443/docs>
|
|
162
|
+
|
|
163
|
+
Por padrão, o proxy Nginx aplica TLS 1.2/1.3, HSTS e limite de `10 req/s` (`burst=20`) e `30` conexões simultâneas por IP (retornando `429`). Para usar certificado próprio, coloque `fullchain.pem` e `privkey.pem` em `./certs/`.
|
|
164
|
+
|
|
165
|
+
### Local, sem banco
|
|
166
|
+
|
|
167
|
+
Sem `DATABASE_URL`, cache e cotas ficam em memória. Sem chave de provedor, um modelo falso responde.
|
|
168
|
+
|
|
169
|
+
```bash
|
|
170
|
+
python -m venv .venv
|
|
171
|
+
# Linux/macOS: source .venv/bin/activate | Windows: .venv\Scripts\activate
|
|
172
|
+
pip install -r requirements.txt
|
|
173
|
+
pip install -e . --no-deps
|
|
174
|
+
uvicorn app.main:app --port 8000
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
### Chamada
|
|
178
|
+
|
|
179
|
+
```bash
|
|
180
|
+
curl http://localhost:8000/v1/chat/completions \
|
|
181
|
+
-H "Authorization: Bearer $GATEWAY_API_KEY" -H "Content-Type: application/json" \
|
|
182
|
+
-d '{"model": "auto", "messages": [{"role": "user", "content": "Resuma: CPF 529.982.247-25 pediu 2a via"}]}'
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
### Só o pacote
|
|
186
|
+
|
|
187
|
+
```python
|
|
188
|
+
from lgpd_guard import BrPiiProtector
|
|
189
|
+
|
|
190
|
+
protector = BrPiiProtector(enable_ner=True)
|
|
191
|
+
masked, mapping, kinds = protector.mask_texts(["Cliente: Maria da Silva, CPF 529.982.247-25"])
|
|
192
|
+
# masked[0] == "Cliente: <PERSON_1>, CPF <CPF_1>"
|
|
193
|
+
protector.restore(masked[0], mapping)
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
### Guardrail do LiteLLM
|
|
197
|
+
|
|
198
|
+
Crie `custom_guardrail.py` ao lado do `config.yaml`:
|
|
199
|
+
|
|
200
|
+
```python
|
|
201
|
+
from lgpd_guard.litellm_guardrail import LgpdLiteLlmGuardrail
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
```yaml
|
|
205
|
+
guardrails:
|
|
206
|
+
- guardrail_name: lgpd
|
|
207
|
+
litellm_params:
|
|
208
|
+
guardrail: custom_guardrail.LgpdLiteLlmGuardrail
|
|
209
|
+
mode: [pre_call, post_call]
|
|
210
|
+
default_on: true
|
|
211
|
+
ner_mode: light # ou spacy, strict
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
Testado com o proxy do LiteLLM em chat, com e sem streaming, nos modos `light`, `spacy` e `strict`. Outros endpoints são
|
|
215
|
+
recusados, para não vazar texto sem máscara. O mapa de dados fica na memória do processo.
|
|
216
|
+
|
|
217
|
+
## Testes
|
|
218
|
+
|
|
219
|
+
```bash
|
|
220
|
+
pip install -r requirements-dev.txt
|
|
221
|
+
pytest -q
|
|
222
|
+
python -m evals.run_evals
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
`evals` é uma **suíte de regressão** com textos escritos pelos autores e a lista de lacunas
|
|
226
|
+
conhecidas. Serve para notar quebras, **não** para estimar acertos.
|
|
227
|
+
|
|
228
|
+
## Comparação com outras ferramentas
|
|
229
|
+
|
|
230
|
+
Dados públicos e **sintéticos**, de outros autores. Um dado só conta quando sai inteiro coberto.
|
|
231
|
+
Presidio usa o modelo português grande; "+ BR" soma regras de CPF, CNPJ e CEP feitas por nós.
|
|
232
|
+
No conjunto principal, os 2.000 textos medidos (linhas 8000 a 10000) não orientaram nenhuma
|
|
233
|
+
correção. Os outros três conjuntos **foram consultados durante o ajuste** e não são teste cego.
|
|
234
|
+
|
|
235
|
+
**2.000 documentos de [privacy-filter-br](https://huggingface.co/datasets/lucianfialho/privacy-filter-br-dataset)**
|
|
236
|
+
|
|
237
|
+
| % coberto | light | spacy | strict | tarja 0.12 | Presidio | Presidio + BR |
|
|
238
|
+
| --- | --- | --- | --- | --- | --- | --- |
|
|
239
|
+
| CPF | 99,9 | 99,9 | 99,9 | 99,9 | 18,5 | 99,9 |
|
|
240
|
+
| CNPJ | 100 | 100 | 100 | 100 | 8,3 | 100 |
|
|
241
|
+
| E-mail | 99,8 | 99,8 | 99,8 | — | 99,4 | 99,4 |
|
|
242
|
+
| Telefone | 99,9 | 99,9 | 99,9 | 76,5 | 76,7 | 76,7 |
|
|
243
|
+
| CEP | 99,1 | 99,1 | 99,1 | 83,5 | 3 | 54,7 |
|
|
244
|
+
| PIS | 93,7 | 93,7 | 93,7 | **99,3** | 23,4 | 14,4 |
|
|
245
|
+
| CNH | 84,8 | 84,8 | 84,8 | **100** | 23,8 | 18,1 |
|
|
246
|
+
| RG | 89 | 89 | 89 | — | 1,9 | 0 |
|
|
247
|
+
| Endereço | 84,3 | 84,3 | **88,2** | — | 0 | 0 |
|
|
248
|
+
| Nome | 91,2 | 98,4 | **98,7** | — | 94,1 | 94,1 |
|
|
249
|
+
| Qualquer data | 14,9 | 14,9 | 14,9 | — | 100 | 100 |
|
|
250
|
+
| Documentos sem vazamento | 82,5 | 84,5 | **84,8** | 0,1 | 11,4 | 37,6 |
|
|
251
|
+
| Mediana por texto (ms) | **2,9** | 23 | 23,2 | 4,7 | 36,9 | 27,5 |
|
|
252
|
+
|
|
253
|
+
**Outros dados** (usados também para ajustar o código)
|
|
254
|
+
|
|
255
|
+
| | light | spacy | strict | Presidio |
|
|
256
|
+
| --- | --- | --- | --- | --- |
|
|
257
|
+
| Nomes, [nym-pii](https://huggingface.co/datasets/Wismut/nym-pii-multilingual-data) em português (273 textos) | 52,4 | 93,4 | **97,7** | 95,1 |
|
|
258
|
+
| Textos sem vazamento, nym-pii | 36,6 | 53,9 | **59,4** | 47,6 |
|
|
259
|
+
| Nomes, [corpus-synthetic-lgpd](https://huggingface.co/datasets/celiudos/corpus-synthetic-lgpd) (105 documentos longos) | 49,9 | 83,8 | **85,4** | 76,1 |
|
|
260
|
+
| Falso alarme, [pii-br-synthetic](https://huggingface.co/datasets/ai-safety-brazil/pii-br-synthetic) | **2** | 2,2 | 15,4 | 74,5 |
|
|
261
|
+
|
|
262
|
+
O tarja teve 19,6% de falso alarme e vence em CNH e PIS. O Presidio cobre datas e lugares de
|
|
263
|
+
propósito, por isso tem mais falso alarme e vence em datas. No modo `light`, o Presidio cobre mais
|
|
264
|
+
nomes que o `lgpd-guard` no conjunto principal, no nym-pii e no corpus longo.
|
|
265
|
+
|
|
266
|
+
Ressalvas: o conjunto principal tem rótulos incompletos e formatos parecidos com os dados de treino
|
|
267
|
+
que estudamos. No corpus longo, não contamos títulos ("Sr.", "Dra."), para todas as ferramentas.
|
|
268
|
+
Dados sintéticos não preveem o resultado em textos reais. Todos os números:
|
|
269
|
+
[benchmark_results.json](evals/benchmark_results.json). Para repetir: `pip install -e ".[bench]"`,
|
|
270
|
+
`python -m spacy download pt_core_news_lg` e `python -m evals.benchmark_external`.
|
|
271
|
+
|
|
272
|
+
## Configuração
|
|
273
|
+
|
|
274
|
+
| Variável | Padrão | Uso |
|
|
275
|
+
| --- | --- | --- |
|
|
276
|
+
| `GATEWAY_API_KEY` | vazio | Chave única do gateway (tenant `default`) |
|
|
277
|
+
| `TENANT_API_KEYS_JSON` | vazio | Uma chave por tenant: `{"chave":"tenant"}` |
|
|
278
|
+
| `ALLOW_ANONYMOUS_TENANTS` | `false` | Só desenvolvimento: sem chave configurada, aceita qualquer Bearer |
|
|
279
|
+
| `AUDIT_HMAC_SECRET` | aleatório por processo | Segredo dos hashes; **obrigatório** com `DATABASE_URL` |
|
|
280
|
+
| `AUDIT_RETENTION_DAYS` | `180` | Depois disso, a auditoria é apagada |
|
|
281
|
+
| `CACHE_ENABLED`, `CACHE_TTL_HOURS` | `true`, `168` | Cache e validade |
|
|
282
|
+
| `MAX_OUTPUT_TOKENS` | `2048` | Teto por resposta, que também define a reserva de cota |
|
|
283
|
+
| `MODEL_PRICES_JSON` | vazio | `{"modelo":[entrada,saída]}` em USD por 1M de tokens; sem preço, usa um valor alto |
|
|
284
|
+
| `GEMINI_API_KEY`, `OPENAI_API_KEY`, `ANTHROPIC_API_KEY` | vazio | Provedores |
|
|
285
|
+
| `GEMINI_PRIMARY_MODEL` | `gemini-3-flash-preview` | Modelo forte |
|
|
286
|
+
| `GEMINI_FALLBACK_MODEL` | `gemini-3.1-flash-lite` | Modelo rápido e fallback |
|
|
287
|
+
| `OPENAI_MODEL` | `gpt-6-luna` | Modelo OpenAI |
|
|
288
|
+
| `OPENAI_BASE_URL` | API da OpenAI | Outro provedor compatível |
|
|
289
|
+
| `ANTHROPIC_MODEL` | `claude-haiku-5-5` | Modelo Claude |
|
|
290
|
+
| `NER_MODE` | `light` | Nomes e endereços: `off`, `light`, `spacy` ou `strict` |
|
|
291
|
+
| `SPACY_MODEL` | `pt_core_news_lg` | Modelo dos modos `spacy` e `strict` |
|
|
292
|
+
| `DAILY_QUOTA_USD`, `WEEKLY_QUOTA_USD`, `MONTHLY_QUOTA_USD` | `1`, `5`, `20` | Cotas por tenant |
|
|
293
|
+
| `GLOBAL_DAILY_QUOTA_USD` | `15` | Teto diário do servidor |
|
|
294
|
+
| `TENANT_LIMITS_JSON` | vazio | `{"tenant":{"daily":2,"weekly":10,"monthly":30}}` |
|
|
295
|
+
| `DATABASE_URL` | vazio | PostgreSQL com pgvector |
|
|
296
|
+
| `ENABLE_XRAY` | `true` | Painel `/xray` |
|
|
297
|
+
| `HTTPS_PORT`, `HTTP_PORT` | `8443`, `8080` | Portas do proxy Nginx (`8080` redireciona para HTTPS) |
|
|
298
|
+
| `RATE_LIMIT_RPS`, `RATE_LIMIT_BURST`, `CONN_LIMIT_PER_IP` | `10r/s`, `20`, `30` | Limite de requisições e conexões por IP no Nginx |
|
|
299
|
+
| `TRUSTED_PROXY_CIDR` | `127.0.0.1/32` | CIDR de balanceador confiável autorizado a informar o IP real em `X-Forwarded-For` |
|
|
300
|
+
| `UVICORN_WORKERS` | `1` (`2` no Compose) | Processos Uvicorn no container; `/xray/traces` usa o PostgreSQL quando há `DATABASE_URL` (`/metrics` mantém contadores em memória por processo) |
|
|
301
|
+
|
|
302
|
+
## Estrutura
|
|
303
|
+
|
|
304
|
+
```text
|
|
305
|
+
lgpd_guard/ pacote independente: validação, detecção, streaming e LiteLLM
|
|
306
|
+
app/ gateway: domain, application, infrastructure e api
|
|
307
|
+
evals/ suíte de regressão e lacunas conhecidas
|
|
308
|
+
tests/ testes automatizados
|
|
309
|
+
```
|
|
310
|
+
|
|
311
|
+
## Contribuir
|
|
312
|
+
|
|
313
|
+
Veja [CONTRIBUTING.md](CONTRIBUTING.md) e [SECURITY.md](SECURITY.md).
|
|
314
|
+
Licença [Apache-2.0](LICENSE).
|