agent-security-hardening
Torna seu agente mais seguro ao lidar com informações sensíveis ou ferramentas externas. Protege contra acessos não autorizados e erros.
O que ela faz
Este guia ensina como proteger sistemas de IA que lidam com informações não confiáveis. Ele ajuda a criar barreiras de segurança para evitar que dados perigosos causem problemas.
Quando usar
- ✓Ao construir um sistema de IA que recebe dados de fora.
- ✓Ao revisar o código que transforma dados em ações.
- ✓Ao separar diferentes usuários ou tarefas dentro de um sistema de IA.
Exemplo do que pedir para a IA
“Como posso garantir que a IA não execute comandos perigosos com base em dados que recebi?”
Quer saber mais? Abra as seções abaixo.
Como usar
O jeito mais fácil: copie a mensagem abaixo e cole no Claude, ChatGPT, Cursor ou outra IA. Ela lê a skill e segue as instruções.
Link da skill
Mensagem pronta para colar
Como funciona
O guia sugere mapear onde os dados não confiáveis entram, validar tudo rigorosamente antes de qualquer ação e conter o acesso a arquivos e outras partes do sistema.
Instalação
Jeito mais fácil: copie o link da skill e cole no Claude, ChatGPT ou Cursor pedindo para seguir as instruções.
No terminal (Claude Code, Codex, Cursor), na pasta do projeto:
npx skills add affaan-m/ECC --skill agent-security-hardeningOu baixe só o arquivo:
curl -L https://raw.githubusercontent.com/affaan-m/ECC/main/pi/core/skills/agent-security-hardening/SKILL.md -o SKILL.mdConteúdo técnico (SKILL.md)
Tradução do texto original do autor no GitHub. Os comandos e códigos estão como no original.
Agent Security Hardening
Harden the boundaries where an agent turns untrusted data into filesystem, network, memory, or tool actions. Produce concrete controls and tests for the framework being reviewed; a checklist without enforcement evidence is incomplete.
Important
- Treat model output, retrieved content, tool output, memory, and cross-agent messages as untrusted input.
- Default external integrations to read-only and grant each write capability separately.
- Validate at the action boundary even when an upstream prompt or schema already validated the value.
- Fail closed before a side effect when identity, destination, ownership, or containment cannot be proven.
- Before a delete, publish, credential rotation, or other irreversible action, the real tool entry point must authorize the authenticated principal for that exact operation and resource scope, then require explicit confirmation or a valid scoped pre-approval. Missing or invalid evidence blocks the action.
- Use hard bounds defined by the governing requirement and stricter values verified from deployment configuration. When neither defines a value, mark it as a required decision and test that the implementation rejects an unbounded configuration; do not invent a plausible value.
When to Activate
- Building an autonomous agent, tool gateway, memory service, or agent-to-agent protocol
- Reviewing code that maps model output into commands, paths, URLs, credentials, or API mutations
- Isolating tenants, projects, sessions, or workspaces in a long-running agent process
- Hardening temporary files, logs, tool responses, or external-content ingestion
Hardening Workflow
1. Map Trust Boundaries
List every boundary as source -> parser -> validator -> side effect. Include direct user input, model output, retrieved documents, memory, environment variables, tool results, and messages from other agents.
For each side effect, record:
- the identity and scope authorizing it;
- the exact validator that runs immediately before it;
- the maximum input and output size;
- the audit evidence produced;
- the recovery path if the operation is interrupted.
This step is complete when every write, command, network mutation, and credential use has one named authorization boundary.
2. Validate Identifiers, Environment Values, and URLs
Use an allowlist for identifiers that become filenames, keys, selectors, or command arguments. Agent IDs have the issue-defined hard maximum of 64 characters; deployment configuration may choose a stricter positive limit but cannot raise that boundary:
import re
SAFE_AGENT_ID_CHARS = re.compile(r"^[A-Za-z0-9_][A-Za-z0-9_-]*$")
HARD_MAX_AGENT_ID_LENGTH = 64
def require_agent_id(value: object, *, max_length: int) -> str:
if (
isinstance(max_length, bool)
or not isinstance(max_length, int)
or not 1 <= max_length <= HARD_MAX_AGENT_ID_LENGTH
):
raise RuntimeError("configured agent ID limit must be between 1 and 64")
if (
not isinstance(value, str)
or len(value) > max_length
or not SAFE_AGENT_ID_CHARS.fullmatch(value)
):
raise ValueError("invalid agent identifier")
return value
When an identifier becomes a CLI argument, pass it through an argv API and place it after the command's end-of-options marker where supported. Character validation is not a substitute for argument separation.
Reject missing and whitespace-only environment values before constructing a client:
def require_env(name: str, environ: dict[str, str]) -> str:
value = environ.get(name)
if value is None or not value.strip():
raise RuntimeError(f"{name} is required")
return value
Parse URLs, allow only schemes required by the deployment, require a host, reject embedded credentials, and block private-network destinations when the URL is attacker-controlled. For every outbound connection and redirect hop, pin the connection to a validated public address or verify the connected peer address at connection time so DNS rebinding cannot cross the boundary. A credential-bearing request must use HTTPS with certificate verification before credentials are attached. Disable automatic cross-origin credential forwarding; when the scheme or origin changes, strip the credentials and reauthorize the new destination or reject the redirect. Re-run destination, connected-address, and transport validation on every hop.
…
Perguntas frequentes
O que significa 'tratar saída do modelo como entrada não confiável'?
Significa que qualquer coisa que a IA gera, mesmo que pareça segura, deve ser verificada antes de ser usada, pois pode conter algo inesperado ou perigoso.
Por que é importante validar mesmo que já tenha sido validado antes?
Porque a validação em cada etapa, especialmente antes de uma ação que pode causar um efeito colateral (como apagar algo), garante que nada perigoso passe despercebido.
O que é 'fail closed'?
É uma regra de segurança que diz: na dúvida, bloqueie o acesso ou a ação. Se não for possível provar que algo é seguro, é melhor não permitir que aconteça.
Detalhes
Descrição original do autor
Security hardening guidance for AI agent frameworks that process untrusted content, invoke tools, write workspace files, manage runtime identifiers, or handle credentials. Use when building or reviewing an agent runtime, autonomous worker, tool gateway, memory service, or multi-tenant agent deployment. Do not use for general web application security or offensive testing.
repo: affaan-m/ECC
Popularidade
- Estrelas no GitHub
- 280 mil
- Posição no ranking
- #6
- Licença
- MIT
- Atualizada em
- 15/10/2026
Comentários
- …
Mais skills deste repositório
accessibility
Ajuda seu agente a criar interfaces que todos possam usar. Garante que sites e aplicativos funcionem bem para pessoas com deficiência, como cegos ou com mobilidade reduzida.
affaan-m/ECC
agent-architecture-audit
Faz seu agente verificar se tudo está funcionando corretamente. Ele encontra e conserta problemas em sistemas de IA, garantindo que funcionem como esperado.
affaan-m/ECC
agent-eval
Ajuda seu agente a comparar diferentes ferramentas de programação de IA. Ele mede qual é mais rápido, barato e confiável para realizar tarefas específicas.
affaan-m/ECC
agent-harness-construction
Faz seu agente entender melhor como realizar tarefas. Ele otimiza as ferramentas e instruções que o agente usa para aumentar suas chances de sucesso.
affaan-m/ECC
Skills parecidas
mcp-builder
Ajuda seu agente a criar servidores que conectam LLMs a serviços externos. Essencial para integrar APIs e serviços usando Python ou Node/TypeScript.
anthropics/skills
prepare-mcp-integration
Prepara integrações com fornecedores (MCP) através de pesquisa e aprovação humana. Segue um processo guiado para novas integrações.
paperclipai/paperclip
first-task
Guia o agente na primeira tarefa do usuário. Ele interpreta a resposta inicial, esclarece o objetivo e propõe um plano ou tarefa única para aprovação.
paperclipai/paperclip