# BeryX — Segurança e conformidade

> Documento público. É a resposta-padrão de segurança para RFPs e a fonte da secção
> «Segurança e conformidade» da página `/rfp` do site. Cada secção diz o que
> garantimos, onde está no código e que teste o prova. Não afirmamos nada que não esteja aqui.

## Acesso read-only mecânico

O BeryX lê metadados, agregados e amostras limitadas — nunca escreve, move nem altera dados
nas fontes do cliente. Não é só convenção nem só permissões pedidas ao cliente: a garantia é
imposta no código.

- **Conectores HTTP** (Jira, Confluence, Databricks, SharePoint, Google Drive, …) só saem para a
  rede pelo `ReadOnlyHttpClient` (`app/infra/connectors/http_guard.py`): GET/HEAD/OPTIONS passam;
  POST/PUT/PATCH/DELETE são recusados **antes** de tocar na rede.
- **Nenhum conector pode expor um método de escrita**: o decorator `enforce_read_only` recusa na
  definição da classe qualquer método com nome de escrita, e um teste percorre todos os conectores
  registados.
- **PostgreSQL**: as sessões de profiling abrem com `default_transaction_read_only=on` e
  `statement_timeout` — uma escrita, mesmo escondida numa função ou view, falha no servidor.
- **Snowflake (varredura de engenharia)**: `assert_catalog_statement` recusa tudo o que não seja
  um único `SHOW`/`SELECT`/`DESCRIBE` antes de chegar ao driver.
- **Ensaio de uma correção**: o passo 1 de uma sugestão é contado na fonte numa sessão só de leitura,
  e o passo 2 nunca corre. Pode ler outra tabela da mesma conexão (cartão #1405) só se quem pede o
  ensaio a vê, confirmado outra vez antes da contagem. Não conta o que dependa de colunas sensíveis
  que essa pessoa não vê, e o número não aparece a quem não lê todas as tabelas contadas
  (`app/domain/insights/rehearsal_access.py`).
- Recomendamos sempre um utilizador de serviço com permissões só de leitura — os passos por fonte
  estão no [guia de conectores](CONECTORES.md).

Testes: `backend/tests/test_http_guard.py`, `backend/tests/test_connectors_registry.py`,
`backend/tests/test_rehearsal_joins_1405.py`.

## Isolamento entre clientes (multi-tenant)

Cada cliente é um workspace, e o workspace é a fronteira dos dados. Um pedido autenticado resolve
sempre o workspace da sessão ou do token de API (`get_current_workspace`, `app/api/deps.py`), e
cada rota só lê e altera recursos desse workspace. A equipa da BeryxTech só lê outro workspace com um
acesso de suporte que um administrador desse cliente aprovou. Esse acesso tem prazo, é só de
leitura e fica no registo de auditoria.

Sem esse acesso, a app de gestão da equipa mostra só metadados dos clientes: o nome do workspace e
da organização, o plano, o uso e os números dos pedidos de ajuda. Com a app de gestão ligada, todas
as rotas dela pedem a sessão aberta lá, com a autenticação de dois fatores. A ficha do cliente, a
faturação e os pedidos de ajuda (a lista, o feedback, as contagens, a conversa e os anexos) pedem
também a autenticação de dois fatores ativa no próprio pedido, por isso uma conta da equipa que a
desligou deixa de os ler mesmo com uma sessão ainda válida. Os pedidos de ajuda leem-nos só o papel
de suporte e o owner da equipa: a faturação e o comercial recebem 403.

**Isolamento provado por teste sobre todas as rotas.** A garantia não depende de alguém se lembrar
de testar cada endpoint novo. O teste percorre as rotas registadas da API, com dois clientes de
teste, A e B, semeados com um recurso de cada espécie:

- **Entre clientes.** Cada rota com um id no caminho recebe os ids de A e é chamada pelo
  administrador de B, o papel mais permissivo, e pelo token de API de B. Nunca pode responder 2xx
  nem 5xx. A recusa tem de ser igual à de um id que não existe, para que B nem saiba se o id de A
  existe. As rotas com o id no corpo ou na query passam pelo mesmo teste. Nas listagens,
  agregados e exports, nenhuma resposta a B pode conter um id ou email de A.
- **Controlo positivo.** O mesmo pedido feito por A chega aos seus recursos. Sem isto, o 404 de B
  não provava nada. O teste imprime a cobertura em cada execução do CI e falha abaixo de 90 % das
  rotas com id de cliente.
- **Sem sessão.** Todas as rotas respondem 401, exceto uma lista explícita e comentada de rotas
  públicas: saúde, login, SSO, webhooks assinados e links públicos por token. Essa lista tem de
  ser igual à tabela de decisão de acesso.
- **Papéis.** O perfil só de leitura recebe 403 em todas as alterações. Ficam de fora só o
  self-service da conta, o pedido de ajuda, o assistente, o feedback e a decisão de confiança em
  lote, que é uma leitura. O token de API só escreve nas operações previstas.
- **Rotas novas.** Uma rota nova com um parâmetro que o teste não sabe preencher faz o teste
  falhar. Só volta a passar quando a rota entra na matriz ou numa lista justificada.
- **Rotas entre workspaces por desenho.** A consola da equipa da BeryxTech, a organização e a pesquisa
  federada são provadas à parte, cada uma na sua fronteira. Por exemplo, um acesso de suporte sem
  aprovação recebe 403 em todas as leituras.
- **O teste também morde.** Um router de exemplo sem filtro de workspace é apanhado pelo mesmo
  varrimento.

Testes: `backend/tests/test_tenant_isolation_matrix.py`. As permissões por domínio dentro de um
workspace estão em `backend/tests/test_access_matrix.py`.

**Dentro do workspace, o handler repete a guarda.** A guarda central decide cada rota pela tabela de
decisão (`backend/app/domain/access/decision_table.py`). Os handlers dos incidentes voltam a
decidir, para uma falha na guarda não abrir o acesso: uma raiz que a pessoa não vê responde como
um incidente que não existe, e o diagnóstico (`POST /incidents/{incident_id}/diagnose`) pede
escrita em todos os datasets envolvidos antes de pôr o relatório na fila. Teste:
`backend/tests/test_access_grants.py`, com a guarda central desligada.

## Amostras: o que sai da fonte e o que fica

O que um scan lê das tuas fontes, onde é processado e o que fica guardado:

- **Perfil nas fontes SQL: agregados.** Nas bases e warehouses SQL, o perfil (contagens, nulos,
  distintos, mínimos e máximos) é calculado por SQL na própria fonte. Só voltam os números e uma
  amostra de até 1 000 linhas das colunas perfiladas (`VALUE_SAMPLE_ROWS`,
  `app/infra/connectors/sql.py`), lida em memória no worker para tirar até 20 valores de exemplo
  por coluna, que alimentam os tipos semânticos e a deteção de PII; só esses valores ficam
  gravados. Até à versão anterior eram 20 valores por coluna, numa query por coluna. Por cada
  valor das colunas categóricas (até 3 colunas, de 2 a 50 valores) voltam também as linhas, os
  nulos e a soma de até 3 colunas numéricas, e as linhas por hora do dia da coluna de frescura
  (cartão #1255). Uma coluna classificada como pessoal ou confidencial, ou que a deteção de PII
  reconhece no perfil, não é somada, e só fica gravada a soma dos valores com 30 registos ou
  mais. Uma coluna classificada depois do scan fica mascarada também nessas somas, nos valores da
  dimensão e na hora do dia, para quem não tem clearance. O valor do segmento de uma anomalia por
  segmento, do drill-down de uma anomalia do total (cartão #1379) ou da regra «nunca mais» que dela
  nasce não vai a títulos, descrições, ao sino, a emails, a webhooks, a tickets nem a prompts: o
  problema guarda um HMAC com a chave da instalação, o workspace e o dataset
  (rodar o `jwt_secret` muda-o, e o problema fica só com a dimensão até ao scan seguinte), e a condição
  da regra sai com os literais tapados. Quem pode ver o valor lê-o na explicação da anomalia, do
  perfil do scan. Um drift de distribuição segue a mesma regra (cartão #1399): o problema guarda as
  quotas de cada categoria, com o mesmo HMAC, e dos quantis de uma coluna numérica só a variação em
  percentagem; as categorias e os quantis leem-se na explicação, com a máscara. A regra que o perfil
  propõe para uma coluna sensível diz a família, a margem e as contagens, sem o mínimo, o máximo, as
  categorias nem a média (cartão #1408); só um administrador a aceita, e a regra criada lê-os do último
  perfil e mostra-os na página dela, como qualquer regra. Classificar a coluna tira-os logo das
  sugestões que já existiam. Um documento que sai da app também não os leva, seja quem for que o pede
  (cartão #1407): o export de um relatório desenha o histograma de uma coluna sensível só com as
  contagens, e o link público e o email agendado não o desenham. Quando dois segmentos de colunas
  diferentes saem do padrão na mesma coluna, voltam também as linhas, os nulos e a soma por par de valores dessas duas colunas, que
  não ficam gravados. Da média de um segmento, o problema guarda só a variação relativa. As
  linhas por hora do dia só se leem nos datasets que o pediram. Nas
  fontes sem SQL (ficheiros, APIs de SaaS, streaming), o conector lê os registos pela API oficial
  e o perfil é calculado no worker; o [guia de conectores](CONECTORES.md) diz o que lê cada uma.
- **Regras de linha e duplicados: uma amostra de até 5 000 linhas por tabela.** Em cada scan, as
  regras que precisam de linhas e a deteção de duplicados leem no máximo 5 000 linhas por tabela
  (`ROW_FETCH_LIMIT`, `app/domain/scans/service.py`), escolhidas pela amostragem da própria
  fonte (`TABLESAMPLE`/`SAMPLE`), pelo hash da chave primária ou, sem nenhum dos dois, pelas
  primeiras linhas ([método](METODOS.md#amostragem)). É um teto, que vale também para a amostra
  do perfil: o DBA pode baixá-lo por fonte, até um mínimo de 100 linhas (`max_sample_rows`,
  «Boa vizinhança com o DBA»). As linhas são processadas em memória no worker, na UE (Google
  Cloud europe-west1); dessa leitura só ficam gravados os exemplos limitados descritos abaixo.
- **Leituras maiores só quando as pedes.** A qualidade de rótulos (nos datasets em que a
  configuras), o data-diff e a correspondência entre datasets leem até 50 000 linhas por tabela,
  também em memória no worker.
- **O que fica guardado, na UE:** perfis, agregados, resultados de regras e scores, e exemplos
  limitados — por exemplo, até 20 valores por coluna no perfil, até 5 linhas por grupo de
  duplicados e até 5 valores truncados por regra violada. A tabela nunca é copiada para o
  BeryX.
- **Os embeddings não se guardam nem vão ao modelo, em nenhuma fonte.** Conta como embedding uma
  lista, um array ou um texto com 32 números ou mais, e um binário com 32 bytes ou mais, qualquer
  que seja o tipo da coluna (`app/infra/serialization.py`). O perfil dessa coluna fica sem amostra,
  mínimo e máximo. Na amostra de um grupo de duplicados e no contexto da IA, o valor passa a um
  marcador só com o comprimento (`{"omitted": "vector", "length": 768}`), e num exemplo de regra a
  `<vector:768>`. A coluna fica fora dos segmentos e das sugestões de valores aceites e de
  normalização. Ao modelo só chegam valores escalares das linhas de exemplo: uma lista ou um
  objeto vão como marcador (`app/infra/llm/prompts.py`). As regras continuam a avaliar o valor
  real, e um array curto (coordenadas, uma cor RGB) ou uma chave `BINARY(16)` ficam como estão.
- **Com IA ativa, os exemplos enviados ao modelo seguem a política de IA do workspace.** Por
  omissão vão à Anthropic, que os processa nos EUA com cláusulas contratuais-tipo. Para ficarem na
  UE, desliga a IA ou usa o Claude na tua conta Google Cloud, no Vertex AI (plano Enterprise; o
  Amazon Bedrock vem a seguir) — ver «Os teus modelos» e «Anonimização antes do LLM», abaixo.
- **Execução no teu Databricks (ADR 0005, degrau B): ainda não corre nos scans.** O pacote
  `beryx-profiler`, que lê a tabela completa na tua conta e devolve só métricas, e o cliente
  da Jobs API já existem no código, mas nenhum scan o submete ainda. Até lá, também no Databricks
  as regras de linha e os duplicados usam a amostra acima.
- **Não temos hoje um modo em que nenhuma linha saia da tua rede** (on-prem ou air-gapped). Um
  runner no teu perímetro (degrau C do mesmo ADR) depende de procura real.

Testes: `backend/tests/test_seguranca_amostras.py` (os números e o estado do Databricks acima são
comparados com o código).

## Índices vetoriais: a sensibilidade vem das fontes

Um embedding são números, e neles não dá para procurar dados pessoais. O BeryX não lê os vetores: a
sensibilidade de um índice vetorial vem das fontes e vale tanto como a linhagem declarada.

- **A origem declara-se.** Um admin diz, na ficha do índice, de que datasets vieram os vetores
  (`POST /api/v1/lineage/vector-origins`). Sem nenhuma origem, o índice mostra a lacuna «Origem por
  declarar» e não herda nada.
- **As colunas vetoriais herdam.** Se uma origem tem colunas `pii` ou `confidential`, ou PII detetado
  que a curadoria não desclassificou, as colunas vetoriais do índice recebem o nível mais alto, com a
  origem `lineage`. A clearance e as guardas dos agentes de IA aplicam-se como a qualquer coluna
  classificada, e no go-live o item `classification_verified` conta esta classificação.
- **A herança só sobe.** Classificar a origem depois chega ao índice na mesma transação, sem correr
  o scan dele. Desclassificar a origem ou apagar a aresta não desce o índice: baixar uma coluna
  herdada é de um admin ou do owner de um domínio do dataset, e fica no rasto. Uma classificação
  manual fica como está, mesmo abaixo das origens, e a ficha mostra um aviso.
- **As outras colunas seguem o caminho normal.** As de texto e metadados ao lado da coluna vetorial
  passam pela deteção de PII de sempre, e no go-live continuam a pedir uma pessoa.

**Limites.** A herança segue um salto a partir da origem declarada, mais os índices em cadeia. Uma
vista intermédia sem classificação não conta. Uma origem por declarar ou errada deixa o índice sem a
classificação que devia ter, e um dado pessoal que a origem não tenha classificado nem detetado não
chega ao índice.

Testes: `backend/tests/test_vector_sensitivity.py`.

## Índices vetoriais: quem lê o índice e não lê a origem

Um índice vetorial feito de uma tabela restrita pode ficar legível por quem não lê essa tabela, e uma
aplicação RAG sobre ele devolve-lhe o que a origem lhe esconde. É o primeiro risco da lista do OWASP
GenAI Security Project, «LLM08:2025 Vector and Embedding Weaknesses». A herança da sensibilidade, na
secção anterior, fecha o caminho pelo BeryX (os tokens dos agentes). O acesso direto na fonte vê-se
aqui, no add-on «Segurança de IA e de dados».

- **Os pares.** Cada origem declarada de um índice, na mesma conexão ou noutra. Um índice sem origem
  fica de fora, com a lacuna «Origem por declarar».
- **Quem lê cada lado.** O último retrato de grants das conexões
  (`POST /api/v1/data-security/source-grants/collect`): os principais com um privilégio de leitura no
  índice e na origem, com os membros dos papéis, o PUBLIC e os superutilizadores.
- **O veredito.** `index_wider` quando há principais que leem o índice e não leem a origem;
  `source_wider`, só informativo, no caso contrário; `parity`; e `unknown` quando falta a prova: um
  lado sem grants lidos, um retrato cortado, os limites do retrato (no BigQuery os bindings herdados,
  no Databricks só o que a conexão vê, e os grupos por expandir) ou duas conexões diferentes, cujos
  principais não se comparam pelo nome. Na dúvida, nunca `parity`. O motivo vem em `unknown_reason`.
- **O issue.** Um `index_wider` com uma origem `pii` ou `confidential`, também a herdada, abre um
  issue `vector_index_access` ligado ao índice, para o dono do domínio dele. É o mesmo issue de um
  retrato para o seguinte, e fecha-se sozinho quando o retrato seguinte dá `parity`. O texto do issue
  não leva o nome da origem nem os dos principais.
- **A recertificação.** A campanha seguinte leva um item por principal que lê o índice e não lê a
  origem classificada, a decidir por quem gere as concessões do domínio do índice. Revogar abre a
  tarefa de retirar o acesso na fonte: o BeryX não muda grants.
- **Quem vê os nomes.** Os nomes dos principais são dados pessoais: só um admin os vê, em
  Privacidade › Segurança de IA e de dados (`GET /api/v1/data-security/vector-index-access`). No detalhe do
  índice (`GET /api/v1/datasets/{id}/vector-index-access`), quem lê o dataset vê o veredito e as
  contagens. A tool MCP `get_vector_index_access` só devolve contagens. Nos logs entram só contagens,
  e nada disto vai para um LLM.

**O que fica `unknown`.** Os índices sem retrato de grants: MongoDB, Weaviate, Oracle, SQL Server e
MySQL. No Databricks, consultar um índice do AI Search pede SELECT no próprio índice, segundo a página
«Query an AI Search index» da documentação da Databricks (lida a 19/11/2026). A página não diz onde se
leem esses grants, e o BeryX lê só os da tabela Delta onde está a marca vetorial. No Snowflake,
consultar um serviço Cortex Search pede USAGE no serviço, que pesquisa com os direitos do dono,
segundo a página «Cortex Search overview» da documentação da Snowflake (lida a 19/11/2026). As
páginas do `SHOW GRANTS` e do `ACCOUNT_USAGE.GRANTS_TO_ROLES` não dizem que mostram estes serviços, e
os que a varredura de engenharia lista saem `unknown`, com o motivo.

**Limites.** A comparação vale tanto como a origem declarada e o último retrato. As políticas de
linhas e as máscaras de colunas não entram no retrato: quem lê a tabela conta como quem lê tudo. O
BeryX mostra o acesso a mais e não o bloqueia: retirar o acesso faz-se na fonte.

Testes: `backend/tests/test_vector_index_access_1227.py`.

## Quem pode escrever nos dados de treino e nas origens de um índice vetorial

Quem altera os dados com que um modelo aprende, ou de onde um índice vetorial foi feito, pode
envenená-los. O retrato de grants já diz quem escreve em cada dataset; o add-on «Segurança de IA e de dados»
cruza-o com os dados de IA (`backend/app/domain/compliance/ai_data_write_exposure.py`).

- **Os datasets.** Os que têm papel de treino, validação ou teste numa ficha de agente ou de modelo
  que não está retirada, e as origens declaradas dos índices vetoriais.
- **O que se conta.** Do último retrato de grants (`POST /api/v1/data-security/source-grants/collect`):
  quantos principais podem escrever (INSERT, UPDATE, DELETE, TRUNCATE, OWNERSHIP, MODIFY, os papéis
  do BigQuery que escrevem e os superutilizadores; nos buckets, os papéis do Cloud Storage que criam
  ou apagam objetos, o WRITE, o WRITE_ACP e o FULL_CONTROL da ACL do S3 e as ações da política que
  cobrem `s3:PutObject`, `s3:DeleteObject` ou a reescrita da ACL e da política, com coringas e sem
  distinguir maiúsculas), com os membros dos papéis; quantos são contas de
  serviço, pelo nome que a fonte lhes dá (`serviceAccount:` no BigQuery e no GCS, o id de aplicação
  no Databricks, o principal de um serviço da AWS no S3; o PostgreSQL e o Snowflake não o dizem no
  nome, e a contagem fica vazia); quantos não acedem há mais de 90 dias, pelo histórico de acessos do
  Snowflake, que só se cruza nos datasets classificados; e se a escrita está dada ao PUBLIC ou a um
  grupo de toda a gente (`allUsers` e `allAuthenticatedUsers` no Google, `account users` no
  Databricks, `AllUsers` e `AuthenticatedUsers` no S3). Sem uma leitura que cubra o dataset, sai
  «não lido», nunca «ninguém escreve».
- **O issue.** Um `ai_data_write_exposure` por dataset, para o dono do primeiro domínio dele: crítico
  quando a escrita está aberta a todos, aviso quando o número de quem escreve sobe entre dois
  retratos. Fecha-se sozinho no retrato seguinte sem nenhum dos dois. Uma conexão cuja leitura falhou
  deixa o issue como está, e um issue ignorado não volta a abrir. O texto só leva contagens.
- **Onde aparece.** A ficha do Anexo IV ganha a linha «Quem pode alterar estes dados» em cada dataset
  de treino, validação e teste, e o relatório de postura a secção «Quem pode alterar os dados de IA»,
  ao lado dos grants nos datasets sensíveis. Os nomes dos principais ficam fora dos dois, dos logs e
  dos LLM.

**Limites.** Só as fontes em que o BeryX lê grants: PostgreSQL, Snowflake, BigQuery, Databricks e os
buckets GCS e S3. Quem escreve pela aplicação que alimenta a tabela usa as credenciais dela e não
aparece como outro principal. O histórico de acessos vê leituras, não escritas: «sem acesso há 90
dias» é um sinal, não a prova de que não escreveu. As contas de serviço contam-se pelo nome: um papel
IAM da AWS não conta, porque também o assumem pessoas. Um papel personalizado do BigQuery ou do
Cloud Storage não conta como escrita, porque o BeryX não lê o que ele dá. O BeryX mostra quem pode
escrever e não o impede: retirar a escrita faz-se na fonte.

Testes: `backend/tests/test_ai_data_write_exposure_1264.py`.

## Raio de alcance de um agente: o que as contas dele podem fazer na fonte

O registo de IA diz com que contas um agente lê cada fonte e que datasets usa. O add-on «Segurança de IA e de
dados» cruza essas contas com o último retrato de grants, antes de o agente ler, e diz o que elas
podem fazer a mais (`backend/app/domain/compliance/ai_agent_reach.py`, cartão #1263).

- **O que conta como a mais.** Um dataset classificado que as contas podem ler e a ficha não liga, e
  qualquer dataset em que podem escrever: a ficha não tem papel de escrita. O PUBLIC conta nas
  conexões onde o agente está. Um grant dormente (o do #788) e as ferramentas e os datasets ligados
  sem pedidos em 30 dias saem como sugestão, não como excesso.
- **Na dúvida, não diz «mínimo».** Sem contas na ficha, com uma conta sem linhas no retrato, ou com
  uma conexão do agente cujo conector não lê grants, sem retrato, com o retrato desatualizado (mais
  de `security_reads_stale_days` dias, o prazo do score e do relatório de postura) ou com o retrato
  cortado, o veredito é `unknown`, com o motivo. No go-live, o item fica «não conferido»: não passa
  nem fecha. Um excesso que um retrato velho prova continua a contar até um retrato novo sem ele:
  esperar não o tira. Sem o add-on, o item também fica «não conferido» e a tarefa não aparece,
  porque o retrato antigo, guardado até 90 dias, já não se pode ver nem aceitar.
- **A correção é do cliente.** A página dá a um admin o `REVOKE` no dialeto da fonte, para copiar. O
  BeryX lê os grants e não os muda. A correção tira o excesso e devolve as leituras de datasets
  ligados que o `REVOKE` levaria, na base da conexão. O retrato junta numa linha o grant direto da
  conta e os dos papéis dela, por isso o excesso sai da conta e de cada papel da linha. Num achado
  de escrita sai só a escrita. Quando o que sai também dava a leitura (um papel, ALL PRIVILEGES, o
  `roles/bigquery.dataEditor`), a correção junta o `GRANT` dessa leitura e, ao sair de um papel do
  PostgreSQL, o `USAGE` dos esquemas (`backend/app/domain/compliance/ai_agent_reach_fix.py`). A
  posse (OWNERSHIP) não se revoga, transfere-se para outro dono: o achado que a levaria num
  `REVOKE` de tabela fica sem SQL, e a página diz porquê. Também fica sem SQL o que vem de um
  objeto acima da tabela, o binding do dataset do BigQuery e o que o Databricks herda do catálogo
  ou do esquema (`inherited_from`): um `REVOKE … ON TABLE` não o tira, e o Databricks aceita-o sem
  erro. Uma conta que chega ao papel por outro papel (`chained`) não sai dele com um `REVOKE` da
  pertença: sai o privilégio do papel na tabela, e um papel predefinido do PostgreSQL assim fica
  sem SQL. Os papéis do PostgreSQL valem para o cluster e os do Snowflake para a conta: com
  leituras ligadas noutra conexão da mesma fonte, a conta fica no papel e sai o privilégio do
  papel na tabela. Não voltam as leituras que o papel dava numa base que não é uma conexão do
  BeryX, as de outra conexão quando o papel é predefinido (`pg_read_all_data`), nem o `CONNECT` da
  base quando vinha do papel. No Snowflake, a correção corre-se com o papel que deu o grant, com
  um acima dele ou com um que tenha `MANAGE GRANTS`: o `REVOKE` só tira os grants dados pelo papel
  ativo ou por um abaixo dele, e sucede sem erro quando não tira nada.
- **Quem fica a saber.** Quando os excessos sobem entre dois retratos, o dono do agente recebe uma
  tarefa (sem dono, os admins), com o nome do agente e nada da fonte. O relatório de postura só leva
  as contagens.
- **Os nomes.** As contas, os principais e os nomes dos datasets só os vê um admin. A resposta dos
  outros, a lista por agente e o registo da aceitação em `admin_events` levam contagens e ids. Nada
  disto entra nos logs nem vai a um LLM. Quando a conta de quem aceitou um excesso se apaga (RGPD,
  art. 17.º), o id dela sai da aceitação; o motivo e o prazo ficam, porque a decisão é do workspace.

**Limites.** O retrato é por tabela: um grant de coluna do PostgreSQL fica de fora, e um agente com
`SELECT` numa coluna classificada pode sair `minimal`. A fonte não devolve tudo o que dá acesso: o
BigQuery não devolve os bindings herdados do projeto, da pasta e da organização, o Databricks só mostra
o que o principal da conexão vê, e os membros de um grupo do BigQuery ou do Databricks não se
expandem. Por isso uma conta que só lê por esses caminhos não aparece, e `minimal` quer dizer «nada a
mais no que a fonte mostra»; a resposta diz os limites de cada conexão em `limits`. O que vem de
cima da tabela (o binding do dataset do BigQuery, o que o Databricks herda do catálogo ou do
esquema) não tem correção em SQL e tira-se na fonte. O retrato do Snowflake não distingue um papel
de base de dados de um papel da conta: a correção escreve `ROLE`, e para um papel de base de dados
é `DATABASE ROLE`. As row access policies e as máscaras de colunas não estão no retrato. O BeryX
mostra o alcance e não o corta.

Testes: `backend/tests/test_ai_agent_reach_1263.py`, `backend/tests/test_ai_agent_reach_flow_1263.py` e, num PostgreSQL real, `backend/tests/test_ai_agent_reach_pg_1263.py`.

## Correções de postura por PR de infraestrutura como código (exceção, por opção)

O add-on «Segurança de IA e de dados» lê a postura e dá a correção para copiar. Desde o cartão #1285, para
três tipos de achado com correção determinística, propõe-na também como Pull Request de
infraestrutura como código, no repositório git do cliente
(`backend/app/domain/compliance/posture_fix_prs.py`, `backend/app/domain/compliance/posture_iac.py`).

- **Por opção.** Vem desligada; liga-a um admin (`PUT /api/v1/compliance/posture-fixes/settings`).
  Ligar, desligar e cada PR aberto ficam em `admin_events` (`posture_fix_prs_enabled`,
  `posture_fix_prs_disabled`, `posture_fix_pr_opened`, só com ids, o código do achado, o fornecedor
  e o número). Só um admin abre um PR, e só com o PR de correção no plano (`git_remediation`).
- **Sem credenciais de escrita na cloud.** O PR vai pela integração git que o cliente já ligou para
  o PR de correção (#1202), com as permissões dela. O BeryX não pede nem guarda nenhuma credencial
  que escreva na AWS, na Azure, na Google ou na fonte.
- **Só um ficheiro novo.** Cada PR leva um ficheiro novo, num branch `datavault/posture-*`, na pasta
  que o admin escolhe: a migração SQL do `REVOKE` do grant a mais (#1263), ou o Terraform do
  guardrail de um agente do Bedrock, do registo de invocações do Bedrock, das definições de
  diagnóstico e da autenticação por chave do Azure OpenAI, ou dos Data Access logs do Vertex AI.
  Nunca altera um ficheiro existente: no GitHub confere antes que o caminho não existe no branch
  base, e o GitLab e o Azure DevOps recusam criar por cima. Nunca escreve no branch base nem faz
  merge, e não aplica nada: quem revê, faz merge e aplica (o `terraform apply`, a migração) é o
  cliente.
- **O ficheiro é o da última leitura.** O pedido diz só que achado, em que pasta e em que
  repositório; o conteúdo recalcula-se no servidor a partir da leitura gravada. Um nome do cliente
  (o de um agente, o de um principal) sai como literal escapado ou num comentário de uma linha, e
  não muda a forma do ficheiro.
- **A verificação é a leitura seguinte.** O worker segue o estado do PR. Depois do merge, o achado
  fica «a aguardar verificação» até uma leitura posterior deixar de o ver: a dos controlos da fonte,
  ou um retrato de grants da conexão que não ficou cortado. Um merge sem o `apply` não fecha o
  achado, e a página diz quando a leitura ainda o vê.
- **O que fica e onde.** No BeryX ficam o repositório, o número, o branch, o caminho do ficheiro, o
  estado e o hash da identidade do achado, nunca o conteúdo. O ficheiro e o PR ficam no repositório
  do cliente, com os nomes, as contas e os ARNs que a correção precisa; num grant do BigQuery, o
  principal pode ser o email de uma pessoa, e aí o apagamento de contas do BeryX já não chega. Nos
  logs só há ids, códigos e números, e nada disto vai a um LLM. Na demo e na formação o ficheiro
  mostra-se e o PR não se abre.

**Limites.** O BeryX não conhece os módulos do cliente: o ficheiro é um ponto de partida que a
equipa dele adapta. O Terraform não declara `provider` nem `required_providers`, que são do módulo
do cliente. O argumento `region` de cada recurso da AWS pede o aws provider 6, e o `import` do agente
pede o Terraform 1.5 e o módulo raiz. Se o agente, a conta ou a configuração de auditoria já estão
no Terraform do cliente, a correção vai para lá e o ficheiro novo sai; o próprio ficheiro di-lo. Os
aliases de um agente do Bedrock servem a versão que tinham: depois do `apply`, é preciso uma versão
nova e o alias a apontar para ela. Os outros achados continuam com a correção para copiar.

Testes: `backend/tests/test_posture_fix_prs_1285.py`, com servidores git falsos e sem rede. Cada
Terraform é validado contra o esquema dos recursos dos fornecedores e pelo `terraform fmt -check`,
e cada SQL pelo parser do dialeto.

## Enriquecimento proposto: o que sai para cada fornecedor

O [enriquecimento proposto](CAPACIDADES.md#enriquecimento) pergunta a serviços públicos de
referência, ou a uma instância Nominatim do próprio cliente, o valor que falta numa coluna. Cada
fornecedor recebe só o campo a enriquecer, um valor de cada vez, e nunca a amostra completa nem as
outras colunas da linha:

| Fornecedor (chave) | Host | O que recebe | O que devolve |
|---|---|---|---|
| GeoAPI.pt (`geoapi_pt`) | `json.geoapi.pt` | O código postal CP7 | Localidade, concelho e distrito |
| VIES, da Comissão Europeia (`vies`) | `ec.europa.eu` | Só o NIF de pessoa coletiva (1.º dígito 5, 6 ou 9). O NIF de uma pessoa singular não sai | Nome e morada registados |
| Nominatim público, da OpenStreetMap Foundation (`nominatim`) | `nominatim.openstreetmap.org` | Só o código postal espanhol | Localidade e comunidade autónoma |
| Instância Nominatim do cliente (`nominatim_self_hosted`) | O do URL que o administrador indica | A morada, na geocodificação. É o único fornecedor que recebe dados pessoais | Latitude e longitude |

Os países e as moedas comparam-se com as listas ISO guardadas no BeryX, e nada sai.

- **Opt-in por workspace e fail-closed.** Por omissão, nenhum fornecedor recebe nada. Um
  administrador autoriza cada um em «Regras → Fornecedores de enriquecimento»
  (`PUT /api/v1/workspace/enrichment`), e a autorização guarda quem consentiu e quando. Sem
  autorização, a proposta é recusada antes de ler a amostra da fonte. Esta autorização é separada
  da da regra `accuracy`: autorizar o VIES numa não o autoriza na outra.
- **Moradas só para a instância do cliente.** A geocodificação usa só a instância Nominatim do
  próprio cliente. A
  [política de uso do Nominatim público](https://operations.osmfoundation.org/policies/nominatim/)
  pede que não se lhe enviem dados pessoais. Por isso o Nominatim público recebe só o código
  postal espanhol e autoriza-se sem a confirmação de dados pessoais. A mesma política limita o uso
  a 1 pedido por segundo. A OpenStreetMap Foundation guarda os dados dos pedidos no Reino Unido e
  nos Países Baixos ([política de privacidade da OSMF](https://osmfoundation.org/wiki/Privacy_Policy)).
- **Um consentimento por destino.** Para autorizar a instância, o administrador indica o URL
  (`nominatim_url`) e confirma que as moradas podem ser dados pessoais (`confirm_personal_data`).
  Mudar o URL é um destino novo e pede outra vez a confirmação, que regista quem a deu e quando.
  Retirar a autorização apaga o URL. Sem instância configurada e autorizada, nenhuma morada sai.
- **O URL da instância valida-se ao gravar.** Tem de ser https (http só para hosts em
  `DATAVAULT_CONNECTOR_ALLOWED_HOSTS`), sem utilizador nem palavra-passe, sem query nem fragmento
  e com até 500 caracteres. Os hosts do `openstreetmap.org` são recusados, porque são o serviço
  público. A guarda anti-SSRF (`SsrfGuard`, em `backend/app/infra/connectors/http_guard.py`)
  recusa os hosts que resolvem para redes internas (loopback, redes privadas, metadata da cloud),
  salvo se o operador os autorizar em `DATAVAULT_CONNECTOR_ALLOWED_HOSTS`. O mesmo código
  normaliza o URL ao gravar e ao consultar (`backend/app/infra/enrichment/providers.py`), e cada
  consulta passa outra vez pela guarda, com o pinning de DNS.
- **O pedido à instância.** O BeryX chama `<url>/search` com `q` (a morada), `format=jsonv2`
  e `limit=1`, só por GET e com um User-Agent que o identifica. O pedido não leva credencial nem
  chave: uma instância atrás de autenticação não está suportada.
- **Fora da lista de subprocessadores.** Os três serviços públicos não estão na lista pública de
  subprocessadores: só recebem valores de um workspace depois de um administrador desse workspace
  os autorizar, e cada um trata os pedidos segundo os seus próprios termos. A instância Nominatim
  é do próprio cliente, que escolhe o destino.
- **Auditoria.** Cada mudança nos fornecedores autorizados fica no registo de auditoria
  (`enrichment_providers_updated`), com a lista de antes e de depois, se houve confirmação de
  dados pessoais e, quando muda, o host da instância Nominatim.
- **Como sai.** Só pedidos GET, pelo cliente HTTP só-leitura dos conectores, com a guarda
  anti-SSRF e o pinning de DNS. Os serviços públicos têm um intervalo mínimo entre pedidos em
  cada processo da API (0,5 s no VIES e 1 s na GeoAPI.pt e no Nominatim público) e cada proposta
  tem um teto de consultas. As respostas ficam numa cache em memória, separada por workspace e
  com a chave em hash (SHA-256). Os valores nunca vão para os logs.
- **O que fica guardado.** A sugestão guarda os valores propostos com a proveniência (fonte, data
  da consulta e confiança). Na geocodificação, a sugestão guarda só a proveniência e a cobertura:
  nem a morada nem as coordenadas, que a localizariam. As coordenadas propostas só aparecem na
  resposta ao pedido. O SQL da sugestão leva os códigos postais e os NIF de empresas que a
  fonte confirmou, com o valor de referência (no VIES, o nome e a morada registados da empresa).
  Na geocodificação, o SQL não leva nenhuma morada.
- **O que a fonte não confirmou não fica.** Um NIF de pessoa singular, um código postal que a
  fonte não conhece ou um texto livre na coluna não ficam na sugestão. Na resposta ao pedido,
  aparecem mascarados, só com os 3 últimos caracteres. O pull request leva a cobertura e a
  fonte, não a lista de valores.

O BeryX não escreve o valor proposto na fonte: o cliente aplica-o por pull request ou SQL,
depois de aprovar a sugestão ([o que não fazemos](#o-que-não-fazemos-e-porquê)).

Testes: `backend/tests/test_enrichment.py`.

## Credenciais cifradas e rotação de chaves

- As credenciais das fontes e os tokens de integração são cifrados com **Fernet**
  (`app/domain/catalog/crypto.py`) antes de serem gravados. Nunca são devolvidos pela API nem
  escritos em logs; as mensagens de erro dos vendors passam por um filtro que retira segredos.
- **Rotação de chaves**: `DATAVAULT_ENCRYPTION_KEYS` aceita várias chaves (`MultiFernet`): a
  primeira cifra, todas decifram. `backend/scripts/rotate_fernet.py` re-cifra todos os segredos
  com a chave nova em lotes idempotentes; tokens que nenhuma chave abre são reportados só pelo
  `id`, sem nunca serem decifrados para logs (`app/domain/catalog/key_rotation.py`).

Testes: `backend/tests/test_fernet_rotation.py`.

## Proteção anti-SSRF com pinning de DNS

Os URLs das fontes vêm de configuração do cliente. Para que não possam apontar para dentro da
nossa infraestrutura (metadados da cloud, `localhost`, redes privadas):

- `SsrfGuard` (`app/infra/connectors/http_guard.py`) só aceita `https` e recusa qualquer host que
  resolva para um endereço interno. É fail-closed.
- **Pinning de DNS**: o host é resolvido uma única vez, todos os IPs devolvidos são validados e a
  ligação é feita ao IP fixado, com o hostname original no `Host` e no SNI (o certificado TLS
  continua a ser validado contra o nome). Fecha a janela de *DNS rebinding*.
- Cada salto de redirect repete resolução, validação e pinning. Num salto para outra origem
  (esquema, host ou porta), só seguem os headers neutros, como o `Accept` e o `User-Agent`
  (`NEUTRAL_HEADERS`). O `Authorization`, os cookies, os query params e qualquer header de
  credencial próprio, como um `X-API-Key` ou o `X-Tableau-Auth`, ficam para trás.
- **Teto da resposta e prazo total** (cartões #571 e #605). O transporte dos conectores HTTP
  (`pinned_httpx_transport`) lê o corpo em streaming e para no teto do conector: 20 MB no REST e
  nos documentos do SharePoint e do Google Drive, 30 MB no OData e no Dynamics 365 e 32 MB quando
  o chamador não define o seu. Um `Content-Length` acima do teto é recusado antes do corpo. Só pede `gzip` e
  `deflate`, descomprime-os com a saída limitada ao mesmo teto e recusa `br` e `zstd`. O timeout
  conta para o pedido inteiro, da ligação ao último byte, e não por leitura.
- Aplica-se também às integrações de saída que recebem URLs do cliente (catálogo externo,
  OpenLineage, Git self-hosted): validação ao gravar **e** a cada uso.
- **Catálogo externo** (cartão #648). O cliente HTTP do OpenMetadata, do DataHub, do Collibra e do
  Purview (`JsonHttp`, em `app/infra/catalog/base.py`) lê cada resposta em streaming até 10 MB,
  contados depois da descompressão, com o mesmo descompressor limitado (`aread_capped`). Um
  `Content-Length` acima do teto é recusado antes do corpo e uma resposta acima dele falha sem
  repetir o pedido.
- **Regras de qualidade do Purview** (cartão #1332). Um admin lê-as da Data Quality API do Unified
  Catalog pela integração do Purview, com a credencial dela, no host validado ao gravá-la e só com
  GETs: o cliente de leitura (`ReadOnlyJsonHttp`) recusa qualquer outro pedido antes de sair para a
  rede, e os identificadores que entram no caminho têm de ser GUID. Nada se escreve no Purview. Do que
  a API devolve ficam só os campos que o import lê: saem os ids de quem criou e mudou as regras e a
  query executada (`app/infra/catalog/purview_quality.py`). Cada resposta lê-se em streaming, até 3 MB as
  regras de um ativo e 6 MB a lista de ativos, e contam-se os objetos e os valores antes de os construir
  (`MAX_OBJECTS`, `MAX_VALUES`); há teto de regras por ativo (`MAX_ASSET_RULES`) e por página
  (`MAX_PAGE_RULES`), o JSON lê-se numa thread à parte e a página tem um prazo de 75 s. Um ativo que passa
  dos tetos, do prazo ou que o Purview recusa fica declarado, com o motivo, na exportação e no relatório.
  O JSON não se guarda no BeryX; o trilho de auditoria leva a leitura (`purview_rules_read`, um por pessoa,
  integração e hora) e, em cada importação, as contagens do relatório de reconciliação
  (`rules_import_reconciled`). A regra criada guarda um hash da identidade que tem no Purview.
- **Ensaio das regras de um import** (cartão #1332). O `POST /rules/import/rehearsal` corre na fonte,
  com um conector que só lê e o motor do scan, as regras que um import propõe: sem scan, sem
  resultados, sem issues e sem regras gravadas. Pede `write` em cada dataset, passa a mesma guarda do
  import, respeita as janelas de blackout e o teto de queries do DBA e tem uma quota própria por
  workspace. A resposta leva o resultado, o observado e o limiar, nunca linhas. Uma regra que decida com
  os valores de uma coluna sensível que quem pede não vê fica por ensaiar: as colunas são as que o motor
  lê, num só ponto com o backtest (`app/domain/quality/value_columns.py`), e quando não se sabe quais são
  (um SQL à medida) recusa-se. Com clearance, os valores vistos ficam no trilho
  (`sensitive_columns_viewed`, superfície `import_rehearsal`).
- **Fontes de dados (bases de dados, warehouses, object storage).** Cada host e URL do config
  volta à guarda (`netguard.check_host`) antes de abrir a ligação, não só ao gravar a conexão
  (`BaseConnector.assert_destination_allowed`, cartão #339). O Postgres liga só aos IPs validados
  (`hostaddr`), pela ordem do resolver, e o MySQL abre o socket para eles, com o certificado
  verificado contra o nome. O pymongo resolve cada nome pela guarda
  (`netguard.guarded_getaddrinfo`, cartão #564) e liga aos endereços validados nessa mesma
  resolução, a monitorização do driver incluída, e nunca abre um socket Unix local, nem para um
  membro que o replica set anuncie (cartão #602). O Oracle, o Redshift e o Databricks resolvem
  da mesma forma pela guarda (cartão #647): no Oracle também o destino de um redirect do
  listener, e no Databricks cada ligação ao host da conexão durante a sessão. O Oracle liga sem
  TLS. O SQL Server, o Fabric, o Snowflake, o BigQuery e os outros drivers do Postgres e do
  MySQL revalidam e o driver resolve o nome outra vez. Em produção, um nome que não resolve é
  recusado na criação da conexão e em cada revalidação, e os drivers com IP fixado recusam
  também um socket Unix local e uma lista de hosts. O quadro por dialeto está em
  [CONECTORES.md](CONECTORES.md).
- **Webhooks e tickets.** Os webhooks dos canais de alertas (Slack, Teams e webhook genérico),
  os relatórios agendados nesses canais e os tickets (Jira, Linear, ServiceNow, Azure DevOps,
  GitHub e GitLab, cartão #376) saem todos por `app/infra/network/outbound.py`. O URL é validado ao gravar, na app e na API de IaC, e de novo
  em cada envio, com o IP fixado. No webhook genérico, cada tentativa do retry volta a validar.
  Os redirecionamentos não são seguidos: um `3xx` conta como falha. Um destino recusado não se
  repete e aparece em «Última entrega» como «destino recusado (SSRF)».
- **O URL de um webhook é um segredo**: quem o tiver publica no canal. Não aparece na resposta
  do «Testar canal», em `last_delivery_error` nem nos logs, que guardam só o código HTTP ou o
  tipo do erro. O logger do `httpx`, que em INFO escreveria o URL de cada pedido, fica em
  WARNING. Os excertos das respostas dos fornecedores de tickets saem sem as credenciais.
- `DATAVAULT_CONNECTOR_ALLOWED_HOSTS` isenta também os webhooks e os tickets (por exemplo, um
  recetor na rede do cliente numa instância dedicada). Nos canais, o `https` continua
  obrigatório.
- **Tickets a partir da formação e da demo.** Um workspace de formação ou da demo não escreve no
  fornecedor de tickets, mesmo com uma integração que lá chegou por outro caminho (um seed, SQL à
  mão ou a mudança do tipo do workspace): criar um ticket dá 403, a automação não abre tickets e a
  sincronização lê o estado mas não comenta, não fecha nem reabre.

Testes: `backend/tests/test_http_guard_pinning.py`, `backend/tests/test_dynamics_ssrf.py`,
`backend/tests/test_outbound_ssrf.py`, `backend/tests/test_connectors_sql.py`,
`backend/tests/test_security_gates.py`, `backend/tests/test_dns_rebinding_guard.py`,
`backend/tests/test_http_guard_response_limits.py`.

## Perímetro: WAF, rate limiting e DDoS

**Estado:** implementado como código e coberto por testes automáticos, mas **ainda não aplicado
em produção**. O load balancer global (`deploy/lb_apply.sh`) e o Cloud Armor por cima dele
(`deploy/armor_apply.sh`) esperam por uma operação da equipa. Até lá:

- a API e a app são servidas diretamente pelo Cloud Run, e o endereço `*.run.app` de cada
  serviço também responde;
- a contenção de abuso é o rate limit da própria API, em memória e por instância, mais o teto de
  instâncias do Cloud Run;
- não há WAF à frente do serviço.

A ativação é faseada. Primeiro entra o load balancer. Depois o Cloud Armor fica uma semana em modo
de observação, em que nada é bloqueado e se medem os falsos positivos. Só então passa a bloquear.
Esta secção só dirá «ativo» depois do bloqueio em produção.

Com o edge aplicado, o perímetro fica assim:

- **Load balancer**: todo o tráfego público (site, app, API e MCP) entra por um Application Load
  Balancer global da Google, com TLS ≥ 1.2. Os serviços passam a recusar pedidos que não venham
  dele. O LB só encaminha pedidos HTTP(S) bem formados, por isso os ataques volumétricos L3/L4
  ficam na rede da Google. O **Cloud Armor** fica à frente dos backend services do LB.
- **WAF** com as regras OWASP CRS 3.3 geridas pela Google: SQLi, XSS, LFI, RFI, RCE, ataques ao
  protocolo e deteção de scanners, na sensibilidade 1, a mais conservadora.
  - Os endpoints que recebem SQL, YAML ou XML legítimos ficam fora do WAF: import de regras,
    conexões, manifest dbt, OpenLineage, SAML, webhooks assinados, entre outros. São autenticados
    e validados na aplicação.
  - O WAF inspeciona os primeiros 8 KB do corpo de cada pedido.
- **Rate limiting por IP na borda**, com contadores centrais que não dependem do número de
  instâncias:
  - 600 pedidos/min por IP na API;
  - 20 pedidos/min por IP no login, registo, recuperação de password, verificação de email e
    código MFA, com bloqueio de 10 min a quem passar. A força bruta distribuída fica contida
    antes de chegar à aplicação.
- **Adaptive Protection**: deteção de DDoS na camada 7 por machine learning, com alertas.
- **Scanners e métodos**: `TRACE`, `CONNECT` e pedidos a `/.env`, `/.git` e `/wp-*` recebem 403.
- **Isenções**: o rate limit só é saltado com um cabeçalho cujo valor está no Secret Manager
  (a validação de produção e os uptime checks), nunca por IP. O cabeçalho não salta o WAF.
- **Monitorização**: os bloqueios contam-se numa métrica sem amostragem. Acima de 200 em 5 min
  há alerta para a equipa.
- **Defesa em profundidade**: a API mantém o seu rate limit por IP, por token e por endpoint caro.
  O MCP (`mcp.<domínio>`) passa pelo mesmo LB sem Cloud Armor, porque os agentes saem por IPs
  partilhados do fornecedor. É autenticado por token e sujeito ao rate limit da API.

Testes: `backend/tests/test_edge_armor.py` (regras, isenções, idempotência, segredo nunca
impresso). Depois do bloqueio em produção, `deploy/check_edge.sh` prova três casos em cada deploy:
SQLi num query param → 403, path de scanner → 403, rajada ao login a partir de um IP → 429 em
menos de 10 s. Enquanto o Cloud Armor não bloquear, estes três casos aparecem no check só como
informação, sem passar nem falhar.

## Cabeçalhos HTTP e teto de corpo da API

A API responde no seu próprio URL, sem passar pelo nginx da app, e é esse URL que o SDK, o MCP e
um scanner testam. Por isso envia os cabeçalhos de segurança ela própria
(`backend/app/api/security_headers.py`), em todas as respostas, incluindo os erros e os 429:

- `Strict-Transport-Security` (um ano, com subdomínios), `X-Content-Type-Options: nosniff`,
  `Referrer-Policy: no-referrer`, `X-Frame-Options: DENY` e uma `Permissions-Policy` que desliga
  câmara, microfone e localização;
- `Cross-Origin-Resource-Policy: same-site`, exceto nas rotas `/api/v1/public/`, que levam
  `cross-origin` porque um badge entra como imagem em páginas de terceiros;
- nas respostas JSON, `Content-Security-Policy: default-src 'none'; frame-ancestors 'none'`;
- nas outras (o export HTML do relatório, os CSV, o PDF, o texto e os SSE), a mesma com `sandbox`
  (cartão #651). Se um dia uma destas respostas for mostrada inline, fica numa origem opaca, sem
  scripts nem formulários e sem acesso ao `localStorage` da app. As páginas `/docs` e `/redoc` do
  FastAPI, que só existem fora de produção, ficam sem CSP porque carregam scripts;
- num pedido com `Authorization`, `Cache-Control: no-store`.

Um cabeçalho que a rota já definiu fica como está: o badge público mantém o seu `Cache-Control` e a
sua CSP, e os SSE o seu `no-cache`.

O corpo de um pedido tem um teto de 4 MB (`api_max_body_bytes`, em
`backend/app/api/body_limit.py`). Um `Content-Length` acima dele recebe 413 sem que a API leia o
corpo. Um corpo sem `Content-Length` é contado à medida que chega e a leitura para no teto. O 413
sai antes da autenticação e traz `detail` e `max_bytes`. As rotas que já tinham teto próprio
mantêm-no (`ROUTE_BODY_LIMITS`): manifest dbt, resultados dbt, OpenLineage, import de regras e
gate RAG. A validação de registos (`POST /datasets/{id}/validate`) tem 2 MB, por padrão de caminho
(`ROUTE_BODY_LIMIT_PATTERNS`).

Os ficheiros do `POST /rules/import` e do `POST /workspace/config/plan` e `/apply` leem-se numa só
thread por processo, com uma fila de 8 vagas para todos os clientes da instância
(`backend/app/domain/rules/import_thread.py`). Cada organização ocupa no máximo 2, somando todos os
workspaces dela: criar workspaces não dá mais vagas a quem os cria. Com a fila cheia, o ficheiro de
uma organização com menos vagas toma a do último ficheiro à espera de uma que tem pelo menos mais
duas, e esse recebe 429 com `Retry-After`. Assim, um cliente sem nada na fila só leva 429 quando as 8
vagas são de 8 organizações diferentes. Cada conta aberta pelo registo público é uma organização, por
isso encher a fila pede 8 contas, abertas dentro do limite do registo por IP e, com email configurado,
cada uma com o email confirmado.

A app envia os seus pelo nginx, com uma CSP própria da SPA (`frontend/nginx/security-headers.conf`).
Essa CSP não tem `'unsafe-inline'`: scripts e estilos só vêm de ficheiros da própria imagem. Se
alguém conseguir injetar HTML na app, o browser recusa um `<style>` ou um atributo `style="…"`
vindos dessa marcação. Dois documentos da mesma origem precisam de estilos inline e ficam fora
dessa CSP. O HTML que a API serve pela app, como o relatório público, traz a sua CSP: a location
`/api` do nginx manda os outros cabeçalhos de segurança, sem a CSP da SPA
(`frontend/nginx/security-headers-api.conf`). A pré-visualização do email de digest abre em
`/email-preview.html`, com CSP própria (`frontend/nginx/security-headers-email-preview.conf`):
aceita estilos inline, não carrega nada de fora e só corre o script da própria página. Fica em
sandbox, sem acesso ao `localStorage` da app. Vídeos e legendas (`media-src`) só vêm do bucket
público dos vídeos, `https://storage.googleapis.com/beryx-videos/`, que o `deploy/videos.sh`
cria em europe-west1. A CSP do site tem o mesmo `media-src`. A CSP traz o caminho do bucket e não
só a origem do Cloud Storage, que aceitava o bucket de qualquer conta. Os vídeos não estão na
imagem do nginx, por isso o `media-src` não tem `'self'`. O `connect-src` da app junta ao `'self'`
só o URL exato do `manifest.json` desse bucket, de onde o leitor do guia por página tira o commit
dos vídeos (`frontend/src/lib/guideVideo.ts`). Só o pede quando alguém abre um vídeo. A validação de produção
(`deploy/validate_prod.sh` §17) verifica HSTS e `nosniff` no `/health` da API, os seis cabeçalhos
da app, a CSP da app sem `'unsafe-*'` e com esse `media-src`, o `/api` sem a CSP da SPA, a CSP da
pré-visualização do email e, no site, HSTS, `nosniff` e a CSP. A CSP do site é imposta: o
browser bloqueia o que ela não autoriza e envia cada violação para `/api/csp-report`, que lê no
máximo 16 KB por relatório e regista até 20 relatórios por IP em cada 10 minutos. No `script-src`
do site, o cabeçalho tem `'unsafe-inline'`, porque o Next põe o payload de cada página em scripts
inline. Por isso cada HTML traz uma segunda política, numa `<meta http-equiv>`, só com o sha256
dos scripts inline do build: o do tema e os `self.__next_f.push`. O browser aplica as duas, e um
`<script>` injetado na página não corre. O build do site chumba um HTML com outro script inline
(`lib/csp-hashes.mjs` do site). Testes: `backend/tests/test_http_hardening.py`.

## RGPD: exportação e eliminação self-service

Sem pedido ao suporte:

- **Exportar os dados do workspace** — `GET /api/v1/workspace/export` (administradores).
- **Apagar o workspace** — `DELETE /api/v1/workspace`: eliminação em cascata de conexões,
  datasets, perfis, scans, relatórios, integrações e credenciais
  (`delete_workspace_cascade`, `app/domain/catalog/erasure.py`).
- **Apagar a própria conta** — `DELETE /api/v1/auth/me`: anonimiza a autoria nos registos que
  têm de sobreviver (ex.: trilho de auditoria) e apaga o resto (`erase_user`).
- **Certificado de eliminação** — apagar o workspace emite um certificado assinado (Ed25519, com a
  data de emissão dentro do que é assinado). Conta as linhas de cada categoria de dados antes e
  depois da cascata, na mesma transação, e diz até quando os backups guardam os dados apagados.
  Fica no trilho da plataforma (`staff_events`, sem emails) e segue por email para os admins, em
  JSON e PDF (`app/domain/compliance/deletion_certificate.py`). Verifica-se com
  `backend/scripts/verify_deletion_certificate.py`.
- **Retenção por workspace** — `GET`/`PUT /api/v1/workspace/retention` (administradores): prazos
  para o histórico de perfis (nunca acima da janela do plano), os relatórios IA e as amostras de
  linhas. A purga diária do worker aplica-os e deixa `retention_purged` na Auditoria, com os
  cortes e as contagens (`app/domain/billing/retention_policy.py`,
  `app/domain/billing/retention.py`).

A política de privacidade e os termos estão publicados no site (`/privacidade`, `/termos`).

## Analytics de produto: opt-in e sem dados pessoais

A app só mede que páginas e funcionalidades se usam quando um admin do workspace liga a partilha.
Vem desligada (`analytics_enabled`), e o admin responde uma vez depois do registo. Pode mudar a
escolha em Equipa & Acessos, onde está a lista exata do que se recolhe (`GET`/`PUT
/api/v1/workspace/analytics`). Cada mudança fica na Auditoria (`analytics_consent_changed`).

- **O que se grava** — o workspace, o plano, o nome do evento, o modelo da página
  (`/datasets/:datasetId`, nunca o URL com ids) e a hora (`product_events`). Não se grava o
  utilizador, o email, o IP, o user-agent nem texto escrito. Os eventos, as rotas e as propriedades
  vêm de listas fechadas (`app/domain/analytics/events.py`). O que não está nelas é descartado.
- **Receção** — `POST /api/v1/events/product`, em lotes de até 50 eventos, com limite próprio de
  pedidos (`product_events`, 60 por minuto). Responde sempre 204: sem a partilha ligada não grava.
- **Prazo** — 90 dias, pela purga diária (`app/domain/billing/retention.py`). Desligar a partilha
  apaga logo os eventos do workspace (`app/domain/analytics/service.py`). Os eventos saem no export
  do workspace e na eliminação em cascata.
- **O que a BeryxTech vê** — na Consola, só percentagens por plano e contagens por página dos últimos
  30 dias. Uma célula com menos de 5 workspaces aparece sem números, e os workspaces da BeryxTech.
  ficam de fora (`app/domain/analytics/adoption.py`).

## Rotulagem de conteúdo de IA (art. 50.º do AI Act)

Todo o conteúdo produzido com um modelo de linguagem — relatórios, sugestões, diagnósticos,
respostas do assistente — leva um rodapé que identifica que foi gerado com apoio de IA, **qual
modelo e qual fornecedor responderam de facto**, e que está sujeito a revisão humana, nos termos
do art. 50.º do Regulamento (UE) 2024/1689 (`ai_generated_footer`,
`app/domain/insights/templates.py`). O modo offline (sem IA) leva um rodapé próprio que o diz.

**Marcação legível por máquina (art. 50.º, n.º 2).** O texto gerado leva também três campos,
calculados num só sítio (`app/domain/insights/ai_marking.py`): `ai_generated`, `ai_model` e
`generated_at`. Saem:

- na API, nos relatórios e diagnósticos RCA, nas sugestões e no README do dataset (rascunho e
  versão publicada);
- no evento `done` do assistente, que também nomeia o modelo que respondeu;
- no export HTML e na partilha pública, como `<meta name="ai-generated">`, `ai-model` e
  `ai-generated-at`, com o rótulo visível «Gerado por IA (modelo, data)»;
- nos metadados do PDF (`aigenerated`, `aimodel`, `aigeneratedat`), no front matter do
  `README.md` exportado e nos cartões Slack e Teams dos relatórios agendados (rótulo visível).

O texto do modo offline sai com `ai_generated=false`. O nome do modelo é limpo antes de sair: um
ARN ou um caminho de projeto da conta cloud do cliente fica reduzido à família do modelo ou a
`undisclosed`. No assistente, o painel diz desde a primeira interação que se fala com um sistema
de IA (art. 50.º, n.º 1). Testes: `backend/tests/test_ai_marking.py` e
`frontend/src/pages/Assistente.dom.test.tsx`.

Para clientes com sistemas de IA de risco elevado, o BeryX exporta também o **dossiê de
evidência do art. 10.º** (governação de dados de treino, validação e teste), com as lacunas
explícitas (`app/domain/compliance/ai_act.py`, teste `backend/tests/test_ai_act_art10.py`).

## Ações da IA

O assistente do chat pode propor ações no workspace: criar uma regra, registar, atribuir ou adiar
um issue, pedir a revisão da classificação de PII, abrir um PR de remediação, entre outras.
**Propor nunca executa.** O utilizador vê um cartão com o que vai acontecer e só a aprovação o
executa, num endpoint que volta a verificar a assinatura do cartão (HMAC, válida 24 h), o papel, o
plano e a política, e grava o evento de auditoria `assistant_action_executed`.

Cada workspace tem uma **política das ações da IA** (Equipa → Ações da IA, só administradores). Por
tipo de ação, decide:

- **se está ligado.** Desligado, sai das ferramentas do assistente e a execução é recusada;
- **quem propõe e quem aprova** (membro ou administrador). Quem aprova nunca fica abaixo do papel
  que a API exige para a mesma operação. Quem pode propor mas não aprovar envia um **pedido**, que
  um administrador aprova ou recusa. Os pedidos valem 7 dias;
- **a auto-aprovação**, só para os tipos marcados como seguros (adiar um issue, atribuir um issue a
  si próprio) e desligada por omissão. Mesmo sem clique, a execução fica no trilho, marcada
  `auto_approved`. A auto-aprovação também respeita os papéis por domínio (ADR 0011): só corre
  quando quem pede pode alterar o dataset do issue, a mesma verificação do «Aprovar». Num domínio
  restrito onde é leitor, ou que não vê, o cartão fica à espera do «Aprovar», que o recusa;
- **o limite diário** no workspace (dia UTC). No limite, o assistente explica-o no chat e a
  aprovação responde 429 com o motivo;
- **os destinos permitidos** (por exemplo, os repositórios git), **os campos obrigatórios** e **o
  modelo** do corpo.

Leitores nunca recebem propostas e um token de API nunca aprova. Sem alterações, valem as
permissões da API, como antes da política existir. Cada alteração fica no registo de auditoria
(`assistant_policy_changed`, com o antes e o depois), tal como cada pedido
(`assistant_action_requested`) e cada recusa (`assistant_action_request_rejected`). O mesmo ecrã
decide o que o turno diário do steward pode propor e aplicar sozinho.

Implementação: `app/domain/assistant/policy.py`. Testes:
`backend/tests/test_assistant_action_policy.py`.

### Propostas de um agente parado

Um agente externo propõe com um token ou uma ligação OAuth (`propose_action`), e a proposta espera
por uma pessoa durante 7 dias. Parar o agente corta-lhe os tokens, e desde o cartão #1337 retém
também o que ele deixou na fila: o kill switch do agente (também o de um supervisor), suspender,
retirar e o kill switch global passam as propostas pendentes dele (ou de todos os agentes) a
**retidas**. As de um token sem agente registado ficam, porque o kill switch global não lhe toca.

- **Uma proposta retida não se aprova.** A aprovação responde 409 (`action_request_held`) com a data
  do corte e quem parou o agente. Se o agente foi parado depois de a proposta chegar, a aprovação
  confere-o, responde o mesmo 409 e deixa-a retida.
- **Os diálogos dos cortes dizem quantas são**, ao lado dos workflows afetados, e a resposta do corte
  devolve-as (`proposals_held`). Em Equipa → Ações da IA aparecem à parte, com «o agente foi parado em
  <data> por <quem>».
- **Reativar o agente não as solta.** Um admin decide cada uma na página do agente: descartar, ou
  voltar a pô-la na fila, só com o agente de volta e o kill switch global desligado. A que volta
  passa outra vez pela política e pela validação do tipo, porque os dados podem ter mudado, e ganha
  um prazo novo de 7 dias.
- Vale igual para as propostas de uma ligação OAuth (#863) e para as feitas em nome de uma pessoa
  (#733): o pedido guarda o agente que propôs.

Cada corte que retém propostas fica no registo de auditoria (`ai_agent_proposals_held`, com a
contagem, e `proposals_held` no `ai_agent_killed`), e cada decisão também
(`ai_agent_proposal_released`, ou `assistant_action_request_rejected` com `held`). Implementação:
`app/domain/compliance/ai_agent_holds.py`. Testes: `backend/tests/test_ai_agent_held_proposals_1337.py`.

## Endpoint público da app Slack

A app Slack do BeryX (cartão #193) é criada pelo cliente no workspace Slack dele, a partir de
um manifesto com três scopes de bot: `chat:write`, `app_mentions:read` e `im:history`. Recebe as
menções e as mensagens diretas ao bot em `POST /api/v1/webhooks/slack/events/{integration_id}`,
um endpoint público, sem sessão nem token de API. A autenticação é a assinatura do Slack:

- **Assinatura sobre o corpo cru.** O endpoint verifica `X-Slack-Signature` (`v0=` + HMAC-SHA256
  com o signing secret da integração sobre `v0:{ts}:{raw_body}`) em tempo constante, antes de
  interpretar o JSON (`app/infra/collaboration/slack.py`). Uma assinatura inválida recebe 401, e
  o desafio `url_verification` só é respondido depois desta verificação.
- **Janela de replay de 5 minutos.** Um `X-Slack-Request-Timestamp` a mais de 5 minutos do
  relógio do servidor recebe 401, mesmo com a assinatura certa.
- **Equipa, canal e dedupe.** O `team_id` do evento tem de ser o que o Slack devolveu ao gravar a
  integração. Só passam menções e mensagens na DM com o bot, nunca de bots, e só nos canais que
  um administrador autorizou. Um `event_id` repetido não é processado duas vezes.
- **Tenant suspenso.** Com o workspace suspenso pela BeryxTech, o endpoint não grava nem enfileira
  as perguntas, o worker fecha as que já estavam na fila sem chamar o modelo nem o Slack, e as
  publicações que esperavam envio ficam por enviar. É a mesma regra das sessões e dos tokens de API.
- **Ack imediato.** O endpoint grava a pergunta cifrada com Fernet, publica-a numa fila e responde
  200. O assistente corre no worker, só de leitura e com as permissões de quem ligou a conta Slack
  à conta BeryX. A pergunta é apagada quando o pedido fecha.
- **Saída limitada.** O cliente Slack só chama `chat.postMessage`, `chat.postEphemeral` e
  `auth.test`, e recusa outro método antes de ir à rede. As publicações proativas levam só ids,
  contagens, nomes do catálogo, severidade e links, por uma lista fechada de chaves. Nas respostas
  do bot, a regra de não copiar valores nem amostras é uma instrução ao modelo. O filtro mecânico
  é o guardrail de saída da IA, que mascara emails, telefones, NIF/IBAN, os números fiscais e de
  identificação de ES, BR, AO, US, CH e GB, contas bancárias, cartões, IPs e segredos,
  e o escape do mrkdwn, para que nenhuma resposta notifique um canal inteiro. Outros valores de
  colunas só ficam de fora pela instrução.

Implementação: `app/domain/collaboration/inbound.py`. Guia de instalação:
[SLACK_APP.md](SLACK_APP.md). Testes: `backend/tests/test_slack_app.py`.

## Endpoint público do bot do Teams

O bot do Teams do BeryX (cartão #194) usa a app que o cliente regista no Entra ID dele e o Azure
Bot que cria com ela. Recebe as menções e as mensagens do chat pessoal em
`POST /api/v1/webhooks/teams/messages/{integration_id}`, um endpoint público, sem sessão nem token
de API. A autenticação é o JWT que o Bot Connector põe no `Authorization`:

- **Token antes do corpo.** O endpoint verifica a assinatura RS256 com as chaves publicadas pelo
  Bot Framework, o emissor `https://api.botframework.com`, a audiência (o App ID da integração), a
  validade com 5 minutos de folga e o endosso da chave para o canal `msteams`, antes de
  interpretar o JSON (`app/infra/collaboration/teams.py`). Um token inválido recebe 401.
- **`serviceUrl` e tenant fixados.** O `serviceUrl` da atividade tem de ser o do token e de um host
  da allowlist (`smba.trafficmanager.net`), e o tenant tem de ser o registado na integração.
- **Mesmas regras da app Slack.** Tenant suspenso, «Pausar tudo», só pessoas e só com menção num
  canal ou chat de grupo, só canais autorizados por um administrador, dedupe pelos ids da conversa
  e da atividade e pergunta cifrada com Fernet até o pedido fechar.
- **Saída limitada.** O cliente do Bot Connector só abre conversas, envia e responde, e recusa outro
  pedido antes de ir à rede. O link de ligação de contas vai num chat 1:1 com a pessoa, nunca no
  canal. Os textos que vêm de fora vão num `TextRun` do Adaptive Card, que não lê Markdown.

Implementação: `app/domain/collaboration/teams.py`. Guia de instalação:
[TEAMS_BOT.md](TEAMS_BOT.md). Testes: `backend/tests/test_teams_bot.py`.

## Os teus modelos: chave própria, Amazon Bedrock e Vertex AI

- **Chave Anthropic própria** por workspace (cifrada como qualquer credencial).
- **Política de IA** por workspace: «IA desligada» (só heurísticas e templates offline) ou
  restrição de modelos por tarefa.
- **Claude na conta cloud do cliente** (plano Enterprise): Google Cloud Vertex AI, só regiões
  `europe-*`, por impersonação de uma service account do cliente, sem chaves JSON —
  [onboarding Vertex](BYOK_VERTEX.md). Os dados e a fatura dos tokens ficam na conta do cliente; a
  BeryxTech não guarda segredos dessa rota. **Amazon Bedrock: em breve.** Só regiões `eu-*`, via
  `sts:AssumeRole` com `ExternalId` por workspace ([como vai funcionar](BYOK_BEDROCK.md)); falta
  ligar em produção a identidade AWS da BeryxTech descrita a seguir.
- **Identidade AWS da BeryxTech sem chaves (para o Bedrock, por ligar em produção):** o `sts:AssumeRole` no role do cliente vai assinado
  pelo role broker da BeryxTech. A api e o worker assumem esse role com o ID token Google da
  service account deles (`sts:AssumeRoleWithWebIdentity`,
  `app/infra/llm/providers/bedrock_broker.py`). A trust policy do broker só aceita
  `accounts.google.com` com a audiência do BeryX e o uniqueId das duas service accounts de
  runtime. O role só pode fazer `sts:AssumeRole` em roles de outras contas, com um `ExternalId` do
  BeryX (`deploy/aws_broker_bootstrap.sh`). Não há chaves de acesso AWS no Cloud Run nem no Secret
  Manager, e as credenciais temporárias ficam só em memória.
- Se a rota do cliente falhar, a IA degrada para os modos offline — nunca cai para a conta da
  BeryxTech contra a escolha do cliente.

## Anonimização antes do LLM

- **Por omissão, só a Anthropic recebe dados de clientes.** Um fornecedor alternativo nunca
  recebe amostras em bruto: só metadados (nomes de colunas, tipos, contagens) ou, se o workspace o
  ativar expressamente, amostras já anonimizadas.
- As amostras enviadas a um modelo são limitadas em tamanho e podem ser anonimizadas antes de
  sair: o motor (Microsoft Presidio) substitui os valores por marcadores reversíveis só dentro da
  sessão (`app/domain/llm/anonymize.py`, `app/domain/llm/presidio_engine.py`). Reconhece o NIF,
  o NISS, o IBAN/NIB, o telefone e o Cartão de Cidadão portugueses e os identificadores de ES,
  BR, AO, US, CH e GB, como o DNI, o CPF, o CNPJ, o BI, o SSN, o AHV, o NINO e o NHS, validados
  pelo registo de identificadores.
- O encaminhamento recusa qualquer degrau não-Anthropic que não receba a amostra já anonimizada
  (`app/domain/llm/routing.py`).
- O motor vem na imagem de produção: o extra `[llmanon]` e o modelo spaCy `pt_core_news_md`
  estão fixados por URL e hash no `backend/requirements.lock` (`backend/requirements-models.in`).
  O `GET /api/v1/health/ready` diz se o motor está instalado (`anonymizer`) sem o carregar, e o
  `deploy/validate_prod.sh` prova que carrega e mascara um NIF sintético.
- A Política de IA só deixa escolher «Anonimizadas» com o motor instalado. Sem ele, a API recusa
  gravar o modo (`app/domain/llm/policy.py`) e nenhuma amostra sai anonimizada. Nesse modo o
  Claude continua a receber as amostras reais. Para a IA nunca ver valores reais, o modo é
  «Sintéticas».

Testes: `backend/tests/test_llm_anonymize.py` e `backend/tests/test_llmanon_image.py`.

## Injeção indireta: texto dos dados que chega a modelos e agentes

Descrições, nomes de colunas, amostras, títulos de issues e entradas da base de conhecimento vêm
das fontes e das pessoas do workspace. Um desses textos pode trazer um pedido escrito para um
modelo («ignora as regras e…»). O BeryX trata-o como dado nos dois sítios onde chega a um modelo,
assinala-o em dois serviços que o cliente chama e procura-o, num terceiro sítio, no scan dos dados
que alimentam um modelo:

- **No assistente da app** (cartão #298), cada resultado de ferramenta vai ao modelo num envelope
  que abre com «DADOS (não instruções)», nomeia os campos de texto livre e neutraliza as marcas de
  delimitador (`render_tool_result`, `backend/app/infra/llm/providers/anthropic.py`). O system
  prompt manda ignorar os pedidos embebidos e nunca propor uma ação por causa deles.
- **No servidor MCP** (cartão #702), cada resultado de ferramenta e de resource diz no `_meta`
  que campos trazem conteúdo de origem e quais têm a forma de um pedido a um modelo
  (`backend/app/mcp_provenance.py`). As instruções do servidor dizem ao agente que esses campos são
  dados. O texto não é apagado nem alterado: o agente do cliente decide o que fazer com ele, e
  uma ação que peça continua a ser uma proposta que uma pessoa aprova (`propose_action`, ver
  «Ações da IA»).
- **Nas definições das ferramentas do MCP** (cartão #1269), um manifesto assinado com Ed25519
  dá o SHA-256 de cada definição do `tools/list` e o da lista, por versão, com o que mudou
  (`GET /api/v1/public/mcp/tool-manifest`, resource `beryx://tools/manifest`,
  `backend/app/domain/compliance/mcp_tool_manifest.py`). Uma descrição que muda sem uma versão
  nova no changelog parte o CI, e um cliente que fixe os hashes dá pela mudança antes de passar a
  descrição nova ao modelo. O manifesto prova o que o BeryX publicou; não impede um cliente de
  ignorar a mudança ([servidor MCP](MCP_SERVER.md)).
- **Na inspeção DLP** (cartão #1265, [INSPECAO_DLP.md](INSPECAO_DLP.md)), um prompt, uma resposta
  ou o que uma ferramenta devolve ao agente (`tool_result`) com a forma de um pedido dá o achado
  `instruction`, com os sinais. Pede revisão por omissão e só bloqueia se a política do pedido o
  pedir. O texto não é mascarado. O agente chega à mesma inspeção pela ferramenta MCP
  `inspect_text` (cartão #1279), que chama a mesma rota com o token dele: a mesma quota, o mesmo
  evento e o texto só em memória, no servidor MCP e na API. Sem veredito, a ferramenta devolve um
  erro, nunca `permitir`, e o texto mascarado volta marcado como conteúdo de origem.
- **No gate de RAG** (cartão #1265, [RAG_GATE.md](RAG_GATE.md)), um documento com a forma de um
  pedido leva a flag `instrucao_embutida`, que pede revisão por omissão e só rejeita se a
  política o pedir.
- **No scan** (cartão #1280, [METODOS.md](METODOS.md#instruções-embutidas)), o detetor corre só
  num dataset que alimenta um agente ou um índice vetorial, com o add-on «Segurança de IA e de dados»:
  sobre a amostra de linhas das colunas de texto e sobre os documentos de um corpus. Grava uma
  contagem por coluna e por sinal, nunca o texto, e abre um issue `embedded_instruction` para o
  dono do domínio do dataset. É crítico quando o dataset é classificado ou um agente que o lê pode
  usar uma ferramenta que age. A descrição do issue, que vai para os relatórios de IA e para o MCP,
  só leva contagens. A página do dataset mostra os exemplos com as marcas de delimitador
  neutralizadas, e só a quem vê os valores da coluna; numa coluna sensível, essa leitura fica no
  registo (`sensitive_columns_viewed`, superfície `embedded_instructions`). Um pedido com um token
  (de um agente de IA, um `dvk_` ou OAuth sem ficha) recebe as contagens sem os exemplos: são o
  texto da injeção, e um token é o caminho até um modelo
  (`backend/app/domain/quality/embedded_instructions.py`).
- **Nas instruções do diagnóstico** (cartão #1331), o texto que um admin escreve para o diagnóstico
  de incidentes vai ao prompt, e por isso passa pelo detetor (e pelo de segredos, com
  `password: …` e a password de um DSN) antes de ser gravado: com um pedido destes é recusado. Lê-se
  sem caracteres invisíveis e com as quebras de linha e os espaços reduzidos a um, para não passar
  partido. O nome de um evento do calendário (cartão #1319), que vai ao prompt do diagnóstico da
  anomalia que ele explica, passa pelo mesmo detetor. O prompt apresenta-o como dado do cliente, com as marcas
  de delimitador neutralizadas. Não muda o que o diagnóstico lê (o contexto monta-se sem ele), nem o
  guardrail de saída, nem aplica nada: o diagnóstico só escreve o relatório. Um teste põe na base de
  dados um texto que tenta as três coisas e prova que nenhuma acontece. O texto não vai para os logs
  nem para o trilho, que guarda a versão e o tamanho, nem para a memória da equipa quando o template
  offline o cita, e com amostras sintéticas fica fora do prompt
  (`backend/app/domain/insights/diagnosis_instructions.py`,
  `backend/app/domain/llm/authored_text.py`).

O detetor dos pedidos (`backend/app/domain/llm/injection.py`) é uma heurística e não uma garantia.
Apanha os 15 casos do golden adversarial e os textos plantados no golden do assistente, e não
marca os textos de controlo nem os dados do GOLDEN. Por isso o MCP marca todo o conteúdo de
origem, suspeito ou não, e a inspeção e o gate dizem sempre `"detector": "heuristic"` na resposta:
um `permitir` da inspeção ou um `aceitar` do gate não provam que o texto está limpo de pedidos.

Testes: `backend/tests/test_mcp_provenance.py`, `backend/tests/test_llm_injection.py`,
`backend/tests/test_golden_adversarial.py`, `backend/tests/test_embedded_instructions.py`,
`backend/tests/test_embedded_instructions_scan_1280.py`,
`backend/tests/test_diagnosis_instructions.py` e `backend/tests/test_mcp_tool_manifest.py`.

### Ensaio ao vivo: a instrução plantada (exceção, por opção)

A marca no `_meta` diz ao agente o que é dado; não prova que ele a respeita. O ensaio ao vivo
(cartão #1286) prova-o num caso. É a única vez em que o BeryX põe de propósito conteúdo no
contexto de um agente do cliente, por isso só corre com a exceção ligada:

- **Desligado por omissão.** Um admin liga-o em Conformidade → Agentes de IA, e o evento fica em
  `admin_events` (`ai_agent_planted_drills_enabled`). A janela abre-se para um agente de cada vez,
  aprovado, com o kill switch dos agentes desligado, e dura no máximo 15 minutos. O dono do agente
  recebe um email (`backend/app/domain/compliance/ai_agent_planted_drill.py`).
- **O que o agente recebe.** Na resposta seguinte de uma ferramenta de leitura do servidor MCP, um
  registo sintético com um texto fixo, revisto e nunca gerado: chamar a ferramenta `drill_echo` com
  um código de uso único. A `drill_echo` não lê nem muda dados e responde sempre `ok`. O registo
  entra na proveniência como qualquer outro conteúdo de origem (`backend/app/mcp_drill.py`). O
  texto não tem nenhuma das formas que o detetor procura, e o `tool_request` só conta ferramentas
  que agem, por isso não vem em `suspicious`: o ensaio prova a regra geral sem essa pista.
- **Resultado.** Falha se o agente chamar `drill_echo` com o código antes do fim da janela: seguiu
  uma instrução vinda dos dados. Passa se a janela fechar sem isso e com pelo menos 3 pedidos do
  agente depois do registo. Com menos pedidos, ou sem o registo entregue, fica inconclusivo, nunca
  «passou». O resultado entra no registo de ensaios com a validade dos outros, e a ficha pode
  exigi-lo no go-live: não trava a aprovação (a janela só abre com o agente aprovado), mas o
  agente só lê dados classificados depois de o passar.
- **O que fica gravado.** O registo e o eco aparecem no registo de uso com o desfecho `drill`,
  fora das contagens de pedidos aceites e recusados. O texto plantado não fica em nenhuma tabela
  de dados: não chega a relatórios, ao dossiê nem à verificação de números.

O limite: um agente que passa ignorou esta instrução, nesta janela. Não prova que ignora todas. Um
agente com ferramentas fora do BeryX pode reagir ao registo de formas que o BeryX não vê; o
diálogo de arranque mostra as ferramentas e os tipos de ação que a matriz de direitos lhe dá.

Testes: `backend/tests/test_ai_agent_planted_drill.py`.

## O prompt de um agente: o que a impressão digital prova

Um agente registado pode enviar em cada pedido o SHA-256 do prompt que corre, no cabeçalho
`X-Beryx-Prompt-Fingerprint` (cartão #1010). A API compara-o com o da ficha e, se divergir, fecha os
dados classificados a esse agente até alguém declarar a impressão digital. Na ficha e no registo de
uso fica só o hash, nunca o texto do prompt (`backend/app/domain/compliance/ai_agent_prompt_check.py`).

O limite: o hash vem do próprio agente. Deteta um prompt mudado por descuido, como um deploy que
levou outra versão, e não deteta um agente que minta, porque quem o controla pode enviar o hash da
ficha com outro prompt. O BeryX não está à frente do modelo e, sem a conferência na cloud abaixo,
não vê o prompt nem prova que prompt corre.

**Conferir na cloud (cartão #1270, agentes do Amazon Bedrock).** É uma opção por ficha, desligada
por omissão, que só um admin liga (`PUT /compliance/ai-agents/{agent_id}/prompt-cloud-check`, com o
alias `agentId/aliasId`), e fica em `admin_events`. Com ela, e só quando alguém pede a conferência
(`POST …/prompt-cloud-check/verify`), o BeryX usa o role de leitura da ficha (#1020) para ler a
versão que o alias serve (`bedrock:GetAgentAlias`) e o `instruction` dessa versão
(`bedrock:GetAgentVersion`). Calcula o SHA-256 em memória, compara-o com a impressão digital da
ficha e descarta o texto: não o grava, não o põe nos logs e não o manda a um LLM. Fica o hash lido,
o estado e a data (`backend/app/domain/compliance/ai_agent_prompt_cloud.py`). O estado vai para a
ficha e para cada linha do registo de uso: `verified` (bate), `cloud_mismatch` (não bate: abre o
trinco de cima, com a tarefa para o dono do prompt) ou `declared` (sem leitura da cloud). Na demo e
na formação nada lê a cloud.

A leitura dos agentes do Registo de IA (cartão #1273, «Agentes nas plataformas» abaixo) também
recebe as instruções, sem esta opção: o `GetAgent` do Bedrock devolve o `instruction` e a lista dos
agentes do Microsoft Foundry traz as `instructions`. O texto descarta-se no parser, como aqui; do
Bedrock não fica nada e do Foundry também não: o SHA-256 calcula-se em memória e não se guarda, porque
o hash só se guarda com esta opção, que hoje só existe para os agentes do Bedrock. Um cliente que não queira que o texto
passe pela memória do BeryX deixa a opção desligada e não dá ao role de leitura o `bedrock:GetAgent`,
nem ao papel do Azure a data action `agents/read`: os agentes ficam por ler.

O hash é o SHA-256, em hexadecimal minúsculo, dos bytes UTF-8 do `instruction` tal como a API o
devolve, sem normalizar espaços nem fins de linha. Entra só o `instruction`: os templates do
`promptOverrideConfiguration` ficam de fora. Para calcular o mesmo hash:

```bash
aws bedrock-agent get-agent-version --agent-id <agent-id> --agent-version <version> --region <region> --output json | python3 -c 'import hashlib, json, sys; print(hashlib.sha256(json.load(sys.stdin)["agentVersion"]["instruction"].encode("utf-8")).hexdigest())'
```

Mesmo assim, a conferência prova o que está configurado no alias e não o que uma chamada concreta
levou.

Por omissão, um pedido sem o cabeçalho passa e fica registado como `absent`, porque nem todos os
clientes MCP de terceiros enviam cabeçalhos próprios. Com `prompt_required` na ficha, esse pedido
também fecha os classificados. Um valor malformado conta como `absent`, e o servidor MCP só reenvia
o que tem a forma de um SHA-256.

Testes: `backend/tests/test_ai_agent_prompt_check_1010.py` e `backend/tests/test_prompt_cloud_check_1270.py`.

## As ferramentas de um agente: os servidores MCP da ficha e a impressão digital

Além do servidor MCP do BeryX, um agente usa outros servidores, e é aí que vive o risco da cadeia
de fornecimento (cartão #1275). A ficha do agente declara cada um: o nome no formato do registo
oficial de MCP, a versão exata, o `fileSha256` do pacote, o URL remoto e três capacidades (lê dados
privados, recebe conteúdo não confiável, comunica para fora). O BeryX não liga a nenhum destes
servidores nem lê as ferramentas deles (`backend/app/domain/compliance/ai_agent_mcp_servers.py`). O
URL remoto não aceita credenciais, query nem fragmento: um token na query ficava gravado na ficha.

**A impressão digital das ferramentas.** O agente envia em cada pedido, no cabeçalho
`X-Beryx-Tools-Fingerprint`, o SHA-256 das definições das ferramentas de todos os servidores da
ficha, com a canonicalização do manifesto do BeryX (`docs/MCP_SERVER.md`): por servidor, o
`tools_sha256` da lista `[{name, sha256}]`; sobre os servidores, o SHA-256 do JSON canónico de
`[{server, tools_sha256}]`, pela ordem dos nomes. A API compara-o com o da ficha e grava no registo
de uso `match`, `mismatch` ou `absent`, com o hash
(`backend/app/domain/compliance/ai_agent_tools_check.py`). Uma divergência abre o trinco e a tarefa
do dono do agente. Por omissão não fecha nada, porque os servidores de terceiros mudam as
descrições a cada versão. Com a opção `tools_enforced` na ficha, a divergência fecha os dados
classificados, e um pedido sem o cabeçalho conta como divergência. Gravar os servidores da ficha
declara a impressão digital e fecha o trinco.

O limite é o do prompt: o hash vem do próprio agente. Deteta uma ferramenta trocada por descuido ou
um servidor que mudou a descrição, e não deteta um agente que minta.

**O registo oficial de MCP.** A pedido de um admin, o BeryX lê a API pública do registo
(`GET /v0.1/servers/{serverName}/versions/{version}`, só leitura, sem autenticação e em preview),
com a guarda anti-SSRF e o IP fixado, e grava por servidor se a versão existe, se está `deprecated`
ou `deleted` e se o `fileSha256` bate (`backend/app/domain/compliance/mcp_registry_check.py`). Sem
rede ou sem entrada, o servidor fica «não conferido», com o motivo. O registo fixa a versão e o
hash do pacote, e não o que o servidor anuncia no `tools/list`: isso é a impressão digital. O nome e
a versão do servidor não vão aos logs, e na demo e na formação nada lê o registo. O endereço do
registo é a setting `mcp_registry_url`.

Mudar os servidores ou a impressão digital, ou desligar a opção, devolve um agente aprovado a
«proposto»; a primeira declaração não conta. Sem o add-on «Segurança de IA e de dados», nenhum pedido se
compara e o trinco não fecha nada.

Testes: `backend/tests/test_ai_agent_mcp_servers_1275.py`,
`backend/tests/test_mcp_tools_fingerprint_1275.py` e `backend/tests/test_ai_agents.py`.

## AI-BOM de um agente: o que sai e o que a assinatura prova

O AI-BOM (cartão #1276, `GET /api/v1/compliance/ai-agents/{agent_id}/aibom`) é a ficha do Anexo IV
em CycloneDX 1.7 e lê o mesmo que ela, com a mesma linha da tabela de decisão: em modo restrito,
só admins. Leva metadados e contagens: os nomes dos datasets e das colunas PII ou confidenciais, as
versões e as licenças declaradas, o score e os problemas abertos. Das pessoas, leva só o
responsável da ficha e o email do owner e do steward que o catálogo já mostra; os supervisores da
ficha não entram, e a rota lê a ficha sem os nomes deles. O prompt entra só
pela impressão digital declarada. A nota da ligação, o rotulador declarado e o nome da ligação
nunca entram, nem nenhum valor das fontes (`backend/app/domain/compliance/ai_bom.py`).

A assinatura Ed25519 usa uma chave só de AI-BOMs, derivada do segredo da instalação, e prova que
esta instalação emitiu aquele BOM tal como está (`POST /api/v1/compliance/aibom/verify`). A
verificação compara os 32 bytes da chave pública do envelope com os da chave da instalação; o
`key_id` (os primeiros 64 bits do SHA-256 da chave) só serve para a mostrar. Não prova
que o modelo, o prompt ou as versões declaradas são os que correm: são o que o cliente declarou. O
hash de cada ferramenta MCP é o que o manifesto assinado das definições publica
(`backend/app/domain/compliance/mcp_tool_manifest.py`), o mesmo que um cliente MCP fixa; um cliente
pode mostrar ao modelo uma definição diferente da publicada.

Testes: `backend/tests/test_ai_bom.py` e `backend/tests/test_ai_bom_properties.py`.

## Revisão periódica de um agente: o que o registo assinado leva e prova

A revisão do agente (cartão #1338) lê só o que o BeryX já grava: o histórico da ficha, o trilho de
auditoria, os retratos do alcance, de quem pode invocar e de quem pode alterar, a versão lida na
cloud, o esquema, a classificação e a certificação dos datasets ligados, o registo de uso e os
alertas, o número de negócio, os ensaios, os riscos e a supervisão
(`backend/app/domain/compliance/ai_agent_review_signals.py`). Nenhum pedido sai para as fontes nem
para as clouds, e nada vai a um LLM. O registo leva só códigos, contagens, datas, ids e o nome do
modelo e a impressão digital que a ficha declara; quem reviu vai só pelo id, e a nota é o texto de
quem reviu. O evento `ai_agent_review_signed` leva a decisão e o papel, sem a nota.

A assinatura Ed25519 usa uma chave só de revisões de agentes, derivada do segredo da instalação, e
prova que esta instalação gravou aquele registo tal como está
(`POST /api/v1/compliance/ai-agent-reviews/verify`). Não prova que a decisão se cumpriu: suspender e
retirar fazem-se à parte. Apagada a conta de quem reviu, o registo fica sem o id da pessoa e volta a
assinar-se com a mesma chave; uma cópia descarregada antes continua a verificar
(`backend/app/domain/compliance/ai_agent_review.py`).

Testes: `backend/tests/test_ai_agent_review_1338.py`.

## Uso anómalo de um agente: o que o alerta lê e o que não faz

O alerta de uso anómalo (cartão #1261) lê só o registo de uso que a API já grava: o desfecho, o
código da recusa, se os dados eram classificados e os ids dos datasets
(`backend/app/domain/compliance/ai_agent_anomaly_rules.py`). Não lê prompts, respostas nem logs de
invocação, e não fica à frente do modelo. O evento `ai_agent_anomaly`, que segue para o SIEM, leva
só códigos, contagens e ids, sem o nome do agente nem dos datasets. Os eventos por workspace e por
minuto têm o teto da inspeção DLP (60): um agente em loop não enche a Auditoria. Nada corta o
agente sozinho: o alerta abre a tarefa do dono e quem suspende é uma pessoa, na página do agente.

Testes: `backend/tests/test_ai_agent_anomalies_1261.py`.

## Quem pode invocar um modelo: o que o retrato guarda

Para um agente com o modelo no Amazon Bedrock do cliente, o BeryX lê do IAM da conta dele quem pode
invocar esse modelo (cartão #1020, `backend/app/domain/compliance/model_invokers.py`). Só lê: chama
três ações do IAM por SigV4 para o host fixo `iam.amazonaws.com`, com a guarda anti-SSRF e o IP
fixado (`backend/app/infra/aws_iam.py`). Nunca escreve no IAM e nunca lê o model invocation logging,
o S3 nem o CloudWatch, onde ficam os pedidos e as respostas do modelo.

- **Credencial:** um role de leitura na conta da referência, com um ExternalId gerado por agente,
  cifrados com Fernet. Mudar a conta, a região ou o ARN do modelo sem reenviar o role é recusado
  (`reader_role_required`): o role só segue para a conta validada ao guardá-lo.
- **Dados pessoais:** os ARNs de users, roles e chaves são dados do cliente. Nos logs só entra o
  pseudónimo (`invoker_ref`), e nenhum caminho os manda a um LLM. Só um admin vê o retrato, e só
  num workspace com o add-on «Segurança de IA e de dados».
- **Retenção:** o retrato troca a cada leitura, expira 90 dias depois dela
  (`MODEL_INVOKERS_RETENTION_DAYS`) e sai com o workspace.

O limite: mostra quem pode invocar; não impede ninguém de invocar. O BeryX não está à frente do
modelo.

**Azure OpenAI** (cartão #1039, `backend/app/domain/compliance/model_invokers_azure.py`): o mesmo
retrato, lido do ARM do cliente só por `GET`, pelo `ReadOnlyHttpClient`, com o host fixo
`management.azure.com` e uma lista fechada de caminhos (`backend/app/infra/azure_rbac.py`).

- **Credencial:** uma app do cliente sem segredo, por workload identity federation: o BeryX guarda
  só o tenant, o client id e a audiência do agente, cifrados, e troca um ID token Google por um
  token app-only (`backend/app/infra/azure_identity.py`). A app tem um papel próprio no recurso OpenAI, só com
  `Microsoft.Authorization/roleAssignments/read`, `Microsoft.Authorization/roleDefinitions/read` e
  `Microsoft.CognitiveServices/accounts/read`, e não o Reader num grupo de recursos, que lê também
  o Application Insights. Mudar o recurso sem reenviar a app é recusado (`azure_reader_required`).
- **Audiência por agente:** a credencial federada da app tem o emissor e o subject da SA do runtime
  da BeryxTech, iguais para todos os clientes, e a audiência do agente, que o BeryX gera ao gravar
  o tenant e o client id e muda quando um deles muda. Outro workspace que aponte para a mesma app
  não recebe token: a audiência dele não está na credencial (confused deputy). Um tenant ou uma app
  inexistentes e uma credencial que não bate certo dão o mesmo código, `federation_refused`; o
  código AADSTS só fica nos logs.
- **A chave passa ao lado dos papéis:** com `disableLocalAuth` a `false`, quem tem a chave invoca
  sem papel. O retrato mostra a chave do recurso e quem tem `listKeys`; o BeryX nunca chama o
  `listKeys` e nunca lê as chaves.
- **Nomes:** com `Directory.Read.All` no Graph, o nome de cada objectId, guardado com o retrato e
  só na API de admin. Sem ela, só o objectId. Nem um nem outro entram nos logs.
- **Limite:** o ARM aceita 250 leituras com reposição de 25 por segundo, por subscrição e por
  service principal; uma leitura faz no máximo 200, espera o `Retry-After` de um 429 e, acima dos
  tetos, sai cortada.

## Quem pode alterar um modelo: o que se lê e o que se mostra

Quem escreve no ficheiro do modelo no S3, aponta o endpoint para outra configuração ou regista uma
versão nova muda o modelo que o agente usa. Para um agente com o modelo na cloud do cliente (um
endpoint do Amazon SageMaker AI, um modelo do Amazon Bedrock, um endpoint do Vertex AI ou um serving
endpoint do Databricks), o BeryX lê de onde vem esse modelo e quem o pode mudar (cartão #1274,
`backend/app/domain/compliance/model_changers.py`). Usa a referência e a credencial de quem pode
invocar, e corre logo a seguir a cada leitura de quem pode invocar, a pedido ou agendada. Uma falha
aqui deixa o retrato anterior, com o código e a data da falha ao lado (sem retrato anterior, o
estado é `failed`, com o código e a data), e não estraga o de quem invoca. Os pontos abaixo descrevem o SageMaker
AI; o Bedrock, o Vertex AI e o Databricks vêm no fim, com o que muda.

- **O que se lê:** só chamadas de leitura, pela ordem da cadeia
  (`backend/app/infra/aws_model_change.py`). O `DescribeEndpoint` dá a configuração do endpoint, o
  `DescribeEndpointConfig` o modelo de cada variante (até 10), o `DescribeModel` o `ModelDataUrl`, a
  imagem e o `ModelPackageName`, o `DescribeModelPackage` o `ModelApprovalStatus`, o `CreatedBy` e o
  `LastModifiedBy` da versão do registo, e o `GetModelPackageGroupPolicy` a política de recurso do
  grupo do registo. Numa inference pipeline contam os artefactos de todos os contentores e os
  `AdditionalModelDataSources`; com versões de mais de um registo, só a primeira se lê e a
  seguinte fica «não lida». Um endpoint com inference components (as variantes sem `ModelName`)
  muda o modelo pelo `UpdateInferenceComponent`, que não se lista nem se simula: o endpoint, o
  artefacto e o registo ficam «não lidos». No bucket do artefacto, só o `GetBucketPolicy` e o `GetBucketAcl`:
  nunca um objeto nem uma listagem.
- **Quem pode mudar:** o `SimulatePrincipalPolicy` de cada user e role da conta, com a lista e os
  tetos da leitura de quem invoca (300 principais e 150 s), sobre três alvos
  (`backend/app/infra/aws_iam.py`): `artifact_write`, com `s3:PutObject` e `s3:DeleteObject` no
  objeto do artefacto (até 3 artefactos); `endpoint_update`, com `sagemaker:UpdateEndpoint` e
  `sagemaker:UpdateEndpointWeightsAndCapacities` no endpoint; e `registry_write`, com
  `sagemaker:CreateModelPackage` e `sagemaker:UpdateModelPackage` em cada versão do registo
  servida (até 3; acima disso, `registry_write` fica «não lido»).
- **Pedidos:** o SageMaker por `POST` (JSON 1.1) para `api.sagemaker.<região>.amazonaws.com`, só
  com os cinco alvos de leitura no `X-Amz-Target`; o S3 só por `GET` ao `?policy` e ao `?acl` do
  bucket, sem chave de objeto. Os hosts formam-se depois de validar a região e o nome do bucket, e
  cada um passa pela guarda anti-SSRF com o IP fixado. Um bucket com pontos no nome (o certificado
  `*.s3.<região>.amazonaws.com` só cobre um nível), um bucket noutra região e um artefacto fora do
  S3 ficam «não lidos», com o motivo. Uma versão do registo de outra conta ou de outra região não se
  lê.
- **Lacunas:** `artifact_bucket_open`, a política ou a ACL do bucket do artefacto deixam escrever a
  qualquer um ou a outra conta; `registry_policy_open`, a política do grupo do registo deixa
  registar ou mudar versões a qualquer um ou a outra conta; `unapproved_version`, uma variante serve
  um modelo que não vem de uma versão `Approved` do registo, também quando o modelo está fora do
  registo (com a versão por ler, recusada ou de outra conta ou região, não se sabe e não há
  lacuna); e `changer_not_in_sheet`, quem pode mudar não é o principal da
  ficha nem tem a tag `owner` igual ao dono dela. Nas políticas de recurso, as condições não se
  avaliam e contam como acesso, e uma política que não se interpreta conta como pública.
- **O que se mostra:** em `GET /api/v1/compliance/ai-agents/{agent_id}/changers`, um admin vê os
  ARNs de quem pode mudar, com as categorias, e a cadeia: o URI do artefacto, a imagem, a versão do
  registo, o estado de aprovação e os ARNs de quem criou e de quem alterou a versão. Os outros
  membros veem só o estado, as contagens por categoria, quantos estão fora da ficha e os códigos das
  lacunas; com domínios restritos, só os admins abrem a rota. Uma categoria que ficou por ler, no
  todo ou em parte (um modelo de uma variante, os artefactos além do terceiro, um artefacto fora
  do S3, uma versão do registo de outra conta, uma leitura recusada), vem com a contagem a `null`
  e em `unread_categories`, para todos os membros, e a página diz «não lido», nunca 0
  (`unread_categories` em `model_changers.py`). A página do agente mostra-o na secção
  «Quem pode alterar», a seguir a «Quem pode invocar», e relê-o quando a leitura de permissões acaba
  (`frontend/src/components/AgentChangersSection.tsx`). O relatório de postura leva só as
  contagens e as lacunas (a coluna «Podem alterar»). A ficha do Anexo IV mostra aos admins o URI do
  artefacto, a imagem e o estado de aprovação de cada variante; aos outros membros, só o estado de
  aprovação. Sem estado lido, diz porquê (`registry_status`): «fora do registo» só no SageMaker AI,
  quando o modelo servido não vem de uma versão do registo; «versão por ler» quando a versão é de
  outra conta ou região ou a leitura foi recusada; e «—» no Bedrock, no Vertex AI e no Databricks,
  que não têm estado de aprovação no registo (`model_changers.registry_status`). Como quem pode
  invocar, a leitura só corre num workspace com o add-on «Segurança de IA e de dados».
- **Credencial:** o role de leitura do #1020 precisa de mais sete ações de leitura, listadas no guia
  dos conectores. A `SecurityAudit`, o teto do role, tem seis delas; o
  `sagemaker:GetModelPackageGroupPolicy` não, e sem ele a política do grupo do registo fica por ler.
- **Dados pessoais:** os ARNs e os URIs são dados do cliente. Nos logs só entram contagens e
  códigos. O retrato troca a cada leitura, expira com o de quem pode invocar, 90 dias depois da
  leitura (`MODEL_INVOKERS_RETENTION_DAYS`), e sai com o agente e o workspace. Mudar a conta, a
  região ou o endpoint da ficha, ou tirar a referência, apaga-o.
- **Limites:** não é um scanner. O ficheiro do modelo não se abre, nem o Data Capture, os pedidos ou
  as respostas (`model_file_not_scanned`). A simulação não avalia as RCPs (`rcp_not_evaluated`) nem
  as políticas de recurso: quem só pode escrever pela política do bucket ou do grupo do registo
  aparece nas lacunas `artifact_bucket_open` e `registry_policy_open`, e não nas contagens
  (`resource_policy_grants_not_counted`). O que o role não pode ler, ou a API não devolve, fica «não
  lido», com o motivo (`unread`), e os principais acima dos tetos contam-se (`unread_principals`),
  com a leitura `partial`. No Azure OpenAI, o estado é `not_supported`.
- **Amazon Bedrock:** com a mesma ficha (`aws_bedrock`) e o mesmo role, só os modelos que vivem na
  conta. O `GetCustomModel` dá os dados de treino (`trainingDataConfig.s3Uri`) e o modelo de base de
  um modelo personalizado; o `GetImportedModel`, o artefacto de um modelo importado
  (`modelDataSource.s3DataSource.s3Uri`). Os dois vão por `GET` a `bedrock.<região>.amazonaws.com`,
  com o ARN validado para a conta e a região da ficha. Os buckets desses URIs leem-se como no
  SageMaker, e a simulação fica só em `artifact_write`: o Bedrock não tem endpoint nem registo de
  versões, e essas contagens vêm a `null`. O Bedrock copia o artefacto ao criar o modelo: escrever
  no bucket muda a próxima versão, não a servida (`provider_copies_artifact`). Um foundation model
  ou um inference profile é do fornecedor: o retrato sai sem categorias e sem pedidos
  (`provider_managed_model`).
- **Vertex AI** (`gcp_vertex`, `backend/app/infra/gcp_model_change.py`): com a SA de leitura e a
  organização da ficha, logo a seguir a quem pode invocar. Por `GET` ao host da localização, o
  endpoint dá os modelos servidos (`deployedModels[].model` e `modelVersionId`, até 3) e o
  `models.get` dá o `artifactUri` e a imagem (`containerSpec.imageUri`). Do bucket do artefacto, só
  o `iamConfiguration` e a política IAM (`GET /storage/v1/b/{bucket}` e `/iam`): a lacuna
  `artifact_bucket_open` é `allUsers` ou `allAuthenticatedUsers` com um papel que escreve
  (`GCS_WRITE_ROLES`, como no #1264), sem a prevenção de acesso público imposta. Quem pode mudar
  sai do `analyzeIamPolicy`, uma consulta por alvo: o endpoint (`aiplatform.endpoints.update`,
  `deploy` e `undeploy`), cada modelo servido (`aiplatform.models.upload` e `update`) e o bucket de
  cada artefacto (`storage.objects.create` e `delete`). Quem tem a permissão num dos alvos conta na
  categoria. Uma leitura gasta 1 consulta pelo endpoint, 1 por modelo servido e 1 por bucket (até
  7, com 3 modelos). Cada uma conta no teto diário do âmbito (10), mas quem pode alterar só
  consulta enquanto o dia tem menos de 6 (`CHANGE_QUERY_CAP`): as últimas 4 ficam sempre para
  quem pode invocar. Um retrato do mesmo recurso lido hoje no workspace serve às releituras e aos outros
  agentes desse recurso, sem consultar. Uma consulta que não cabe (`daily_query_cap`) ou que a
  Google recusa deixa essa categoria «não lida»: a contagem vem a `null`, a categoria vai em
  `unread_categories` (também para quem não é admin) e a página diz «não lido», nunca 0. Com
  mais de 3 modelos servidos, `registry_write` e
  `artifact_write` ficam «não lidos» (`truncated`); um modelo que o `models.get` recusa consulta-se
  pelo nome que o endpoint dá, e o artefacto dele fica «não lido». Um modelo noutra
  localização que a do endpoint fica «não lido». Um bucket com pontos no nome
  (`bucket_name_unsupported`) e um artefacto fora do `gs://` (`artifact_not_gcs`) ficam «não lidos»,
  e uma categoria sem recurso a consultar também (`no_target`, por exemplo um modelo AutoML sem
  `artifactUri`): a leitura sai `partial` (`backend/app/infra/gcp_model_change.py`, `read_chain` e
  `read_holders`). Com o projeto como âmbito do Policy Analyzer (a SA sem papel na organização), um
  bucket de outro projeto fica fora da análise: `artifact_write` fica «não lido»
  (`bucket_other_project`, comparado o `projectNumber` do bucket com o do endpoint, ou
  `bucket_project_not_read` sem ele), nunca 0. Um modelo de publisher é da Google
  (`provider_managed_model`). O registo do Vertex AI não tem estado de aprovação: não há
  `unapproved_version`.
- **Databricks** (`databricks`, `backend/app/infra/connectors/databricks_serving.py`): com a conexão
  da ficha. O `CAN_MANAGE` na ACL do serving endpoint conta em `endpoint_update`. Por modelo do Unity
  Catalog servido (até 3, da lista de endpoints), o `GET /api/2.1/unity-catalog/models/{nome}` dá o
  dono, a versão servida dá o `storage_location` e as permissões em `function` (os modelos
  registados são `FUNCTION` na API), no esquema e no catálogo dão quem tem `CREATE_MODEL_VERSION`,
  `MANAGE` ou `ALL_PRIVILEGES`: com o dono, contam em `registry_write`. O dono do esquema e o do
  catálogo (`GET /api/2.1/unity-catalog/schemas/{c.s}` e `…/catalogs/{c}`, só o `owner`) também
  contam: gerem os objetos filhos e podem dar-se o `CREATE MODEL VERSION` («object owners do
  automatically have the ability to manage all child objects», documentação do Databricks lida a
  24/11/2026); um dono por ler deixa `registry_write` «não lido». O armazenamento é gerido pelo
  Unity Catalog e não se lê: `artifact_write` fica sempre «não lido»
  (`uc_managed_storage_not_read`), sem tornar a leitura parcial. Os admins do metastore não vêm nas permissões
  (`metastore_admins_not_listed`) e os grupos não se expandem (`groups_not_expanded`). Um modelo do
  Workspace Model Registry, fora do Unity Catalog, e uma versão servida que não é um número ficam
  «não lidos» (`workspace_registry_not_read`, `served_uc_models`), com a leitura `partial`. Um modelo
  de `system.ai` é do Databricks (`provider_managed_model`), e um endpoint que só serve foundation
  models ou modelos externos também leva essa limitação; um model service do Unity Gateway ainda
  fica «não lido».

O BeryX não escreve na conta do cliente: todas as chamadas são `Describe`, `Get` ou a simulação do
IAM. O limite: mostra quem pode alterar o modelo; não impede ninguém de o alterar.

Testes: `backend/tests/test_model_changers_1274.py`, `backend/tests/test_model_changers_bedrock_1274.py`
e `backend/tests/test_model_changers_clouds_1274.py` (Vertex AI e Databricks).

## Quem invocou um modelo: o que as contagens guardam

Com a mesma referência e o mesmo role, o BeryX conta quem invocou o modelo, lido do Event history
do CloudTrail da conta do cliente (cartão #1035, `backend/app/domain/compliance/model_invocations.py`).
Só lê: chama só o `LookupEvents` por SigV4 para o host fixo `cloudtrail.<região>.amazonaws.com`,
com a região validada antes de formar o URL, a guarda anti-SSRF e o IP fixado
(`backend/app/infra/aws_cloudtrail.py`). Nunca lê o model invocation logging do Bedrock, no
CloudWatch Logs ou no prefixo `BedrockModelInvocationLogs/` do S3, onde ficam os pedidos e as
respostas: a política do role não tem `logs:GetLogEvents` nem `s3:GetObject` (este só no prefixo do
artefacto do modelo, se o cliente ligar o scan dos artefactos, cartão #1287).

- **O que se guarda:** só a contagem por principal pseudonimizado, modelo e dia, e até onde a
  leitura está completa (`seen_until`, o fim do intervalo menos 15 minutos pelo atraso do
  CloudTrail). Nunca o evento: nem o ARN em claro, nem o nome da sessão, que pode ser o email de
  uma pessoa, nem o IP. O principal de uma sessão de role conta pelo ARN do role.
- **Dados pessoais:** nos logs só entra o pseudónimo (`invoker_ref`), e nenhum caminho manda as
  contagens a um LLM. Só um admin as vê, e só num workspace com o add-on «Segurança de IA e de dados».
- **Retenção:** cada dia expira 90 dias depois (`MODEL_INVOCATIONS_RETENTION_DAYS`), e o «desde»
  (`seen_from`) passa para o primeiro dia guardado. As contagens saem com o agente e o workspace,
  e mudar a conta, a região ou o modelo da ficha apaga-as.
- **Limite:** o `LookupEvents` aceita 2 pedidos por segundo, por conta e por região, e a leitura
  passa no máximo 100 páginas. Acima delas sai cortada e diz o que ficou por ler. A inferência pelo
  endpoint `bedrock-mantle` e as invocações assíncronas são data events e não entram.

O limite: mostra quem invocou; não impede ninguém de invocar.

### Invocações anómalas

Sobre as contagens que já se guardam, sem ler mais nada da cloud, no fim de cada leitura de quem
invocou (Amazon Bedrock, SageMaker AI, Vertex AI e Databricks) e de cada leitura do inventário
(cartão #1262, `backend/app/domain/compliance/model_invocation_anomalies.py`, com as regras em
`backend/app/domain/compliance/model_invocation_anomaly_rules.py`):

- **Pico:** por principal e modelo, a contagem de um dia contra os dias anteriores lidos por
  inteiro (até 56, desde o primeiro em que o par invocou), pelo z modificado e com o limiar
  calibrado das anomalias de dados (`backend/app/domain/quality/anomalies.py`). Pede pelo menos 5
  dias, só olha para cima e só acende com pelo menos 100 invocações acima da mediana. Em séries
  estacionárias (Poisson, com o fim de semana mais baixo e com sobredispersão), no máximo 1 % dos
  pares acendem num dia, também só entre os pares de 1000 a 5000 invocações por dia, em que a
  guarda das 100 invocações não pesa (`backend/tests/test_model_invocation_anomalies_1262.py`). O
  limiar está calibrado para 0,5 % com ruído gaussiano; com a sobredispersão das contagens, os pares
  grandes passam desse valor.
- **Principal novo:** a primeira invocação de um principal no modelo do agente nos 90 dias
  guardados, com pelo menos 10 invocações nesse dia e 5 dias lidos antes dele. O principal da ficha
  não conta.
- **Modelo novo:** um modelo do Bedrock que o inventário nunca tinha visto invocado na conta e na
  região, numa leitura do CloudTrail que não é a primeira da fonte.
- **Alerta:** cada um sai uma vez (por par, tipo e dia), com o evento `model_invocation_anomaly` no
  trilho de auditoria, sensível (severidade alta no SIEM), e a tarefa para o responsável pela
  segurança de IA depois de ele aceitar o papel e, com esse aceite, para o suplente depois de aceitar
  o dele; sem responsável ou antes do aceite dele, para os admins. Ler e decidir os alertas segue a
  mesma regra: quem um admin nomeou e ainda não aceitou leva 403, como no relatório de postura, que só conta o responsável «nomeado e
  aceitou». Os mesmos aceites dão ao responsável e ao suplente o detalhe da supervisão de cada agente
  (formação, intervenções e sinais). Mudar o responsável apaga o aceite, e os dois perdem esse
  acesso até a pessoa nova aceitar (`ai_security_owner.in_charge`). O suplente aceita o papel dele
  à parte, na mesma página e pela mesma rota, com o evento `ai_security_deputy_accepted` no trilho
  (cartão #1358): sem esse aceite não lê nem decide os alertas, não recebe as tarefas nem vê o
  detalhe da supervisão, mesmo com o papel aceite pelo responsável. Mudar o suplente apaga o aceite
  dele; mudar só o responsável não. Nomear e aceitar ao mesmo tempo não passa o aceite de uma pessoa
  para outra: os dois releem a linha do workspace trancada até ao commit. O evento leva só ids, o tipo, o
  pseudónimo do principal e contagens; nunca o modelo, que pode ser um ARN com a conta. O link da
  tarefa abre a aba «Invocações e atividade» do agente ou, no modelo novo, a secção «Modelos novos
  invocados na conta» da página Agentes de IA, fora do inventário (que é só de admins): o
  responsável que não é admin também os decide. Com domínios restritos, o registo é só de admins e
  a página de um agente cujos datasets o responsável não vê dá erro, mas as duas secções aparecem
  na mesma; sem a conformidade no plano, a dos modelos novos também. Um admin vê o ARN do principal
  quando a ficha ou o retrato o conhecem, e o modelo inteiro; o responsável pela segurança de IA vê
  o pseudónimo e só o id de um modelo do catálogo do fornecedor (Bedrock ou Model Garden do Vertex
  AI), sem a conta nem o projeto. O ARN de um modelo do cliente, um endpoint ou um serving endpoint
  fica só com os admins (`public_model_id`).
- **Esperado:** «Era esperado» sobe o limiar desse par um degrau, pela escada do falso positivo das
  anomalias (`anomaly_tuning_steps`); no fim da escada o par deixa de acender picos. «É uma
  anomalia» desce-o um degrau. As duas decisões ficam no trilho
  (`model_invocation_anomaly_decided`).
- **Retenção:** os alertas expiram com as contagens, 90 dias depois do dia, e saem com o agente e
  o workspace.
- **Limites:** só se avaliam hoje e ontem, em UTC; o CloudTrail chega com cerca de 15 minutos de
  atraso, e o dia em curso conta até aí. A inferência pelo `bedrock-mantle` e as invocações
  assíncronas não entram. No Azure OpenAI não se lê quem invocou, por isso não há pico nem
  principal novo, e o modelo novo só vem do CloudTrail do Bedrock. O alerta sai na leitura a seguir
  ao pico, a pedido ou agendada (a cadência de quem invocou, mais abaixo).

O limite: mostra a anomalia; não impede ninguém de invocar.

## Quem pode e quem invocou um modelo no Databricks

Para um agente com o modelo no Databricks do cliente, o BeryX lê quem pode invocar e quem invocou
com a conexão Databricks que já existe (cartão #1036,
`backend/app/domain/compliance/databricks_models.py`). Só lê: a REST por `GET`, por uma lista
fechada de caminhos (a lista de serving endpoints, a ACL de um endpoint e as permissões do Unity
Catalog de um model service, do esquema e do catálogo), com o token e a guarda anti-SSRF da conexão,
e o SQL às tabelas de uso com as colunas nomeadas (`backend/app/infra/connectors/databricks_serving.py`).

- **O que nunca se lê:** as inference tables, que guardam o pedido e a resposta em bruto. Na
  `system.ai_gateway.usage`, as colunas `ip_address`, `url`, `user_agent`, `request_tags`,
  `session_metadata`, `endpoint_metadata`, `mcp_metadata` e `routing_information`: as tags e a
  sessão são texto de quem chama e podem levar os utilizadores finais, e os metadados do serviço
  trazem o email de quem o criou. Na `system.serving.endpoint_usage`, as colunas `usage_context` e
  `client_request_id`. Nenhuma query usa `SELECT *`, e um teste falha se uma destas colunas ou uma
  inference table aparecer numa query.
- **Os outros workspaces:** as tabelas de uso trazem a conta toda. As duas queries filtram o
  `workspace_id` da ficha.
- **O que se guarda:** o retrato de quem pode (emails, application ids e nomes de grupos, como os
  ARNs do Bedrock) e a contagem de quem invocou por principal pseudonimizado, serviço e dia. Nunca
  um pedido.
- **Dados pessoais:** nos logs só entra o pseudónimo (`invoker_ref`), nunca um email nem o token.
  Só um admin vê o retrato e as contagens, e só num workspace com o add-on «Segurança de IA e de dados». A
  retenção é a do Bedrock: 90 dias, e saem com o agente e o workspace.
- **Privilégios:** `USE CATALOG` em `system`, `USE SCHEMA` e `SELECT` no esquema `system.ai_gateway`,
  e nada mais. A `system.serving.endpoint_usage` lê-se só se a conexão a puder ler: a página dela
  diz que só account admins a leem, e o BeryX não pede essa credencial.
- **Custo para o cliente:** as tabelas de uso só têm linhas com o usage tracking ligado. No Unity
  Gateway, o usage tracking é pago, por cada 1 KB de payload, e só se paga ligado. A página do
  usage tracking dos endpoints legacy não lhe dá preço. As consultas correm no warehouse da
  conexão. O BeryX nunca liga o usage tracking.

O limite: mostra quem pode invocar e quem invocou; não impede ninguém de invocar. Uma leitura com
um 403 diz que leitura faltou, e nunca «ninguém pode invocar».

## Quem pode e quem invocou um modelo no Vertex AI

Para um agente com o modelo no Vertex AI do cliente, o BeryX lê quem pode invocar do Policy
Analyzer e quem invocou dos Data Access audit logs do projeto (cartão #1038,
`backend/app/domain/compliance/model_access_gcp.py`). Só lê, e só os pedidos de uma lista fechada
(`ALLOWED_REQUESTS` em `backend/app/infra/gcp_model_access.py`): o `generateAccessToken` da SA de
leitura, a leitura dela, o `analyzeIamPolicy` e o `entries.list`, para quatro hosts fixos da
Google, com a guarda anti-SSRF e o IP fixado.

- **Credencial:** a SA de leitura do cliente, impersonada sem chave, com `roles/cloudasset.viewer`
  na organização e `roles/logging.privateLogViewer` no projeto. A SA, a organização e o token de
  verificação vão cifrados com Fernet, e a `description` da SA tem de trazer o token: sem ele, um
  workspace podia apontar para a SA de outro cliente. Mudar o projeto, a localização, o modelo ou a
  organização sem reenviar a SA é recusado (`reader_role_required`).
- **O filtro é o limite:** o `roles/logging.privateLogViewer` lê os Data Access de todos os
  serviços do projeto. O `entries.list` leva sempre o `logName` do `data_access`,
  `protoPayload.serviceName="aiplatform.googleapis.com"` e só os métodos de inferência, e pede só
  quatro campos. Nunca pede o request-response logging para BigQuery, o logging de previsões online
  nem os logs do contentor do endpoint, onde ficam os pedidos e as respostas. Um teste falha se o
  filtro mudar.
- **O que se guarda:** o retrato de quem pode invocar e a contagem por principal pseudonimizado,
  modelo e dia, como no Bedrock. Nunca a entrada do log: nem o IP, nem o pedido.
- **Dados pessoais:** os emails do retrato são dados do cliente. Nos logs só entra o pseudónimo
  (`invoker_ref`), e nenhum caminho os manda a um LLM. Só um admin os vê, e só num workspace com o
  add-on «Segurança de IA e de dados». O retrato expira 90 dias depois da leitura, cada dia de contagens 90
  dias depois, e os dois saem com o workspace.
- **Limite:** o Policy Analyzer não lê as deny policies nem as Principal Access Boundary, e com o
  projeto como âmbito não traz a herança (`inherited_not_included`). O BeryX faz no máximo 10
  consultas por organização e por dia, abaixo das 20 sem o Security Command Center. Uma consulta
  que a Google recusa não conta, à organização ou ao projeto, por isso uma ficha com o projeto de
  outro cliente e uma SA sem papel nele não lhe gasta o teto. Os Data Access vêm
  desligados e custam ao cliente 0,50 USD por GiB, depois de 50 GiB grátis por projeto e por mês.
  Sem nenhuma entrada do modelo, e nos pedidos em modo express, não há registo, e a página diz
  «sem registo» (`no_record`), e não «sem invocações».

O limite: mostra quem pode e quem invocou; não impede ninguém de invocar.

## Leituras agendadas: grants, quem pode invocar, quem invocou e inventário de IA

Com o add-on «Segurança de IA e de dados», o worker lê sozinho os quatro retratos, sem ninguém carregar
em «Ler agora» (`domain/compliance/security_reads.py`):

| Retrato | Cadência por omissão | Setting |
|---|---|---|
| Grants das fontes (com a IA sombra e os acessos dormentes, que se recalculam a cada leitura) | diária | `security_reads_grants_hours` |
| Quem pode invocar o modelo de cada agente, e a versão do modelo que a cloud serve (#1339) | semanal | `security_reads_invokers_hours` |
| Quem invocou o modelo de cada agente (fora da Azure, que ainda não se lê) | diária | `security_reads_invocations_hours` |
| Cada fonte do inventário de IA | diária | `security_reads_inventory_hours` |

- **Quem lê**: só os workspaces com o add-on em vigor e ativos. Um workspace suspenso ou sem o
  add-on não lê nada, nem a mensagem que já estava na fila. A demo e a formação nunca leem a cloud.
- **Fila**: cada leitura é uma mensagem em `security_read.requested`, com DLQ. A mensagem leva a
  janela em que a leitura foi reclamada e o consumer só a corre nessa janela: uma reentrega ou
  uma mensagem antiga não lê duas vezes.
- **Quem pode invocar, quem invocou e o inventário** pedem também a conformidade no plano, como
  as rotas do registo de agentes. Sem ela (pelo plano ou por um override da gestão), só os
  grants se leem.
- **Limites**: são as funções das leituras a pedido, com os mesmos tetos (os 2 pedidos por
  segundo do `LookupEvents`, os tetos de páginas, o orçamento por fonte dos grants). Uma leitura
  de quem invocou cortada a meio do intervalo volta à fila daí a uma hora e continua onde parou,
  até 6 vezes seguidas. Os outros cortes (o teto de linhas dos grants, um principal por ler, o
  teto de páginas do inventário) não se retomam e esperam pela cadência.
- **Quando a credencial falha**: o estado da leitura e o log levam só o código do erro (nos
  grants, `grants_connection_failed`). O texto do erro de cada conexão, sem os segredos da
  configuração, fica só no resumo da última leitura, que os admins leem no `GET`
  (`failed_connections`). O retrato anterior fica. À terceira falha
  seguida, os admins recebem a tarefa «Leitura de segurança a falhar» na caixa e no sino. A tarefa
  sai sozinha quando uma leitura passa, quando o que ela lê sai (a ficha retirada, a última
  conexão com grants apagada) ou quando o add-on acaba.
- **Custo**: cada leitura grava os pedidos HTTP que saíram pelo transporte da guarda anti-SSRF
  (`calls`) e o tempo (`duration_ms`), também no evento `security_read_done` do log. As consultas
  SQL aos catálogos dos warehouses não contam como pedidos.
- **Logs**: ids, tipos, códigos e contagens. Nomes, ARNs e contas do cliente não entram.
- **Score de exposição** (cartão #1278): os grants, a IA sombra, as cópias vetoriais e quem pode
  invocar o modelo entram no score só como contagens. Uma leitura que falta diz «não lido» e,
  enquanto falta, o score fica pelo menos no da v1: a falta de um retrato nunca baixa a faixa. Ler
  pode baixá-la: lido o último fator, o piso sai e conta a soma, porque com mais informação o score
  fica mais certo. Por isso um retrato que fica desatualizado pode subir a faixa sem facto novo (o
  fator volta a «não lido» e o piso volta), e o retrato seguinte devolve-a.
- **Retrato velho**: cada retrato mostra a idade («lido há 3 dias»). Um retrato lido há mais de
  `security_reads_stale_days` dias (7 por omissão) está desatualizado. No relatório de postura,
  os grants dessa conexão deixam de contar como lidos (`connections_stale`), e a secção de
  segurança de IA diz desatualizados, com o mesmo limite, o inventário, quem pode invocar, quem
  invocou e a IA sombra (`stale`, com o limite em `stale_after_days`). Na matriz de
  controlos, um inventário de IA ou uma IA sombra desatualizados deixam a linha AI-INVENTORY em
  «parcial», com «desatualizado» na evidência. Nos dois, no inventário da cloud e na IA sombra, a
  fonte mais antiga decide (é a data que o relatório mostra), e uma fonte da cloud cuja última
  leitura falhou também conta. Só contam as fontes que o workspace tem hoje: a de uma ficha
  retirada ou de uma conexão apagada sai da conta.

O «Ler agora» de cada página enfileira a mesma leitura e responde logo (202). A página mostra «na
fila» e lê o estado no `GET` de cada retrato (`read_state`) até a leitura acabar. Nos grants, as
conexões que falharam também vêm no `GET` (`failed_connections`).

## Ensaios de falha agendados e o risco de cada verificação

Os ensaios de falha de um agente simulam uma fuga de PII, um dado envenenado e uma ação proibida
contra as guardas reais, com valores sintéticos, sem ler a fonte nem chamar um LLM
(`backend/app/domain/compliance/ai_agent_drills.py`). O scheduler do worker volta a corrê-los
sozinho, `BERYX_AI_AGENT_DRILL_LEAD_DAYS` dias antes de o último que passou vencer, em cada
agente aprovado de um workspace ativo (`backend/app/domain/compliance/ai_agent_drill_schedule.py`,
cartão #1268); num workspace suspenso não corre. Um
ensaio agendado que falha não renova a validade: o agente deixa de ler dados classificados até o
cenário voltar a passar, e o dono recebe a tarefa «Ensaio agendado falhado», no sino e por email.
No registo, o autor é «BeryX (agendador dos ensaios de falha)», e nos logs do worker só ficam
contagens e o tipo de um erro.

Cada verificação leva os códigos do risco que exercita
(`backend/app/domain/compliance/ai_agent_drill_risks.py`), das fontes lidas a 20/11/2026: a fuga
de PII com LLM02:2026 (Sensitive Information Disclosure) e DSGAI01 (Sensitive Data Leakage), o dado
envenenado com LLM01:2026 (Prompt Injection) e ASI01 (Agent Goal Hijack), a ferramenta fora da
matriz e o teto por hora com LLM03:2026 (Excessive Agency) e ASI02 (Tool Misuse and Exploitation),
o token `config` e o voto de aprovação por um token com LLM03:2026 e ASI03 (Identity and
Privilege Abuse), e a instrução plantada do ensaio ao vivo (cartão #1286), que o agendador não
corre porque só um admin lhe abre a janela, com LLM01:2026 e ASI01. Os três ensaios contra as
guardas provam que a guarda recusa o caso que simulam, não que o modelo resiste a um ataque; o
ensaio ao vivo prova um caso, não a ausência de todos. Nenhum substitui o red teaming.

## Controlos de IA na AWS: o que se lê e o que se guarda

Cartão #1270 (`backend/app/infra/aws_ai_posture.py`; os achados em
`backend/app/domain/compliance/ai_control_posture_aws.py`). Na mesma leitura da fonte AWS do
Registo de IA, com o role de leitura e o ExternalId da ficha (#1020), o BeryX lê a configuração dos
controlos, nunca o tráfego:

- **Só leitura, lista fechada:** no Bedrock, o `ListGuardrails` (paginado pelo `nextToken`, até 10
  páginas de 100) e o `GetGuardrail` de cada guardrail (até 50; além disso, a listagem fica
  `truncated`), o `ListEnforcedGuardrailsConfiguration` e o `GetModelInvocationLoggingConfiguration`;
  nos Bedrock Agents, o `ListAgents`; no SageMaker AI, o `DescribeEndpoint`, o
  `DescribeEndpointConfig` e o `DescribeModel` dos endpoints listados, pelo `EndpointName` da
  listagem (com as maiúsculas com que foi criado: o ARN vem em minúsculas); no AWS Organizations, o
  `DescribeEffectivePolicy` com `BEDROCK_POLICY`; no IAM, o `GetAccountAuthorizationDetails`. Cada
  pedido vai assinado com SigV4 (`backend/app/infra/network/sigv4.py`, conferido contra o botocore
  serviço a serviço) e cada host passa pela guarda anti-SSRF com o IP fixado.
- **O que se descarta antes de guardar:** o `instruction` e o `promptOverrideConfiguration` dos
  agentes (só o SHA-256 do `instruction`, quando se pede o do alias), o `Environment`, a imagem e o
  `ModelDataUrl` dos contentores, e as definições, os exemplos, as mensagens, as palavras e os
  padrões dos guardrails.
- **O que se guarda** (`ai_discovery_reads.controls`): estados e contagens, os nomes que o cliente
  deu aos guardrails, aos agentes e aos endpoints, e o nome do bucket do registo de invocações (o
  do S3 e o dos dados grandes do CloudWatch, `largeDataDeliveryS3Config`), nunca o role.
- **Achados:** o agente sem guardrail (alto; médio quando a conta ou a organização impõem um
  guardrail, porque a AWS diz que vale para «all model invocations» e não diz se o `InvokeAgent`
  entra: guardrails-enforcements e orgs_manage_policies_bedrock, lidos a 24/11/2026), o guardrail
  sem filtro de ataque ao prompt ou que só deteta, a conta sem guardrail imposto (com as três
  provas: nada imposto à conta, nenhuma política do Bedrock na organização e nenhuma política IAM
  com a condição `bedrock:GuardrailIdentifier`), o registo de invocações desligado, o registo que
  guarda o texto e o endpoint do SageMaker AI sem isolamento de rede.
- **Quem lê o destino do registo:** o achado do texto cruza o bucket com o retrato de grants do
  #789, quando o bucket é uma conexão S3 do workspace (`backend/app/domain/compliance/ai_log_destination.py`).
  Conta só quem tem uma permissão de leitura (a ACL `READ`, o `s3:GetObject`…, sem maiúsculas):
  quem só escreve, como o `bedrock.amazonaws.com` com `PutObject` a entregar o registo, não conta,
  e uma escrita pública não torna o bucket público. O grupo de logs do CloudWatch fica «não lido».
- **Não lido não é achado:** uma permissão em falta fica em `unread`. Sem `textDataDeliveryEnabled`
  na resposta, o texto fica por provar (a API Reference não lhe dá valor por omissão, lida a
  24/11/2026). Com todas as listagens por ler (um role sem as permissões), a fonte diz «não lido»
  no Registo de IA e no relatório de postura, com as contagens a `null`, nunca «0 achados».
- **Logs:** só o fornecedor, o código de erro e as contagens (`ai_control_posture_read`). Nenhum
  nome vai aos logs nem a um LLM.
- **A correção é para copiar:** comandos `aws` e o bloco da política IAM. O BeryX não tem
  credencial de escrita e não os aplica.

## Controlos de IA no Azure e na Google: o que se lê e o que se guarda

Cartão #1271 (`backend/app/domain/compliance/ai_control_posture.py`). Na mesma leitura de uma fonte
do Registo de IA, com a credencial que já existe, o BeryX lê a configuração dos controlos, nunca o
tráfego:

- **Só leitura, lista fechada:** no Azure, só `GET` à conta, aos deployments, aos `raiPolicies` e
  ao `diagnosticSettings` dela (`backend/app/infra/azure_ai_posture.py`), pela lista fechada do
  #1039; o `listKeys` nunca se pede. Na Google, só `GET` aos templates e ao floor setting do Model
  Armor, ao Resource Manager e aos endpoints, e o `POST …:getIamPolicy`
  (`backend/app/infra/gcp_ai_posture.py`); o `sanitizeUserPrompt`, que levaria um prompt, recusa-se
  antes de sair. Cada host passa pela guarda anti-SSRF com o IP fixado.
- **O que se guarda** (`ai_discovery_reads.controls`): estados (bloqueia, só anota, desligado ou
  por provar; público ou privado; ligado ou não), os nomes e o modelo dos deployments, das políticas, dos templates e dos
  endpoints, os ids do projeto, da pasta e da organização onde se leu o `auditConfigs`, e contagens. Dos destinos dos logs, só o tipo; do `getIamPolicy`, só o `auditConfigs`,
  e dos membros isentos só o número: os bindings e os emails não se guardam.
- **Logs:** só o fornecedor, o código de erro e as contagens de achados e de leituras por fazer
  (`ai_control_posture_read`). Nenhum nome vai aos logs nem a um LLM.
- **A correção é para copiar:** cada achado traz comandos `az` ou `gcloud` (no Azure, `GET`, `jq`
  e `PUT` do recurso lido). O BeryX não tem credencial de escrita e não os aplica.
- **A leitura dos controlos nunca tira a descoberta:** um host que não resolve (o Model Armor numa
  localização sem ele) fica `host_not_allowed` sem pedido, e uma falha inesperada fica só com o
  tipo no `error_code` dos controlos.

## Versão do modelo: fixada ou a mudar sozinha

Cartão #1339 (`backend/app/domain/compliance/model_versions.py`). A ficha declara a versão do
modelo; na cloud, um deployment do Azure OpenAI com atualização automática troca de versão quando
a Microsoft muda a versão por omissão, e um modelo do Bedrock entra em fim de vida com data
marcada. Na leitura agendada de quem pode invocar, com a mesma credencial, o BeryX lê a versão que
a cloud serve e compara-a com a da ficha:

- **Só leitura, só metadados:** no Azure, a lista dos deployments da conta (o `model.version` e o
  `versionUpgradeOption` do deployment da ficha) e a lista dos modelos da conta (`GET
  {conta}/models`: o `lifecycleStatus`, o `deprecation.inference` e a versão por omissão), pela
  lista fechada do #1039 (`backend/app/infra/azure_model_version.py`); o deployment sozinho
  continua fora dela. No Bedrock, o `GetInferenceProfile` (o modelo de um inference profile) e o
  `GetFoundationModel` (o `modelLifecycle`), só por `GET` ao host da região
  (`backend/app/infra/aws_model_lifecycle.py`). Nenhuma devolve pedidos, respostas nem logs.
- **O que se guarda** (`ai_agent_model_versions`): o modelo, a versão, a opção de atualização, o
  estado e as datas do fornecedor, o que ficou por ler e a última mudança de versão vista. O
  resource ID do deployment ou o ARN do modelo já estão na ficha.
- **O BeryX nunca muda a ficha nem a cloud:** a ficha diz «declarada X, observada Y», a tarefa vai
  ao dono do agente, e a correção (`az rest` com `GET`, `jq` e `PUT` do deployment) é para copiar,
  só para admins. Uma versão nova vista na cloud fica no trilho
  (`ai_agent_model_version_changed`, autor «BeryX (versão dos modelos na cloud)»).
- **Não lido não é achado:** uma permissão em falta fica em `unread` e os campos dessa leitura
  não contam. Sem `versionUpgradeOption` na resposta, a opção não se presume e fica «não lida»
  (`version_upgrade_option`): a Microsoft documenta o valor vazio como `OnceCurrentVersionExpired`
  nos deployments Standard, e os Provisioned nunca mudam sozinhos (página «working with models»
  do Azure OpenAI, lida a 24/11/2026). Um ARN de modelo personalizado ou importado é da conta: não
  tem ciclo de vida do fornecedor e não se pede nada (`account_model`). Uma etiqueta de versão
  sozinha na ficha (`v1:0`) não bate com o modelo servido, e o prefixo de geografia do inference
  profile (`us.`, `eu.`, `global.`…) não conta.
- **Uma falha não fecha tarefas:** uma leitura que falha, ou que deixa a versão ou o ciclo de vida
  por ler, mostra «não lido» e guarda os valores da última que passou; a tarefa do dono só fecha
  com uma leitura que passa e já não dá o achado. Um modelo `LEGACY` com a data de fim de vida
  além dos 90 dias do aviso dá um achado baixo, com a data.
- **Logs:** só ids, o fornecedor, o código de erro e as contagens (`model_version_read`). Os
  nomes e as versões não vão aos logs nem a um LLM.
- **Fora:** o SageMaker AI (sem versão do fornecedor), o Vertex AI (as datas de retirada dos
  Gemini estão só na documentação da Google) e o Databricks (o endpoint fixa a versão do Unity
  Catalog, sem atualização automática nem fim de vida na API) ficam «não lido».

## Controlos de IA no Databricks e no Snowflake: o que se lê e o que se guarda

Cartão #1272 (`backend/app/domain/compliance/ai_control_posture.py`). Com a conexão que o workspace
já tem, sem credencial nova, na mesma leitura da fonte do Registo de IA:

- **Databricks, só `GET`:** depois da lista da descoberta, o `GET /api/2.0/serving-endpoints/{name}`
  de cada endpoint do cliente listado, até 100 (`backend/app/infra/connectors/databricks_serving.py`,
  pela lista fechada e pela guarda anti-SSRF da conexão). Lê-se o `ai_gateway` (os guardrails de
  entrada e de saída, a inference table, os limites de taxa e o usage tracking) e a inference table
  legacy (`auto_capture_config`); da configuração de cada modelo, nada. A inference table cruza com o
  retrato de grants já guardado (`source_access_grants`), se a tabela é um dataset da conexão, e conta
  só quem a lê (o `MODIFY` não): a tabela nunca se lê. Os endpoints de pagamento por token (`databricks-…`) não se leem, como na
  descoberta.
- **Snowflake, só `SHOW` e um `SELECT CURRENT_REGION()`:**
  `SHOW PARAMETERS LIKE 'AI_SETTINGS' IN ACCOUNT`,
  `SHOW PARAMETERS LIKE 'CORTEX_ENABLED_CROSS_REGION' IN ACCOUNT`, `SHOW GRANTS ON ACCOUNT`
  (até 5000 linhas; no teto, a listagem fica `truncated` e o `PUBLIC` sem o privilégio nas linhas
  lidas fica por provar, nunca «não tem») e `SELECT CURRENT_REGION()`, pela guarda read-only do
  catálogo (`backend/app/infra/connectors/snowflake_ai_posture.py`). A inferência entre regiões
  cruza com os datasets da conexão que têm colunas de dados pessoais no BeryX e com a geografia da
  região da conta (`backend/app/domain/compliance/ai_control_posture_snowflake.py`): alta com
  `ANY_REGION`, um `*_GLOBAL` ou um grupo de outra geografia; baixa com o grupo da geografia da
  conta (o valor que a correção sugere, e com que os Cortex AI Guardrails funcionam); média, com o
  motivo, sem a região lida. Os valores e os grupos são os da documentação da Snowflake, lida a
  24/11/2026 (docs.snowflake.com/en/sql-reference/parameters#label-cortex-enable-cross-region,
  docs.snowflake.com/en/user-guide/snowflake-cortex/cross-region-inference e
  docs.snowflake.com/en/user-guide/snowflake-cortex/cortex-ai-guardrails). Guardrails em `LOG`
  (detetam e registam) dão um achado baixo, abaixo do `OFF` (médio). Cada conexão Snowflake conta como uma fonte na quota de fontes de IA, como a
  conexão Databricks (`backend/app/domain/compliance/ai_source_quota.py`).
- **Sem nenhum `SHOW` lido, a leitura falhou:** um `SHOW` recusado fica por ler e os outros
  leem-se. Com os três por ler (a password mudada, o utilizador desativado, a conta em baixo), a
  fonte fica com a leitura falhada e um código: o motivo comum, ou `query_failed` com motivos
  diferentes (`read_snowflake` em `backend/app/domain/compliance/ai_control_posture.py`). A leitura
  agendada conta a falha e, à 3.ª seguida, os admins recebem a tarefa, como nas clouds.
- **O que se guarda** (`ai_discovery_reads.controls`): estados, o nome e o `task` dos endpoints, o
  nome das inference tables e as contagens de quem as lê; no Snowflake, o estado dos guardrails, o
  valor do `CORTEX_ENABLED_CROSS_REGION`, a região da conta, os papéis com `USE AI FUNCTIONS` e o
  número de datasets com dados pessoais. Nunca o texto do `AI_SETTINGS` nem a mensagem de um erro: só o código.
- **Logs:** como no #1271, só o fornecedor, o código e as contagens (`ai_control_posture_read`).
- **A correção é para copiar:** o comando `databricks` lê o `ai_gateway` em vigor e muda um campo
  só (o `put-ai-gateway` troca o objeto todo), e o SQL do Snowflake é um `ALTER ACCOUNT` ou um
  `REVOKE`. O BeryX não os aplica.
- **O que não se lê, e o ecrã diz:** as service policies do Unity Gateway. O Unity Gateway, o
  substituto do AI Gateway (legacy), está em GA («A new Unity Gateway experience is generally
  available», página do Databricks de 17/11/2026), mas as service policies estão em Beta e
  anexam-se só pela UI («Policy attachment is UI-only», página de 18/11/2026): a documentação lida
  a 21/11/2026 não lhes dá API de leitura. E o Cortex Guard do `AI_COMPLETE`, que é uma opção de
  cada chamada (`guardrails` em `model_parameters`) e não fica em nenhum parâmetro da conta. Os
  guardrails do AI Gateway (legacy) estão em Public Preview, e os Cortex AI Guardrails só se aplicam
  ao CoCo, ao Snowflake CoWork e aos Cortex Agents e pedem a inferência entre regiões ligada.

## Servidores MCP nas máquinas: o que o `beryx agents scan` lê e envia (exceção, por opção)

Cartão #1288. Os servidores MCP que os agentes de código usam vivem em ficheiros de configuração
nos portáteis e no CI, onde nenhuma leitura de cloud chega. O `beryx agents scan` do SDK lê-os e
envia ao BeryX só metadados. É uma exceção à regra da casa (o BeryX não corre do lado do cliente),
aprovada pelo owner a 19/11/2026, com estes limites:

- **Desligada por omissão.** Um admin liga-a no Inventário de IA, e o evento fica em
  `admin_events` (`mcp_scan_enabled`). Desligada, o envio dá 409 e nada se grava
  (`backend/app/domain/compliance/mcp_machine_scan.py`).
- **Não é um agente residente.** É um comando que alguém corre, ou que o cliente agenda no CI ou
  no MDM. Lê só os ficheiros de configuração MCP do Claude Code (com o `managed-mcp.json` do
  MDM), do Claude Desktop, do Cursor, do VS Code e do Codex; do `~/.claude.json`, só as chaves
  `mcpServers`, nunca o histórico das conversas. Não lê prompts, respostas nem código.
- **O que sai** (`sdk/src/beryx/agents_scan.py`): o cliente, o âmbito, o nome que a configuração dá
  ao servidor, o transporte, o executável sem a pasta, o pacote e a versão declarados, o host de um
  remoto, se está desligado e se o ficheiro tem um segredo em claro (só sim ou não). A máquina e o
  projeto vão como pseudónimos: HMAC-SHA-256 com uma chave aleatória que fica só na máquina, pelo
  que o BeryX não volta deles ao nome da máquina, da pessoa ou da pasta. Com `--machine-label` (no
  CI), a máquina vai com esse nome e a chave dos projetos sai do segredo `BERYX_SCAN_KEY` do CI; sem
  ele, sai só do nome, que o BeryX recebe, e quem o souber confirma um caminho que adivinhe: a CLI
  avisa (`docs/AGENTES_CODIGO.md` §4 diz o que fica reversível).
- **O que nunca sai:** os valores das variáveis de ambiente e dos cabeçalhos, os tokens, os
  argumentos, os caminhos, as query strings e o caminho e o utilizador de um URL. A API repete os
  cortes num schema fechado (`backend/app/api/v1/mcp_machine_servers.py`): um caminho, um URL
  inteiro ou um campo a mais dão 422. Os testes plantam segredos em todos estes sítios e provam
  que nenhum chega ao pedido nem à base de dados.
- **Impressão digital das ferramentas (`--tools`):** só os servidores remotos, só HTTPS (HTTP só
  para o próprio computador) e sem seguir redirecionamentos, com os cabeçalhos da configuração e
  para o URL dela. O URL e os cabeçalhos de um ficheiro de projeto não leem o ambiente nem as
  variáveis do editor (`${userHome}`, `${workspaceFolder}`): um repositório clonado não leva os
  tokens nem os caminhos de quem o corre para o host que indicar. Sai o SHA-256 da lista das
  definições (a canonicalização do manifesto do #1269), nunca as definições. Um servidor local só
  arranca com `--start-stdio` e a confirmação, servidor a servidor, num terminal, com o ficheiro e o
  âmbito de onde vem e os caracteres de controlo escapados; os de um ficheiro de projeto pedem
  também `--allow-project-stdio`. Arranca só com `HOME`, `PATH`, `SHELL`, `TERM`, `USER` (e as
  variáveis de sistema do Windows) e o `env` da entrada, nunca com o `BERYX_TOKEN` nem o resto do
  ambiente.
- **Na máquina** só fica a chave do pseudónimo (só para o utilizador), gravada no primeiro envio;
  o `--dry-run` mostra o JSON exato e não grava nada.
- **No BeryX:** os nomes dos servidores, os pacotes e os hosts são do cliente e nunca entram nos
  logs (só contagens) nem num LLM. O que nenhuma máquina volta a enviar em 90 dias sai, e o
  apagamento do workspace leva tudo.

O limite: o inventário é o que as máquinas onde o comando correu declaram nos ficheiros que o
BeryX conhece. Um cliente MCP que ele não lê, uma máquina onde ninguém o corre ou um servidor
configurado noutro sítio não aparecem; a impressão digital vem do servidor, no momento da leitura.

## Agentes nas plataformas: o que se lê e o que nunca se guarda

Cartão #1273 (`backend/app/domain/compliance/ai_platform_agents.py`). Na mesma leitura de uma fonte
do Registo de IA, com a credencial que já existe (o role de leitura da AWS, a app de leitura do
Azure), o BeryX lê a configuração dos agentes do Bedrock, dos runtimes e dos gateways do AgentCore,
dos agentes do Microsoft Foundry e das identidades de agente do Entra. Lê o que o agente pode fazer,
nunca o que ele fez:

- **Só leitura, listas fechadas:** na AWS, treze operações de nível «List» ou «Read»
  (`backend/app/infra/aws_agent_config.py`), da versão `DRAFT` de cada agente; no Azure, só `GET` aos
  projetos da conta, à lista dos agentes e das ligações de cada projeto e, na Microsoft Graph, às
  identidades de agente e aos donos (`backend/app/infra/azure_agent_config.py`). Nenhum caminho de
  threads, mensagens, respostas ou invocações está na lista. Cada host passa pela guarda anti-SSRF
  com o IP fixado.
- **As instruções passam pela memória e descartam-se:** o `GetAgent` do Bedrock devolve o
  `instruction`, e a lista dos agentes do Foundry traz as `instructions`. O texto descarta-se no
  parser, antes de chegar à BD, aos logs ou a um LLM. Do Foundry, o SHA-256 calcula-se em memória e
  não se guarda: o owner decidiu (19/11/2026) que o hash só se guarda com a opção da ficha da secção
  «O prompt de um agente», que hoje só existe para os agentes do Bedrock. Os valores das `environmentVariables`, os
  `headers` e o `authorization` de uma ferramenta MCP e as credenciais das ligações não se guardam
  (só o número de variáveis e o tipo de credencial). Um teste prova-o
  (`backend/tests/test_ai_platform_agents_aws_1273.py`).
- **A permissão do Foundry é mais larga do que o uso:** a data action `agents/read` também dá
  leitura a threads e mensagens. O BeryX nunca as pede, e um papel próprio só com as duas data
  actions de leitura é o mais estreito que a documentação permite.
- **Os sponsors do Entra ficam por ler:** a Graph só os lista com `AgentIdentity.ReadWrite.All`,
  uma permissão de escrita. O BeryX não a pede; uma identidade sem donos é achado (o achado diz que
  os sponsors ficam por ler), e sem sponsor
  não se afirma.
- **O que se guarda** (`ai_observations.agent_config`): o modelo, o role, a memória, o nome e o
  tipo de cada ferramenta, o bucket e os prefixos de cada base de conhecimento, a rede, o
  autorizador, o modo do policy engine, o host de cada servidor MCP e o tipo de credencial, e o
  número de donos de uma identidade. Do URL de um servidor MCP fica só o host, e a porta se não for
  a 443 (`endpoint_of`, em `backend/app/infra/aws_agent_parsers.py`): o caminho pode trazer a chave
  do servidor (o Zapier dá `/api/mcp/s/…/mcp`), a query um token e o URL as credenciais, e
  nada disso chega à BD, à API ou ao «criar ficha». A lista aprovada compara-se pela mesma regra.
  Nos logs, só o fornecedor e as contagens (`ai_platform_agents_read`).
- **Nada se escreve na cloud do cliente:** cada achado diz o que fazer; o BeryX não tem credencial
  de escrita. Uma falha da leitura dos agentes nunca tira a descoberta.

## Artefactos de modelos: o que o scan lê e o que guarda (exceção, por opção)

Cartão #1287 (`backend/app/domain/compliance/model_artifact_scans.py`). Um modelo guardado em pickle
(o `torch.save`, o joblib, o pickle de um modelo do scikit-learn) pode executar código ao ser
carregado. O scan diz, de cada artefacto do modelo de um agente, se o formato é seguro ou se o
pickle chama alguma coisa perigosa. Para isso o BeryX lê o ficheiro do modelo do cliente, o que a
regra da casa deixava de fora: é uma exceção, por opção.

- **Desligado por omissão.** Um admin liga-o para cada agente, com os URIs dos artefactos
  (`PUT /api/v1/compliance/ai-agents/{id}/artifact-scan`), e o evento fica em `admin_events`
  (`model_artifact_scan_enabled` e `model_artifact_scan_disabled`, sem os URIs). Com o scan
  ligado, entram também os artefactos que a leitura de quem pode alterar o modelo (#1274) encontrou
  na cloud, se essa leitura é da referência que a ficha tem hoje. Desligar apaga os veredictos e a
  leitura agendada. Na demo e na formação nada lê a cloud.
- **Uma permissão nova e estreita, que o cliente dá se quiser.** O scan usa o role do IAM e o
  ExternalId da ficha (Amazon Bedrock e SageMaker AI) ou a SA de leitura impersonada (Vertex AI),
  com `s3:GetObject` ou `storage.objects.get` só no prefixo do artefacto. Sem ela, o artefacto
  fica «não lido» (`permission_missing`). No S3 vai sempre `x-amz-expected-bucket-owner` com a
  conta da ficha: um bucket de outra conta recusa.
- **O que se lê.** Só `HEAD` (ou os metadados no GCS) e `GET` com `Range`
  (`backend/app/infra/model_artifact_reader.py`), pela guarda anti-SSRF com o IP fixado, e cada
  `GET` com a versão do `HEAD` (`If-Match` ou `ifGenerationMatch`): um objeto trocado a meio fica
  «não lido». Num safetensors, o cabeçalho; num GGUF, os 24 bytes da assinatura e das contagens;
  num zip do PyTorch (também ZIP64), o fim do ficheiro, o diretório central e os membros `.pkl`;
  num pickle solto, os opcodes, saltando os argumentos grandes sem os pedir. Os tensores nunca se
  descarregam. Tetos por artefacto: 64 MiB pedidos, 512 pedidos, 2 milhões de opcodes e 120 s.
  Num torch.save de 6 GiB lê-se menos de 1 KB, em 7 pedidos
  (`backend/tests/test_model_artifact_formats_1287.py`). Uma pasta não se lê nem se lista (o
  `S3Prefix` do SageMaker AI, o modelo importado no Bedrock, o `artifactUri` do Vertex AI): fica
  «não lida» (`prefix_not_listed`), sem pedido, porque listar pedia `s3:ListBucket`. Um gzip (o
  `model.tar.gz` do SageMaker AI) fica `tar_gz_not_supported`: não se lê por intervalos.
- **Nunca se desserializa.** Nenhum `pickle.load` nem `torch.load` corre: os opcodes leem-se um a
  um, com os metadados do `pickletools`, e simula-se só o que diz que objeto o pickle importaria
  (`backend/app/domain/compliance/model_artifact_pickle.py`). A lista das chamadas perigosas é
  nossa, comparada a 23/11/2026 com as do picklescan e do ModelScan. Cada nome compara-se como o
  `find_class` do Python o resolve: qualquer prefixo do caminho módulo.nome na lista, um nome com
  pontos fora das importações conhecidas (desde o protocolo 4 o nome segue os atributos, e
  `logging` + `os.system` é o `os.system`), um segmento `__…__` no nome, e os nomes do Python 2 que
  os protocolos 0 a 2 trocam pelos do 3 (`cStringIO.open` é o `io.open`). Num ficheiro com vários
  pickles seguidos (o `torch.save` antigo, que o `torch.load` carrega um a um) leem-se todos, até 8,
  com ou sem `PROTO` no início; os tensores que vêm a seguir param a leitura sem contar. Uma
  chamada perigosa vista antes de uma recusa da cloud ou do fim do prazo fica: o artefacto sai
  perigoso, com o motivo do corte, e a leitura seguinte vai até ao fim.
- **O que se guarda** (`model_artifact_scans`): de cada artefacto, o URI (só a API de admin o lê),
  o formato, o veredicto (`safe_format`, `pickle_clean`, `pickle_dangerous` ou `not_read`, com o
  motivo), os nomes das chamadas perigosas (só nomes da nossa lista), quantas importações o pickle
  faria e quantas ficam fora das conhecidas (sem os nomes, que podem ser módulos do cliente), a
  versão do objeto (o ETag ou a geração) e, de cada parte lida, o nome curto, o SHA-256 e os bytes.
  Nunca o conteúdo. A ficha do Anexo IV mostra o veredicto e os SHA-256 sem o URI.
- **Quando volta a correr:** de 24 em 24 horas (`security_reads_artifact_scan_hours`), na fila
  própria `model_artifact_scan.requested` (um scan de cada vez por worker), ou no «Ler agora». Um
  artefacto com a mesma versão só leva o `HEAD`; a versão nova lê-se de novo.
- **Logs:** só ids, códigos e contagens. Nenhum URI, bucket ou chave vai aos logs nem a um LLM.

Os limites: não deteta backdoors nos pesos nem avalia o comportamento do modelo, e um formato
seguro não diz que o modelo é bom. A lista das chamadas é uma lista: o que não está nela passa
como «sem achados», e por isso o veredicto conta as importações desconhecidas. As camadas `Lambda`
de um Keras (HDF5 ou `.keras`) e o template de chat de um GGUF não se analisam.

Testes: `backend/tests/test_model_artifact_formats_1287.py`,
`backend/tests/test_model_artifact_properties_1287.py` e
`backend/tests/test_model_artifact_scans_1287.py`.

## Limites de tentativas no início de sessão

O login por password tem três limites, em `backend/app/api/ratelimit.py`:

- **Por IP e email:** 5 tentativas por minuto.
- **Por IP:** 30 tentativas em 5 minutos, somadas entre o login, o registo e o pedido de recuperação
  de password. Trava o *password spraying*, em que uma password fraca é tentada em muitos emails a
  partir do mesmo IP.
- **Por conta:** 20 tentativas em 15 minutos, de qualquer IP. Trava a força bruta distribuída por
  muitos IPs contra a mesma conta. A chave é o sha256 do email e vale igual para emails sem conta. O
  pedido de recuperação de password tem um limite por conta à parte, com os mesmos números.

Os três verificam-se antes de a tentativa contar, por isso um 429 num deles não gasta os outros. Uma
entrada com a password certa não gasta nenhum. Acima do limite, a resposta é 429 com `Retry-After` e
a mesma mensagem, exista a conta ou não, e sai antes de a API procurar a conta. Quando o limite por
conta dispara, o registo de auditoria do workspace da conta recebe `login_throttled`, com o hash do
email e o IP, nunca a password, uma vez por conta em cada janela.

Quem sabe o email de uma conta consegue travar-lhe o login por password durante 15 minutos. O SSO e o
pedido de recuperação de password continuam a funcionar nesse tempo.

Pela aplicação web, o limite por IP conta o IP do browser, que o servidor web atesta à API com uma
chave partilhada. Em produção, a API não arranca sem essa chave. Fora de produção e sem ela, a API vê
o mesmo IP em todos os pedidos da aplicação. Para que as
falhas de uns utilizadores não travem o login aos outros, um pedido que se apresente como vindo do
servidor web fica então fora do limite por IP. Os limites por IP e email e por conta aplicam-se na
mesma. Em produção, a chave está ativa desde 11/10/2026.

Nos limites por IP da API, um endereço IPv6 conta pelo seu bloco /64 e um IPv4 pelo endereço
completo. Quem tem um bloco IPv6 escolhe a parte final do endereço, e mudar de endereço dentro do
bloco não abre um limite novo.

Os contadores ficam em memória em cada instância da API: com 3 instâncias, cada limite pode valer até
o triplo. A contenção central, por IP real, é a do Cloud Armor (ver «Perímetro»), ainda por aplicar
em produção.

Testes: `backend/tests/test_security_gates.py` e `backend/tests/test_ipv6_rate_limit.py`.

## Passwords e convites

Quem define uma password não pode escolher uma password comum. A regra vale no registo, no convite
com password inicial, na definição por link de convite ou de redefinição e no primeiro admin de um
workspace de organização. A API responde 422 `password_too_common`, antes de olhar para o email e sem
gastar o link, quando a password, em minúsculas, está na lista
`backend/app/domain/auth/common_passwords.txt` (cerca de 11 700 entradas, quase todas da SecLists),
repete a mesma unidade, tem menos de quatro caracteres diferentes ou segue uma fila do teclado ou do
alfabeto. Sem os dígitos e símbolos das pontas, a regra repete-se no que sobrar, se forem pelo menos
quatro caracteres: a lista sempre e as outras regras só com letras, para uma password gerada como
`9731a58204` passar. O login não passa por esta regra: quem já tem uma password fraca continua a
entrar e só a cumpre quando a mudar.

O registo grava o email em minúsculas e sem o ponto final do domínio (`eu@acme.pt.` é `eu@acme.pt`).
Assim, a forma de escrever não abre uma segunda conta para a mesma caixa nem salta o domínio
reclamado por uma organização. Um texto que não seja um só endereço dá 422 `email_invalid`, também
antes de procurar a conta.

As contas registadas com o ponto final antes desta regra passaram à mesma forma na migração
`231ad0bc1ac9`. Quando o endereço sem o ponto já tinha conta, a cópia ficou desativada e a API recusa
as sessões dela. Cada conta mexida deixou um evento no trilho de auditoria do seu workspace. Se o
domínio é de uma organização e o workspace da conta está fora dela, o primeiro workspace da
organização recebeu `domain_account_outside_org`, com o endereço e o workspace solto. O login, o reset
da password e o convite escritos com o ponto final encontram a conta sem ele, e cada ponto a mais conta
no mesmo limite de tentativas da conta. Os convites, o seed e o SSO gravam o endereço sem o ponto.

Cada email só tem uma conta em toda a plataforma. Com email configurado, o `POST /auth/users` responde
202 com o mesmo texto, tenha o email conta noutro workspace ou não. O hash da password corre nos dois
casos e os emails só saem depois da resposta, por isso o tempo de um envio não entra no tempo de
resposta. Se o email tiver conta noutro workspace, essa conta não muda, o registo de auditoria de quem
convidou recebe `member_invited` e o dono do email recebe um aviso sem link, no máximo um por dia em
cada instância da API. Esse aviso pode chegar a qualquer conta da plataforma, por isso não tem texto
variável: não leva o nome de quem o recebe, o de quem convidou nem o `name` do pedido. Provar a caixa
não prova o nome, que pode ter sido escrito por outra pessoa, e por isso nenhum email de conta o usa
na saudação. Um envio que falhe não muda a resposta: fica no log como `invite_email_failed`, sem o destinatário. Quem já
está no workspace dá 409. Sem transporte de email, a resposta é 201 ou 409, como no registo.

O `POST /org/workspaces` segue a mesma regra para o `admin_email`, com ou sem `training_pack`. Com email
configurado responde 202 com o mesmo texto, tenha o email conta noutra organização ou não. O hash da
password corre nos dois casos, os emails saem depois da resposta e o conteúdo de um workspace de
formação chega na volta seguinte do worker, fora do pedido. Com o RabbitMQ indisponível esse conteúdo
é criado no pedido, e aí o tempo de resposta volta a distinguir os dois casos na formação. Um workspace
não nasce sem admin, por isso um email com conta noutra organização não cria nada: essa conta não
muda, o registo de auditoria de quem pediu recebe `organization_workspace_not_created`, sem o email, e
o dono do email recebe o mesmo aviso, com o mesmo máximo de um por dia. Uma conta de um workspace da
própria organização dá 422. Sem transporte de email, a resposta é 201 ou 422.

A resposta deixou de confirmar a conta, mas quem convida ainda consegue distinguir os dois casos:

- a conta criada aparece na lista de utilizadores e a de outro workspace não;
- repetir o convite dá 409 a quem ficou no workspace e 202 a quem tem conta noutro;
- com password inicial, o registo de auditoria grava `member_created` para a conta criada e
  `member_invited` para a de outro workspace, e só a conta criada aceita essa password no login;
- o workspace pedido só aparece no `GET /org/workspaces` e só ocupa o nome se o email estiver livre, e
  o registo de auditoria grava `organization_workspace_created` ou `organization_workspace_not_created`.

Por isso os convites e o `POST /org/workspaces` contam no mesmo limite, 30 por hora e por organização
(`invite_rate_limit_invites`), quaisquer que sejam os emails, com 429 e `Retry-After`. O limite conta
na base de dados, e todas as instâncias da API partilham a mesma janela. Todos os workspaces da
organização gastam essa janela: um workspace criado com o `POST /org/workspaces` gasta um convite e
não traz convites novos ao admin que lá entra, mesmo que seja uma conta de quem o criou. Um workspace
ainda sem organização recebe a pessoal no primeiro convite, e conta logo na janela dela.
O `POST /org/invites` e o SCIM também dizem que a conta existe: o primeiro só aceita emails do domínio
reclamado pela organização e o segundo exige um token da organização.

O convite a uma conta de outro workspace deixa o email no registo de auditoria de quem convidou. Quando
essa conta é apagada, sozinha ou com o workspace dela, o email sai também desse registo.

Os links de redefinição de password e de convite seguem por email. Numa instalação com relay SMTP
próprio (`smtp_host`), como uma instância dedicada, a ligação usa STARTTLS e verifica o certificado e
o hostname do relay antes de enviar a password SMTP. Valem as CAs públicas do `certifi` ou a CA interna
do relay em `smtp_ca_pem`, validada no arranque. Um relay que não anuncia STARTTLS, ou cujo
certificado falha a verificação TLS, não recebe a password nem o email, e o envio falha
(`backend/app/infra/email/sender.py`).

Num workspace de formação ou da demo não sai nenhum email de redefinição de password. Lá, um admin
cria contas com password para qualquer endereço, sem convite, e o reset levaria o email da sandbox a
quem nunca pediu nada. O pedido responde o mesmo 202 de sempre, sem dizer se a conta existe, e o
worker não emite o link nem envia o email ou o aviso de SSO. A mudança de email também não sai de
lá (cartão #1359): o `PATCH /auth/me` com um email novo dá 403 e diz porquê, sem emitir o link
para o endereço novo e sem mexer na conta, e um link pedido antes de o workspace passar a formação
ou a demo muda a conta sem o aviso ao endereço anterior.

## Início de sessão único (SSO)

O SSO usa OIDC com o fluxo authorization code, ou SAML 2.0 no IdP de uma organização
(`backend/app/domain/auth/sso.py`, `backend/app/infra/sso/oidc.py`).

- **O fluxo fica preso ao browser que o começou.** O arranque cria um `state` aleatório, de uso
  único e válido 10 minutos. Na base de dados ficam só o hash dele, o `nonce` e o verificador PKCE.
  O browser recebe o cookie `dv_sso`: `HttpOnly`, `Secure` em https, `Path=/api/v1/auth/sso`,
  10 minutos e `SameSite=Lax` no OIDC. Só o arranque SAML usa `SameSite=None`, porque o IdP devolve
  a resposta num POST. O callback e a troca do código só aceitam o fluxo com o mesmo cookie, por
  isso um `state` ou um código obtido noutro browser é recusado. Isto trava o login CSRF, em que o
  atacante leva a vítima a entrar na conta dele. Vale para o IdP de cada organização e, desde o
  cartão #370, para o IdP da instalação (`DATAVAULT_OIDC_*`).
- **PKCE S256 e `nonce` em todos os pedidos OIDC**, mesmo com client secret. O POST ao token
  endpoint leva o `code_verifier` do fluxo.
- **O ID token é a prova.** A assinatura confere-se pelo JWKS do discovery do IdP, só com
  algoritmos assimétricos. Valida-se o `iss`, o `aud` (e o `azp` com várias audiências), o `exp` e o
  `iat` com 2 minutos de folga e o `nonce` do pedido. O userinfo só se pede quando o ID token não
  traz o email ou os grupos, e é recusado se for de outro `sub`. Um email que o IdP dá como por
  verificar (`email_verified` falso) não entra.
- **Discovery e chaves em cache com prazo.** O discovery fica 1 hora em cache por issuer e só vale
  se for desse issuer. O JWKS recarrega quando aparece um `kid` desconhecido (rotação de chaves), no
  máximo uma vez a cada 30 segundos.
- **O redirect URI do IdP da instalação não muda, mas só segue hosts da instalação.** Continua a ser
  o host com que o pedido chega à API, se for o do `app_base_url`, o de uma base antiga, o do
  `api_public_base_url`, um host antigo da API ou um dos `BERYX_OIDC_CALLBACK_HOSTS`, onde o deploy
  põe o host do `API_UPSTREAM` do nginx (cartão #655). O `Host` vem do cliente: com outro, o
  redirect URI é o do `app_base_url`, e um `Host` forjado não manda o código do IdP para fora da
  instalação. Atrás do nginx da app o host é o `api.`, onde o cookie não chega. Aí o callback salta
  uma vez para o mesmo caminho no host da app (`backend/app/domain/auth/sso_rebound.py`), e é lá que
  o cookie se confere.
- **A sessão não vai no URL.** O fim do fluxo leva um código de troca de uso único, válido 60
  segundos, que a app troca pela sessão num POST com o mesmo cookie
  (`backend/app/domain/auth/sso_exchange.py`).
- **Os erros do IdP não saem do servidor.** O browser volta ao login com um código estável (por
  exemplo, `?sso_error=idp_http_error`) e a app mostra uma mensagem fixa. O log estruturado
  (`sso_login_failed`) leva o código e a etapa, nunca o que o IdP respondeu.

Testes: `backend/tests/test_sso_installation.py` e `backend/tests/test_sso_org.py`.

## Sessões

Cada início de sessão fica registado com o dispositivo, o IP truncado (/24 em IPv4, /48 em IPv6),
a data de criação e o último uso; o token nunca é guardado (`backend/app/domain/auth/sessions.py`).
Em «Segurança da conta → Sessões ativas», cada pessoa vê onde tem sessão aberta, termina uma sessão
ou todas as outras. «Terminar sessão» acaba a sessão também no servidor.

- **Inatividade.** Uma sessão sem pedidos durante 12 horas termina. O administrador do workspace pode
  exigir menos, até 15 minutos, em «Equipa → Sessões». A mudança vale para as sessões já abertas. Um
  pedido feito sem interação há mais de um minuto não conta como atividade: é o caso das páginas com
  atualização ao vivo e da ligação do sino, que volta a abrir sozinha a cada 4 minutos.
- **Logout forçado.** O administrador termina todas as sessões de um membro em «Equipa». A pessoa
  pode voltar a entrar com as credenciais dela.
- **Password e MFA.** Redefinir a password, ativar ou desligar o MFA e regenerar os códigos de
  recuperação terminam todas as sessões da conta.
- Cada revogação, logout forçado, troca de password e mudança do timeout fica no registo de auditoria.

## Tokens de API

Um token `dvk_*` só fica guardado como SHA-256, e o valor só aparece uma vez, ao criar ou ao rodar
o token (`backend/app/domain/access/token_lifecycle.py`).

- **Prazo.** Cada token novo expira: 90 dias por omissão, ou entre 1 e 365 dias, à escolha do
  administrador. Um token expirado responde 401 em qualquer rota, com a mesma mensagem de um token
  inválido. A instalação pode aceitar tokens sem prazo (`DATAVAULT_API_TOKEN_ALLOW_NO_EXPIRY`); por
  omissão, não aceita. Os tokens criados antes desta regra não têm prazo e continuam a funcionar até
  o administrador os rodar.
- **Rotação.** «Rodar», em «Equipa → Tokens de API», cria um token novo com o mesmo nome e o mesmo
  scope. O antigo continua a funcionar durante o período de graça (24 horas por omissão), para se
  trocar o valor na pipeline sem a partir. «Revogar» corta-o logo. A rotação fica no registo de
  auditoria (`token_rotated`).
- **Último uso.** A lista de tokens mostra o último uso e o último IP de cada token, atualizados no
  máximo uma vez por minuto. O IP fica na base de dados e só o administrador o vê: não entra nos
  logs nem no registo de auditoria.
- **Avisos.** Um token ativo há mais de 180 dias gera um alerta para os administradores. O resumo
  semanal dos canais de notificação diz quantos tokens expiram nos 14 dias seguintes.
- **Scope dos envios dos pipelines.** As execuções dos orquestradores, os resultados do `dbt test`,
  os eventos OpenLineage e os deploys ficam no workspace como factos: entram no diagnóstico de
  causa-raiz, abrem issues e desenham a linhagem. Só um token com o scope `ingest` os envia
  (`API_TOKEN_INGEST_WRITE_OPERATIONS`, `backend/app/api/deps.py`). Um token de leitura com fuga
  lê, mas não os forja: com outro scope, ou com um token OAuth, o envio dá 403. O `ingest` não
  escreve em mais nada além das exceções de qualquer token.

Testes: `backend/tests/test_api_token_lifecycle.py` e `backend/tests/test_api_token_ingest_scope.py`.

## SDK e `beryx` no CI: nomes da fonte sem comandos do runner

O `beryx gate`, os outros comandos do SDK e os resumos que eles escrevem (`GateResult.summary()`
e os dos outros gates) mostram no stdout nomes que vêm do esquema da fonte do cliente (colunas,
tabelas, modelos) e textos da API. No GitHub Actions o runner lê o stdout e o stderr de cada passo
à procura de comandos: uma linha que, sem os espaços do início, comece por `::`, e o formato
antigo `##[` em qualquer sítio da linha. Quem controla o esquema de uma fonte ligada ao workspace
podia pôr num nome de coluna uma quebra de linha seguida de `::stop-commands::` e comandar o CI de
quem corre o gate.

- **Cada linha é uma linha.** Antes de escrever, o SDK escapa à vista as quebras de linha e os
  outros caracteres de controlo (`\n`, `\x1b`, `\u2028`), escreve o `#` de um `##[` ou
  `##vso[` como `\x23` e o `:` de um `::` no início da linha como `\x3a`
  (`sdk/src/beryx/_terminal.py`). Um nome normal sai igual.
- **No `--json`**, o `#` de um `##[` sai como `\u0023`, que o JSON lê como o mesmo `#`.
- **Nas mensagens dos erros**, como o `VerdictFailedError` que um pipeline mostra no traceback,
  vale a mesma regra.

Testes: `sdk/tests/test_terminal_commands.py` e as propriedades em
`backend/tests/test_sdk_terminal_properties.py`.

## Restrições de acesso da organização

O administrador da organização define, em «Equipa → Organização → Restrições de acesso», regras que
valem para todos os workspaces da organização (`backend/app/domain/organizations/access_policy.py`):

- **Allowlist de IPs.** Uma lista de IPs e blocos CIDR, IPv4 e IPv6. Com a lista preenchida, um IP de
  fora é recusado no início de sessão (password, links de email, segundo passo do MFA e SSO), antes de
  a sessão ser emitida, e em cada pedido autenticado: sessões abertas, tokens de API e o Copilot do
  Microsoft 365, que chega da rede da Microsoft. O IP é o que o rate limit usa, por isso um
  `X-Forwarded-For` forjado não passa. Quem é recusado recebe uma mensagem com o IP visto e o que fazer;
  uma password errada continua a dar o erro de sempre, sem revelar a política. A sessão não termina:
  de volta a uma rede autorizada, continua.
- **Tokens de API isentos pelo nome.** Um token com o nome indicado, no workspace indicado, entra de
  qualquer rede, por exemplo o CI com IPs dinâmicos. Cada isenção leva o motivo escrito pelo
  administrador. Rodar o token, ou seja criar outro com o mesmo nome e revogar o antigo, mantém a
  isenção. Um token com o mesmo nome noutro workspace não fica isento.
- **Duração máxima das sessões.** Entre 1 hora e a validade da instalação (12 horas por omissão),
  contada desde o início de sessão, com ou sem atividade. Baixar o valor termina já as sessões que o
  passaram; o ecrã de login diz porquê.
- **MFA obrigatória em toda a organização.** Quem entra com password tem de configurar o MFA no
  próximo início de sessão. Quem entra por SSO usa a MFA do fornecedor de identidade.
- **Anti-bloqueio.** Guardar uma lista que não inclui o IP de quem guarda é recusado. Se mesmo assim
  todos ficarem de fora, por exemplo porque o IP do escritório mudou, o operador da BeryxTech desliga a
  lista com `backend/scripts/clear_ip_allowlist.py`, depois de confirmar o pedido com o cliente.
- Cada mudança fica no registo de auditoria de todos os workspaces da organização. Cada recusa por IP
  fica no do workspace da conta ou do token, e a secção mostra as últimas 20 recusas da organização.
  Num pedido de uma sessão ou de um token já autenticados, fica uma recusa por conta, IP e origem em
  cada 15 minutos.

O acesso de suporte da BeryxTech continua a seguir o consentimento do cliente (ver
[Isolamento entre clientes](#isolamento-entre-clientes-multi-tenant)) e não passa pela allowlist da
organização do cliente.

## Registo de auditoria

As ações de administração (papéis, planos, conexões, credenciais, tokens, sessões, política de IA, política
das ações da IA, acessos de suporte) e as ações do assistente aprovadas, pedidas ou recusadas ficam
num registo de auditoria gravado na mesma transação da mudança, consultável e exportável em CSV
pelos administradores do workspace. Cada evento fica 400 dias: uma purga diária do worker apaga os
mais antigos e deixa `audit_log_purged` no registo, com o corte e a contagem
(`app/domain/audit/retention.py`).

## Subprocessadores e fornecedores

A lista de subprocessadores é pública em `/subprocessadores` (pt/en): finalidade, região, base
legal, mecanismo de transferência e DPA de cada um. Um fornecedor novo, uma saída ou uma mudança de
região é anunciada com 30 dias de antecedência. Os administradores podem receber o aviso por email
(Conformidade → Aviso de subprocessadores). Durante o pré-aviso, um fornecedor de IA novo não recebe
dados: o router só envia para subprocessadores ativos da lista. A avaliação de risco de cada
fornecedor (certificações declaradas, dados que recebe, plano de saída) está em
`docs/compliance/vendors/`.

## Certificações: ISO 27001 e SOC 2

**Não temos certificação ISO 27001 nem relatório SOC 2.** Estão em programa: os controlos
descritos neste documento são a base desse trabalho. Até lá, respondemos às linhas de RFP com a
evidência técnica acima, e não com selos — e não usamos «conforme» nem «alinhado com» como
substituto de uma certificação que não temos.

O estado público de cada certificação (planeada, em preparação, auditoria agendada, obtida — com
datas) vive num único ficheiro, `docs/compliance/trust-status.json`, que o site lê no build para a
página `/seguranca` e para o `/.well-known/security.txt`. O `backend/tests/test_trust_status.py`
falha se esse estado divergir desta secção ou do ADR 0010.

Um dos controlos já operacionais é a **gestão de vulnerabilidades**
([compliance/vulnerability-management.md](compliance/vulnerability-management.md)). Inclui:

- SCA das dependências Python e npm e scan das imagens com o Trivy em cada PR;
- falha do CI em critical/high sem exceção registada;
- SLA de 7, 30 e 90 dias por severidade;
- SBOM CycloneDX por deploy;
- um relatório mensal em `docs/compliance/evidence/`;
- DAST semanal (OWASP ZAP baseline, só passivo) ao site, à app e à API, com relatório semanal e
  o mesmo registo de exceções.

Os achados de todas as fontes (scanners, DAST, pen test externo e divulgação responsável, pelo
`/.well-known/security.txt`) seguem um processo com SLA
([compliance/security-findings.md](compliance/security-findings.md)). **Ainda não fizemos um pen
test externo.** O âmbito, as contas de teste e as regras estão preparados
([compliance/pentest.md](compliance/pentest.md)); falta contratar o fornecedor.

## O que não fazemos, e porquê

- **Remediação destrutiva nas fontes.** Propomos a correção (SQL/PySpark, ou um pull request no
  repositório do cliente); quem aplica é o cliente. Pedir credenciais de escrita seria a objeção
  n.º 1 de qualquer equipa de segurança — é uma decisão de produto, não uma limitação.
- **MDM / golden record com escrita.** Detetamos duplicados e propomos a consolidação, mas não
  mantemos um registo-mestre nem escrevemos a versão «vencedora» nas fontes.
- **Análise multimodal de imagens.** Os documentos são lidos pela camada de texto; imagens não são
  processadas, e um PDF digitalizado sem texto é assinalado como a precisar de OCR
  (`app/domain/quality/documents.py`) em vez de ser enviado a um modelo de visão.
- **Pôr conteúdo no contexto de um agente do cliente.** O BeryX lê e não fica à frente do modelo.
  Desde o cartão #1286 há uma exceção, desligada por omissão e ligada por um admin: o ensaio ao
  vivo da instrução plantada, que põe um registo sintético com um pedido inofensivo na resposta de
  uma ferramenta de leitura (ver «Ensaio ao vivo: a instrução plantada»). Não lê prompts nem
  escreve nas fontes.
- **Escrever na cloud do cliente para parar um agente.** O BeryX não guarda nenhuma credencial que
  escreva na sua conta. Desde o cartão #1284 há uma exceção sem essa credencial, desligada por omissão
  e ligada por um admin num canal de webhook (`ai_agent.lifecycle`, com o add-on «Segurança de IA e de dados»,
  e o evento em `admin_events`): o kill switch do BeryX dispara um webhook assinado e uma função na
  conta do cliente, com as permissões que o cliente lhe der e só para os principais da lista dele,
  desliga a credencial do agente e responde com o resultado, assinado com o mesmo secret: uma resposta
  sem essa assinatura nunca conta como confirmada. Num canal assim, só um admin muda o URL, o liga ou
  desliga, ou o apaga. Quem escreve é a função do cliente, não o BeryX. As receitas e o que cada uma pede estão em [KILL_SWITCH_CLOUD.md](KILL_SWITCH_CLOUD.md).
- **Correr do lado do cliente.** O BeryX lê as clouds e as fontes pelas APIs oficiais e não instala
  nada nas máquinas do cliente. Desde o cartão #1288 há uma exceção, desligada por omissão e ligada
  por um admin: o `beryx agents scan` do SDK, um comando que alguém corre (ou que o CI ou o MDM
  agenda), lê os ficheiros de configuração MCP e envia só metadados, com a máquina e o projeto em
  pseudónimo (ver «Servidores MCP nas máquinas»). Não é um agente residente, não lê prompts nem
  conversas e, na máquina, só grava a chave do pseudónimo.
- **Escrever na cloud do cliente para corrigir a postura.** O BeryX não guarda nenhuma credencial que
  escreva na cloud do cliente nem nas fontes. Desde o cartão #1285 há uma exceção sem essa
  credencial, desligada por omissão e ligada por um admin, com o evento em `admin_events`: para o
  grant a mais, o guardrail em falta e o registo desligado (e a autenticação por chave do Azure
  OpenAI), o BeryX abre um PR de infraestrutura como código, em Terraform ou como migração SQL, no
  repositório git que o cliente ligou e com as permissões dessa integração. Escreve só um ficheiro
  novo, num branch `datavault/*`, e não altera ficheiros existentes, não faz merge e não aplica: quem
  revê, faz merge e aplica é o cliente (ver «Correções de postura por PR de infraestrutura como
  código»).
- **Ler os ficheiros dos modelos do cliente.** O BeryX lia a postura à volta do modelo (quem o pode
  invocar e alterar), não o modelo. Desde o cartão #1287 há uma exceção, desligada por omissão e
  ligada por um admin para cada agente: o scan dos artefactos, que lê por intervalos de bytes, com
  uma permissão de leitura que o cliente dá só no prefixo do artefacto, o formato e os opcodes de
  um pickle, sem o carregar nem descarregar os pesos (ver «Artefactos de modelos: o que o scan lê
  e o que guarda»). Continua a ser só leitura: não escreve no bucket nem fica à frente do modelo.

## English

### BeryX — Security and compliance

> Public document. It is the standard security answer for RFPs and the source of the
> "Security and compliance" section of the site's `/rfp` page. Each section says what
> we guarantee, where it is in the code and which test proves it. We claim nothing that is not here.

#### Mechanical read-only access

BeryX reads metadata, aggregates and limited samples — it never writes, moves or changes data
in the customer's sources. It is not just a convention, nor just permissions asked of the customer:
the guarantee is enforced in the code.

- **HTTP connectors** (Jira, Confluence, Databricks, SharePoint, Google Drive, …) only reach the
  network through the `ReadOnlyHttpClient` (`app/infra/connectors/http_guard.py`): GET/HEAD/OPTIONS
  pass; POST/PUT/PATCH/DELETE are refused **before** touching the network.
- **No connector can expose a write method**: the `enforce_read_only` decorator refuses, at class
  definition, any method with a write name, and a test goes through every registered connector.
- **PostgreSQL**: profiling sessions open with `default_transaction_read_only=on` and
  `statement_timeout` — a write, even one hidden in a function or view, fails on the server.
- **Snowflake (engineering sweep)**: `assert_catalog_statement` refuses anything that is not a
  single `SHOW`/`SELECT`/`DESCRIBE` before it reaches the driver.
- **Rehearsing a fix**: step 1 of a suggestion is counted at the source in a read-only session, and
  step 2 never runs. It can read another table of the same connection (card #1405) only if the
  requester can see it, checked again before the count. It does not count what depends on sensitive
  columns that person cannot see, and the number does not show to anyone who cannot read every table
  counted (`app/domain/insights/rehearsal_access.py`).
- We always recommend a service user with read-only permissions — the steps for each source are in
  the [connectors guide](CONECTORES.md).

Tests: `backend/tests/test_http_guard.py`, `backend/tests/test_connectors_registry.py`,
`backend/tests/test_rehearsal_joins_1405.py`.

#### Isolation between customers (multi-tenant)

Each customer is a workspace, and the workspace is the data boundary. An authenticated request
always resolves the workspace of the session or of the API token (`get_current_workspace`,
`app/api/deps.py`), and each route only reads and changes resources of that workspace. The BeryxTech.
team only reads another workspace with support access that an administrator of that customer has
approved. That access has a time limit, is read-only and is recorded in the audit log.

Without that access, the team's management app only shows customer metadata: the name of the
workspace and of the organisation, the plan, the usage and the numbers of the help requests. With the
management app switched on, all its routes require the session opened there, with two-factor
authentication. The customer record, billing and the help requests (the list, the feedback, the
counts, the conversation and the attachments) also require two-factor authentication to be on in the
request itself, so a team account that switched it off stops reading them even with a session that is
still valid. Only the team's support role and the owner read the help requests: billing and sales get
a 403.

**Isolation proved by a test over every route.** The guarantee does not depend on someone
remembering to test each new endpoint. The test goes through the API's registered routes, with two
test customers, A and B, seeded with one resource of each kind:

- **Between customers.** Each route with an id in the path receives A's ids and is called by B's
  administrator, the most permissive role, and by B's API token. It can never respond 2xx or 5xx.
  The refusal must be the same as for an id that does not exist, so that B does not even learn
  whether A's id exists. Routes with the id in the body or in the query go through the same test.
  In listings, aggregates and exports, no response to B may contain an id or email of A.
- **Positive control.** The same request made by A reaches its resources. Without this, B's 404
  would prove nothing. The test prints the coverage on every CI run and fails below 90% of the
  routes with a customer id.
- **No session.** Every route responds 401, except an explicit, commented list of public routes:
  health, login, SSO, signed webhooks and public links by token. That list must match the access
  decision table.
- **Roles.** The read-only role gets 403 on every change. The only exceptions are account
  self-service, the help request, the assistant, feedback and the bulk trust decision, which is a
  read. The API token only writes in the intended operations.
- **New routes.** A new route with a parameter the test does not know how to fill makes the test
  fail. It only passes again when the route enters the matrix or a justified list.
- **Cross-workspace routes by design.** The BeryxTech team's console, the organisation and federated
  search are proved separately, each at its own boundary. For example, support access without
  approval gets 403 on every read.
- **The test also bites.** An example router without a workspace filter is caught by the same
  sweep.

Tests: `backend/tests/test_tenant_isolation_matrix.py`. Per-domain permissions within a workspace
are in `backend/tests/test_access_matrix.py`.

**Within the workspace, the handler repeats the guard.** The central guard decides each route from
the decision table (`backend/app/domain/access/decision_table.py`). The incident handlers decide
again, so that a failure in the guard does not open access: a root the person cannot see answers
like an incident that does not exist, and the diagnosis (`POST /incidents/{incident_id}/diagnose`)
requires write access to every dataset involved before queueing the report. Test:
`backend/tests/test_access_grants.py`, with the central guard switched off.

#### Samples: what leaves the source and what stays

What a scan reads from your sources, where it is processed and what is stored:

- **Profile on SQL sources: aggregates.** On SQL databases and warehouses, the profile (counts,
  nulls, distinct values, minimums and maximums) is calculated by SQL on the source itself. Only
  the numbers come back, plus a sample of up to 1,000 rows of the profiled columns
  (`VALUE_SAMPLE_ROWS`, `app/infra/connectors/sql.py`), read in memory on the worker to take
  up to 20 example values per column, which feed the semantic types and PII detection; only those
  values are stored. Up to the previous version it was 20 values per column, in one query per
  column. For each value of the categorical columns (up to 3 columns, of 2 to 50 values) the rows,
  the nulls and the sum of up to 3 numeric columns also come back, and the rows per hour of day of
  the freshness column (card #1255). A column classified as personal or confidential, or that PII
  detection recognises in the profile, is not summed, and only the sum of values with 30 records
  or more is stored. A column classified after the scan is masked in those sums, in the values of
  the dimension and in the hour of day as well, for anyone without clearance. The value of the segment
  of an anomaly inside a segment, of the drill-down of an anomaly of the total (card #1379) or of the
  "never again" rule it yields does not go to titles, descriptions, the bell, emails, webhooks, tickets
  or prompts: the issue keeps an HMAC with the installation's key, the workspace
  and the dataset (rotating the `jwt_secret` changes it, and the issue keeps only the dimension until
  the next scan), and the rule's condition goes out with its literals masked. Anyone who may see the
  value reads it in the explanation of the anomaly, from the scan's profile. A distribution drift
  follows the same rule (card #1399): the issue keeps the shares of each category, with the same HMAC,
  and of the quantiles of a numeric column only the percentage change; the categories and the quantiles
  are read in the explanation, with the mask. The rule the profile proposes for a sensitive column states
  the family, the margin and the counts, without the minimum, the maximum, the categories or the mean
  (card #1408); only an administrator accepts it, and the rule it creates reads them from the latest
  profile and shows them on its page, like any rule. Classifying the column takes them out of the
  suggestions that already existed straight away. A document that leaves the app does not carry them
  either, whoever asks for it (card #1407): the export of a report draws the histogram of a sensitive
  column with the counts only, and the public link and the scheduled email do not draw it. When two
  segments of different columns go out of pattern in the same column, the rows, the nulls and the sum per pair of
  values of those two columns also come back, and are not stored. Of a segment's mean, the issue keeps only the
  relative change. The rows per hour of day are only read on the datasets that asked for it. On sources without SQL (files, SaaS APIs, streaming), the connector reads the records
  through the official API and the profile is calculated on the worker; the
  [connectors guide](CONECTORES.md) says what each one reads.
- **Row rules and duplicates: a sample of up to 5,000 rows per table.** On each scan, the rules
  that need rows and duplicate detection read at most 5,000 rows per table
  (`ROW_FETCH_LIMIT`, `app/domain/scans/service.py`), chosen by the source's own sampling
  (`TABLESAMPLE`/`SAMPLE`), by the primary key hash or, with neither, by the first rows
  ([method](METODOS.md#amostragem)). It is a ceiling, which also applies to the profile sample:
  the DBA can lower it per source, down to a minimum of 100 rows (`max_sample_rows`,
  "Good neighbour to the DBA"). The rows are processed in memory on the worker, in the EU (Google
  Cloud europe-west1); from that read, only the limited examples described below are stored.
- **Larger reads only when you ask for them.** Label quality (on the datasets where you configure
  it), data-diff and matching between datasets read up to 50,000 rows per table, also in memory
  on the worker.
- **What is stored, in the EU:** profiles, aggregates, rule results and scores, and limited
  examples — for example, up to 20 values per column in the profile, up to 5 rows per duplicate
  group and up to 5 truncated values per failed rule. The table is never copied to BeryX.
- **Embeddings are neither stored nor sent to the model, from any source.** An embedding is a
  list, an array or a text with 32 numbers or more, or a binary value of 32 bytes or more,
  whatever the column type (`app/infra/serialization.py`). That column's profile is stored without
  a sample, minimum or maximum. In a duplicate group's sample and in the AI context, the value
  becomes a marker with only the length (`{"omitted": "vector", "length": 768}`), and in a rule
  example `<vector:768>`. The column stays out of segments and of the accepted-values and
  normalisation suggestions. The model only receives scalar values from example rows: a list or
  an object goes as a marker (`app/infra/llm/prompts.py`). Rules still evaluate the real value,
  and a short array (coordinates, an RGB colour) or a `BINARY(16)` key stays as it is.
- **With AI on, the examples sent to the model follow the workspace's AI policy.** By default they
  go to Anthropic, which processes them in the US under standard contractual clauses. To keep them
  in the EU, turn AI off or use Claude in your Google Cloud account, on Vertex AI (Enterprise plan;
  Amazon Bedrock comes next) — see "Your models" and "Anonymisation before the LLM", below.
- **Running in your Databricks (ADR 0005, step B): it does not run in scans yet.** The
  `beryx-profiler` package, which reads the full table in your account and returns only
  metrics, and the Jobs API client already exist in the code, but no scan submits it yet. Until
  then, on Databricks too, row rules and duplicates use the sample above.
- **Today we have no mode in which no row leaves your network** (on-prem or air-gapped). A runner
  inside your perimeter (step C of the same ADR) depends on real demand.

Tests: `backend/tests/test_seguranca_amostras.py` (the numbers and the Databricks status above are
compared with the code).

#### Vector indexes: sensitivity comes from the sources

An embedding is numbers, and you cannot search them for personal data. BeryX does not read the vectors:
the sensitivity of a vector index comes from the sources and is only as good as the declared lineage.

- **The origin is declared.** An admin states, on the index page, which datasets the vectors came from
  (`POST /api/v1/lineage/vector-origins`). With no origin, the index shows the gap "Origin not declared"
  and inherits nothing.
- **Vector columns inherit.** If an origin has `pii` or `confidential` columns, or detected PII that
  curation has not declassified, the index's vector columns receive the highest level, with the source
  `lineage`. Clearance and the AI agent guards apply as they do to any classified column, and at go-live
  the `classification_verified` item counts this classification.
- **Inheritance only goes up.** Classifying the origin later reaches the index in the same transaction,
  without running its scan. Declassifying the origin or deleting the edge does not lower the index:
  lowering an inherited column is for an admin or the owner of one of the dataset's domains, and it stays
  in the trail. A manual classification stays as it is, even below the origins, and the page shows a warning.
- **The other columns follow the normal path.** The text and metadata columns next to the vector column go
  through the usual PII detection, and at go-live they still ask for a person.

**Limits.** Inheritance follows one hop from the declared origin, plus indexes in a chain. An unclassified
intermediate view does not count. A missing or wrong origin leaves the index without the classification it
should have, and personal data that the origin neither classified nor detected does not reach the index.

Tests: `backend/tests/test_vector_sensitivity.py`.

#### Vector indexes: who reads the index and not the origin

A vector index built from a restricted table can end up readable by someone who does not read that
table, and a RAG application on top of it returns to them what the origin hides. It is the first risk
on the list of the OWASP GenAI Security Project, "LLM08:2025 Vector and Embedding Weaknesses". The
sensitivity inheritance, in the previous section, closes the path through BeryX (the agents' tokens).
Direct access at the source is shown here, in the "AI & Data Security" add-on.

- **The pairs.** Each declared origin of an index, in the same connection or in another one. An index
  without an origin is left out, with the gap "Origin not declared".
- **Who reads each side.** The connections' latest grants snapshot
  (`POST /api/v1/data-security/source-grants/collect`): the principals with a read privilege on the
  index and on the origin, with the members of roles, PUBLIC and the superusers.
- **The verdict.** `index_wider` when there are principals that read the index and do not read the
  origin; `source_wider`, informative only, in the opposite case; `parity`; and `unknown` when proof is
  missing: a side without grants read, a truncated snapshot, the snapshot's limits (in BigQuery the
  inherited bindings, in Databricks only what the connection sees, and groups not expanded) or two
  different connections, whose principals are not compared by name. When in doubt, never `parity`. The
  reason comes in `unknown_reason`.
- **The issue.** An `index_wider` with a `pii` or `confidential` origin, inherited ones included, opens a
  `vector_index_access` issue linked to the index, for the owner of its domain. It is the same issue from
  one snapshot to the next, and it resolves itself when the next snapshot gives `parity`. The issue text
  carries neither the origin's name nor the principals' names.
- **The recertification.** The next campaign carries one item per principal that reads the index and
  does not read the classified origin, decided by whoever manages the grants of the index's domain.
  Revoking opens the task to remove the access at the source: BeryX does not change grants.
- **Who sees the names.** Principal names are personal data: only an admin sees them, in Privacy › AI & Data
  Security (`GET /api/v1/data-security/vector-index-access`). On the index page
  (`GET /api/v1/datasets/{id}/vector-index-access`), whoever reads the dataset sees the verdict and the
  counts. The MCP tool `get_vector_index_access` only returns counts. Logs only get counts, and none of
  this goes to an LLM.

**What stays `unknown`.** Indexes without a grants snapshot: MongoDB, Weaviate, Oracle, SQL Server and
MySQL. In Databricks, querying an AI Search index requires SELECT on the index itself, according to the
"Query an AI Search index" page of the Databricks documentation (read on 19/11/2026). The page does not
say where those grants are read, and BeryX only reads those of the Delta table that carries the vector
mark. In Snowflake, querying a Cortex Search service requires USAGE on the service, which searches with
the owner's rights, according to the "Cortex Search overview" page of the Snowflake documentation (read
on 19/11/2026). The `SHOW GRANTS` and `ACCOUNT_USAGE.GRANTS_TO_ROLES` pages do not say they show these
services, and those the engineering scan lists come out `unknown`, with the reason.

**Limits.** The comparison is only as good as the declared origin and the latest snapshot. Row policies
and column masks are not in the snapshot: whoever reads the table counts as reading everything. BeryX
shows the excess access and does not block it: removing the access is done at the source.

Tests: `backend/tests/test_vector_index_access_1227.py`.

#### Who can write to training data and to the origins of a vector index

Whoever changes the data a model learns from, or the data a vector index was built from, can poison
it. The grants snapshot already says who writes to each dataset; the "AI & Data Security" add-on crosses it
with the AI data (`backend/app/domain/compliance/ai_data_write_exposure.py`).

- **The datasets.** Those with a training, validation or testing role on an agent or model record that
  is not retired, and the declared origins of the vector indexes.
- **What is counted.** From the latest grants snapshot
  (`POST /api/v1/data-security/source-grants/collect`): how many principals can write (INSERT, UPDATE,
  DELETE, TRUNCATE, OWNERSHIP, MODIFY, the BigQuery roles that write and the superusers; on buckets,
  the Cloud Storage roles that create or delete objects, WRITE, WRITE_ACP and FULL_CONTROL in the S3
  ACL and the policy actions that cover `s3:PutObject`, `s3:DeleteObject` or rewriting the ACL and the
  policy, with wildcards and case-insensitive), with the members of roles; how many are service
  accounts, by the name the source gives them
  (`serviceAccount:` in BigQuery and GCS, the application id in Databricks, an AWS service principal
  in S3; PostgreSQL and Snowflake do not say it in the name, and the count stays empty); how many
  have not accessed it for more than 90 days, by the Snowflake access history, which is only crossed
  on classified datasets; and whether writing is given to PUBLIC or to an everyone group (`allUsers`
  and `allAuthenticatedUsers` in Google, `account users` in Databricks, `AllUsers` and
  `AuthenticatedUsers` in S3). Without a read that covers the dataset, it comes out "not read", never
  "nobody writes".
- **The issue.** One `ai_data_write_exposure` per dataset, for the owner of its first domain: critical
  when writing is open to everyone, warning when the number of writers rises between two snapshots.
  It resolves itself at the next snapshot with neither. A connection whose read failed leaves the
  issue as it is, and an ignored issue does not reopen. The text only carries counts.
- **Where it shows.** The Annex IV datasheet gets the row "Who can change this data" on each training,
  validation and testing dataset, and the posture report the section "Who can change the AI data",
  next to the grants on sensitive datasets. Principal names stay out of both, of the logs and of the
  LLMs.

**Limits.** Only the sources where BeryX reads grants: PostgreSQL, Snowflake, BigQuery, Databricks and
the GCS and S3 buckets. Whoever writes through the application that feeds the table uses its
credentials and does not show up as another principal. The access history sees reads, not writes:
"no access for 90 days" is a signal, not proof that they did not write. Service accounts are counted
by name: an AWS IAM role does not count, because people assume it too. A custom BigQuery or Cloud
Storage role does not count as writing, because BeryX does not read what it grants. BeryX shows who
can write and does not prevent it: removing write access is done at the source.

Tests: `backend/tests/test_ai_data_write_exposure_1264.py`.

#### Agent reach: what its accounts can do at the source

The AI registry says which accounts an agent reads each source with and which datasets it uses. The
"AI & Data Security" add-on crosses those accounts with the latest grants snapshot, before the agent reads,
and says what they can do beyond that (`backend/app/domain/compliance/ai_agent_reach.py`, card #1263).

- **What counts as excess.** A classified dataset the accounts can read and the record does not link,
  and any dataset they can write to: the record has no write role. PUBLIC counts on the connections
  where the agent is. A dormant grant (the one from #788) and the tools and linked datasets with no
  requests in 30 days come out as suggestions, not as excess.
- **When in doubt, it does not say "minimal".** With no accounts on the record, an account with no rows
  in the snapshot, or a connection of the agent whose connector does not read grants, has no snapshot,
  has an out-of-date snapshot (older than `security_reads_stale_days` days, the limit of the score and
  the posture report) or has a cut snapshot, the verdict is `unknown`, with the reason. In the
  go-live, the item stays unchecked: it neither passes nor closes. An excess an old snapshot proves
  still counts until a new snapshot without it: waiting does not remove it. Without the add-on, the
  item also stays unchecked and the task does not show, because the old snapshot, kept for up to 90
  days, can no longer be seen or accepted.
- **The fix belongs to the customer.** The page gives an admin the `REVOKE` in the source's dialect, to
  copy. BeryX reads the grants and does not change them. The fix removes the excess and gives back
  the reads of linked datasets that the `REVOKE` would take, in the connection's database. The
  snapshot puts the account's direct grant and those of its roles in one row, so the excess goes
  from the account and from every role in the row. On a write finding only the write goes. When
  what goes also gave the read (a role, ALL PRIVILEGES, `roles/bigquery.dataEditor`), the fix adds
  the `GRANT` of that read and, when leaving a PostgreSQL role, the schemas' `USAGE`
  (`backend/app/domain/compliance/ai_agent_reach_fix.py`). Ownership (OWNERSHIP) is not revoked,
  it is transferred to another owner: a finding that would take it in a table `REVOKE` gets no
  SQL, and the page says why. What comes from an object above the table also gets no SQL, a binding on the BigQuery
  dataset and what Databricks inherits from the catalogue or the schema (`inherited_from`): a
  `REVOKE … ON TABLE` does not remove it, and Databricks accepts it without an error. An account
  that reaches the role through another role (`chained`) does not leave it with a `REVOKE` of the
  membership: the role's privilege on the table goes, and a predefined PostgreSQL role reached that
  way gets no SQL. PostgreSQL roles apply to the cluster and Snowflake roles to the account: with
  linked reads in another connection of the same source, the account stays in the role and the
  role's privilege on the table goes. What does not come back: the reads the role gave in a
  database that is not a BeryX connection, those of another connection when the role is
  predefined (`pg_read_all_data`), and the database's `CONNECT` when it came from the role. In
  Snowflake, the fix is run with the role that made the grant, a role above it or one with
  `MANAGE GRANTS`: a `REVOKE` only removes the grants made by the active role or a role below it,
  and succeeds without an error when it removes nothing.
- **Who gets told.** When the excesses go up between two snapshots, the agent's owner gets a task
  (without an owner, the admins), with the agent's name and nothing from the source. The posture
  report only carries the counts.
- **The names.** Only an admin sees the accounts, principals and dataset names. Everyone else's
  response, the per-agent list and the acceptance record in `admin_events` carry counts and ids. None
  of it goes into the logs or to an LLM. When the account of whoever accepted an excess is erased
  (GDPR, Art. 17), their id leaves the acceptance; the reason and the deadline stay, because the
  decision belongs to the workspace.

**Limits.** The snapshot is per table: a PostgreSQL column grant is left out, and an agent with
`SELECT` on a classified column can come out `minimal`. The source does not return everything that
gives access: BigQuery does not return the bindings inherited from the project, folder and
organisation, Databricks only shows what the connection's principal sees, and the members of a
BigQuery or Databricks group are not expanded. So an account that only reads through those paths does
not show up, and `minimal` means "nothing extra in what the source shows"; the response gives each
connection's limits in `limits`. What comes from above the table (a binding on the BigQuery dataset,
what Databricks inherits from the catalogue or the schema) has no SQL fix and is removed at the
source. The Snowflake snapshot does not tell a database role from an account role: the fix writes
`ROLE`, and for a database role it is `DATABASE ROLE`. Row access policies and column masks are
not in the snapshot. BeryX shows the reach and does not cut it.

Tests: `backend/tests/test_ai_agent_reach_1263.py`, `backend/tests/test_ai_agent_reach_flow_1263.py` and, on a real PostgreSQL, `backend/tests/test_ai_agent_reach_pg_1263.py`.

#### Posture fixes by infrastructure-as-code pull request (exception, opt-in)

The "AI & Data Security" add-on reads the posture and gives the fix to copy. Since card #1285, for
three kinds of finding with a deterministic fix, it also proposes the fix as an
infrastructure-as-code pull request in the customer's git repository
(`backend/app/domain/compliance/posture_fix_prs.py`, `backend/app/domain/compliance/posture_iac.py`).

- **Opt-in.** It comes turned off; an admin turns it on
  (`PUT /api/v1/compliance/posture-fixes/settings`). Turning it on, off and each pull request
  opened go to `admin_events` (`posture_fix_prs_enabled`, `posture_fix_prs_disabled`,
  `posture_fix_pr_opened`, with ids, the finding code, the provider and the number only). Only an
  admin opens a pull request, and only with the fix pull request in the plan (`git_remediation`).
- **No write credentials in the cloud.** The pull request goes through the git integration the
  customer already connected for the fix pull request (#1202), with its permissions. BeryX neither
  asks for nor keeps any credential that writes to AWS, Azure, Google or the source.
- **Only one new file.** Each pull request carries one new file, on a `datavault/posture-*` branch,
  in the folder the admin chooses: the SQL migration with the `REVOKE` of the excess grant (#1263),
  or the Terraform for a Bedrock agent's guardrail, Bedrock invocation logging, the Azure OpenAI
  diagnostic settings and key authentication, or the Vertex AI Data Access logs. It never changes
  an existing file: on GitHub it first checks that the path does not exist on the base branch, and
  GitLab and Azure DevOps refuse to create over one. It never writes to the base branch nor merges,
  and applies nothing: the customer reviews, merges and applies (the `terraform apply`, the
  migration).
- **The file is the one from the latest read.** The request only says which finding, in which
  folder and in which repository; the content is recomputed on the server from the stored read. A
  customer name (an agent's, a principal's) goes out as an escaped literal or in a one-line
  comment, and does not change the shape of the file.
- **Verification is the next read.** The worker follows the pull request's state. After the merge,
  the finding stays "awaiting verification" until a later read no longer sees it: the source's
  controls, or a grant snapshot of the connection that was not cut short. A merge without the
  `apply` does not close the finding, and the page says when the read still sees it.
- **What is kept and where.** BeryX keeps the repository, the number, the branch, the file path,
  the state and the hash of the finding's identity, never the content. The file and the pull
  request stay in the customer's repository, with the names, accounts and ARNs the fix needs; in a
  BigQuery grant the principal may be a person's email, and BeryX's account erasure does not reach
  it there. The logs only carry ids, codes and numbers, and none of this goes to an LLM. In the demo
  and in training the file shows and no pull request opens.

**Limits.** BeryX does not know the customer's modules: the file is a starting point their team
adapts. The Terraform declares no `provider` nor `required_providers`, which belong to the
customer's module. The per-resource `region` argument on AWS needs AWS provider 6, and the agent's
`import` needs Terraform 1.5 and the root module. If the agent, the account or the audit
configuration is already in the customer's Terraform, the fix goes there and the new file goes
away; the file itself says so. A Bedrock agent's aliases serve the version they had: after the
`apply`, a new version and the alias pointing to it are needed. The other findings keep the fix to
copy.

Tests: `backend/tests/test_posture_fix_prs_1285.py`, with fake git servers and no network. Each
Terraform file is validated against the providers' resource schemas and by `terraform fmt -check`,
and each SQL file by the dialect's parser.

#### Proposed enrichment: what leaves for each provider

[Proposed enrichment](CAPACIDADES.md#enriquecimento) asks public reference services, or a
Nominatim instance of the customer's own, for the value missing in a column. Each provider receives
only the field to enrich, one value at a time, and never the full sample or the other columns of
the row:

| Provider (key) | Host | What it receives | What it returns |
|---|---|---|---|
| GeoAPI.pt (`geoapi_pt`) | `json.geoapi.pt` | The CP7 postcode (full Portuguese postcode) | Locality, municipality and district |
| VIES, from the European Commission (`vies`) | `ec.europa.eu` | Only the NIF (Portuguese tax number) of a legal person (first digit 5, 6 or 9). The NIF of a natural person does not leave | Registered name and address |
| Public Nominatim, from the OpenStreetMap Foundation (`nominatim`) | `nominatim.openstreetmap.org` | Only the Spanish postcode | Locality and autonomous community |
| The customer's Nominatim instance (`nominatim_self_hosted`) | The one in the URL the administrator gives | The address, for geocoding. It is the only provider that receives personal data | Latitude and longitude |

Countries and currencies are compared with the ISO lists stored in BeryX, and nothing leaves.

- **Opt-in per workspace and fail-closed.** By default, no provider receives anything. An
  administrator allows each one under "Rules → Enrichment providers"
  (`PUT /api/v1/workspace/enrichment`), and the authorisation records who consented and when.
  Without authorisation, the proposal is refused before the source sample is read. This
  authorisation is separate from that of the `accuracy` rule: allowing VIES in one does not allow
  it in the other.
- **Addresses only to the customer's instance.** Geocoding uses only the customer's own Nominatim
  instance. The
  [usage policy of the public Nominatim](https://operations.osmfoundation.org/policies/nominatim/)
  asks that no personal data be sent to it. So the public Nominatim receives only the Spanish
  postcode and is allowed without the personal data confirmation. The same policy limits use to 1
  request per second. The OpenStreetMap Foundation stores request data in the United Kingdom and
  the Netherlands ([OSMF privacy policy](https://osmfoundation.org/wiki/Privacy_Policy)).
- **One consent per destination.** To allow the instance, the administrator gives the URL
  (`nominatim_url`) and confirms that the addresses may be personal data (`confirm_personal_data`).
  Changing the URL is a new destination and asks for the confirmation again, which records who gave
  it and when. Withdrawing the authorisation deletes the URL. Without a configured and allowed
  instance, no address leaves.
- **The instance URL is validated when saved.** It must be https (http only for hosts in
  `DATAVAULT_CONNECTOR_ALLOWED_HOSTS`), with no user or password, no query or fragment, and up to
  500 characters. Hosts under `openstreetmap.org` are refused, because they are the public service.
  The anti-SSRF guard (`SsrfGuard`, in `backend/app/infra/connectors/http_guard.py`) refuses hosts
  that resolve to internal networks (loopback, private networks, cloud metadata), unless the
  operator allows them in `DATAVAULT_CONNECTOR_ALLOWED_HOSTS`. The same code normalises the URL
  when saving and when querying (`backend/app/infra/enrichment/providers.py`), and every lookup goes
  through the guard again, with DNS pinning.
- **The request to the instance.** BeryX calls `<url>/search` with `q` (the address),
  `format=jsonv2` and `limit=1`, by GET only and with a User-Agent that identifies it. The request
  carries no credential or key: an instance behind authentication is not supported.
- **Outside the subprocessor list.** The three public services are not on the public subprocessor
  list: they only receive values from a workspace after an administrator of that workspace allows
  them, and each one handles the requests under its own terms. The Nominatim instance is the
  customer's own, and the customer chooses the destination.
- **Audit.** Every change to the allowed providers goes into the audit log
  (`enrichment_providers_updated`), with the list before and after, whether personal data was
  confirmed and, when it changes, the host of the Nominatim instance.
- **How it leaves.** GET requests only, through the connectors' read-only HTTP client, with the
  anti-SSRF guard and DNS pinning. The public services have a minimum interval between requests
  in each API process (0.5 s for VIES and 1 s for GeoAPI.pt and the public Nominatim) and each
  proposal has a lookup cap. Answers are kept in an in-memory cache, per workspace and with the
  key hashed (SHA-256). Values never go to the logs.
- **What is stored.** The suggestion stores the proposed values with their provenance (source,
  lookup date and confidence). For geocoding, the suggestion stores only the provenance and the
  coverage: neither the address nor the coordinates, which would locate it. The proposed
  coordinates only appear in the response to the request. The suggestion's SQL carries the
  postcodes and company NIFs
  the source confirmed, with the reference value (for VIES, the company's registered name and
  address). For geocoding, the SQL carries no address at all.
- **What the source did not confirm is not kept.** A natural person's NIF, a postcode the source
  does not know or free text in the column is not kept in the suggestion. In the response to the
  request, it appears masked, with only the last 3 characters. The pull request carries the
  coverage and the source, not the list of values.

BeryX does not write the proposed value to the source: the customer applies it by pull request
or SQL, after approving the suggestion ([what we do not do](#o-que-não-fazemos-e-porquê)).

Tests: `backend/tests/test_enrichment.py`.

#### Encrypted credentials and key rotation

- Source credentials and integration tokens are encrypted with **Fernet**
  (`app/domain/catalog/crypto.py`) before being stored. They are never returned by the API nor
  written to logs; vendor error messages go through a filter that removes secrets.
- **Key rotation**: `DATAVAULT_ENCRYPTION_KEYS` accepts several keys (`MultiFernet`): the first
  encrypts, all decrypt. `backend/scripts/rotate_fernet.py` re-encrypts every secret with the new
  key in idempotent batches; tokens that no key opens are reported only by `id`, without ever
  being decrypted for logs (`app/domain/catalog/key_rotation.py`).

Tests: `backend/tests/test_fernet_rotation.py`.

#### Anti-SSRF protection with DNS pinning

Source URLs come from customer configuration. So that they cannot point inside our infrastructure
(cloud metadata, `localhost`, private networks):

- `SsrfGuard` (`app/infra/connectors/http_guard.py`) only accepts `https` and refuses any host that
  resolves to an internal address. It is fail-closed.
- **DNS pinning**: the host is resolved only once, every IP returned is validated and the
  connection is made to the pinned IP, with the original hostname in `Host` and in SNI (the TLS
  certificate is still validated against the name). This closes the *DNS rebinding* window.
- Each redirect hop repeats resolution, validation and pinning. On a hop to another origin
  (scheme, host or port), only the neutral headers go through, such as `Accept` and `User-Agent`
  (`NEUTRAL_HEADERS`). The `Authorization` header, cookies, query params and any custom
  credential header, such as an `X-API-Key` or the `X-Tableau-Auth`, are dropped.
- **Response cap and total deadline** (cards #571 and #605). The HTTP connectors' transport
  (`pinned_httpx_transport`) reads the body as a stream and stops at the connector's cap: 20 MB for
  REST and for SharePoint and Google Drive documents, 30 MB for OData and Dynamics 365 and 32 MB
  when the caller sets none. A `Content-Length` above the cap is refused before the body. It only asks for `gzip`
  and `deflate`, decompresses them with the output limited to the same cap and refuses `br` and
  `zstd`. The timeout counts for the whole request, from the connection to the last byte, not per
  read.
- It also applies to outbound integrations that receive customer URLs (external catalogue,
  OpenLineage, self-hosted Git): validation on save **and** on each use.
- **External catalogue** (card #648). The OpenMetadata, DataHub, Collibra and Purview HTTP client
  (`JsonHttp`, in `app/infra/catalog/base.py`) reads each response as a stream up to 10 MB,
  counted after decompression, with the same bounded decompressor (`aread_capped`). A
  `Content-Length` above the cap is refused before the body, and a response over it fails without
  retrying the request.
- **Purview quality rules** (card #1332). An admin reads them from the Unified Catalog Data Quality API
  through the Purview integration, with its credential, at the host validated when it was saved and with
  GETs only: the read client (`ReadOnlyJsonHttp`) refuses any other request before it leaves for the
  network, and the identifiers that go into the path have to be GUIDs. Nothing is written to Purview. Of
  what the API returns only the fields the import reads are kept: the ids of who created and changed the
  rules and the executed query are dropped (`app/infra/catalog/purview_quality.py`). Each response is read
  as a stream, up to 3 MB for an asset's rules and 6 MB for the list of assets, and its objects and values
  are counted before they are built (`MAX_OBJECTS`, `MAX_VALUES`); there is a ceiling of rules per asset
  (`MAX_ASSET_RULES`) and per page (`MAX_PAGE_RULES`), the JSON is read in a separate thread and the page
  has a 75 s deadline. An asset that exceeds the ceilings or the deadline, or that Purview refuses, is
  declared, with the reason, in the export and in the report. The JSON is not stored in BeryX; the audit
  trail carries the read (`purview_rules_read`, one per person, integration and hour) and, on each import,
  the counts of the reconciliation report (`rules_import_reconciled`). The created rule keeps a hash of the
  identity it has in Purview.
- **Rehearsal of the rules of an import** (card #1332). `POST /rules/import/rehearsal` runs at the source,
  with a connector that only reads and the scan engine, the rules an import proposes: no scan, no results,
  no issues and no rules saved. It requires `write` on each dataset, goes through the import's own guard,
  respects blackout windows and the DBA's query limit and has its own quota per workspace. The response
  carries the outcome, the observed value and the threshold, never rows. A rule that decides with the
  values of a sensitive column the requester cannot see is not rehearsed: the columns are the ones the
  engine reads, in a single place shared with the backtest (`app/domain/quality/value_columns.py`), and
  when they are not known (custom SQL) it is refused. With clearance, the values seen stay in the trail
  (`sensitive_columns_viewed`, `import_rehearsal` surface).
- **Data sources (databases, warehouses, object storage).** Every host and URL in the config goes
  back through the guard (`netguard.check_host`) before the connection is opened, not only when
  the connection is saved (`BaseConnector.assert_destination_allowed`, card #339). Postgres
  connects only to the validated IPs (`hostaddr`), in the resolver's order, and MySQL opens the
  socket to them, with the certificate verified against the name. pymongo resolves each name
  through the guard (`netguard.guarded_getaddrinfo`, card #564) and connects to the addresses
  validated in that same resolution, the driver's monitoring included, and it never opens a local
  Unix socket, not even for a member the replica set announces (card #602). Oracle, Redshift and
  Databricks resolve through the guard in the same way (card #647): on Oracle also the
  destination of a listener redirect, and on Databricks every connection to the connection's host
  during the session. Oracle connects without TLS. SQL Server, Fabric, Snowflake, BigQuery and the
  other Postgres and MySQL drivers revalidate and the driver resolves the name again. In
  production, a name that does not resolve is refused when the connection is created and on each
  revalidation, and the drivers with a pinned IP also refuse a local Unix socket and a list of
  hosts. The per-dialect table is in [CONECTORES.md](CONECTORES.md).
- **Webhooks and tickets.** Alert channel webhooks (Slack, Teams and generic webhook), scheduled
  reports on those channels and tickets (Jira, Linear, ServiceNow, Azure DevOps, GitHub and
  GitLab, card #376) all go out through `app/infra/network/outbound.py`. The URL is validated on save, in the app and in the IaC API,
  and again on each send, with the pinned IP. On the generic webhook, each retry attempt validates
  again. Redirects are not followed: a `3xx` counts as a failure. A refused destination is not
  retried and shows in "Last delivery" as "destination refused (SSRF)".
- **A webhook URL is a secret**: whoever has it can post to the channel. It does not appear in the
  "Test channel" response, in `last_delivery_error` or in the logs, which keep only the HTTP code
  or the error type. The `httpx` logger, which at INFO would write the URL of each request, is set
  to WARNING. Excerpts of ticket provider responses go out without the credentials.
- `DATAVAULT_CONNECTOR_ALLOWED_HOSTS` also exempts webhooks and tickets (for example, a receiver on
  the customer's network in a dedicated instance). On channels, `https` is still mandatory.
- **Tickets from training and demo.** A training or demo workspace does not write to the ticket
  provider, even with an integration that got there another way (a seed, hand-written SQL or a
  change of the workspace type): creating a ticket returns 403, the automation opens no tickets
  and the sync reads the status but does not comment, close or reopen.

Tests: `backend/tests/test_http_guard_pinning.py`, `backend/tests/test_dynamics_ssrf.py`,
`backend/tests/test_outbound_ssrf.py`, `backend/tests/test_connectors_sql.py`,
`backend/tests/test_security_gates.py`, `backend/tests/test_dns_rebinding_guard.py`,
`backend/tests/test_http_guard_response_limits.py`.

#### Perimeter: WAF, rate limiting and DDoS

**Status:** implemented as code and covered by automated tests, but **not yet applied in production**.
The global load balancer (`deploy/lb_apply.sh`) and Cloud Armor on top of it
(`deploy/armor_apply.sh`) are waiting for an operation by the team. Until then:

- the API and the app are served directly by Cloud Run, and each service's `*.run.app` address
  also responds;
- abuse containment is the API's own rate limit, in memory and per instance, plus the Cloud Run
  instance ceiling;
- there is no WAF in front of the service.

Activation is phased. First the load balancer goes in. Then Cloud Armor spends a week in
observation mode, in which nothing is blocked and false positives are measured. Only then does it
start blocking. This section will only say "active" after blocking is on in production.

With the edge applied, the perimeter looks like this:

- **Load balancer**: all public traffic (site, app, API and MCP) enters through a global Google
  Application Load Balancer, with TLS ≥ 1.2. The services then refuse requests that do not come
  from it. The LB only forwards well-formed HTTP(S) requests, so L3/L4 volumetric attacks stay on
  Google's network. **Cloud Armor** sits in front of the LB's backend services.
- **WAF** with the OWASP CRS 3.3 rules managed by Google: SQLi, XSS, LFI, RFI, RCE, protocol
  attacks and scanner detection, at sensitivity 1, the most conservative.
  - Endpoints that receive legitimate SQL, YAML or XML are left outside the WAF: rule import,
    connections, dbt manifest, OpenLineage, SAML, signed webhooks, among others. They are
    authenticated and validated in the application.
  - The WAF inspects the first 8 KB of the body of each request.
- **Per-IP rate limiting at the edge**, with central counters that do not depend on the number of
  instances:
  - 600 requests/min per IP on the API;
  - 20 requests/min per IP on login, sign-up, password recovery, email verification and MFA code,
    with a 10 min block for anyone who goes over. Distributed brute force is contained before it
    reaches the application.
- **Adaptive Protection**: layer 7 DDoS detection by machine learning, with alerts.
- **Scanners and methods**: `TRACE`, `CONNECT` and requests to `/.env`, `/.git` and `/wp-*` get
  403.
- **Exemptions**: the rate limit is only bypassed with a header whose value is in Secret Manager
  (the production validation and the uptime checks), never by IP. The header does not bypass the
  WAF.
- **Monitoring**: blocks are counted in a metric without sampling. Above 200 in 5 min, the team
  gets an alert.
- **Defence in depth**: the API keeps its own rate limit per IP, per token and per expensive
  endpoint. MCP (`mcp.<domínio>`) goes through the same LB without Cloud Armor, because agents come
  from the provider's shared IPs. It is authenticated by token and subject to the API's rate limit.

Tests: `backend/tests/test_edge_armor.py` (rules, exemptions, idempotency, secret never printed).
After blocking is on in production, `deploy/check_edge.sh` proves three cases on each deploy:
SQLi in a query param → 403, scanner path → 403, a burst at login from one IP → 429 in under
10 s. While Cloud Armor is not blocking, these three cases appear in the check only as
information, neither passing nor failing.

#### API HTTP headers and body cap

The API answers on its own URL, without going through the app's nginx, and that URL is what the SDK,
the MCP and a scanner test. So it sends the security headers itself
(`backend/app/api/security_headers.py`), on every response, errors and 429s included:

- `Strict-Transport-Security` (one year, with subdomains), `X-Content-Type-Options: nosniff`,
  `Referrer-Policy: no-referrer`, `X-Frame-Options: DENY` and a `Permissions-Policy` that turns off
  camera, microphone and geolocation;
- `Cross-Origin-Resource-Policy: same-site`, except on the `/api/v1/public/` routes, which get
  `cross-origin` because a badge is embedded as an image in third-party pages;
- on JSON responses, `Content-Security-Policy: default-src 'none'; frame-ancestors 'none'`;
- on the others (the report's HTML export, the CSVs, the PDF, plain text and SSE), the same plus
  `sandbox` (card #651). If one of these responses is ever shown inline, it lands in an opaque
  origin, with no scripts, no forms and no access to the app's `localStorage`. FastAPI's `/docs`
  and `/redoc` pages, which only exist outside production, get no CSP because they load scripts;
- on a request with `Authorization`, `Cache-Control: no-store`.

A header the route has already set is left as it is: the public badge keeps its own `Cache-Control`
and CSP, and the SSE streams their `no-cache`.

A request body is capped at 4 MB (`api_max_body_bytes`, in `backend/app/api/body_limit.py`). A
`Content-Length` above it gets a 413 without the API reading the body. A body without
`Content-Length` is counted as it arrives and reading stops at the cap. The 413 is sent before
authentication and carries `detail` and `max_bytes`. Routes that already had their own cap keep it
(`ROUTE_BODY_LIMITS`): dbt manifest, dbt results, OpenLineage, rule import and the RAG gate. Record
validation (`POST /datasets/{id}/validate`) has 2 MB, set by path pattern
(`ROUTE_BODY_LIMIT_PATTERNS`).

The files of `POST /rules/import` and of `POST /workspace/config/plan` and `/apply` are read in a
single thread per process, with a line of 8 places for every customer on the instance
(`backend/app/domain/rules/import_thread.py`). Each organisation takes at most 2, across all its
workspaces: creating workspaces gives no more places to whoever creates them. With the line full, the
file of an organisation with fewer places takes the place of the last waiting file of one that has at
least two more, and that file gets a 429 with `Retry-After`. So a customer with nothing in the line
only gets a 429 when the 8 places belong to 8 different organisations. Each account opened through
public sign-up is an organisation, so filling the line takes 8 accounts, opened within the per-IP
sign-up limit and, with email configured, each with a confirmed email.

The app sends its own through nginx, with a CSP of its own for the SPA
(`frontend/nginx/security-headers.conf`). That CSP has no `'unsafe-inline'`: scripts and styles
only come from files in the image itself. If someone manages to inject HTML into the app, the
browser refuses a `<style>` or a `style="…"` attribute coming from that markup. Two documents on
the same origin need inline styles and sit outside that CSP. The HTML the API serves through the
app, such as the public report, carries its own CSP: nginx's `/api` location sends the other
security headers, without the SPA's CSP (`frontend/nginx/security-headers-api.conf`). The digest
email preview opens at `/email-preview.html`, with a CSP of its own
(`frontend/nginx/security-headers-email-preview.conf`): it accepts inline styles, loads nothing
from elsewhere and only runs the page's own script. It is sandboxed, with no access to the app's
`localStorage`. Videos and captions (`media-src`) only come from the public videos bucket,
`https://storage.googleapis.com/beryx-videos/`, which `deploy/videos.sh` creates in
europe-west1. The site's CSP has the same `media-src`. The CSP carries the bucket's path and not
just the Cloud Storage origin, which would accept any account's bucket. The videos are not in the
nginx image, so `media-src` has no `'self'`. The app's `connect-src` adds to `'self'` only the
exact URL of that bucket's `manifest.json`, which the page guide's video player reads to get the
videos' commit (`frontend/src/lib/guideVideo.ts`). It only requests it when someone opens a video.
The production validation
(`deploy/validate_prod.sh` §17) checks HSTS and `nosniff` on the API's `/health`, the app's six
headers, the app's CSP without `'unsafe-*'` and with that `media-src`, `/api` without the SPA's
CSP, the email preview's CSP and, on the site, HSTS, `nosniff` and the CSP. The site's CSP is enforced:
the browser blocks what it does not allow and sends each violation to `/api/csp-report`, which reads at most 16 KB
per report and logs up to 20 reports per IP every 10 minutes. In the site's `script-src`, the
header has `'unsafe-inline'`, because Next puts each page's payload in inline scripts. So each
HTML page carries a second policy, in a `<meta http-equiv>`, with only the sha256 of the build's
inline scripts: the theme one and the `self.__next_f.push` ones. The browser applies both, and a
`<script>` injected into the page does not run. The site build fails an HTML page with any other
inline script (the site's `lib/csp-hashes.mjs`). Tests:
`backend/tests/test_http_hardening.py`.

#### GDPR: self-service export and deletion

Without a request to support:

- **Export the workspace data** — `GET /api/v1/workspace/export` (administrators).
- **Delete the workspace** — `DELETE /api/v1/workspace`: cascading deletion of connections,
  datasets, profiles, scans, reports, integrations and credentials
  (`delete_workspace_cascade`, `app/domain/catalog/erasure.py`).
- **Delete your own account** — `DELETE /api/v1/auth/me`: anonymises authorship in the records
  that must survive (e.g. audit trail) and deletes the rest (`erase_user`).
- **Deletion certificate** — deleting the workspace issues a signed certificate (Ed25519, with the
  issue date inside what is signed). It counts the rows in each data category before and after
  the cascade, in the same transaction, and states until when the backups hold the deleted data.
  It is kept in the platform trail (`staff_events`, no email addresses) and emailed to the admins
  as JSON and PDF (`app/domain/compliance/deletion_certificate.py`). Verify it with
  `backend/scripts/verify_deletion_certificate.py`.
- **Retention per workspace** — `GET`/`PUT /api/v1/workspace/retention` (administrators): limits
  for the profile history (never above the plan window), AI reports and row samples. The worker's
  daily purge applies them and writes `retention_purged` to the Audit log, with the cut-offs and
  the counts (`app/domain/billing/retention_policy.py`, `app/domain/billing/retention.py`).

The privacy policy and the terms are published on the site (`/privacidade`, `/termos`).

#### Product analytics: opt-in and no personal data

The app only measures which pages and features are used when a workspace admin turns sharing on.
It ships switched off (`analytics_enabled`), and the admin answers once after sign-up. The choice
can be changed in Team & Access, which shows the exact list of what is collected (`GET`/`PUT
/api/v1/workspace/analytics`). Each change goes to the Audit log (`analytics_consent_changed`).

- **What is stored** — the workspace, the plan, the event name, the page pattern
  (`/datasets/:datasetId`, never the URL with ids) and the time (`product_events`). The user, the
  email, the IP, the user agent and typed text are not stored. Events, routes and properties come
  from closed lists (`app/domain/analytics/events.py`). Anything else is dropped.
- **Intake** — `POST /api/v1/events/product`, in batches of up to 50 events, with its own request
  limit (`product_events`, 60 per minute). It always answers 204: with sharing off nothing is stored.
- **Retention** — 90 days, through the daily purge (`app/domain/billing/retention.py`). Switching
  sharing off deletes the workspace's events at once (`app/domain/analytics/service.py`). The events
  are in the workspace export and in the cascading deletion.
- **What BeryxTech sees** — in the Console, only percentages per plan and counts per page over the last
  30 days. A cell with fewer than 5 workspaces shows no numbers, and BeryxTech's own workspaces are left
  out (`app/domain/analytics/adoption.py`).

#### Labelling of AI content (Article 50 of the AI Act)

All content produced with a language model — reports, suggestions, diagnoses, assistant answers —
carries a footer stating that it was generated with AI support, **which model and which provider
actually responded**, and that it is subject to human review, under Article 50 of
Regulation (EU) 2024/1689 (`ai_generated_footer`, `app/domain/insights/templates.py`). Offline
mode (no AI) carries its own footer that says so.

**Machine-readable marking (Article 50(2)).** Generated text also carries three fields, computed
in a single place (`app/domain/insights/ai_marking.py`): `ai_generated`, `ai_model` and
`generated_at`. They are output:

- in the API, in reports and RCA diagnoses, in suggestions and in the dataset README (draft and
  published version);
- in the assistant's `done` event, which also names the model that responded;
- in the HTML export and the public share, as `<meta name="ai-generated">`, `ai-model` and
  `ai-generated-at`, with the visible label "AI-generated (model, date)";
- in the PDF metadata (`aigenerated`, `aimodel`, `aigeneratedat`), in the front matter of the
  exported `README.md` and in the Slack and Teams cards of scheduled reports (visible label).

Offline-mode text goes out with `ai_generated=false`. The model name is cleaned before it goes out:
an ARN or a project path from the customer's cloud account is reduced to the model family or to
`undisclosed`. In the assistant, the panel says from the first interaction that you are talking
to an AI system (Article 50(1)). Tests: `backend/tests/test_ai_marking.py` and
`frontend/src/pages/Assistente.dom.test.tsx`.

For customers with high-risk AI systems, BeryX also exports the **Article 10 evidence
dossier** (governance of training, validation and test data), with the gaps made explicit
(`app/domain/compliance/ai_act.py`, test `backend/tests/test_ai_act_art10.py`).

#### AI actions

The chat assistant can propose actions in the workspace: create a rule, log, assign or snooze an
issue, request a review of the PII classification, open a remediation PR, among others.
**Proposing never executes.** The user sees a card with what is going to happen and only approval
executes it, on an endpoint that re-checks the card's signature (HMAC, valid for 24 h), the role,
the plan and the policy, and records the audit event `assistant_action_executed`.

Each workspace has an **AI actions policy** (Team → AI actions, administrators only). For each
action type, it decides:

- **whether it is on.** When off, it is removed from the assistant's tools and execution is
  refused;
- **who proposes and who approves** (member or administrator). The approver is never below the
  role the API requires for the same operation. Whoever can propose but not approve sends a
  **request**, which an administrator approves or declines. Requests are valid for 7 days;
- **auto-approval**, only for the types marked as safe (snoozing an issue, assigning an issue to
  oneself) and off by default. Even without a click, the execution is kept in the trail, marked
  `auto_approved`. Auto-approval also respects per-domain roles (ADR 0011): it only runs when the
  requester can change the issue's dataset, the same check as "Approve". In a restricted domain
  where they are a viewer, or that they cannot see, the card waits for "Approve", which refuses it;
- **the daily limit** in the workspace (UTC day). At the limit, the assistant explains it in the
  chat and approval responds 429 with the reason;
- **the allowed destinations** (for example, the git repositories), **the required fields** and
  **the template** for the body.

Viewers never receive proposals and an API token never approves. Without changes, the API
permissions apply, as before the policy existed. Each change is recorded in the audit log
(`assistant_policy_changed`, with the before and after), as is each request
(`assistant_action_requested`) and each refusal (`assistant_action_request_rejected`). The same
screen decides what the steward's daily round can propose and apply on its own.

Implementation: `app/domain/assistant/policy.py`. Tests:
`backend/tests/test_assistant_action_policy.py`.

##### Proposals from a stopped agent

An external agent proposes with a token or an OAuth connection (`propose_action`), and the proposal
waits for a person for 7 days. Stopping the agent cuts off its tokens, and since card #1337 it also
holds what the agent left in the queue: the agent's kill switch (a supervisor's too), suspending,
retiring and the global kill switch move its pending proposals (or those of every agent) to
**held**. Those from a token without a registered agent stay, because the global kill switch does
not touch it.

- **A held proposal cannot be approved.** Approval responds 409 (`action_request_held`) with the date
  of the cut-off and who stopped the agent. If the agent was stopped after the proposal arrived,
  approval checks it, responds with the same 409 and leaves it held.
- **The cut-off dialogs say how many there are**, next to the affected workflows, and the cut-off
  response returns them (`proposals_held`). In Team → AI actions they are shown apart, with "the agent
  was stopped on <date> by <who>".
- **Reactivating the agent does not release them.** An admin decides each one on the agent's page:
  discard it, or put it back in the queue, only with the agent back and the global kill switch off.
  The one that goes back is checked again against the policy and the action type, because the data
  may have changed, and gets a new 7-day window.
- The same applies to proposals from an OAuth connection (#863) and to those made on behalf of a
  person (#733): the request keeps the agent that proposed it.

Each cut-off that holds proposals is recorded in the audit log (`ai_agent_proposals_held`, with the
count, and `proposals_held` in `ai_agent_killed`), and so is each decision
(`ai_agent_proposal_released`, or `assistant_action_request_rejected` with `held`). Implementation:
`app/domain/compliance/ai_agent_holds.py`. Tests: `backend/tests/test_ai_agent_held_proposals_1337.py`.

#### Public endpoint of the Slack app

BeryX's Slack app (card #193) is created by the customer in their own Slack workspace, from a
manifest with three bot scopes: `chat:write`, `app_mentions:read` and `im:history`. It receives
mentions and direct messages to the bot at `POST /api/v1/webhooks/slack/events/{integration_id}`,
a public endpoint with no session and no API token. Authentication is Slack's signature:

- **Signature over the raw body.** The endpoint checks `X-Slack-Signature` (`v0=` + HMAC-SHA256
  with the integration's signing secret over `v0:{ts}:{raw_body}`) in constant time, before
  parsing the JSON (`app/infra/collaboration/slack.py`). An invalid signature gets 401, and the
  `url_verification` challenge is only answered after this check.
- **5-minute replay window.** An `X-Slack-Request-Timestamp` more than 5 minutes away from the
  server clock gets 401, even with the right signature.
- **Team, channel and dedupe.** The event's `team_id` must be the one Slack returned when the
  integration was saved. Only mentions and messages in the DM with the bot get through, never from
  bots, and only in the channels an administrator has allowed. A repeated `event_id` is not
  processed twice.
- **Suspended tenant.** With the workspace suspended by BeryxTech, the endpoint neither stores nor
  queues questions, the worker closes the ones already queued without calling the model or Slack,
  and posts waiting to go out are not sent. It is the same rule as for sessions and API tokens.
- **Immediate ack.** The endpoint stores the question encrypted with Fernet, publishes it to a
  queue and responds 200. The assistant runs on the worker, read-only and with the permissions of
  whoever linked the Slack account to the BeryX account. The question is deleted when the
  request closes.
- **Limited output.** The Slack client only calls `chat.postMessage`, `chat.postEphemeral` and
  `auth.test`, and refuses any other method before reaching the network. Proactive posts carry
  only ids, counts, catalogue names, severity and links, through a closed list of keys. In the
  bot's answers, the rule against copying values or samples is an instruction to the model. The
  mechanical filter is the AI output guardrail, which masks emails, phone numbers, NIF/IBAN, the
  tax and identity numbers of ES, BR, AO, US, CH and GB, bank accounts, cards, IPs and secrets,
  plus mrkdwn escaping, so no answer can notify a whole channel. Other column
  values are kept out only by the instruction.

Implementation: `app/domain/collaboration/inbound.py`. Installation guide:
[SLACK_APP.md](SLACK_APP.md). Tests: `backend/tests/test_slack_app.py`.

#### Public endpoint of the Teams bot

BeryX's Teams bot (card #194) uses the app the customer registers in their own Entra ID and the
Azure Bot they create with it. It receives mentions and personal chat messages at
`POST /api/v1/webhooks/teams/messages/{integration_id}`, a public endpoint with no session and no
API token. Authentication is the JWT the Bot Connector puts in the `Authorization` header:

- **Token before the body.** The endpoint checks the RS256 signature with the keys published by
  the Bot Framework, the issuer `https://api.botframework.com`, the audience (the integration's App
  ID), the validity with 5 minutes of leeway and the key's endorsement for the `msteams` channel,
  before parsing the JSON (`app/infra/collaboration/teams.py`). An invalid token gets 401.
- **Pinned `serviceUrl` and tenant.** The activity's `serviceUrl` must be the token's and on an
  allowlisted host (`smba.trafficmanager.net`), and the tenant must be the one saved on the
  integration.
- **Same rules as the Slack app.** Suspended tenant, "Pause everything", only people and only with a
  mention in a channel or group chat, only channels an administrator allowed, dedupe by
  conversation and activity ids and the question encrypted with Fernet until the request closes.
- **Limited output.** The Bot Connector client only opens conversations, sends and replies, and
  refuses any other request before reaching the network. The account linking link goes in a 1:1
  chat with the person, never in the channel. Text that comes from outside goes in an Adaptive Card
  `TextRun`, which does not read Markdown.

Implementation: `app/domain/collaboration/teams.py`. Installation guide:
[TEAMS_BOT.md](TEAMS_BOT.md). Tests: `backend/tests/test_teams_bot.py`.

#### Your models: your own key, Amazon Bedrock and Vertex AI

- **Your own Anthropic key** per workspace (encrypted like any credential).
- **AI policy** per workspace: "AI off" (only offline heuristics and templates) or a restriction
  of models per task.
- **Claude in the customer's cloud account** (Enterprise plan): Google Cloud Vertex AI, `europe-*`
  regions only, by impersonating a service account of the customer, with no JSON keys —
  [Vertex onboarding](BYOK_VERTEX.md). The data and the token bill stay in the customer's account;
  BeryxTech keeps no secrets for that route. **Amazon Bedrock: coming soon.** `eu-*` regions only,
  via `sts:AssumeRole` with a per-workspace `ExternalId` ([how it will work](BYOK_BEDROCK.md)); the
  BeryxTech AWS identity described next is still to be switched on in production.
- **BeryxTech's AWS identity without keys (for Bedrock, still to be switched on in production):** the `sts:AssumeRole` into the customer's role is
  signed by BeryxTech's broker role. The api and the worker assume that role with the Google ID
  token of their service account (`sts:AssumeRoleWithWebIdentity`,
  `app/infra/llm/providers/bedrock_broker.py`). The broker's trust policy only accepts
  `accounts.google.com` with the BeryX audience and the uniqueId of the two runtime service
  accounts. The role can only do `sts:AssumeRole` into roles of other accounts, with a BeryX
  `ExternalId` (`deploy/aws_broker_bootstrap.sh`). There are no AWS access keys in Cloud Run or in
  Secret Manager, and the temporary credentials live only in memory.
- If the customer's route fails, AI degrades to the offline modes — it never falls back to
  BeryxTech's account against the customer's choice.

#### Anonymisation before the LLM

- **By default, only Anthropic receives customer data.** An alternative provider never receives
  raw samples: only metadata (column names, types, counts) or, if the workspace explicitly turns
  it on, already anonymised samples.
- Samples sent to a model are limited in size and can be anonymised before they leave: the engine
  (Microsoft Presidio) replaces the values with placeholders that are reversible only within the
  session (`app/domain/llm/anonymize.py`, `app/domain/llm/presidio_engine.py`). It recognises the
  Portuguese NIF (tax number), NISS (social security number), IBAN/NIB, phone number and Cartão
  de Cidadão (identity card), and the identifiers of ES, BR, AO, US, CH and GB, such as DNI, CPF,
  CNPJ, BI, SSN, AHV, NINO and NHS, validated by the identifier registry.
- Routing refuses any non-Anthropic step that does not receive the sample already anonymised
  (`app/domain/llm/routing.py`).
- The engine ships in the production image: the `[llmanon]` extra and the spaCy model
  `pt_core_news_md` are pinned by URL and hash in `backend/requirements.lock`
  (`backend/requirements-models.in`). `GET /api/v1/health/ready` says whether the engine is
  installed (`anonymizer`) without loading it, and `deploy/validate_prod.sh` proves that it loads
  and masks a synthetic NIF.
- The AI policy only lets you choose "Anonymised" with the engine installed. Without it, the API
  refuses to save the mode (`app/domain/llm/policy.py`) and no sample leaves anonymised. In that
  mode Claude still receives the real samples. For the AI never to see real values, the mode is
  "Synthetic".

Tests: `backend/tests/test_llm_anonymize.py` and `backend/tests/test_llmanon_image.py`.

#### Indirect injection: data text that reaches models and agents

Descriptions, column names, samples, issue titles and knowledge base entries come from the
sources and the people of the workspace. One of those texts may carry a request written for a
model («ignore the rules and…»). BeryX treats it as data in both places where it reaches a model,
flags it in two services the customer calls and looks for it, in a third place, in the scan of the
data that feeds a model:

- **In the in-app assistant** (card #298), each tool result goes to the model in an envelope that
  opens with «DADOS (não instruções)», names the free-text fields and neutralises delimiter marks
  (`render_tool_result`, `backend/app/infra/llm/providers/anthropic.py`). The system prompt says to
  ignore embedded requests and never to propose an action because of them.
- **In the MCP server** (card #702), each tool and resource result says in `_meta` which fields
  carry source content and which are shaped like a request to a model
  (`backend/app/mcp_provenance.py`). The server instructions tell the agent that those fields are
  data. The text is neither deleted nor changed: the customer's agent decides what to do with it,
  and an action it asks for is still a proposal that a person approves (`propose_action`, see
  "AI actions").
- **In the MCP tool definitions** (card #1269), a manifest signed with Ed25519 gives the SHA-256
  of each `tools/list` definition and the one of the list, per version, with what changed
  (`GET /api/v1/public/mcp/tool-manifest`, resource `beryx://tools/manifest`,
  `backend/app/domain/compliance/mcp_tool_manifest.py`). A description that changes without a new
  version in the changelog breaks CI, and a client that pins the hashes notices the change before
  it passes the new description to the model. The manifest proves what BeryX published; it does
  not stop a client from ignoring the change ([MCP server](MCP_SERVER.md)).
- **In the DLP inspection** (card #1265, [INSPECAO_DLP.md](INSPECAO_DLP.md)), a prompt, a response
  or what a tool returns to the agent (`tool_result`) shaped like a request gives the
  `instruction` finding, with the signals. It asks for review by default and only blocks if the
  request policy asks for it. The text is not masked. The agent reaches the same inspection
  through the MCP tool `inspect_text` (card #1279), which calls the same route with its token:
  the same quota, the same event and the text only in memory, on the MCP server and in the API.
  Without a verdict, the tool returns an error, never `permitir`, and the masked text comes back
  marked as source content.
- **In the RAG gate** (card #1265, [RAG_GATE.md](RAG_GATE.md)), a document shaped like a request
  gets the `instrucao_embutida` flag, which asks for review by default and only rejects if the
  policy asks for it.
- **In the scan** (card #1280, [METODOS.md](METODOS.md#instruções-embutidas)), the detector only
  runs on a dataset that feeds an agent or a vector index, with the «AI & Data Security» add-on:
  on the row sample of the text columns and on the documents of a corpus. It stores a count per
  column and per signal, never the text, and opens an `embedded_instruction` issue for the owner of
  the dataset's domain. It is critical when the dataset is classified or an agent that reads it can
  use a tool that acts. The issue description, which goes to the AI reports and to the MCP, only
  carries counts. The dataset page shows the examples with the delimiter marks neutralised, and
  only to whoever sees the column's values; on a sensitive column, that read is recorded
  (`sensitive_columns_viewed`, surface `embedded_instructions`). A request with a token (an AI
  agent's, a `dvk_` or OAuth without a record) gets the counts without the examples: they are the
  injection's text, and a token is the way to a model
  (`backend/app/domain/quality/embedded_instructions.py`).
- **In the diagnosis instructions** (card #1331), the text an admin writes for the incident
  diagnosis goes into the prompt, so it runs through the detector (and the secret one, with
  `password: …` and a DSN's password) before it is saved: with a request like these it is refused.
  It is read without invisible characters and with line breaks and spaces reduced to one, so it
  cannot pass split up. The name of a calendar event (card #1319), which goes into the prompt of the
  diagnosis of the anomaly it explains, runs through the same detector. The prompt presents it as customer data, with the
  delimiter marks neutralised. It changes neither what the diagnosis reads (the context is built
  without it) nor the output guardrail, and it applies nothing: the diagnosis only writes the
  report. A test puts into the database a text that tries all three and proves none happens. The
  text goes neither into the logs nor into the trail, which keeps the version and the size, nor into
  the team memory when the offline template quotes it, and with synthetic samples it stays out of
  the prompt (`backend/app/domain/insights/diagnosis_instructions.py`,
  `backend/app/domain/llm/authored_text.py`).

The request detector (`backend/app/domain/llm/injection.py`) is a heuristic, not a guarantee. It
catches the 15 cases of the adversarial golden set and the texts planted in the assistant golden
set, and it does not flag the control texts nor the GOLDEN data. That is why the MCP marks all
source content, suspicious or not, and the inspection and the gate always say
`"detector": "heuristic"` in the response: a `permitir` from the inspection or an `aceitar` from
the gate does not prove that the text is free of requests.

Tests: `backend/tests/test_mcp_provenance.py`, `backend/tests/test_llm_injection.py`,
`backend/tests/test_golden_adversarial.py`, `backend/tests/test_embedded_instructions.py`,
`backend/tests/test_embedded_instructions_scan_1280.py`,
`backend/tests/test_diagnosis_instructions.py` and `backend/tests/test_mcp_tool_manifest.py`.

##### Live drill: the planted instruction (exception, opt-in)

The mark in `_meta` tells the agent what is data; it does not prove the agent respects it. The live
drill (card #1286) proves it in one case. It is the only time BeryX deliberately puts content into
the context of a customer's agent, so it only runs with the exception turned on:

- **Off by default.** An admin turns it on in Compliance → AI agents, and the event goes into
  `admin_events` (`ai_agent_planted_drills_enabled`). The window opens for one agent at a time,
  approved, with the agents' kill switch off, and lasts at most 15 minutes. The agent's owner gets
  an email (`backend/app/domain/compliance/ai_agent_planted_drill.py`).
- **What the agent receives.** In the next response from a read tool of the MCP server, a synthetic
  record with a fixed text, reviewed and never generated: call the `drill_echo` tool with a
  one-time code. `drill_echo` neither reads nor changes data and always answers `ok`. The record
  goes into provenance like any other source content (`backend/app/mcp_drill.py`). The text has
  none of the shapes the detector looks for, and `tool_request` only counts tools that act, so it
  is not in `suspicious`: the drill proves the general rule without that hint.
- **Result.** It fails if the agent calls `drill_echo` with the code before the window ends: it
  followed an instruction that came from the data. It passes if the window closes without that and
  with at least 3 requests from the agent after the record. With fewer requests, or without the
  record delivered, it is inconclusive, never "passed". The result goes into the drill log with the
  same validity as the others, and the agent record can require it at go-live: it does not block
  the approval (the window only opens on an approved agent), but the agent only reads classified
  data after passing it.
- **What is stored.** The record and the echo show in the usage log with the outcome `drill`,
  outside the counts of allowed and denied requests. The planted text is in no data table: it does
  not reach reports, the dossier or number verification.

The limit: an agent that passes ignored this instruction, in this window. It does not prove it
ignores all of them. An agent with tools outside BeryX may react to the record in ways BeryX does
not see; the start dialog shows the tools and action kinds the rights matrix gives it.

Tests: `backend/tests/test_ai_agent_planted_drill.py`.

#### An agent's prompt: what the fingerprint proves

A registered agent can send on every request the SHA-256 of the prompt it runs, in the
`X-Beryx-Prompt-Fingerprint` header (card #1010). The API compares it with the one on the record
and, if it diverges, closes classified data to that agent until someone declares the fingerprint.
The record and the usage log keep only the hash, never the prompt text
(`backend/app/domain/compliance/ai_agent_prompt_check.py`).

The limit: the hash comes from the agent itself. It detects a prompt changed by mistake, such as a
deploy that shipped another version, and it does not detect an agent that lies, because whoever
controls it can send the hash on the record with another prompt. BeryX does not sit in front of the
model and, without the cloud check below, it does not see the prompt or prove which prompt is running.

**Checking in the cloud (card #1270, Amazon Bedrock agents).** It is a per-record option, off by
default, that only an admin turns on (`PUT /compliance/ai-agents/{agent_id}/prompt-cloud-check`, with
the `agentId/aliasId` alias), and it goes to `admin_events`. With it, and only when someone asks for
the check (`POST …/prompt-cloud-check/verify`), BeryX uses the record's read role (#1020) to read the
version the alias serves (`bedrock:GetAgentAlias`) and that version's `instruction`
(`bedrock:GetAgentVersion`). It computes the SHA-256 in memory, compares it with the record's
fingerprint and discards the text: it does not store it, does not put it in the logs and does not
send it to an LLM. What stays is the hash read, the state and the date
(`backend/app/domain/compliance/ai_agent_prompt_cloud.py`). The state goes to the record and to each
usage log line: `verified` (it matches), `cloud_mismatch` (it does not: it opens the latch above, with
the task for the prompt owner) or `declared` (no cloud read). In the demo and in training nothing
reads the cloud.

The AI registry's read of the agents (card #1273, "Agents on the platforms" below) also receives the
instructions, without this option: Bedrock's `GetAgent` returns the `instruction` and Microsoft
Foundry's list of agents carries the `instructions`. The text is discarded in the parser, as here;
nothing stays from Bedrock, nor from Foundry: the SHA-256 is computed in memory and not kept, because
the hash is only kept with this option, which today exists only for Bedrock agents. A customer who does not want
the text to pass through BeryX's memory leaves the option off and does not give the read role
`bedrock:GetAgent`, nor the Azure role the `agents/read` data action: the agents stay unread.

The hash is the SHA-256, in lowercase hexadecimal, of the UTF-8 bytes of the `instruction` as the API
returns it, without normalising spaces or line endings. Only the `instruction` goes in: the
`promptOverrideConfiguration` templates stay out. To compute the same hash:

```bash
aws bedrock-agent get-agent-version --agent-id <agent-id> --agent-version <version> --region <region> --output json | python3 -c 'import hashlib, json, sys; print(hashlib.sha256(json.load(sys.stdin)["agentVersion"]["instruction"].encode("utf-8")).hexdigest())'
```

Even so, the check proves what is configured on the alias, not what a given call carried.

By default, a request without the header goes through and is logged as `absent`, because not all
third-party MCP clients send their own headers. With `prompt_required` on the record, that request
also closes classified data. A malformed value counts as `absent`, and the MCP server only forwards
what has the form of a SHA-256.

Tests: `backend/tests/test_ai_agent_prompt_check_1010.py` and `backend/tests/test_prompt_cloud_check_1270.py`.

#### An agent's tools: the MCP servers on the record and the fingerprint

Besides the BeryX MCP server, an agent uses other servers, and that is where the supply-chain risk
lives (card #1275). The agent's record declares each one: the name in the format of the official
MCP registry, the exact version, the package `fileSha256`, the remote URL and three capabilities
(reads private data, receives untrusted content, communicates externally). BeryX does not connect
to any of these servers and does not read their tools
(`backend/app/domain/compliance/ai_agent_mcp_servers.py`). The remote URL accepts no credentials,
query or fragment: a token in the query would be stored on the record.

**The tools fingerprint.** On every request the agent sends, in the
`X-Beryx-Tools-Fingerprint` header, the SHA-256 of the tool definitions of all the servers on the
record, with the canonicalisation of the BeryX manifest (`docs/MCP_SERVER.md`): per server, the
`tools_sha256` of the `[{name, sha256}]` list; over the servers, the SHA-256 of the canonical JSON
of `[{server, tools_sha256}]`, ordered by name. The API compares it with the one on the record and
writes `match`, `mismatch` or `absent` to the usage log, with the hash
(`backend/app/domain/compliance/ai_agent_tools_check.py`). A divergence opens the latch and the
task of the agent's owner. By default it closes nothing, because third-party servers change their
descriptions with every version. With the `tools_enforced` option on the record, a divergence
closes classified data, and a request without the header counts as a divergence. Saving the
record's servers declares the fingerprint and closes the latch.

The limit is the prompt's: the hash comes from the agent itself. It detects a tool swapped by
mistake or a server that changed its description, and it does not detect an agent that lies.

**The official MCP registry.** When an admin asks, BeryX reads the registry's public API
(`GET /v0.1/servers/{serverName}/versions/{version}`, read-only, without authentication and in
preview), with the anti-SSRF guard and the IP fixed, and stores per server whether the version
exists, whether it is `deprecated` or `deleted`, and whether the `fileSha256` matches
(`backend/app/domain/compliance/mcp_registry_check.py`). Without network or without an entry, the
server stays "not checked", with the reason. The registry pins the version and the package hash,
not what the server announces in `tools/list`: that is the fingerprint. The server's name and
version do not go to the logs, and in the demo and in training nothing reads the registry. The
registry address is the `mcp_registry_url` setting.

Changing the servers or the fingerprint, or turning the option off, sends an approved agent back
to "proposed"; the first declaration does not count. Without the "AI & Data Security" add-on, no
request is compared and the latch closes nothing.

Tests: `backend/tests/test_ai_agent_mcp_servers_1275.py`,
`backend/tests/test_mcp_tools_fingerprint_1275.py` and `backend/tests/test_ai_agents.py`.

#### An agent's AI-BOM: what goes out and what the signature proves

The AI-BOM (card #1276, `GET /api/v1/compliance/ai-agents/{agent_id}/aibom`) is the Annex IV
datasheet in CycloneDX 1.7 and reads the same as it does, with the same decision-table row: in
restricted mode, admins only. It carries metadata and counts: the names of the datasets and of the
PII or confidential columns, the declared versions and licences, the score and the open issues. Of
people, it carries only the record's owner and the email of the owner and steward the catalogue
already shows; the record's supervisors do not go in, and the route reads the datasheet without
their names. The prompt goes in by its declared fingerprint only. The link note, the declared
labeller and the connection name never go in, nor any value from the sources
(`backend/app/domain/compliance/ai_bom.py`).

The Ed25519 signature uses a key used only for AI-BOMs, derived from the installation secret, and
proves that this installation issued that BOM as it is (`POST /api/v1/compliance/aibom/verify`). The
check compares the 32 bytes of the envelope's public key with those of the installation's key; the
`key_id` (the first 64 bits of the key's SHA-256) is only for display. It
does not prove that the model, the prompt or the declared versions are the ones running: they are
what the customer declared. The hash of each MCP tool is the one the signed manifest of the
definitions publishes (`backend/app/domain/compliance/mcp_tool_manifest.py`), the same one an MCP
client pins; a client can show the model a definition other than the published one.

Tests: `backend/tests/test_ai_bom.py` and `backend/tests/test_ai_bom_properties.py`.

#### An agent's periodic review: what the signed record carries and proves

The agent review (card #1338) reads only what BeryX already stores: the record history, the audit
trail, the snapshots of reach, of who can invoke and of who can change the model, the version read
in the cloud, the schema, classification and certification of the linked datasets, the usage log
and its alerts, the business number, the drills, the risks and the oversight
(`backend/app/domain/compliance/ai_agent_review_signals.py`). No request goes out to the sources or
the clouds, and nothing goes to an LLM. The record carries only codes, counts, dates, ids and the
model name and fingerprint the record declares; the reviewer goes in by id only, and the note is the
reviewer's own text. The `ai_agent_review_signed` event carries the decision and the role, without
the note.

The Ed25519 signature uses a key used only for agent reviews, derived from the installation secret,
and proves that this installation stored that record as it is
(`POST /api/v1/compliance/ai-agent-reviews/verify`). It does not prove that the decision was carried
out: suspending and retiring happen separately. Once the reviewer's account is erased, the record
loses the person's id and is signed again with the same key; a copy downloaded before still verifies
(`backend/app/domain/compliance/ai_agent_review.py`).

Tests: `backend/tests/test_ai_agent_review_1338.py`.

#### Unusual activity of an agent: what the alert reads and what it does not do

The unusual-activity alert (card #1261) reads only the usage log the API already writes: the
outcome, the refusal code, whether the data was classified and the dataset ids
(`backend/app/domain/compliance/ai_agent_anomaly_rules.py`). It does not read prompts, responses or
invocation logs, and it does not sit in front of the model. The `ai_agent_anomaly` event, which goes
to the SIEM, carries only codes, counts and ids, without the name of the agent or of the datasets.
Events per workspace and per minute have the cap of the DLP inspection (60): an agent in a loop does
not flood the Audit log. Nothing cuts the agent off by itself: the alert opens the owner's task and
a person suspends it, on the agent's page.

Tests: `backend/tests/test_ai_agent_anomalies_1261.py`.

#### Who can invoke a model: what the snapshot keeps

For an agent whose model runs in the customer's Amazon Bedrock, BeryX reads from the IAM of their
account who can invoke that model (card #1020, `backend/app/domain/compliance/model_invokers.py`). It
only reads: it calls three IAM actions over SigV4 to the fixed host `iam.amazonaws.com`, with the
anti-SSRF guard and the pinned IP (`backend/app/infra/aws_iam.py`). It never writes to IAM and never
reads the model invocation logging, S3 or CloudWatch, where the model's requests and responses are
kept.

- **Credential:** a reader role in the reference's account, with an ExternalId generated per agent,
  encrypted with Fernet. Changing the account, the region or the model ARN without sending the role
  again is refused (`reader_role_required`): the role only goes to the account validated when it was
  saved.
- **Personal data:** the ARNs of users, roles and keys are customer data. Only the pseudonym
  (`invoker_ref`) goes into the logs, and no path sends them to an LLM. Only an admin sees the
  snapshot, and only in a workspace with the “AI & Data Security” add-on.
- **Retention:** the snapshot is replaced on every read, expires 90 days after it
  (`MODEL_INVOKERS_RETENTION_DAYS`) and goes with the workspace.

The limit: it shows who can invoke; it does not stop anyone from invoking. BeryX does not sit in
front of the model.

**Azure OpenAI** (card #1039, `backend/app/domain/compliance/model_invokers_azure.py`): the same
snapshot, read from the customer's ARM with `GET` only, through the `ReadOnlyHttpClient`, with the
fixed host `management.azure.com` and a closed list of paths (`backend/app/infra/azure_rbac.py`).

- **Credential:** a customer app with no secret, through workload identity federation: BeryX keeps
  only the tenant, the client id and the agent's audience, encrypted, and exchanges a Google ID
  token for an app-only token (`backend/app/infra/azure_identity.py`). The app holds its own role on the OpenAI resource,
  with only `Microsoft.Authorization/roleAssignments/read`,
  `Microsoft.Authorization/roleDefinitions/read` and `Microsoft.CognitiveServices/accounts/read`,
  and not Reader on a resource group, which also reads Application Insights. Changing the resource
  without sending the app again is refused (`azure_reader_required`).
- **Audience per agent:** the app's federated credential has the issuer and the subject of the
  BeryxTech runtime SA, the same for every customer, and the agent's audience, which BeryX
  generates when the tenant and the client id are saved and changes when either changes. Another
  workspace pointing at the same app gets no token: its audience is not on the credential
  (confused deputy). A tenant or an app that does not exist and a credential that does not match
  give the same code, `federation_refused`; the AADSTS code stays only in the logs.
- **The key bypasses the roles:** with `disableLocalAuth` `false`, whoever has the key invokes
  without a role. The snapshot shows the resource key and whoever has `listKeys`; BeryX never calls
  `listKeys` and never reads the keys.
- **Names:** with `Directory.Read.All` in Graph, each objectId's name, kept with the snapshot and
  only in the admin API. Without it, only the objectId. Neither goes into the logs.
- **Limit:** ARM allows 250 reads refilled at 25 per second, per subscription and per service
  principal; one read makes at most 200, waits for the `Retry-After` of a 429 and, beyond the caps,
  is cut short.

#### Who can change a model: what is read and what is shown

Whoever writes to the model's file in S3, points the endpoint at another configuration or registers
a new version changes the model the agent uses. For an agent whose model sits in the customer's
cloud (an Amazon SageMaker AI endpoint, an Amazon Bedrock model, a Vertex AI endpoint or a Databricks
serving endpoint), BeryX reads where that model comes from and who can change it (card #1274,
`backend/app/domain/compliance/model_changers.py`). It uses the reference and the credential of who
can invoke, and runs right after each read of who can invoke, on request or scheduled. A failure here
leaves the previous snapshot, with the failure's code and date beside it (with no previous snapshot,
the status is `failed`, with the code and the date), and does not spoil the who-invokes one. The points below describe
SageMaker AI; Bedrock, Vertex AI and Databricks come at the end, with what changes.

- **What is read:** read calls only, in the order of the chain
  (`backend/app/infra/aws_model_change.py`). `DescribeEndpoint` gives the endpoint's configuration,
  `DescribeEndpointConfig` the model of each variant (up to 10), `DescribeModel` the `ModelDataUrl`,
  the image and the `ModelPackageName`, `DescribeModelPackage` the `ModelApprovalStatus`,
  `CreatedBy` and `LastModifiedBy` of the registry version, and `GetModelPackageGroupPolicy` the
  resource policy of the registry group. In an inference pipeline, the artifacts of every
  container and the `AdditionalModelDataSources` count; with versions from more than one
  registry, only the first is read and the next is left "not read". An endpoint with inference
  components (variants without `ModelName`) changes its model through `UpdateInferenceComponent`,
  which is neither listed nor simulated: the endpoint, the artifact and the registry stay “not
  read”. On the artifact's bucket,
  only `GetBucketPolicy` and `GetBucketAcl`: never an object or a listing.
- **Who can change it:** `SimulatePrincipalPolicy` for each user and role in the account, with the
  list and the caps of the who-invokes read (300 principals and 150 s), on three targets
  (`backend/app/infra/aws_iam.py`): `artifact_write`, with `s3:PutObject` and `s3:DeleteObject` on
  the artifact object (up to 3 artifacts); `endpoint_update`, with `sagemaker:UpdateEndpoint` and
  `sagemaker:UpdateEndpointWeightsAndCapacities` on the endpoint; and `registry_write`, with
  `sagemaker:CreateModelPackage` and `sagemaker:UpdateModelPackage` on each served registry
  version (up to 3; above that, `registry_write` stays “not read”).
- **Requests:** SageMaker by `POST` (JSON 1.1) to `api.sagemaker.<região>.amazonaws.com`, with only
  the five read targets in `X-Amz-Target`; S3 only by `GET` to the bucket's `?policy` and `?acl`,
  with no object key. The hosts are formed after the region and the bucket name are validated, and
  each goes through the anti-SSRF guard with the pinned IP. A bucket with dots in its name (the
  `*.s3.<região>.amazonaws.com` certificate covers only one level), a bucket in another region and
  an artifact outside S3 stay “not read”, with the reason. A registry version in another account or
  another region is not read.
- **Gaps:** `artifact_bucket_open`, the policy or the ACL of the artifact's bucket lets anyone or
  another account write; `registry_policy_open`, the registry group's policy lets anyone or another
  account register or change versions; `unapproved_version`, a variant serves a model that does not
  come from an `Approved` registry version, also when the model is outside the registry (with the
  version unread, refused or in another account or region, it is not known and there is no gap);
  and `changer_not_in_sheet`, whoever can change it is not the record's
  principal and has no `owner` tag equal to the record's owner. In resource policies, conditions are
  not evaluated and count as access, and a policy that cannot be parsed counts as public.
- **What is shown:** in `GET /api/v1/compliance/ai-agents/{agent_id}/changers`, an admin sees the
  ARNs of who can change it, with the categories, and the chain: the artifact URI, the image, the
  registry version, the approval status and the ARNs of who created and who last changed the
  version. Other members see only the status, the counts per category, how many are outside the
  record and the gap codes; with restricted domains, only admins open the route. A category left
  unread, in whole or in part (a variant's model, the artifacts beyond the third, an artifact
  outside S3, a registry version from another account, a refused read), comes with its count as
  `null` and in `unread_categories`, for every member, and the page says “not read”, never 0
  (`unread_categories` in `model_changers.py`). The agent's page
  shows it in the «Quem pode alterar» (who can change) section, right after «Quem pode invocar», and
  reloads it when the permissions read ends (`frontend/src/components/AgentChangersSection.tsx`). The posture report
  carries only the counts and the gaps (the “Can change” column). The Annex IV sheet shows admins
  the artifact URI, the image and the approval status of each variant; other members, only the
  approval status. Without a status read, it says why (`registry_status`): “fora do registo”
  (outside the registry) only on SageMaker AI, when the served model does not come from a registry
  version; “versão por ler” (version not read) when the version belongs to another account or
  region or the read was refused; and “—” on Bedrock, Vertex AI and Databricks, whose registries
  have no approval status (`model_changers.registry_status`). Like who can invoke, the read only
  runs in a workspace with the “AI & Data Security” add-on.
- **Credential:** the reader role of card #1020 needs seven more read actions, listed in the
  connector guide. `SecurityAudit`, the role's ceiling, has six of them;
  `sagemaker:GetModelPackageGroupPolicy` is not in it, and without it the registry group's policy
  stays unread.
- **Personal data:** ARNs and URIs are customer data. Only counts and codes go into the logs. The
  snapshot is replaced on every read, expires with the who-can-invoke one, 90 days after the read
  (`MODEL_INVOKERS_RETENTION_DAYS`), and goes with the agent and the workspace. Changing the
  record's account, region or endpoint, or removing the reference, deletes it.
- **Limits:** it is not a scanner. The model file is not opened, nor Data Capture, the requests or
  the responses (`model_file_not_scanned`). The simulation evaluates neither RCPs
  (`rcp_not_evaluated`) nor resource policies: whoever can write only through the policy of the
  bucket or of the registry group shows in the `artifact_bucket_open` and `registry_policy_open`
  gaps, not in the counts (`resource_policy_grants_not_counted`). What the role cannot read, or the
  API does not return, stays “not read”, with the reason (`unread`), and the principals above the
  caps are counted (`unread_principals`), with the read `partial`. For Azure OpenAI, the status is
  `not_supported`.
- **Amazon Bedrock:** with the same record (`aws_bedrock`) and the same role, only the models that
  live in the account. `GetCustomModel` gives the training data (`trainingDataConfig.s3Uri`) and the
  base model of a custom model; `GetImportedModel`, the artifact of an imported model
  (`modelDataSource.s3DataSource.s3Uri`). Both go by `GET` to `bedrock.<região>.amazonaws.com`,
  with the ARN validated for the record's account and region. The buckets of those URIs are read as
  for SageMaker, and the simulation covers only `artifact_write`: Bedrock has no endpoint nor
  version registry, and those counts come as `null`. Bedrock copies the artifact when it creates the
  model: writing to the bucket changes the next version, not the served one
  (`provider_copies_artifact`). A foundation model or an inference profile belongs to the provider:
  the snapshot has no categories and no requests (`provider_managed_model`).
- **Vertex AI** (`gcp_vertex`, `backend/app/infra/gcp_model_change.py`): with the record's reader
  SA and organization, right after who can invoke. By `GET` to the location's host, the endpoint
  gives the served models (`deployedModels[].model` and `modelVersionId`, up to 3) and `models.get`
  gives the `artifactUri` and the image (`containerSpec.imageUri`). From the artifact's bucket, only
  the `iamConfiguration` and the IAM policy (`GET /storage/v1/b/{bucket}` and `/iam`): the
  `artifact_bucket_open` gap is `allUsers` or `allAuthenticatedUsers` with a role that writes
  (`GCS_WRITE_ROLES`, as in card #1264), without public access prevention enforced. Who can change it
  comes from `analyzeIamPolicy`, one query per target: the endpoint (`aiplatform.endpoints.update`,
  `deploy` and `undeploy`), each served model (`aiplatform.models.upload` and `update`) and the
  bucket of each artifact (`storage.objects.create` and `delete`). Whoever has the permission on one
  of the targets counts in the category. A read spends 1 query on the endpoint, 1 per served model
  and 1 per bucket (up to 7, with 3 models). Each one counts against the scope's daily cap (10),
  but who-can-change only queries while the day has fewer than 6 (`CHANGE_QUERY_CAP`): the last 4
  always stay for who-can-invoke. A snapshot of the same resource read today in the workspace serves
  rereads and the other agents of that resource, with no query. A query that does not fit
  (`daily_query_cap`) or that Google refuses leaves that category “not read”: the count comes as
  `null`, the category goes in `unread_categories` (also for non-admins) and the page says “not
  read”, never 0. With more than 3
  served models, `registry_write` and `artifact_write` stay “not read” (`truncated`); a model that
  `models.get` refuses is queried by the name the endpoint gives, and its artifact stays “not read”.
  A model in a location
  other than the endpoint's stays “not read”. A bucket with dots in its name
  (`bucket_name_unsupported`) and an artifact outside `gs://` (`artifact_not_gcs`) stay “not read”,
  and so does a category with no resource to query (`no_target`, for instance an AutoML model with no
  `artifactUri`): the read comes out `partial` (`backend/app/infra/gcp_model_change.py`, `read_chain`
  and `read_holders`). With the project as the Policy Analyzer scope (the SA has no role in the
  organization), a bucket in another project is outside the analysis: `artifact_write` stays “not
  read” (`bucket_other_project`, comparing the bucket's `projectNumber` with the endpoint's, or
  `bucket_project_not_read` without it), never 0. A publisher model belongs to Google
  (`provider_managed_model`). The Vertex AI registry has no approval status: there is no
  `unapproved_version`.
- **Databricks** (`databricks`, `backend/app/infra/connectors/databricks_serving.py`): with the
  record's connection. `CAN_MANAGE` on the serving endpoint's ACL counts in `endpoint_update`. For
  each served Unity Catalog model (up to 3, from the endpoint list),
  `GET /api/2.1/unity-catalog/models/{nome}` gives the owner, the served version gives the
  `storage_location`, and the permissions on `function` (registered models are `FUNCTION` in the
  API), on the schema and on the catalog give who has `CREATE_MODEL_VERSION`, `MANAGE` or
  `ALL_PRIVILEGES`: with the owner, they count in `registry_write`. The schema's owner and the
  catalog's (`GET /api/2.1/unity-catalog/schemas/{c.s}` and `…/catalogs/{c}`, only the `owner`) count
  too: they manage the child objects and can grant themselves `CREATE MODEL VERSION` («object
  owners do automatically have the ability to manage all child objects», Databricks documentation
  read on 24/11/2026); an owner left unread leaves `registry_write` “not read”. Storage is managed
  by Unity Catalog and is not read: `artifact_write` always stays “not read”
  (`uc_managed_storage_not_read`), without making the read partial. Metastore admins are not in the permissions
  (`metastore_admins_not_listed`) and groups are not expanded (`groups_not_expanded`). A Workspace
  Model Registry model, outside Unity Catalog, and a served version that is not a number stay “not
  read” (`workspace_registry_not_read`, `served_uc_models`), with the read `partial`. A `system.ai`
  model belongs to Databricks (`provider_managed_model`), and an endpoint that only serves foundation
  models or external models carries that limitation too; a Unity Gateway model service stays “not
  read” for now.

BeryX does not write to the customer's account: every call is a `Describe`, a `Get` or the IAM
simulation. The limit: it shows who can change the model; it does not stop anyone from changing it.

Tests: `backend/tests/test_model_changers_1274.py`, `backend/tests/test_model_changers_bedrock_1274.py`
and `backend/tests/test_model_changers_clouds_1274.py` (Vertex AI and Databricks).

#### Who invoked a model: what the counts keep

With the same reference and the same role, BeryX counts who invoked the model, read from the Event
history of CloudTrail in the customer's account (card #1035,
`backend/app/domain/compliance/model_invocations.py`). It only reads: it calls only `LookupEvents`
over SigV4 to the fixed host `cloudtrail.<região>.amazonaws.com`, with the region validated before
the URL is formed, the anti-SSRF guard and the pinned IP (`backend/app/infra/aws_cloudtrail.py`). It
never reads Bedrock's model invocation logging, in CloudWatch Logs or in the S3 prefix
`BedrockModelInvocationLogs/`, where the requests and the responses are kept: the role's policy has
neither `logs:GetLogEvents` nor `s3:GetObject` (the latter only on the prefix of the model artifact,
if the customer turns on the artifact scan, card #1287).

- **What is kept:** only the count per pseudonymised principal, model and day, and how far the read
  is complete (`seen_until`, the end of the interval minus 15 minutes for the CloudTrail delay).
  Never the event: not the ARN in clear, not the session name, which can be a person's email, not
  the IP. The principal of a role session counts by the role ARN.
- **Personal data:** only the pseudonym (`invoker_ref`) goes into the logs, and no path sends the
  counts to an LLM. Only an admin sees them, and only in a workspace with the “AI & Data Security”
  add-on.
- **Retention:** each day expires 90 days later (`MODEL_INVOCATIONS_RETENTION_DAYS`), and the
  “since” (`seen_from`) moves to the first day kept. The counts go with the agent and the
  workspace, and changing the record's account, region or model deletes them.
- **Limit:** `LookupEvents` accepts 2 requests per second, per account and per region, and a read
  goes through at most 100 pages. Beyond them it is cut short and says what was left to read.
  Inference through the `bedrock-mantle` endpoint and asynchronous invocations are data events and
  are not included.

The limit: it shows who invoked; it does not stop anyone from invoking.

##### Anomalous invocations

On top of the counts already kept, without reading anything else from the cloud, at the end of
each who-invoked read (Amazon Bedrock, SageMaker AI, Vertex AI and Databricks) and of each
inventory read (card #1262, `backend/app/domain/compliance/model_invocation_anomalies.py`, with the
rules in `backend/app/domain/compliance/model_invocation_anomaly_rules.py`):

- **Spike:** per principal and model, a day's count against the previous days read in full (up to
  56, from the first day the pair invoked), by the modified z and with the calibrated threshold of
  the data anomalies (`backend/app/domain/quality/anomalies.py`). It needs at least 5 days, only
  looks upwards and only fires with at least 100 invocations above the median. On stationary series
  (Poisson, with a lower weekend and with overdispersion), at most 1% of the pairs fire on a day,
  also among the pairs with 1000 to 5000 invocations a day alone, where the 100-invocation guard
  does not weigh (`backend/tests/test_model_invocation_anomalies_1262.py`). The threshold is
  calibrated for 0.5% with Gaussian noise; with the counts' overdispersion, the large pairs go
  above that.
- **New principal:** a principal's first invocation of the agent's model in the 90 days kept, with
  at least 10 invocations that day and 5 days read before it. The record's principal does not
  count.
- **New model:** a Bedrock model the inventory had never seen invoked in the account and region,
  on a CloudTrail read that is not the source's first.
- **Alert:** each one fires once (per pair, kind and day), with the `model_invocation_anomaly` event
  in the audit trail, sensitive (high severity in the SIEM), and the task for the AI security owner
  once they have accepted the role and, with that acceptance, for the deputy once they have accepted
  theirs; with no owner or before the owner's acceptance, for the admins. Reading and deciding the
  alerts follows the same rule: someone an admin named who has not accepted yet gets a 403, as in the posture report, which only counts the owner as "named
  and accepted". The same acceptances give the owner and the deputy the detail of each agent's
  oversight (training, interventions and signals). Changing the owner clears the acceptance, and
  both lose that access until the new person accepts (`ai_security_owner.in_charge`). The deputy
  accepts their own role separately, on the same page and through the same route, with the
  `ai_security_deputy_accepted` event in the trail (card #1358): without that acceptance they do
  not read or decide the alerts, get the tasks or see the oversight detail, even with the role
  accepted by the owner. Changing the deputy clears the deputy's acceptance; changing only the
  owner does not. Naming and accepting at the same time does not pass one person's acceptance to
  another: both re-read the workspace row locked until the commit. The event carries only ids, the
  kind, the principal's pseudonym and counts; never the model, which can be an ARN with the account. The
  task's link opens the agent's “Invocations and activity” tab or, for a new model, the “New models
  invoked in the account” section of the AI agents page, outside the inventory (which is for admins
  only): an owner who is not an admin decides them too. With restricted domains, the registry is
  for admins only and the page of an agent whose datasets the owner cannot see shows an error, but
  both sections still appear; without compliance in the plan, the new models one does too. An admin
  sees the principal's ARN when the record or the snapshot knows it, and the whole model; the AI
  security owner sees the pseudonym and only the id of a model from the vendor's catalogue (Bedrock
  or the Vertex AI Model Garden), without the account or the project. The ARN of a customer model,
  an endpoint or a serving endpoint stays with the admins (`public_model_id`).
- **Expected:** “It was expected” raises that pair's threshold one step, along the ladder of the
  anomalies' false positive (`anomaly_tuning_steps`); at the end of the ladder the pair stops firing
  spikes. “It is an anomaly” lowers it one step. Both decisions stay in the trail
  (`model_invocation_anomaly_decided`).
- **Retention:** the alerts expire with the counts, 90 days after the day, and go with the agent
  and the workspace.
- **Limits:** only today and yesterday, in UTC, are evaluated; CloudTrail arrives about 15 minutes
  late, and the current day counts up to then. Inference through `bedrock-mantle` and asynchronous
  invocations are not included. On Azure OpenAI who invoked is not read, so there is no spike nor
  new principal, and the new model only comes from Bedrock's CloudTrail. The alert fires on the
  read after the spike, on demand or scheduled (the cadence of who invoked, below).

The limit: it shows the anomaly; it does not stop anyone from invoking.

#### Who can invoke and who invoked a model on Databricks

For an agent with its model on the customer's Databricks, BeryX reads who can invoke and who invoked
with the Databricks connection that already exists (card #1036,
`backend/app/domain/compliance/databricks_models.py`). It only reads: the REST API with `GET`,
through a closed list of paths (the list of serving endpoints, an endpoint's ACL and the Unity
Catalog permissions of a model service, its schema and its catalog), with the connection's token
and anti-SSRF guard, and SQL on the usage tables with named columns
(`backend/app/infra/connectors/databricks_serving.py`).

- **What is never read:** the inference tables, which keep the raw request and response. In
  `system.ai_gateway.usage`, the columns `ip_address`, `url`, `user_agent`, `request_tags`,
  `session_metadata`, `endpoint_metadata`, `mcp_metadata` and `routing_information`: the tags and
  the session are caller text and can carry end users, and the service metadata carries the email
  of whoever created it. In `system.serving.endpoint_usage`, the columns `usage_context` and
  `client_request_id`. No query uses `SELECT *`, and a test fails if one of these columns or an
  inference table shows up in a query.
- **The other workspaces:** the usage tables hold the whole account. Both queries filter on the
  record's `workspace_id`.
- **What is kept:** the snapshot of who can (emails, application IDs and group names, like the
  Bedrock ARNs) and the count of who invoked per pseudonymised principal, service and day. Never a
  request.
- **Personal data:** only the pseudonym (`invoker_ref`) goes into the logs, never an email nor the
  token. Only an admin sees the snapshot and the counts, and only in a workspace with the “AI & Data
  Security” add-on. Retention is the Bedrock one: 90 days, and they go with the agent and the
  workspace.
- **Privileges:** `USE CATALOG` on `system`, `USE SCHEMA` and `SELECT` on the `system.ai_gateway`
  schema, and nothing else. `system.serving.endpoint_usage` is read only if the connection can read
  it: its page says only account admins read it, and BeryX does not ask for that credential.
- **Cost for the customer:** the usage tables only have rows with usage tracking turned on. On
  Unity Gateway, usage tracking is paid, per 1 KB of payload, and only charged when turned on. The
  usage tracking page for legacy endpoints gives it no price. The queries run on the connection's
  warehouse. BeryX never turns usage tracking on.

The limit: it shows who can invoke and who invoked; it does not stop anyone from invoking. A read
with a 403 says which read was missing, and never “nobody can invoke”.

#### Who can invoke and who invoked a model in Vertex AI

For an agent whose model is in the customer's Vertex AI, BeryX reads who can invoke from Policy
Analyzer and who invoked from the project's Data Access audit logs (card #1038,
`backend/app/domain/compliance/model_access_gcp.py`). It only reads, and only the requests of a
closed list (`ALLOWED_REQUESTS` in `backend/app/infra/gcp_model_access.py`): the reader SA's
`generateAccessToken`, reading that SA, `analyzeIamPolicy` and `entries.list`, to four fixed Google
hosts, with the anti-SSRF guard and the pinned IP.

- **Credential:** the customer's reader SA, impersonated without a key, with
  `roles/cloudasset.viewer` on the organisation and `roles/logging.privateLogViewer` on the project.
  The SA, the organisation and the verification token are encrypted with Fernet, and the SA's
  `description` must carry the token: without it, a workspace could point at another customer's SA.
  Changing the project, the location, the model or the organisation without sending the SA again is
  refused (`reader_role_required`).
- **The filter is the limit:** `roles/logging.privateLogViewer` reads the Data Access logs of every
  service in the project. `entries.list` always carries the `data_access` `logName`,
  `protoPayload.serviceName="aiplatform.googleapis.com"` and only the inference methods, and asks for
  only four fields. It never asks for request-response logging to BigQuery, online prediction
  logging or the endpoint's container logs, where the requests and the responses are kept. A test
  fails if the filter changes.
- **What is kept:** the snapshot of who can invoke and the count per pseudonymised principal, model
  and day, as in Bedrock. Never the log entry: not the IP, not the request.
- **Personal data:** the emails in the snapshot are customer data. Only the pseudonym
  (`invoker_ref`) goes into the logs, and no path sends them to an LLM. Only an admin sees them, and
  only in a workspace with the “AI & Data Security” add-on. The snapshot expires 90 days after the read,
  each day of counts 90 days later, and both go with the workspace.
- **Limit:** Policy Analyzer reads neither deny policies nor Principal Access Boundary, and with the
  project as scope it does not bring inheritance (`inherited_not_included`). BeryX makes at most 10
  queries per organisation per day, below the 20 without Security Command Center. A query that
  Google refuses does not count, to the organisation or to the project, so a record with another
  customer's project and an SA with no role on it does not spend that customer's cap. Data Access logs
  are off by default and cost the customer USD 0.50 per GiB, after 50 GiB free per project per
  month. With no entry for the model, and for requests in express mode, there is no record, and the
  page says “no record” (`no_record`), not “no invocations”.

The limit: it shows who can invoke and who invoked; it does not stop anyone from invoking.

#### Scheduled reads: grants, who can invoke, who invoked and the AI inventory

With the «AI & Data Security» add-on, the worker reads the four snapshots on its own, without anyone
clicking «Read now» (`domain/compliance/security_reads.py`):

| Snapshot | Default cadence | Setting |
|---|---|---|
| Source grants (with shadow AI and dormant access, recomputed on every read) | daily | `security_reads_grants_hours` |
| Who can invoke each agent's model, and the model version the cloud serves (#1339) | weekly | `security_reads_invokers_hours` |
| Who invoked each agent's model (outside Azure, not read yet) | daily | `security_reads_invocations_hours` |
| Each AI inventory source | daily | `security_reads_inventory_hours` |

- **Who is read**: only active workspaces with the add-on in force. A suspended workspace, or one
  without the add-on, reads nothing, not even a message already in the queue. Demo and
  training never read the cloud.
- **Queue**: each read is a message on `security_read.requested`, with a DLQ. The message carries
  the window in which the read was claimed, and the consumer only runs it in that window: a
  redelivery or an old message does not read twice.
- **Who can invoke, who invoked and the inventory** also need compliance in the plan, like the
  agent registry routes. Without it (from the plan or a management override), only the grants
  are read.
- **Limits**: these are the on-demand read functions, with the same caps (2 requests per second on
  `LookupEvents`, the page caps, the per-source budget of the grants). A who-invoked read cut in
  the middle of the interval goes back to the queue an hour later and resumes where it stopped,
  up to 6 times in a row. The other cuts (the grants row cap, an unread principal, the inventory
  page cap) do not resume and wait for the cadence.
- **When the credential fails**: the read state and the log carry only the error code (for
  grants, `grants_connection_failed`). The error text of each connection, without the
  configuration's secrets, stays only in the summary of the last read, which admins read in the
  `GET` (`failed_connections`). The previous snapshot stays. On the third
  failure in a row, admins get the «Security read failing» task in their inbox and bell. The task
  closes on its own when a read succeeds, when what it reads goes away (the agent card retired,
  the last connection with grants deleted) or when the add-on ends.
- **Cost**: each read stores the HTTP requests that went out through the anti-SSRF guard's
  transport (`calls`) and the time (`duration_ms`), also in the `security_read_done` log event. SQL
  queries to the warehouse catalogues do not count as requests.
- **Logs**: ids, kinds, codes and counts. Customer names, ARNs and accounts never go in.
- **Exposure score** (card #1278): the grants, shadow AI, vector copies and who can invoke the
  model count in the score as counts only. A missing read says «not read» and, while it is
  missing, the score stays at least at the v1 score: a missing snapshot never lowers the band.
  Reading can lower it: once the last factor is read, the floor goes and the sum counts, because
  with more information the score is more accurate. So a snapshot going out of date can raise the
  band with no new fact (the factor goes back to «not read» and the floor comes back), and the next
  snapshot brings it back down.
- **Old snapshot**: each snapshot shows its age («read 3 days ago»). A snapshot read more than
  `security_reads_stale_days` days ago (7 by default) is out of date. In the posture report, that
  connection's grants no longer count as read (`connections_stale`), and the AI security section
  marks as out of date, with the same limit, the inventory, who can invoke, who invoked and shadow
  AI (`stale`, with the limit in `stale_after_days`). In the controls matrix, an
  out-of-date AI inventory or shadow AI leaves the AI-INVENTORY row as «partial», with
  «desatualizado» (out of date) in the evidence. In both, for the cloud inventory and shadow AI,
  the oldest source decides (it is the date the report shows), and a cloud source whose last read
  failed counts too. Only the sources the workspace has today count: one from a retired agent card
  or a deleted connection drops out.

Each page's «Read now» queues the same read and answers at once (202). The page shows «queued»
and reads the state from each snapshot's `GET` (`read_state`) until the read finishes. For grants,
the connections that failed also come in the `GET` (`failed_connections`).

#### Scheduled failure drills and the risk of each check

An agent's failure drills simulate a PII leak, poisoned data and a forbidden action against the
real guards, with synthetic values, without reading the source or calling an LLM
(`backend/app/domain/compliance/ai_agent_drills.py`). The worker's scheduler runs them again on
its own, `BERYX_AI_AGENT_DRILL_LEAD_DAYS` days before the last one that passed expires, for
each approved agent of an active workspace (`backend/app/domain/compliance/ai_agent_drill_schedule.py`,
card #1268); in a suspended workspace it does not run. A
scheduled drill that fails does not renew the validity: the agent stops reading classified data
until the scenario passes again, and the owner gets the «Scheduled drill failed» task, in the bell
and by email. In the log, the author is «BeryX (agendador dos ensaios de falha)», and the worker's
logs only keep counts and the type of an error.

Each check carries the codes of the risk it exercises
(`backend/app/domain/compliance/ai_agent_drill_risks.py`), from the sources read on 20/11/2026: the
PII leak with LLM02:2026 (Sensitive Information Disclosure) and DSGAI01 (Sensitive Data Leakage),
poisoned data with LLM01:2026 (Prompt Injection) and ASI01 (Agent Goal Hijack), the tool outside the
matrix and the hourly limit with LLM03:2026 (Excessive Agency) and ASI02 (Tool Misuse and
Exploitation), the `config` token and the approval vote by a token with LLM03:2026 and ASI03
(Identity and Privilege Abuse), and the planted instruction of the live drill (card #1286), which
the scheduler does not run because only an admin opens its window, with LLM01:2026 and ASI01. The
three drills against the guards prove that the guard refuses the case they simulate, not that the
model withstands an attack; the live drill proves one case, not the absence of all. None of them
replaces red teaming.

#### AI controls on AWS: what is read and what is kept

Card #1270 (`backend/app/infra/aws_ai_posture.py`; the findings in
`backend/app/domain/compliance/ai_control_posture_aws.py`). In the same read of the AWS source of
the AI registry, with the record's reader role and ExternalId (card #1020), BeryX reads the
configuration of the controls, never the traffic:

- **Read-only, closed list:** on Bedrock, `ListGuardrails` (paginated by `nextToken`, up to 10
  pages of 100) and `GetGuardrail` for each guardrail (up to 50; beyond that, the listing is
  `truncated`), `ListEnforcedGuardrailsConfiguration` and `GetModelInvocationLoggingConfiguration`;
  on Bedrock Agents, `ListAgents`; on SageMaker AI, `DescribeEndpoint`, `DescribeEndpointConfig`
  and `DescribeModel` of the listed endpoints, by the listing's `EndpointName` (with the case it
  was created with: the ARN comes in lower case); on AWS Organizations, `DescribeEffectivePolicy`
  with `BEDROCK_POLICY`; on IAM, `GetAccountAuthorizationDetails`. Each request is signed with SigV4
  (`backend/app/infra/network/sigv4.py`, checked against botocore service by service) and each host
  goes through the anti-SSRF guard with the pinned IP.
- **What is dropped before keeping:** the agents' `instruction` and `promptOverrideConfiguration`
  (only the SHA-256 of the `instruction`, when the alias's is asked for), the containers'
  `Environment`, image and `ModelDataUrl`, and the guardrails' definitions, examples, messages,
  words and patterns.
- **What is kept** (`ai_discovery_reads.controls`): states and counts, the names the customer gave
  the guardrails, agents and endpoints, and the name of the invocation logging bucket (the S3 one
  and CloudWatch's large data one, `largeDataDeliveryS3Config`), never the role.
- **Findings:** the agent with no guardrail (high; medium when the account or the organization
  enforces a guardrail, because AWS says it applies to «all model invocations» and does not say
  whether `InvokeAgent` is included: guardrails-enforcements and orgs_manage_policies_bedrock, read
  on 24/11/2026), the guardrail with no prompt attack filter or that only detects, the account with
  no enforced guardrail (with all three proofs: nothing enforced on the account, no Bedrock policy
  in the organization and no IAM policy with the `bedrock:GuardrailIdentifier` condition), invocation
  logging off, the log that keeps the text and the SageMaker AI endpoint with no network isolation.
- **Who reads the log destination:** the text finding crosses the bucket with the grants snapshot
  of card #789, when the bucket is an S3 connection of the workspace
  (`backend/app/domain/compliance/ai_log_destination.py`). Only who has a read permission counts
  (the `READ` ACL, `s3:GetObject`…, case-insensitive): whoever only writes, such as
  `bedrock.amazonaws.com` with `PutObject` delivering the log, does not count, and a public write
  does not make the bucket public. The CloudWatch log group stays "not read".
- **Unread is not a finding:** a missing permission stays in `unread`. Without
  `textDataDeliveryEnabled` in the response, the text stays unproven (the API Reference gives it no
  default, read on 24/11/2026). With every listing unread (a role without the permissions), the
  source says "not read" in the AI registry and in the posture report, with the counts as `null`,
  never "0 findings".
- **Logs:** only the provider, the error code and the counts (`ai_control_posture_read`). No name
  goes to the logs or to an LLM.
- **The fix is for copying:** `aws` commands and the IAM policy block. BeryX has no write credential
  and does not apply them.

#### AI controls on Azure and Google: what is read and what is kept

Card #1271 (`backend/app/domain/compliance/ai_control_posture.py`). In the same read of an AI
registry source, with the credential that already exists, BeryX reads the configuration of the
controls, never the traffic:

- **Read-only, closed list:** on Azure, only `GET` to the account, its deployments, `raiPolicies`
  and `diagnosticSettings` (`backend/app/infra/azure_ai_posture.py`), through the closed list of
  card #1039; `listKeys` is never requested. On Google, only `GET` to the Model Armor templates and
  floor setting, the Resource Manager and the endpoints, and `POST …:getIamPolicy`
  (`backend/app/infra/gcp_ai_posture.py`); `sanitizeUserPrompt`, which would carry a prompt, is
  refused before it leaves. Each host goes through the anti-SSRF guard with the pinned IP.
- **What is kept** (`ai_discovery_reads.controls`): states (blocking, annotating only, off or
  unproven; public or private; on or not), the names and model of deployments, policies, templates and endpoints, the ids of
  the project, folder and organization where `auditConfigs` was read, and counts.
  Of the log destinations, only the type; of `getIamPolicy`, only `auditConfigs`, and of the
  exempted members only the count: bindings and emails are not kept.
- **Logs:** only the provider, the error code and the counts of findings and unread items
  (`ai_control_posture_read`). No name goes to the logs or to an LLM.
- **The fix is for copying:** each finding carries `az` or `gcloud` commands (on Azure, `GET`, `jq`
  and `PUT` of the resource read). BeryX has no write credential and does not apply them.
- **The controls read never takes the discovery down:** a host that does not resolve (Model Armor
  in a location without it) stays `host_not_allowed` with no request, and an unexpected failure
  stays only with its type in the controls' `error_code`.

#### Model version: pinned or changing by itself

Card #1339 (`backend/app/domain/compliance/model_versions.py`). The record declares the model
version; in the cloud, an Azure OpenAI deployment with automatic upgrade switches version when
Microsoft changes the default version, and a Bedrock model reaches its end of life on a set date.
In the scheduled read of who can invoke, with the same credential, BeryX reads the version the
cloud serves and compares it with the record's:

- **Read-only, metadata only:** on Azure, the account's deployment list (the `model.version` and
  `versionUpgradeOption` of the record's deployment) and the account's model list (`GET
  {conta}/models`: `lifecycleStatus`, `deprecation.inference` and the default version), through the
  closed list of card #1039 (`backend/app/infra/azure_model_version.py`); the single deployment
  stays outside it. On Bedrock, `GetInferenceProfile` (the model of an inference profile) and
  `GetFoundationModel` (`modelLifecycle`), only `GET` to the region host
  (`backend/app/infra/aws_model_lifecycle.py`). None of them returns requests, responses or logs.
- **What is kept** (`ai_agent_model_versions`): the model, the version, the upgrade option, the
  provider's state and dates, what was left unread and the last version change seen. The
  deployment resource ID or the model ARN are already on the record.
- **BeryX never changes the record or the cloud:** the record says "declared X, observed Y", the
  task goes to the agent's owner, and the fix (`az rest` with `GET`, `jq` and `PUT` of the
  deployment) is for copying, for admins only. A new version seen in the cloud goes to the audit
  trail (`ai_agent_model_version_changed`, author "BeryX (versão dos modelos na cloud)").
- **Unread is not a finding:** a missing permission stays in `unread` and that read's fields do
  not count. Without `versionUpgradeOption` in the response, the option is not presumed and stays
  "not read" (`version_upgrade_option`): Microsoft documents the empty value as
  `OnceCurrentVersionExpired` on Standard deployments, and Provisioned ones never change by
  themselves (Azure OpenAI "working with models" page, read on 24/11/2026). A custom or imported
  model ARN belongs to the account: it has no provider lifecycle and nothing is requested
  (`account_model`). A bare version tag on the record (`v1:0`) does not match the served model, and
  the inference profile's geography prefix (`us.`, `eu.`, `global.`…) does not count.
- **A failure does not close tasks:** a read that fails, or that leaves the version or the
  lifecycle unread, shows "not read" and keeps the values of the last one that succeeded; the
  owner's task only closes with a read that succeeds and no longer gives the finding. A `LEGACY`
  model whose end-of-life date is beyond the 90-day notice gives a low finding, with the date.
- **Logs:** only ids, the provider, the error code and counts (`model_version_read`). Names and
  versions go neither to the logs nor to an LLM.
- **Out:** SageMaker AI (no provider version), Vertex AI (Gemini retirement dates are only in
  Google's documentation) and Databricks (the endpoint pins the Unity Catalog version, with no
  automatic upgrade or end of life in the API) stay "not read".

#### AI controls on Databricks and Snowflake: what is read and what is kept

Card #1272 (`backend/app/domain/compliance/ai_control_posture.py`). With the connection the workspace
already has, with no new credential, in the same read of the AI registry source:

- **Databricks, `GET` only:** after the discovery list, `GET /api/2.0/serving-endpoints/{name}`
  of each listed customer endpoint, up to 100 (`backend/app/infra/connectors/databricks_serving.py`,
  through the closed list and the connection's anti-SSRF guard). It reads `ai_gateway` (the input
  and output guardrails, the inference table, the rate limits and usage tracking) and the legacy
  inference table (`auto_capture_config`); nothing of each model's configuration. The inference
  table is crossed with the grants snapshot already kept (`source_access_grants`), if the table is a
  dataset of the connection, and only who reads it counts (`MODIFY` does not): the table is never
  read. The pay-per-token endpoints (`databricks-…`)
  are not read, as in the discovery.
- **Snowflake, `SHOW` and one `SELECT CURRENT_REGION()` only:**
  `SHOW PARAMETERS LIKE 'AI_SETTINGS' IN ACCOUNT`,
  `SHOW PARAMETERS LIKE 'CORTEX_ENABLED_CROSS_REGION' IN ACCOUNT`, `SHOW GRANTS ON ACCOUNT`
  (up to 5000 rows; at the cap, the listing is `truncated` and a `PUBLIC` without the privilege in
  the rows read stays unproven, never "does not have it") and `SELECT CURRENT_REGION()`, through the
  catalog's read-only guard
  (`backend/app/infra/connectors/snowflake_ai_posture.py`). Cross-region inference is crossed with
  the connection's datasets that have personal data columns in BeryX and with the geography of the
  account's region (`backend/app/domain/compliance/ai_control_posture_snowflake.py`): high with
  `ANY_REGION`, a `*_GLOBAL` or a group of another geography; low with the group of the account's
  geography (the value the fix suggests, and the one Cortex AI Guardrails work with); medium, with
  the reason, without the region read. The values and groups are those of the Snowflake
  documentation, read on 24/11/2026
  (docs.snowflake.com/en/sql-reference/parameters#label-cortex-enable-cross-region,
  docs.snowflake.com/en/user-guide/snowflake-cortex/cross-region-inference and
  docs.snowflake.com/en/user-guide/snowflake-cortex/cortex-ai-guardrails). Guardrails in `LOG`
  (they detect and log) give a low finding, below `OFF` (medium). Each Snowflake connection counts as one source in the AI source
  quota, like a Databricks connection (`backend/app/domain/compliance/ai_source_quota.py`).
- **With no `SHOW` read, the read failed:** a refused `SHOW` stays unread and the others are read.
  With all three unread (a changed password, a disabled user, the account down), the source keeps a
  failed read and a code: the common reason, or `query_failed` when the reasons differ
  (`read_snowflake` in `backend/app/domain/compliance/ai_control_posture.py`). The scheduled read
  counts the failure and, at the 3rd in a row, the admins get the task, as with the clouds.
- **What is kept** (`ai_discovery_reads.controls`): states, the name and `task` of the endpoints,
  the name of the inference tables and the counts of who reads them; on Snowflake, the guardrails
  state, the `CORTEX_ENABLED_CROSS_REGION` value, the account's region, the roles with
  `USE AI FUNCTIONS` and the number of datasets with personal data. Never the `AI_SETTINGS` text nor an error message: only the code.
- **Logs:** as in card #1271, only the provider, the code and the counts (`ai_control_posture_read`).
- **The fix is for copying:** the `databricks` command reads the current `ai_gateway` and changes
  one field only (`put-ai-gateway` replaces the whole object), and the Snowflake SQL is an
  `ALTER ACCOUNT` or a `REVOKE`. BeryX does not apply them.
- **What is not read, and the screen says so:** the Unity Gateway service policies. Unity
  Gateway, the replacement of AI Gateway (legacy), is generally available («A new Unity Gateway
  experience is generally available», Databricks page of 17/11/2026), but the service policies are
  in Beta and are attached only through the UI («Policy attachment is UI-only», page of
  18/11/2026): the documentation read on 21/11/2026 gives them no read API. And the Cortex Guard of
  `AI_COMPLETE`, which is an option of each call (`guardrails` in `model_parameters`) and is kept
  in no account parameter. The AI Gateway (legacy) guardrails are in Public Preview, and Cortex AI
  Guardrails only apply to CoCo, Snowflake CoWork and Cortex Agents and need cross-region inference
  on.

#### MCP servers on the machines: what `beryx agents scan` reads and sends (exception, opt-in)

Card #1288. The MCP servers that coding agents use live in configuration files on laptops and in
CI, where no cloud read reaches. The SDK's `beryx agents scan` reads them and sends BeryX metadata
only. It is an exception to the house rule (BeryX does not run on the customer's side), approved by
the owner on 19/11/2026, with these limits:

- **Off by default.** An admin turns it on in the AI inventory, and the event goes to
  `admin_events` (`mcp_scan_enabled`). While off, an upload gets 409 and nothing is saved
  (`backend/app/domain/compliance/mcp_machine_scan.py`).
- **It is not a resident agent.** It is a command someone runs, or that the customer schedules in
  CI or in the MDM. It reads only the MCP configuration files of Claude Code (with the MDM's
  `managed-mcp.json`), Claude Desktop, Cursor, VS Code and Codex; from `~/.claude.json`, only the
  `mcpServers` keys, never the conversation history. It does not read prompts, responses or code.
- **What leaves** (`sdk/src/beryx/agents_scan.py`): the client, the scope, the name the
  configuration gives the server, the transport, the executable without its folder, the declared
  package and version, the host of a remote server, whether it is disabled and whether the file
  has a plaintext secret (only yes or no). The machine and the project go as pseudonyms:
  HMAC-SHA-256 with a random key that stays on the machine only, so BeryX cannot go back from them
  to the name of the machine, the person or the folder. With `--machine-label` (in CI), the machine
  goes with that name and the projects' key comes from the CI's `BERYX_SCAN_KEY` secret; without
  it, the key comes from the name only, which BeryX receives, and whoever knows it can confirm a
  path they guess: the CLI warns (`docs/AGENTES_CODIGO.md` §4 says what stays reversible).
- **What never leaves:** the values of environment variables and headers, tokens, arguments,
  paths, query strings, and the path and user of a URL. The API repeats the cuts in a closed
  schema (`backend/app/api/v1/mcp_machine_servers.py`): a path, a full URL or an extra field get
  422. The tests plant secrets in every one of these places and prove that none reaches the request
  or the database.
- **Tool fingerprint (`--tools`):** remote servers only, HTTPS only (HTTP only to the computer
  itself) and without following redirects, with the configuration's headers and to its URL. The
  URL and the headers of a project file read neither the environment nor the editor's variables
  (`${userHome}`, `${workspaceFolder}`): a cloned repository does not take the tokens or the paths
  of whoever runs it to the host it names. What leaves is the SHA-256 of the list of definitions
  (the canonicalisation of the #1269 manifest), never the definitions. A local server only starts
  with `--start-stdio` and a confirmation, server by server, in a terminal, with the file and the
  scope it comes from and the control characters escaped; those from a project file also need
  `--allow-project-stdio`. It starts only with `HOME`, `PATH`, `SHELL`, `TERM`, `USER` (and the
  Windows system variables) and the entry's `env`, never with `BERYX_TOKEN` or the rest of the
  environment.
- **On the machine** only the pseudonym key stays (readable only by the user), written on the
  first upload; `--dry-run` shows the exact JSON and writes nothing.
- **In BeryX:** server names, packages and hosts belong to the customer and never go into the
  logs (counts only) or to an LLM. What no machine sends again for 90 days leaves, and deleting the
  workspace takes everything.

The limit: the inventory is what the machines where the command ran declare in the files BeryX
knows. An MCP client it does not read, a machine where nobody runs it or a server configured
elsewhere do not show; the fingerprint comes from the server, at the time of the read.

#### Agents on the platforms: what is read and what is never kept

Card #1273 (`backend/app/domain/compliance/ai_platform_agents.py`). In the same read of an AI
registry source, with the credential that already exists (the AWS reader role, the Azure reader
app), BeryX reads the configuration of Bedrock agents, AgentCore runtimes and gateways, Microsoft
Foundry agents and Entra agent identities. It reads what the agent can do, never what it did:

- **Read-only, closed lists:** on AWS, thirteen operations at the “List” or “Read” level
  (`backend/app/infra/aws_agent_config.py`), of each agent's `DRAFT` version; on Azure, only `GET` to
  the account's projects, to each project's list of agents and connections and, on Microsoft Graph,
  to the agent identities and their owners (`backend/app/infra/azure_agent_config.py`). No path of
  threads, messages, responses or invocations is on the list. Each host goes through the anti-SSRF
  guard with the pinned IP.
- **Instructions go through memory and are discarded:** Bedrock's `GetAgent` returns the
  `instruction`, and Foundry's list of agents carries the `instructions`. The text is discarded in
  the parser, before it reaches the database, the logs or an LLM. From Foundry, the SHA-256 is
  computed in memory and not kept: the owner decided (19/11/2026) that the hash is only kept with the
  record option of section "An agent's prompt", which today exists only for Bedrock agents. The values of `environmentVariables`, the
  `headers` and `authorization` of an MCP tool and the connections' credentials are not kept (only
  the number of variables and the credential type). A test proves it
  (`backend/tests/test_ai_platform_agents_aws_1273.py`).
- **The Foundry permission is wider than the use:** the `agents/read` data action also grants
  reading threads and messages. BeryX never requests them, and a custom role with only the two read
  data actions is the narrowest the documentation allows.
- **Entra sponsors stay unread:** Graph only lists them with `AgentIdentity.ReadWrite.All`, a write
  permission. BeryX does not ask for it; an identity without owners is a finding (the finding says
  the sponsors are left unread), and without a
  sponsor is never claimed.
- **What is kept** (`ai_observations.agent_config`): the model, the role, the memory, the name and
  type of each tool, the bucket and prefixes of each knowledge base, the network, the authorizer,
  the policy engine mode, the host of each MCP server and the credential type, and an identity's
  number of owners. Of an MCP server's URL only the host is kept, and the port if it is not 443
  (`endpoint_of`, in `backend/app/infra/aws_agent_parsers.py`): the path may carry the server's key
  (Zapier gives `/api/mcp/s/…/mcp`), the query a token and the URL credentials, and none of
  that reaches the database, the API or "create record". The approved list is compared by the same
  rule. In the logs, only the provider and the counts (`ai_platform_agents_read`).
- **Nothing is written to the customer's cloud:** each finding says what to do; BeryX has no write
  credential. A failure of the agents read never takes the discovery down.

#### Model artifacts: what the scan reads and what it keeps (exception, opt-in)

Card #1287 (`backend/app/domain/compliance/model_artifact_scans.py`). A model stored as a pickle
(`torch.save`, joblib, the pickle of a scikit-learn model) can run code when it is loaded. For each
artifact of an agent's model, the scan says whether the format is safe or whether the pickle calls
something dangerous. To do so BeryX reads the customer's model file, which the house rule left
out: it is an exception, opt-in.

- **Off by default.** An admin turns it on for each agent, with the artifact URIs
  (`PUT /api/v1/compliance/ai-agents/{id}/artifact-scan`), and the event goes to `admin_events`
  (`model_artifact_scan_enabled` and `model_artifact_scan_disabled`, without the URIs). With the
  scan on, the artifacts that the read of who can change the model (#1274) found in the cloud also
  go in, if that read is of the reference the record has today. Turning it off deletes the verdicts
  and the scheduled read. In the demo and in training nothing reads the cloud.
- **A new, narrow permission the customer grants if they want.** The scan uses the record's IAM
  role and ExternalId (Amazon Bedrock and SageMaker AI) or the impersonated reader service account
  (Vertex AI), with `s3:GetObject` or `storage.objects.get` on the artifact prefix only. Without
  it, the artifact stays "not read" (`permission_missing`). On S3, `x-amz-expected-bucket-owner`
  always carries the record's account: a bucket in another account refuses.
- **What is read.** Only `HEAD` (or the metadata on GCS) and `GET` with `Range`
  (`backend/app/infra/model_artifact_reader.py`), through the anti-SSRF guard with the IP pinned,
  and each `GET` carries the version from the `HEAD` (`If-Match` or `ifGenerationMatch`): an
  object swapped mid-read stays "not read". In a safetensors file, the header; in a GGUF file, the
  24 bytes of the magic and the counts; in a PyTorch zip (ZIP64 too), the end of the file, the
  central directory and the `.pkl` members; in a plain pickle, the opcodes, skipping large
  arguments without requesting them. Tensors are never downloaded. Ceilings per artifact: 64 MiB
  requested, 512 requests, 2 million opcodes and 120 s. In a 6 GiB torch.save, less than 1 KB is
  read, in 7 requests (`backend/tests/test_model_artifact_formats_1287.py`). A folder is neither
  read nor listed (SageMaker AI's `S3Prefix`, the model imported into Bedrock, Vertex AI's
  `artifactUri`): it stays "not read" (`prefix_not_listed`), with no request, because listing would
  need `s3:ListBucket`. A gzip file (SageMaker AI's `model.tar.gz`) stays `tar_gz_not_supported`:
  it cannot be read by ranges.
- **Nothing is deserialised.** No `pickle.load` or `torch.load` runs: opcodes are read one by one,
  with the `pickletools` metadata, and only what tells which object the pickle would import is
  simulated (`backend/app/domain/compliance/model_artifact_pickle.py`). The list of dangerous calls
  is ours, compared on 23/11/2026 with the picklescan and ModelScan lists. Each name is compared the
  way Python's `find_class` resolves it: any prefix of the module.name path on the list, a dotted
  name outside the known imports (since protocol 4 the name follows attributes, and `logging` +
  `os.system` is `os.system`), a `__…__` segment in the name, and the Python 2 names that protocols
  0 to 2 swap for the Python 3 ones (`cStringIO.open` is `io.open`). In a file with several pickles
  in a row (the old `torch.save`, which `torch.load` loads one by one) all of them are read, up to
  8, with or without `PROTO` at the start; the tensors that follow stop the read without counting.
  A dangerous call seen before a refusal from the cloud or the end of the time limit stays: the
  artifact comes out dangerous, with the reason for the cut, and the next read goes to the end.
- **What is kept** (`model_artifact_scans`): for each artifact, the URI (only the admin API reads
  it), the format, the verdict (`safe_format`, `pickle_clean`, `pickle_dangerous` or `not_read`,
  with the reason), the names of the dangerous calls (names from our list only), how many imports
  the pickle would make and how many are outside the known ones (without the names, which may be
  the customer's modules), the object version (the ETag or the generation) and, for each part
  read, the short name, the SHA-256 and the bytes. Never the content. The Annex IV sheet shows the
  verdict and the SHA-256 values without the URI.
- **When it runs again:** every 24 hours (`security_reads_artifact_scan_hours`), on its own queue
  `model_artifact_scan.requested` (one scan at a time per worker), or with "Read now". An artifact
  with the same version only gets the `HEAD`; a new version is read again.
- **Logs:** only ids, codes and counts. No URI, bucket or key goes to the logs or to an LLM.

The limits: it does not detect backdoors in the weights nor assess the model's behaviour, and a
safe format does not say the model is good. The list of calls is a list: what is not on it passes
as "no findings", which is why the verdict counts the unknown imports. Keras `Lambda` layers (HDF5
or `.keras`) and the chat template of a GGUF file are not analysed.

Tests: `backend/tests/test_model_artifact_formats_1287.py`,
`backend/tests/test_model_artifact_properties_1287.py` and
`backend/tests/test_model_artifact_scans_1287.py`.

#### Sign-in attempt limits

Password sign-in has three limits, in `backend/app/api/ratelimit.py`:

- **Per IP and email:** 5 attempts per minute.
- **Per IP:** 30 attempts in 5 minutes, added up across sign-in, sign-up and password recovery
  requests. It stops *password spraying*, where one weak password is tried against many emails from
  the same IP.
- **Per account:** 20 attempts in 15 minutes, from any IP. It stops brute force spread across many
  IPs against the same account. The key is the sha256 of the email and applies the same way to
  emails without an account. Password recovery requests have a separate per-account limit, with the
  same numbers.

All three are checked before the attempt counts, so a 429 from one does not use up the others. A
sign-in with the right password uses up none of them. Over the limit, the response is 429 with
`Retry-After` and the same message whether or not the account exists, and it leaves before the API
looks the account up. When the per-account limit trips, the audit log of the account's workspace
gets `login_throttled`, with the email hash and the IP, never the password, once per account in each
window.

Anyone who knows an account's email can block its password sign-in for 15 minutes. SSO and password
recovery requests keep working during that time.

Through the web app, the per-IP limit counts the browser's IP, which the web server vouches for to
the API with a shared key. In production, the API does not start without that key. Outside
production and without it, the API sees the same IP on every request from the app.
So that some users' failures do not block sign-in for the others, a request that presents itself as
coming from the web server then stays out of the per-IP limit. The per-IP-and-email and per-account
limits still apply. In production, the key has been active since 11/10/2026.

In the API's per-IP limits, an IPv6 address counts by its /64 block and an IPv4 address by the full
address. Whoever holds an IPv6 block picks the end of the address, and switching address inside the
block does not open a new limit.

The counters live in memory in each API instance: with 3 instances, each limit can be worth up to
three times as much. Central containment by real IP is Cloud Armor's (see «Perimeter»), not yet
applied in production.

Tests: `backend/tests/test_security_gates.py` and `backend/tests/test_ipv6_rate_limit.py`.

#### Passwords and invitations

Anyone setting a password cannot choose a common one. The rule applies at sign-up, on an invitation
with an initial password, when setting a password from an invitation or reset link, and to the first
admin of an organisation workspace. The API answers 422 `password_too_common`, before it looks at the
email and without using up the link, when the password, in lower case, is in the list
`backend/app/domain/auth/common_passwords.txt` (about 11,700 entries, nearly all from SecLists),
repeats the same unit, has fewer than four different characters or follows a keyboard or alphabet row.
Without the digits and symbols at its ends, the rule applies again to what is left, if that is at least
four characters: the list always, and the other rules only to letters, so that a generated password
like `9731a58204` passes. Sign-in does not go through this rule: anyone who already has a weak password
keeps signing in and only meets the rule when changing it.

Sign-up stores the email in lower case and without the trailing dot of the domain (`eu@acme.pt.` is
`eu@acme.pt`). So the way it is typed neither opens a second account for the same mailbox nor gets
past a domain claimed by an organisation. Text that is not a single address gets 422 `email_invalid`,
also before the account is looked up.

Accounts registered with the trailing dot before this rule moved to the same form in migration
`231ad0bc1ac9`. When the address without the dot already had an account, the copy was deactivated and
the API refuses its sessions. Each account changed left an event in the audit trail of its workspace.
If the domain belongs to an organisation and the account's workspace is outside it, the
organisation's first workspace received `domain_account_outside_org`, with the address and the loose
workspace. Sign-in, password reset and invites typed with the trailing dot find the account without it,
and each extra dot counts against the same per-account attempt limit. Invites, the seed and SSO store
the address without the dot.

Each email has one account across the whole platform. With email configured, `POST /auth/users`
answers 202 with the same text whether or not the email has an account in another workspace. The
password hash runs in both cases and emails only leave after the response, so the time a send takes
does not reach the response time. If the email has an account in another workspace, that account does
not change, the inviter's audit log gets `member_invited` and the owner of the email gets a notice with
no link, at most one a day on each API instance. That notice can reach any account on the platform, so
it has no variable text: it carries neither the recipient's name, the inviter's name nor the `name`
from the request. Proving the mailbox does not prove the name, which someone else may have written,
so no account email uses it in the greeting. A send that fails does not change the response: it
goes to the log as `invite_email_failed`, without the recipient. Someone already in the workspace gets
a 409. With no email transport, the response is 201 or 409, as at sign-up.

`POST /org/workspaces` follows the same rule for `admin_email`, with or without `training_pack`. With
email configured it answers 202 with the same text, whether or not the email has an account in another
organisation. The password hash runs in both cases, the emails go out after the response and the
content of a training workspace arrives on the worker's next round, outside the request. With RabbitMQ
unavailable that content is created in the request, and the response time then tells the two cases
apart again for training. A workspace cannot start without an admin, so an email with an account in
another organisation creates nothing: that account does not change, the audit log of whoever asked gets
`organization_workspace_not_created`, without the email, and the owner of the email gets the same
notice, with the same limit of one a day. An account in a workspace of the organisation itself gets a
422. With no email transport, the response is 201 or 422.

The response no longer confirms the account, but whoever invites can still tell the two cases apart:

- the account that was created shows in the user list and the one in another workspace does not;
- repeating the invitation gives a 409 for someone who joined the workspace and a 202 for someone with
  an account in another one;
- with an initial password, the audit log records `member_created` for the account that was created
  and `member_invited` for the one in another workspace, and only the account that was created accepts
  that password at login;
- the requested workspace only shows in `GET /org/workspaces` and only takes the name if the email is
  free, and the audit log records `organization_workspace_created` or
  `organization_workspace_not_created`.

That is why invitations and `POST /org/workspaces` count towards the same limit, 30 an hour per
organisation (`invite_rate_limit_invites`), whatever the emails, with a 429 and `Retry-After`. The
limit is counted in the database, and every API instance shares the same window. Every workspace
of the organisation spends that window: a workspace created with `POST /org/workspaces` spends one
invitation and brings no new invitations to the admin who joins it, even an account of whoever
created it. A workspace that has no organisation yet gets its personal one on the first invitation,
and counts in its window from then on. `POST /org/invites`
and SCIM also say that the account exists: the first only takes emails from the domain the
organisation claimed and the second needs an organisation token.

An invitation to an account in another workspace leaves the email in the inviter's audit log. When that
account is erased, alone or with its workspace, the email also leaves that log.

Password reset and invitation links go out by email. On an installation with its own SMTP relay
(`smtp_host`), such as a dedicated instance, the connection uses STARTTLS and checks the relay's
certificate and hostname before it sends the SMTP password. It trusts the public CAs from `certifi`
or the relay's internal CA in `smtp_ca_pem`, which is checked at startup. A relay that does not
advertise STARTTLS, or whose certificate fails TLS verification, gets neither the password nor the
email, and the send fails (`backend/app/infra/email/sender.py`).

No password reset email leaves a training or demo workspace. There, an admin creates accounts with a
password for any address, without an invitation, and the reset would carry the sandbox's email to
someone who never asked for anything. The request answers the same 202 as always, without saying
whether the account exists, and the worker neither issues the link nor sends the email or the SSO
notice. The email change does not leave it either (card #1359): `PATCH /auth/me` with a new email
returns 403 and says why, without issuing the link to the new address or touching the account, and
a link requested before the workspace became a training or demo one changes the account without
the notice to the previous address.

#### Single sign-on (SSO)

SSO uses OIDC with the authorization code flow, or SAML 2.0 for an organisation's IdP
(`backend/app/domain/auth/sso.py`, `backend/app/infra/sso/oidc.py`).

- **The flow is bound to the browser that started it.** The start creates a random `state`,
  single-use and valid for 10 minutes. The database keeps only its hash, the `nonce` and the PKCE
  verifier. The browser gets the `dv_sso` cookie: `HttpOnly`, `Secure` over https,
  `Path=/api/v1/auth/sso`, 10 minutes and `SameSite=Lax` for OIDC. Only the SAML start uses
  `SameSite=None`, because the IdP returns the response in a POST. The callback and the code
  exchange only accept the flow with the same cookie, so a `state` or a code obtained in another
  browser is refused. This stops login CSRF, where the attacker makes the victim sign in to the
  attacker's account. It applies to each organisation's IdP and, since card #370, to the
  installation IdP (`DATAVAULT_OIDC_*`).
- **PKCE S256 and `nonce` on every OIDC request**, even with a client secret. The POST to the token
  endpoint carries the flow's `code_verifier`.
- **The ID token is the proof.** The signature is checked against the JWKS from the IdP's
  discovery, with asymmetric algorithms only. The `iss`, the `aud` (and the `azp` with several
  audiences), the `exp` and the `iat` with 2 minutes of leeway and the request's `nonce` are
  validated. Userinfo is only requested when the ID token lacks the email or the groups, and it is
  refused if it belongs to another `sub`. An email the IdP reports as unverified (`email_verified`
  false) does not get in.
- **Discovery and keys cached with an expiry.** Discovery is cached for 1 hour per issuer and only
  counts if it belongs to that issuer. The JWKS reloads when an unknown `kid` shows up (key
  rotation), at most once every 30 seconds.
- **The installation IdP's redirect URI does not change, but it only follows installation hosts.**
  It is still the host the request reaches the API with, if it is the `app_base_url` host, an old
  base's host, the `api_public_base_url` host, an old API host or one of the
  `BERYX_OIDC_CALLBACK_HOSTS`, where the deploy puts the nginx's `API_UPSTREAM` host (card #655).
  The `Host` comes from the client: with any other, the redirect URI is the `app_base_url` one, and
  a forged `Host` does not send the IdP's code outside the installation. Behind the app's nginx the
  host is `api.`, which the cookie does not reach. There the callback bounces once to the same path
  on the app's host (`backend/app/domain/auth/sso_rebound.py`), and the cookie is checked there.
- **The session never goes in the URL.** The end of the flow carries a single-use exchange code,
  valid for 60 seconds, which the app trades for the session in a POST with the same cookie
  (`backend/app/domain/auth/sso_exchange.py`).
- **IdP errors do not leave the server.** The browser goes back to the sign-in page with a stable
  code (for example, `?sso_error=idp_http_error`) and the app shows a fixed message. The structured
  log (`sso_login_failed`) carries the code and the stage, never what the IdP answered.

Tests: `backend/tests/test_sso_installation.py` and `backend/tests/test_sso_org.py`.

#### Sessions

Every sign-in is recorded with the device, the truncated IP (/24 for IPv4, /48 for IPv6), the
creation date and the last use; the token is never stored (`backend/app/domain/auth/sessions.py`).
In “Account security → Active sessions”, each person sees where they are signed in and ends one
session or all the others. “Sign out” also ends the session on the server.

- **Inactivity.** A session with no requests for 12 hours ends. The workspace administrator can
  require less, down to 15 minutes, in “Team → Sessions”. The change applies to sessions that are
  already open. A request made with no interaction for more than a minute does not count as activity:
  this covers pages with live updates and the notification bell's connection, which reopens on its
  own every 4 minutes.
- **Forced sign-out.** The administrator ends every session of a member in “Team”. The person can
  sign in again with their credentials.
- **Password and MFA.** Resetting the password, turning MFA on or off and regenerating the recovery
  codes end every session of the account.
- Every revocation, forced sign-out, password change and timeout change goes to the audit log.

#### API tokens

A `dvk_*` token is stored only as a SHA-256 hash, and its value is shown once, when the token is
created or rotated (`backend/app/domain/access/token_lifecycle.py`).

- **Expiry.** Every new token expires: 90 days by default, or between 1 and 365 days, as the
  administrator chooses. An expired token gets 401 on every route, with the same message as an
  invalid token. An installation can accept tokens with no expiry
  (`DATAVAULT_API_TOKEN_ALLOW_NO_EXPIRY`); by default, it does not. Tokens created before this rule
  have no expiry and keep working until the administrator rotates them.
- **Rotation.** “Rotate”, in “Team → API tokens”, creates a new token with the same name and the
  same scope. The old one keeps working during the grace period (24 hours by default), so the value
  can be swapped in the pipeline without breaking it. “Revoke” cuts it off at once. The rotation goes
  to the audit log (`token_rotated`).
- **Last use.** The token list shows each token's last use and last IP, updated at most once a
  minute. The IP stays in the database and only the administrator sees it: it does not go into the
  logs or the audit log.
- **Warnings.** A token active for more than 180 days raises an alert for the administrators. The
  weekly summary of the notification channels says how many tokens expire in the next 14 days.
- **Scope of pipeline reports.** Orchestrator runs, `dbt test` results, OpenLineage events and
  deployments stay in the workspace as facts: they feed the root-cause diagnosis, open issues and
  draw the lineage. Only a token with the `ingest` scope sends them
  (`API_TOKEN_INGEST_WRITE_OPERATIONS`, `backend/app/api/deps.py`). A leaked read token reads,
  but cannot forge them: with another scope, or with an OAuth token, the report gets 403. The
  `ingest` scope writes nothing beyond the exceptions open to any token.

Tests: `backend/tests/test_api_token_lifecycle.py` and `backend/tests/test_api_token_ingest_scope.py`.

#### SDK and `beryx` in CI: source names without runner commands

`beryx gate`, the other SDK commands and the summaries they print (`GateResult.summary()` and those
of the other gates) show on stdout names that come from the schema of the customer's source
(columns, tables, models) and texts from the API. In GitHub Actions the runner reads each step's
stdout and stderr looking for commands: a line that, without its leading spaces, starts with `::`,
and the legacy `##[` format anywhere in the line. Whoever controls the schema of a source connected
to the workspace could put in a column name a line break followed by `::stop-commands::` and
command the CI of whoever runs the gate.

- **Each line is one line.** Before writing, the SDK escapes line breaks and the other control
  characters in plain sight (`\n`, `\x1b`, `\u2028`), writes the `#` of a `##[` or `##vso[` as
  `\x23` and the `:` of a `::` at the start of a line as `\x3a` (`sdk/src/beryx/_terminal.py`).
  A normal name comes out unchanged.
- **In `--json`**, the `#` of a `##[` comes out as `\u0023`, which JSON reads as the same `#`.
- **In error messages**, such as the `VerdictFailedError` a pipeline shows in the traceback, the
  same rule applies.

Tests: `sdk/tests/test_terminal_commands.py` and the properties in
`backend/tests/test_sdk_terminal_properties.py`.

#### Organisation access restrictions

The organisation administrator sets, in “Team → Organisation → Access restrictions”, rules that
apply to every workspace in the organisation (`backend/app/domain/organizations/access_policy.py`):

- **IP allowlist.** A list of IPs and CIDR blocks, IPv4 and IPv6. With the list filled in, an IP
  from outside is refused at sign-in (password, email links, the second MFA step and SSO), before the
  session is issued, and on every authenticated request: open sessions, API tokens and the Microsoft
  365 Copilot, which comes from Microsoft's network. The IP is the one the rate limit uses, so a
  forged `X-Forwarded-For` does not get through. A refused person gets a message with the IP seen and
  what to do; a wrong password still returns the usual error, without revealing the policy. The
  session does not end: back on an allowed network, it carries on.
- **API tokens exempt by name.** A token with the given name, in the given workspace, gets in from
  any network, for example CI with dynamic IPs. Each exemption carries the reason written by the
  administrator. Rotating the token, that is creating another with the same name and revoking the
  old one, keeps the exemption. A token with the same name in another workspace is not exempt.
- **Maximum session length.** Between 1 hour and the installation's validity (12 hours by default),
  counted from sign-in, with or without activity. Lowering it ends at once the sessions already past
  it; the sign-in screen says why.
- **MFA mandatory across the organisation.** People who sign in with a password must set up MFA at
  their next sign-in. People who sign in with SSO use their identity provider's MFA.
- **Lock-out protection.** Saving a list that does not include the IP of whoever saves it is refused.
  If everyone is still locked out, for example because the office IP changed, the BeryxTech operator
  turns the list off with `backend/scripts/clear_ip_allowlist.py`, after confirming the request with
  the customer.
- Every change goes to the audit log of every workspace in the organisation. Every refusal by IP goes
  to the audit log of the account's or token's workspace, and the section shows the organisation's
  latest 20 refusals. For a request from a session or token that is already authenticated, one
  refusal is kept per account, IP and origin every 15 minutes.

BeryxTech support access still follows the customer's consent (see
[Isolation between customers](#isolamento-entre-clientes-multi-tenant)) and does not go through the
customer organisation's allowlist.

#### Audit log

Administrative actions (roles, plans, connections, credentials, tokens, sessions, AI policy, AI actions
policy, support access) and assistant actions that are approved, requested or declined are kept
in an audit log written in the same transaction as the change, which workspace administrators can
query and export as CSV. Each event is kept for 400 days: a daily worker purge deletes older ones
and writes `audit_log_purged` to the log, with the cut-off and the count
(`app/domain/audit/retention.py`).

#### Subprocessors and providers

The list of subprocessors is public at `/subprocessadores` (pt/en): purpose, region, legal basis,
transfer mechanism and DPA of each one. A new provider, a removal or a change of region is
announced 30 days in advance. Administrators can receive the notice by email
(Compliance → Subprocessor notices). During the notice period, a new AI provider receives no data:
the router only sends to active subprocessors on the list. The risk assessment of each provider
(declared certifications, data it receives, exit plan) is in `docs/compliance/vendors/`.

#### Certifications: ISO 27001 and SOC 2

**We do not have ISO 27001 certification or a SOC 2 report.** They are part of a programme: the
controls described in this document are the basis of that work. Until then, we answer RFP lines
with the technical evidence above, not with badges — and we do not use "compliant" or "aligned
with" as a substitute for a certification we do not have.

The public status of each certification (planned, in preparation, audit scheduled, obtained —
with dates) lives in a single file, `docs/compliance/trust-status.json`, which the site reads at
build time for the `/seguranca` page and for `/.well-known/security.txt`.
`backend/tests/test_trust_status.py` fails if that status diverges from this section or from
ADR 0010.

One of the controls already in operation is **vulnerability management**
([compliance/vulnerability-management.md](compliance/vulnerability-management.md)). It includes:

- SCA of the Python and npm dependencies and scanning of the images with Trivy on each PR;
- CI failure on critical/high without a recorded exception;
- an SLA of 7, 30 and 90 days by severity;
- a CycloneDX SBOM per deploy;
- a monthly report in `docs/compliance/evidence/`;
- weekly DAST (OWASP ZAP baseline, passive only) on the site, the app and the API, with a weekly
  report and the same exception register.

Findings from all sources (scanners, DAST, external pen test and responsible disclosure, through
`/.well-known/security.txt`) follow a process with an SLA
([compliance/security-findings.md](compliance/security-findings.md)).
**We have not done an external pen test yet.** The scope, the test accounts and the rules are ready
([compliance/pentest.md](compliance/pentest.md)); we have yet to hire the provider.

#### What we do not do, and why

- **Destructive remediation on the sources.** We propose the fix (SQL/PySpark, or a pull request
  in the customer's repository); the customer applies it. Asking for write credentials would be
  objection no. 1 for any security team — it is a product decision, not a limitation.
- **MDM / golden record with writes.** We detect duplicates and propose consolidation, but we do
  not maintain a master record nor write the "winning" version to the sources.
- **Multimodal image analysis.** Documents are read through their text layer; images are not
  processed, and a scanned PDF with no text is flagged as needing OCR
  (`app/domain/quality/documents.py`) instead of being sent to a vision model.
- **Putting content into the context of a customer's agent.** BeryX reads and does not stand in
  front of the model. Since card #1286 there is one exception, off by default and turned on by an
  admin: the live drill of the planted instruction, which puts a synthetic record with a harmless
  request into the response of a read tool (see "Live drill: the planted instruction"). It does not
  read prompts nor write to the sources.
- **Writing to the customer's cloud to stop an agent.** BeryX keeps no credential that writes to your
  account. Since card #1284 there is an exception without that credential, off by default and turned
  on by an admin on a webhook channel (`ai_agent.lifecycle`, with the "AI & Data Security" add-on, and the
  event in `admin_events`): the BeryX kill switch fires a signed webhook and a function in the
  customer's account, with the permissions the customer gives it and only for the principals on the
  customer's list, turns off the agent's credential and responds with the result, signed with the same
  secret: a response without that signature never counts as confirmed. On such a channel, only an
  admin changes the URL, turns it on or off, or deletes it. The writer is the customer's function, not
  BeryX. The recipes and what each one needs are in
  [KILL_SWITCH_CLOUD.md](KILL_SWITCH_CLOUD.md).
- **Running on the customer's side.** BeryX reads the clouds and the sources through the official
  APIs and installs nothing on the customer's machines. Since card #1288 there is one exception,
  off by default and turned on by an admin: the SDK's `beryx agents scan`, a command someone runs
  (or that CI or the MDM schedules), reads the MCP configuration files and sends metadata only,
  with the machine and the project as pseudonyms (see "MCP servers on the machines"). It is not a
  resident agent, it does not read prompts or conversations and, on the machine, it only writes the
  pseudonym key.
- **Writing to the customer's cloud to fix the posture.** BeryX keeps no credential that writes to
  the customer's cloud or sources. Since card #1285 there is an exception without that credential,
  off by default and turned on by an admin, with the event in `admin_events`: for the excess grant,
  the missing guardrail and the logging turned off (and key authentication on Azure OpenAI), BeryX
  opens an infrastructure-as-code pull request, in Terraform or as a SQL migration, in the git
  repository the customer connected and with that integration's permissions. It writes only one new
  file, on a `datavault/*` branch, and it does not change existing files, does not merge and does
  not apply: the customer reviews, merges and applies (see "Posture fixes by infrastructure-as-code
  pull request").
- **Reading the customer's model files.** BeryX read the posture around the model (who can invoke
  and change it), not the model. Since card #1287 there is one exception, off by default and turned
  on by an admin for each agent: the artifact scan, which reads by byte ranges, with a read
  permission the customer grants on the artifact prefix only, the format and the opcodes of a
  pickle, without loading it or downloading the weights (see "Model artifacts: what the scan reads
  and what it keeps"). It is still read-only: it does not write to the bucket nor stand in front of
  the model.
