@acropole/skills 0.0.0-stage → 1.1.0
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.
- package/README.md +181 -2
- package/agents/revisor-deploy.md +73 -0
- package/agents/revisor-documentacao.md +78 -0
- package/agents/revisor-orfeu.md +80 -0
- package/agents/revisor-trismegisto.md +81 -0
- package/bin/install.js +252 -0
- package/package.json +15 -4
- package/skills/acropole/SKILL.md +80 -0
- package/skills/acropole/references/arquitetura.md +174 -0
- package/skills/acropole/references/fluxos/app-novo.md +34 -0
- package/skills/acropole/references/fluxos/doctor.md +55 -0
- package/skills/acropole/references/fluxos/endpoint-novo.md +22 -0
- package/skills/acropole/references/fluxos/revisar.md +56 -0
- package/skills/acropole/references/fluxos/tela-nova.md +27 -0
- package/skills/acropole/scripts/doctor.mjs +439 -0
- package/skills/angular/SKILL.md +155 -0
- package/skills/angular/references/armadilhas.md +99 -0
- package/skills/angular/references/dados.md +251 -0
- package/skills/angular/references/estrutura.md +279 -0
- package/skills/angular/references/features.md +219 -0
- package/skills/angular/references/testes-build.md +257 -0
- package/skills/angular/scripts/checar.mjs +182 -0
- package/skills/angular/scripts/nucleo.mjs +227 -0
- package/skills/apollo/SKILL.md +226 -0
- package/skills/apollo/references/armadilhas.md +99 -0
- package/skills/apollo/references/envelope-erros.md +120 -0
- package/skills/apollo/references/estrutura-bootstrap.md +310 -0
- package/skills/apollo/references/schema-resolvers.md +183 -0
- package/skills/apollo/references/subscriptions.md +224 -0
- package/skills/apollo/references/testes-build.md +181 -0
- package/skills/apollo/scripts/checar.mjs +160 -0
- package/skills/apollo/scripts/nucleo.mjs +227 -0
- package/skills/docker/SKILL.md +102 -0
- package/skills/docker/references/modelos.md +251 -0
- package/skills/docker/references/porques.md +286 -0
- package/skills/documentacao/SKILL.md +146 -0
- package/skills/documentacao/references/checklist-coerencia.md +59 -0
- package/skills/documentacao/references/ligar-app-novo.md +107 -0
- package/skills/documentacao/references/modelo-especificacao.md +51 -0
- package/skills/documentacao/references/modelo-readme.md +75 -0
- package/skills/documentacao/scripts/checar.mjs +454 -0
- package/skills/documentacao/scripts/nucleo.mjs +227 -0
- package/skills/express/SKILL.md +156 -0
- package/skills/express/references/dados.md +180 -0
- package/skills/express/references/estrutura.md +157 -0
- package/skills/express/references/middlewares.md +227 -0
- package/skills/express/references/rotas-erros.md +286 -0
- package/skills/express/references/testes-deploy.md +154 -0
- package/skills/express/scripts/checar.mjs +115 -0
- package/skills/express/scripts/nucleo.mjs +227 -0
- package/skills/fastapi/SKILL.md +132 -0
- package/skills/fastapi/references/banco.md +197 -0
- package/skills/fastapi/references/estrutura.md +325 -0
- package/skills/fastapi/references/integracoes.md +145 -0
- package/skills/fastapi/references/rotas-erros.md +140 -0
- package/skills/fastapi/references/testes-deploy.md +190 -0
- package/skills/fastapi/scripts/checar.mjs +108 -0
- package/skills/fastapi/scripts/nucleo.mjs +227 -0
- package/skills/hefesto/SKILL.md +119 -0
- package/skills/hefesto/references/conceitos.md +131 -0
- package/skills/hefesto/references/diagnostico.md +70 -0
- package/skills/hefesto/references/fluxo.md +122 -0
- package/skills/hefesto/references/preparar-app.md +105 -0
- package/skills/orfeu/SKILL.md +162 -0
- package/skills/orfeu/references/angular-api.md +201 -0
- package/skills/orfeu/references/angular-armadilhas.md +116 -0
- package/skills/orfeu/references/angular-recipes.md +474 -0
- package/skills/orfeu/references/angular.md +212 -0
- package/skills/orfeu/references/diferencas.md +56 -0
- package/skills/orfeu/references/node-api.md +354 -0
- package/skills/orfeu/references/node-armadilhas.md +158 -0
- package/skills/orfeu/references/node-recipes.md +541 -0
- package/skills/orfeu/references/node.md +204 -0
- package/skills/orfeu/references/python-api.md +346 -0
- package/skills/orfeu/references/python-recipes.md +479 -0
- package/skills/orfeu/references/python.md +240 -0
- package/skills/orfeu/scripts/checar.mjs +126 -0
- package/skills/orfeu/scripts/nucleo.mjs +227 -0
- package/skills/trismegisto/SKILL.md +194 -0
- package/skills/trismegisto/references/angular-api.md +2788 -0
- package/skills/trismegisto/references/angular-exports.md +4020 -0
- package/skills/trismegisto/references/angular-recipes.md +1883 -0
- package/skills/trismegisto/references/angular-types.md +492 -0
- package/skills/trismegisto/references/angular.md +390 -0
- package/skills/trismegisto/references/catalogo/icones.json +912 -0
- package/skills/trismegisto/references/catalogo/seletores.json +7013 -0
- package/skills/trismegisto/references/catalogo/tokens.json +240 -0
- package/skills/trismegisto/references/spine-api.md +1530 -0
- package/skills/trismegisto/references/spine-recipes.md +581 -0
- package/skills/trismegisto/references/spine.md +343 -0
- package/skills/trismegisto/scripts/checar.mjs +216 -0
- package/skills/trismegisto/scripts/nucleo.mjs +227 -0
|
@@ -0,0 +1,479 @@
|
|
|
1
|
+
# orfeu — receitas
|
|
2
|
+
|
|
3
|
+
Todas para a API 1.0.0. URLs e nomes de variáveis são exemplos; os nomes `ORFEU_*` são convenção do app
|
|
4
|
+
(a lib não lê ambiente).
|
|
5
|
+
|
|
6
|
+
Sumário: §1 app FastAPI protegido · §2 operação com permissão (`protected`) · §3 rota pública e opcional ·
|
|
7
|
+
§4 anotar o alvo na auditoria · §5 chamar outro serviço em nome do usuário · §6 chamar outro serviço como o
|
|
8
|
+
próprio serviço (e fora de requisição) · §7 WebSocket guardado · §8 log JSON · §9 testes · §10 cliente
|
|
9
|
+
avulso (script/worker) · §11 Strawberry · §12 Flask e Django · §13 armadilhas
|
|
10
|
+
|
|
11
|
+
---
|
|
12
|
+
|
|
13
|
+
## §1. App FastAPI protegido
|
|
14
|
+
|
|
15
|
+
```
|
|
16
|
+
app/
|
|
17
|
+
config.py
|
|
18
|
+
main.py
|
|
19
|
+
forms/router.py
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
`app/config.py`:
|
|
23
|
+
|
|
24
|
+
```python
|
|
25
|
+
import os
|
|
26
|
+
|
|
27
|
+
def orfeu_config() -> dict:
|
|
28
|
+
return {
|
|
29
|
+
"authorizer_url": os.environ["ORFEU_AUTHORIZER_URL"],
|
|
30
|
+
"realm_id": os.environ["ORFEU_REALM_ID"],
|
|
31
|
+
"app_id": os.environ["ORFEU_APP_ID"],
|
|
32
|
+
"secret": os.environ["ORFEU_SECRET"],
|
|
33
|
+
"tls_verify": os.environ.get("ORFEU_TLS_VERIFY", "true").lower() != "false",
|
|
34
|
+
}
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
`app/forms/router.py`:
|
|
38
|
+
|
|
39
|
+
```python
|
|
40
|
+
from fastapi import APIRouter, Request # Request no topo do módulo (ver §13)
|
|
41
|
+
from orfeu import Level, Method, NotFound, ok
|
|
42
|
+
from orfeu.adapters.fastapi import Envelope, operation
|
|
43
|
+
|
|
44
|
+
from .schemas import FormOut
|
|
45
|
+
from . import service
|
|
46
|
+
|
|
47
|
+
router = APIRouter(prefix="/forms", tags=["forms"])
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@router.get("", response_model=Envelope[list[FormOut]])
|
|
51
|
+
@operation(id="forms.list", level=Level.PRIVATE, method=Method.READ)
|
|
52
|
+
async def list_forms(request: Request):
|
|
53
|
+
# request.state.user é None se quem chamou usou x-api-token (backend); ver §13
|
|
54
|
+
return ok(await service.list_for(request.state.user.sub))
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@router.get("/{form_id}", response_model=Envelope[FormOut])
|
|
58
|
+
@operation(id="forms.get", level=Level.PRIVATE, method=Method.READ)
|
|
59
|
+
async def get_form(form_id: str):
|
|
60
|
+
form = await service.get(form_id)
|
|
61
|
+
if form is None:
|
|
62
|
+
raise NotFound("Formulário não encontrado.") # → 404 {status, message, data: null}
|
|
63
|
+
return ok(form)
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
`app/main.py`:
|
|
67
|
+
|
|
68
|
+
```python
|
|
69
|
+
from contextlib import asynccontextmanager
|
|
70
|
+
from fastapi import FastAPI
|
|
71
|
+
from orfeu.adapters.fastapi import Orfeu, install_envelope
|
|
72
|
+
|
|
73
|
+
from .config import orfeu_config
|
|
74
|
+
from .forms.router import router as forms_router # importa os módulos com @operation ANTES do startup
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
@asynccontextmanager
|
|
78
|
+
async def lifespan(app: FastAPI):
|
|
79
|
+
# recursos do app (banco, filas...). NÃO chame o orfeu aqui: ele roda antes deste bloco.
|
|
80
|
+
yield
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
app = FastAPI(lifespan=lifespan)
|
|
84
|
+
install_envelope(app)
|
|
85
|
+
app.include_router(forms_router, prefix="/api") # prefixos e routers aninhados são guardados
|
|
86
|
+
orfeu = Orfeu(app, **orfeu_config())
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
Resultado: no boot o catálogo `forms.list`/`forms.get` é sincronizado com o Argos; `GET /api/forms` sem
|
|
90
|
+
credencial → 401; com `x-access-token` de usuário com algum grupo → 200.
|
|
91
|
+
|
|
92
|
+
## §2. Operação com permissão (`protected`)
|
|
93
|
+
|
|
94
|
+
```python
|
|
95
|
+
from orfeu import Conflict, Level, Method, annotate_operation, ok
|
|
96
|
+
|
|
97
|
+
@router.post("", response_model=Envelope[FormOut], status_code=201)
|
|
98
|
+
@operation(id="forms.create", level=Level.PROTECTED, method=Method.WRITE)
|
|
99
|
+
async def create_form(payload: FormIn, request: Request):
|
|
100
|
+
if await service.exists(payload.slug):
|
|
101
|
+
raise Conflict("Já existe um formulário com esse identificador.")
|
|
102
|
+
form = await service.create(payload, owner=request.state.user.sub)
|
|
103
|
+
annotate_operation(target_type="form", target_id=form.id)
|
|
104
|
+
return ok(form, "Formulário criado.", 201)
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
- Quais grupos podem chamar `forms.create` é definido **no Argos** (grupos permitidos da operação). O código só
|
|
108
|
+
declara a operação; depois do primeiro deploy ela aparece no Argos para receber os grupos.
|
|
109
|
+
- Usuário válido fora desses grupos → **403** `"Insufficient permissions."` sem rodar o handler.
|
|
110
|
+
- Um `x-api-token` só passa se a operação `forms.create`/`write` foi concedida a esse token neste backend
|
|
111
|
+
(senão 401).
|
|
112
|
+
- Os grupos permitidos são lidos **no startup**. Depois de mudar os grupos no Argos, reinicie o serviço — ou
|
|
113
|
+
recarregue periodicamente:
|
|
114
|
+
|
|
115
|
+
```python
|
|
116
|
+
import asyncio, logging
|
|
117
|
+
from orfeu import OrfeuError
|
|
118
|
+
|
|
119
|
+
async def refresh_operations(orfeu, every: float = 300.0) -> None:
|
|
120
|
+
while True:
|
|
121
|
+
await asyncio.sleep(every)
|
|
122
|
+
try:
|
|
123
|
+
await orfeu.client.authenticate() # o token do app expira; fetch_operations não renova sozinho
|
|
124
|
+
await orfeu.client.fetch_operations()
|
|
125
|
+
except OrfeuError:
|
|
126
|
+
logging.getLogger(__name__).warning("falha ao recarregar operações", exc_info=True)
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
(dispare com `asyncio.create_task(refresh_operations(orfeu))` no seu lifespan e cancele no shutdown.)
|
|
130
|
+
|
|
131
|
+
Precisa de uma regra além dos grupos (ex.: só o dono edita)? Faça no handler e levante `Forbidden(...)` do
|
|
132
|
+
envelope — é uma regra de negócio, não da guarda:
|
|
133
|
+
|
|
134
|
+
```python
|
|
135
|
+
from orfeu import Forbidden
|
|
136
|
+
|
|
137
|
+
if form.owner != request.state.user.sub:
|
|
138
|
+
raise Forbidden("Só o autor pode alterar este formulário.")
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
## §3. Rota pública e rota opcional
|
|
142
|
+
|
|
143
|
+
```python
|
|
144
|
+
@router.get("/public/{slug}")
|
|
145
|
+
@operation(id="forms.public_get", level=Level.PUBLIC, method=Method.READ)
|
|
146
|
+
async def public_form(slug: str, request: Request):
|
|
147
|
+
user = getattr(request.state, "user", None) # pode não existir
|
|
148
|
+
return ok(await service.public_view(slug, viewer=user.sub if user else None))
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
@router.get("/feed")
|
|
152
|
+
@operation(id="forms.feed", level=Level.OPTIONAL, method=Method.READ)
|
|
153
|
+
async def feed(request: Request):
|
|
154
|
+
user = getattr(request.state, "user", None) # None = anônimo
|
|
155
|
+
return ok(await service.feed(personal_for=user.sub if user else None))
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
- `PUBLIC`: nunca bloqueia; credencial inválida é ignorada (roda anônimo).
|
|
159
|
+
- `OPTIONAL`: sem credencial roda anônimo; com credencial **inválida** → 401; com credencial válida exige
|
|
160
|
+
ao menos um grupo (igual a `PRIVATE`).
|
|
161
|
+
- Rotas públicas também geram log e auditoria (com `actor_type` `public` ou o ator real, se veio credencial
|
|
162
|
+
válida).
|
|
163
|
+
|
|
164
|
+
## §4. Anotar o alvo na auditoria
|
|
165
|
+
|
|
166
|
+
```python
|
|
167
|
+
from orfeu import annotate_operation
|
|
168
|
+
|
|
169
|
+
@router.put("/{form_id}")
|
|
170
|
+
@operation(id="forms.update", level=Level.PROTECTED, method=Method.WRITE)
|
|
171
|
+
async def update_form(form_id: str, payload: FormIn):
|
|
172
|
+
annotate_operation(target_type="form", target_id=form_id) # já no início: vale até em erro
|
|
173
|
+
changed = await service.update(form_id, payload)
|
|
174
|
+
annotate_operation(details={"campos": sorted(changed)}) # mesclado ao anterior
|
|
175
|
+
return ok({"id": form_id}, "Formulário atualizado.")
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
@router.delete("/{form_id}")
|
|
179
|
+
@operation(id="forms.delete", level=Level.PROTECTED, method=Method.DELETE)
|
|
180
|
+
async def delete_form(form_id: str):
|
|
181
|
+
annotate_operation(target_type="form", target_id=form_id)
|
|
182
|
+
await service.delete(form_id)
|
|
183
|
+
return ok(form_id, "Formulário removido.")
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
- Anote **assim que o alvo for conhecido** — se o handler levantar depois, o evento de falha já leva o alvo.
|
|
187
|
+
- `details` é para contexto pequeno e não sensível (nomes de campos, quantidade, motivo). Nada de valores
|
|
188
|
+
pessoais, segredos ou tokens; acima de 4 KB vira `{"truncated": true, ...}`.
|
|
189
|
+
- Fora de chamada guardada (`@operation` ausente, job em segundo plano) `annotate_operation` devolve `False`.
|
|
190
|
+
- Em serviço de domínio chamado pelo handler, pode chamar `annotate_operation` lá dentro: o contexto é por
|
|
191
|
+
`ContextVar` e segue a mesma task.
|
|
192
|
+
|
|
193
|
+
## §5. Chamar outro serviço em nome do usuário (propagando o trace)
|
|
194
|
+
|
|
195
|
+
```python
|
|
196
|
+
import httpx
|
|
197
|
+
from fastapi import Request
|
|
198
|
+
from orfeu import EnvelopeError, Level, Method, Unavailable, ok
|
|
199
|
+
from orfeu.adapters.fastapi import operation, orfeu_headers
|
|
200
|
+
|
|
201
|
+
REPORTS_URL = settings.reports_url # configuração do app
|
|
202
|
+
|
|
203
|
+
@router.post("/{form_id}/report")
|
|
204
|
+
@operation(id="forms.report", level=Level.PROTECTED, method=Method.WRITE)
|
|
205
|
+
async def build_report(form_id: str, request: Request):
|
|
206
|
+
try:
|
|
207
|
+
async with httpx.AsyncClient(timeout=10.0) as http:
|
|
208
|
+
r = await http.post(f"{REPORTS_URL}/reports", json={"form_id": form_id},
|
|
209
|
+
headers=orfeu_headers(request))
|
|
210
|
+
except httpx.RequestError:
|
|
211
|
+
raise Unavailable("Serviço de relatórios indisponível.")
|
|
212
|
+
body = r.json()
|
|
213
|
+
if r.status_code >= 400:
|
|
214
|
+
raise EnvelopeError(body.get("message") or "Falha ao gerar o relatório.", r.status_code)
|
|
215
|
+
return ok(body["data"], "Relatório solicitado.")
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
- `orfeu_headers(request)` leva `traceparent` (o evento do outro serviço fica com o mesmo `trace_id`,
|
|
219
|
+
`entry=False` e este span como pai), `x-route-id`/`x-client-id` e a credencial do usuário
|
|
220
|
+
(`x-access-token` ou `x-app-token`). O outro serviço decide a permissão **do usuário** lá.
|
|
221
|
+
- O `x-api-token` recebido nunca é repassado (ele identifica quem chamou este serviço, não o usuário).
|
|
222
|
+
- Não junte `Authorization`: o orfeu do outro lado ignora.
|
|
223
|
+
|
|
224
|
+
## §6. Chamar outro serviço como o próprio serviço (e fora de requisição)
|
|
225
|
+
|
|
226
|
+
Quando a ação é do serviço (não do usuário), use um token de API emitido no Argos **para o serviço de
|
|
227
|
+
destino**, com as operações necessárias concedidas, e mantenha só a correlação:
|
|
228
|
+
|
|
229
|
+
```python
|
|
230
|
+
API_TOKEN = os.environ["REPORTS_API_TOKEN"] # nome escolhido pelo app; nunca no código
|
|
231
|
+
|
|
232
|
+
headers = {**orfeu_headers(request, credential=False), "x-api-token": API_TOKEN}
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
Fora de uma requisição (job agendado, consumidor de fila) não há contexto: `orfeu_headers(...)` devolve `{}`.
|
|
236
|
+
Comece um trace para correlacionar as chamadas do job:
|
|
237
|
+
|
|
238
|
+
```python
|
|
239
|
+
from orfeu import format_traceparent, resolve_trace
|
|
240
|
+
|
|
241
|
+
trace = resolve_trace(None) # trace novo, entry=True
|
|
242
|
+
headers = {"traceparent": format_traceparent(trace), "x-api-token": API_TOKEN}
|
|
243
|
+
```
|
|
244
|
+
|
|
245
|
+
## §7. WebSocket guardado
|
|
246
|
+
|
|
247
|
+
```python
|
|
248
|
+
from fastapi import WebSocket
|
|
249
|
+
|
|
250
|
+
@app.websocket("/ws/forms/{form_id}")
|
|
251
|
+
@operation(id="forms.watch", level=Level.PRIVATE, method=Method.STREAM)
|
|
252
|
+
async def watch_form(websocket: WebSocket, form_id: str):
|
|
253
|
+
user = websocket.state.user # TokenClaims (ou None + websocket.state.api_token)
|
|
254
|
+
await websocket.accept()
|
|
255
|
+
async for event in service.events(form_id):
|
|
256
|
+
await websocket.send_json(event)
|
|
257
|
+
```
|
|
258
|
+
|
|
259
|
+
- Mesmos 3 headers no handshake e mesma regra do HTTP. Negação → fecha com **1008** antes do `accept`.
|
|
260
|
+
- Navegador não manda header customizado em WebSocket: o cliente precisa ser um backend/ferramenta que
|
|
261
|
+
envie `x-access-token` no handshake (ou use Strawberry/graphql-ws, §11, que lê do `connection_init`).
|
|
262
|
+
- A sessão inteira é uma operação (um log, um evento de auditoria ao fechar).
|
|
263
|
+
|
|
264
|
+
## §8. Log JSON
|
|
265
|
+
|
|
266
|
+
```python
|
|
267
|
+
import logging
|
|
268
|
+
from orfeu import JsonLogFormatter
|
|
269
|
+
|
|
270
|
+
handler = logging.StreamHandler()
|
|
271
|
+
handler.setFormatter(JsonLogFormatter())
|
|
272
|
+
log = logging.getLogger("orfeu")
|
|
273
|
+
log.addHandler(handler)
|
|
274
|
+
log.setLevel(logging.INFO)
|
|
275
|
+
log.propagate = False # evita linha duplicada se o root também tiver handler
|
|
276
|
+
```
|
|
277
|
+
|
|
278
|
+
Saída (uma linha):
|
|
279
|
+
|
|
280
|
+
```json
|
|
281
|
+
{"timestamp": "2026-01-01T12:00:00.123456Z", "level": "INFO", "logger": "orfeu.operation", "message": "operação executada", "operation": "forms.list", "operation_method": "read", "operation_level": "private", "agent_id": "…", "actor_type": "user", "permission_result": "allowed", "duration_ms": 3.21, "user": "…", "trace_id": "…", "span_id": "…"}
|
|
282
|
+
```
|
|
283
|
+
|
|
284
|
+
Com uma biblioteca de log estruturado já configurada no app, basta ler os atributos de
|
|
285
|
+
`OPERATION_LOG_FIELDS` do `LogRecord`.
|
|
286
|
+
|
|
287
|
+
## §9. Testes
|
|
288
|
+
|
|
289
|
+
Princípios: app real, `TestClient` do FastAPI, sem rede — troque só os métodos do cliente que falam com o
|
|
290
|
+
Argos. Desligue a auditoria (`audit=False`) ou capture os eventos.
|
|
291
|
+
|
|
292
|
+
```python
|
|
293
|
+
# tests/conftest.py
|
|
294
|
+
from unittest.mock import AsyncMock, MagicMock
|
|
295
|
+
import pytest
|
|
296
|
+
from fastapi.testclient import TestClient
|
|
297
|
+
from orfeu.models import ApiTokenClaims, TokenClaims
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def claims(sub="11111111-1111-4111-8111-111111111111", groups=("g1",)):
|
|
301
|
+
return TokenClaims(sub=sub, realm_id="realm", groups=list(groups), exp=9_999_999_999, raw={})
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
@pytest.fixture()
|
|
305
|
+
def client(monkeypatch):
|
|
306
|
+
# app.main lê ORFEU_* do ambiente na importação: defina valores falsos no ambiente de teste
|
|
307
|
+
from app.main import app, orfeu
|
|
308
|
+
monkeypatch.setattr(orfeu.client, "startup", AsyncMock()) # lifespan sem rede
|
|
309
|
+
monkeypatch.setattr(orfeu.client, "validate_token", AsyncMock(return_value=claims()))
|
|
310
|
+
monkeypatch.setattr(orfeu.client, "check_permission", MagicMock(return_value=True))
|
|
311
|
+
monkeypatch.setattr(orfeu.client, "_audit_sink", None) # sem auditoria
|
|
312
|
+
with TestClient(app) as http: # roda o lifespan
|
|
313
|
+
yield http, orfeu
|
|
314
|
+
```
|
|
315
|
+
|
|
316
|
+
```python
|
|
317
|
+
from orfeu import OrfeuTokenError
|
|
318
|
+
|
|
319
|
+
def test_sem_credencial_401(client):
|
|
320
|
+
http, _ = client
|
|
321
|
+
r = http.get("/api/forms")
|
|
322
|
+
assert r.status_code == 401 and r.json()["message"] == "Invalid or missing credentials."
|
|
323
|
+
|
|
324
|
+
def test_token_invalido_401(client, monkeypatch):
|
|
325
|
+
http, orfeu = client
|
|
326
|
+
monkeypatch.setattr(orfeu.client, "validate_token", AsyncMock(side_effect=OrfeuTokenError("expirado")))
|
|
327
|
+
assert http.get("/api/forms", headers={"x-access-token": "x"}).status_code == 401
|
|
328
|
+
|
|
329
|
+
def test_sem_permissao_403(client):
|
|
330
|
+
http, orfeu = client
|
|
331
|
+
orfeu.client.check_permission.return_value = False
|
|
332
|
+
assert http.get("/api/forms", headers={"x-access-token": "x"}).status_code == 403
|
|
333
|
+
|
|
334
|
+
def test_token_de_api(client, monkeypatch):
|
|
335
|
+
http, orfeu = client
|
|
336
|
+
monkeypatch.setattr(orfeu.client, "validate_api_token",
|
|
337
|
+
AsyncMock(return_value=ApiTokenClaims(token_id="t-1", app_id="a-1")))
|
|
338
|
+
r = http.get("/api/forms/1", headers={"x-api-token": "y"})
|
|
339
|
+
assert r.status_code != 401 # passou pela guarda; no handler, request.state.user é None
|
|
340
|
+
```
|
|
341
|
+
|
|
342
|
+
Capturar a auditoria:
|
|
343
|
+
|
|
344
|
+
```python
|
|
345
|
+
from orfeu.audit import AuditOptions, AuditSink
|
|
346
|
+
|
|
347
|
+
sent: list[dict] = []
|
|
348
|
+
orfeu.client._audit_sink = AuditSink(lambda batch: sent.extend(batch) or 202, AuditOptions(flush_interval=60))
|
|
349
|
+
# ... faça a requisição ...
|
|
350
|
+
orfeu.client.flush_audit()
|
|
351
|
+
(event,) = sent
|
|
352
|
+
assert event["target_type"] == "form" and event["outcome"] == "success"
|
|
353
|
+
```
|
|
354
|
+
|
|
355
|
+
Logs: `caplog.set_level(logging.INFO, logger="orfeu.operation")` e leia `record.permission_result`,
|
|
356
|
+
`record.operation` etc.
|
|
357
|
+
|
|
358
|
+
Cuidados:
|
|
359
|
+
- O registro de `@operation` é **global do processo**. Ao montar apps de teste em funções (`def build_app()`),
|
|
360
|
+
chame `orfeu.decorators.clear_registry()` antes de declarar as rotas.
|
|
361
|
+
- Com `from __future__ import annotations`, importe `Request`/`WebSocket` no topo do módulo de teste/rota: o
|
|
362
|
+
FastAPI resolve a anotação nos globais do módulo; importado dentro da função, `request` vira parâmetro de
|
|
363
|
+
query obrigatório (422).
|
|
364
|
+
- `check_permission` mockado ignora o nível; para testar a regra real, deixe `check_permission` original e
|
|
365
|
+
preencha `orfeu.client._operations` com `OperationWithGroups(...)` (interno, como a suíte do pacote faz).
|
|
366
|
+
|
|
367
|
+
## §10. Cliente avulso (script, worker, framework sem adapter)
|
|
368
|
+
|
|
369
|
+
```python
|
|
370
|
+
import asyncio
|
|
371
|
+
from orfeu import Level, Method, OperationDescriptor, OrfeuClient, OrfeuTokenError
|
|
372
|
+
|
|
373
|
+
client = OrfeuClient(url, realm, app_id, secret, audit=False)
|
|
374
|
+
client.register_operation(OperationDescriptor("reports.run", Method.WRITE, Level.PROTECTED))
|
|
375
|
+
|
|
376
|
+
async def main(raw_jwt: str) -> None:
|
|
377
|
+
await client.startup() # token → JWKS → sync → operações
|
|
378
|
+
try:
|
|
379
|
+
claims = await client.validate_token(raw_jwt)
|
|
380
|
+
except OrfeuTokenError:
|
|
381
|
+
raise SystemExit("credencial inválida")
|
|
382
|
+
if not client.check_permission(claims, "reports.run", Method.WRITE):
|
|
383
|
+
raise SystemExit("sem permissão")
|
|
384
|
+
...
|
|
385
|
+
|
|
386
|
+
asyncio.run(main(token))
|
|
387
|
+
```
|
|
388
|
+
|
|
389
|
+
- Código síncrono: `client.run_sync(client.startup())` e `client.run_sync(client.validate_token(t))` (loop
|
|
390
|
+
dedicado do cliente; nunca `asyncio.run()` por chamada num servidor).
|
|
391
|
+
- `startup()` sem nenhuma operação registrada levanta `OrfeuConfigError`.
|
|
392
|
+
- Para um framework sem adapter, monte a decisão com as mesmas peças dos adapters: `orfeu.guard.decide`,
|
|
393
|
+
`orfeu.guard.CallContext` e `record_operation` — prefira, porém, um dos adapters prontos.
|
|
394
|
+
|
|
395
|
+
## §11. Strawberry (GraphQL) dentro do FastAPI
|
|
396
|
+
|
|
397
|
+
```python
|
|
398
|
+
import strawberry
|
|
399
|
+
from contextlib import asynccontextmanager
|
|
400
|
+
from fastapi import FastAPI
|
|
401
|
+
from strawberry.fastapi import GraphQLRouter
|
|
402
|
+
from orfeu import Level, Method
|
|
403
|
+
from orfeu.adapters.strawberry import Orfeu, operation
|
|
404
|
+
|
|
405
|
+
orfeu = Orfeu(**orfeu_config())
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
@strawberry.type
|
|
409
|
+
class Query:
|
|
410
|
+
@strawberry.field
|
|
411
|
+
@operation(id="forms.list", level=Level.PRIVATE, method=Method.READ)
|
|
412
|
+
async def forms(self, info: strawberry.Info) -> list[Form]:
|
|
413
|
+
user = info.context["orfeu_user"] # None em campo opcional anônimo / token de API
|
|
414
|
+
return await service.list_for(user.sub)
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
schema = strawberry.Schema(query=Query, extensions=[orfeu.extension])
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
@asynccontextmanager
|
|
421
|
+
async def lifespan(app: FastAPI):
|
|
422
|
+
await orfeu.startup_async() # obrigatório aqui: o adapter Strawberry não liga sozinho
|
|
423
|
+
yield
|
|
424
|
+
orfeu.client.flush_audit()
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
app = FastAPI(lifespan=lifespan)
|
|
428
|
+
app.include_router(GraphQLRouter(schema), prefix="/graphql")
|
|
429
|
+
```
|
|
430
|
+
|
|
431
|
+
Negação vira erro GraphQL com `extensions = {"code": "UNAUTHENTICATED", "status": 401}` ou
|
|
432
|
+
`{"code": "FORBIDDEN", "status": 403}`. Cada campo guardado é uma operação. Repasse: `orfeu_headers(info.context)`.
|
|
433
|
+
Não instale também o `Orfeu` do FastAPI no mesmo app para guardar as mesmas operações (seriam dois clientes
|
|
434
|
+
sincronizando o mesmo registro).
|
|
435
|
+
|
|
436
|
+
## §12. Flask e Django
|
|
437
|
+
|
|
438
|
+
Flask — o startup roda **na construção**, então declare/importe as rotas antes:
|
|
439
|
+
|
|
440
|
+
```python
|
|
441
|
+
from flask import Flask, g
|
|
442
|
+
from orfeu import Level, Method
|
|
443
|
+
from orfeu.adapters.flask import Orfeu, operation, orfeu_headers
|
|
444
|
+
|
|
445
|
+
app = Flask(__name__)
|
|
446
|
+
|
|
447
|
+
@app.get("/forms")
|
|
448
|
+
@operation(id="forms.list", level=Level.PRIVATE, method=Method.READ)
|
|
449
|
+
def list_forms():
|
|
450
|
+
return {"status": 200, "message": "", "data": service.list_for(g.orfeu_user.sub)}
|
|
451
|
+
|
|
452
|
+
Orfeu(app, **orfeu_config()) # depois das rotas
|
|
453
|
+
```
|
|
454
|
+
|
|
455
|
+
Django — `"orfeu.adapters.django.OrfeuMiddleware"` em `MIDDLEWARE` e os settings `ORFEU_AUTHORIZER_URL`,
|
|
456
|
+
`ORFEU_REALM_ID`, `ORFEU_APP_ID`, `ORFEU_SECRET` (opcionais `ORFEU_TLS_VERIFY`, `ORFEU_AUDIT`) lidos do
|
|
457
|
+
ambiente no `settings.py`. Na view decorada com `@operation`: `request.orfeu_user` /
|
|
458
|
+
`request.orfeu_api_token`; `annotate_operation(...)` e `orfeu_headers(request)` como no FastAPI. As views
|
|
459
|
+
precisam estar importadas (via `urls.py`) quando o middleware é construído.
|
|
460
|
+
|
|
461
|
+
## §13. Armadilhas
|
|
462
|
+
|
|
463
|
+
| Sintoma | Causa | Correção |
|
|
464
|
+
|---|---|---|
|
|
465
|
+
| Rota responde sem pedir credencial | sem `@operation`, ou um decorator entre a rota e `@operation` sem `functools.wraps` apagou os atributos | `@operation` logo abaixo de `@router.get(...)`; wrappers com `functools.wraps` |
|
|
466
|
+
| App não sobe: `OrfeuConfigError: No operations registered` | nenhum módulo com `@operation` importado antes do lifespan | importe os routers no `main` antes de servir |
|
|
467
|
+
| 403 numa operação recém-criada, mesmo com grupo certo | módulo importado **depois** do startup (fora do sync), ou grupos alterados no Argos depois do boot | importe tudo antes do startup; reinicie ou recarregue (§2) |
|
|
468
|
+
| `AttributeError: 'State' object has no attribute 'user'` | leitura direta de `request.state.user` em `public`/`optional` anônimo | `getattr(request.state, "user", None)` |
|
|
469
|
+
| `request.state.user` é `None` numa rota `private` | chamada com `x-api-token` (backend) | leia `request.state.api_token` nesse caso |
|
|
470
|
+
| 401 mesmo mandando `Authorization: Bearer ...` | o orfeu não lê `Authorization` | mande em `x-access-token` (JWT) / `x-app-token` / `x-api-token` |
|
|
471
|
+
| 401 em `optional` | credencial presente e inválida nunca vira anônima | não mande credencial vencida; trate o 401 no cliente |
|
|
472
|
+
| Operação mudou de `write` para `read` sozinha | `method` inferido do nome da função, que foi renomeada | passe `method=` explícito |
|
|
473
|
+
| `request` virou parâmetro de query (422) | `from __future__ import annotations` + `Request` importado dentro de função | importe `Request` no topo do módulo |
|
|
474
|
+
| Evento de auditoria sem alvo | `annotate_operation` chamado numa task/thread iniciada depois da resposta, ou fora de `@operation` | chame no fluxo do handler, antes de retornar |
|
|
475
|
+
| `route_id`/`client_id` não aparecem na auditoria | `x-route-id`/`x-client-id` não estão em formato GUID | mande o id GUID (no log eles aparecem como vieram) |
|
|
476
|
+
| Eventos perdidos ao encerrar | processo morto sem shutdown gracioso | deixe o lifespan terminar; em scripts, `client.flush_audit()` |
|
|
477
|
+
| 500 `route_unresolved` | a guarda não conseguiu reproduzir o roteamento (internos do FastAPI mudaram) | é falha fechada de propósito; atualize o orfeu e veja o logger `orfeu.guard` |
|
|
478
|
+
| Testes vazando operações entre si | registro global de `@operation` | `orfeu.decorators.clear_registry()` ao montar cada app de teste |
|
|
479
|
+
| `tls_verify=False` em produção | atalho de desenvolvimento esquecido | use certificado válido; o parâmetro só afeta chamadas ao Argos, mas ainda assim desliga a verificação |
|