Sua chave API CaptchaAI controla o acesso ao seu saldo. Uma chave vazada significa uso não autorizado e fundos drenados. Este guia aborda lista branca de IP, armazenamento seguro e controle de acesso.
Ameaças de chave de API
Exposed API key:
├── Leaked in Git repository
├── Hardcoded in client-side code
├── Shared in documentation
└── Visible in logs
Impact:
├── Balance drained by unauthorized users
├── Usage spikes from abuse
└── Key disabled by service provider
Armazenamento seguro de chaves
Nunca codifique chaves
# BAD — key in source code
API_KEY = "abc123def456" # DO NOT DO THIS
# GOOD — environment variable
import os
API_KEY = os.environ["CAPTCHAAI_API_KEY"]
# GOOD — .env file (not committed to Git)
from dotenv import load_dotenv
load_dotenv()
API_KEY = os.environ["CAPTCHAAI_API_KEY"]
Arquivo .env
# .env (add to .gitignore!)
CAPTCHAAI_API_KEY=your_api_key_here
.gitignore
# Always ignore .env files
.env
.env.local
.env.production
Configuração baseada no ambiente
import os
class CaptchaConfig:
"""Load CaptchaAI config from environment."""
def __init__(self):
self.api_key = os.environ.get("CAPTCHAAI_API_KEY")
if not self.api_key:
raise EnvironmentError(
"CAPTCHAAI_API_KEY not set. "
"Set it in your environment or .env file."
)
self.base_url = os.environ.get(
"CAPTCHAAI_URL", "https://ocr.captchaai.com"
)
def validate(self):
"""Verify the API key works."""
import requests
resp = requests.get(f"{self.base_url}/res.php", params={
"key": self.api_key,
"action": "getbalance",
"json": 1,
}, timeout=10)
data = resp.json()
if data.get("status") != 1:
raise RuntimeError(f"Invalid API key: {data.get('request')}")
return float(data["request"])
# Usage
config = CaptchaConfig()
balance = config.validate()
print(f"Key valid, balance: ${balance:.2f}")
Rotação de Chave
Alterne as chaves de API periodicamente:
import os
import datetime
class KeyManager:
"""Manage API key rotation."""
def __init__(self):
self.primary_key = os.environ.get("CAPTCHAAI_API_KEY")
self.secondary_key = os.environ.get("CAPTCHAAI_API_KEY_BACKUP")
self.active_key = self.primary_key
def get_key(self):
return self.active_key
def rotate(self):
"""Switch to secondary key."""
if self.secondary_key:
self.active_key = self.secondary_key
print("Rotated to secondary key")
else:
print("No secondary key configured")
def test_key(self, key):
"""Verify a key is valid."""
import requests
resp = requests.get("https://ocr.captchaai.com/res.php", params={
"key": key, "action": "getbalance", "json": 1,
}, timeout=10)
return resp.json().get("status") == 1
# Usage
keys = KeyManager()
# If primary fails, rotate to secondary
if not keys.test_key(keys.get_key()):
keys.rotate()
Solicitar Validação
Valide as solicitações antes de enviar para evitar a exposição acidental da chave:
import requests
import logging
logger = logging.getLogger(__name__)
class SecureSolver:
"""Solver with security best practices."""
def __init__(self, api_key):
self.api_key = api_key
self.base = "https://ocr.captchaai.com"
def solve(self, method, **params):
# Validate inputs
self._validate_params(method, params)
data = {"key": self.api_key, "method": method, "json": 1}
data.update(params)
# Log without exposing key
logger.info(
"Submitting %s solve for %s",
method, params.get("pageurl", "unknown"),
)
resp = requests.post(
f"{self.base}/in.php", data=data, timeout=30,
)
return resp.json()
def _validate_params(self, method, params):
"""Prevent common security mistakes."""
# Ensure pageurl is a valid URL
pageurl = params.get("pageurl", "")
if pageurl and not pageurl.startswith(("http://", "https://")):
raise ValueError(f"Invalid pageurl: {pageurl}")
# Ensure method is valid
valid_methods = {
"userrecaptcha", "turnstile", "geetest",
"base64", "post", "bls", "turnstile_staging",
}
if method not in valid_methods:
raise ValueError(f"Unknown method: {method}")
Registrando sem expor chaves
import logging
import re
logger = logging.getLogger(__name__)
class SafeFormatter(logging.Formatter):
"""Redact API keys from log messages."""
KEY_PATTERN = re.compile(r'[a-f0-9]{32}', re.IGNORECASE)
def format(self, record):
msg = super().format(record)
return self.KEY_PATTERN.sub("[REDACTED]", msg)
# Configure safe logging
handler = logging.StreamHandler()
handler.setFormatter(SafeFormatter("%(levelname)s: %(message)s"))
logger.addHandler(handler)
logger.setLevel(logging.INFO)
# Key is automatically redacted in logs
logger.info(f"Using key: abc123def456ghi789jkl012mno345pq")
# Output: INFO: Using key: [REDACTED]
Segredos do Docker
Para implantações em contêineres:
# Dockerfile — DO NOT embed keys here
FROM python:3.11-slim
WORKDIR /app
COPY . .
RUN pip install requests
CMD ["python", "solver.py"]
# docker-compose.yml
services:
solver:
build: .
environment:
- CAPTCHAAI_API_KEY=${CAPTCHAAI_API_KEY}
# Or use Docker secrets:
secrets:
- captchaai_key
secrets:
captchaai_key:
file: ./secrets/captchaai_key.txt
Segurança CI/CD
Ações do GitHub
# .github/workflows/test.yml
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Run tests
env:
CAPTCHAAI_API_KEY: ${{ secrets.CAPTCHAAI_API_KEY }}
run: python test_solver.py
Nunca registre ou repita o segredo na saída do CI.
Solução de problemas
| Problema | Causa | Correção |
|---|---|---|
ERROR_WRONG_USER_KEY |
Chave incorreta ou expirada | Verifique a chave do painel CaptchaAI |
| Dreno de equilíbrio inesperado | Chave vazada ou compartilhada | Gire a chave imediatamente, audite o acesso |
| A chave funciona localmente, mas não no CI | Variável de ambiente não definida | Adicionar aos segredos CI/CD |
| Chave na história do Git | Arquivo .env confirmado | Gire a chave, adicione .env a .gitignore, use git filter-branch |
Lista de verificação de segurança
| Pratique | Estado |
|---|---|
| Chave de API na variável de ambiente | ☠|
| .env adicionado a .gitignore | ☠|
| Nenhuma chave no código-fonte | ☠|
| Chaves editadas nos registros | ☠|
| CI/CD usa gerenciador de segredos | ☠|
| Cronograma de rotação de chaves | ☠|
| Monitoramento de saldo ativo | ☠|
Perguntas frequentes
E se minha chave de API vazar?
Gere uma nova chave imediatamente no painel CaptchaAI. Atualize todos os aplicativos usando a chave antiga. Verifique seu saldo quanto a uso não autorizado.
Posso restringir a chave API por endereço IP?
Verifique seu painel CaptchaAI para configurações de restrição de IP. Se disponível, coloque apenas os IPs do seu servidor na lista de permissões para evitar o uso não autorizado.
Devo usar chaves diferentes para desenvolvimento e produção?
Sim. Use chaves separadas para desenvolvimento, preparação e produção. Isso limita o raio de explosão se uma chave de desenvolvimento vazar.
Guias Relacionados
Proteja seu investimento -proteja sua chave API CaptchaAIhoje.