MVP
Última atualização: N/AN/A
Sem data
📊 Observabilidade e Auditoria MVP — AegisTech IA
Framework completo de observabilidade e auditoria para MVP GovTech com compliance LGPD/CNMP
📋 Índice
- Visão Geral
- SDK de Auditoria
- Logs Estruturados
- Métricas e KPIs
- Traces Distribuídos
- Cadeia de Custódia
- Dashboards e Alertas
1. Visão Geral
Objetivo
Implementar sistema robusto de observabilidade e auditoria para garantir transparência total, compliance LGPD/CNMP e capacidade de investigação forense completa.
Princípios de Observabilidade
- Transparência Total: Todos os eventos são registrados
- Imutabilidade: Logs não podem ser alterados
- Integridade: Verificação de integridade com hash
- Correlação: Rastreamento distribuído de requisições
- Retenção: Conformidade com prazos legais (7 anos)
Arquitetura de Observabilidade
Carregando diagrama...
2. SDK de Auditoria
2.1 Interface do SDK
TypeScript SDK
interface AuditEvent {
// Identificação obrigatória
traceId: string; // ID de rastreamento distribuído
spanId: string; // ID do span atual
requestId: string; // ID único da requisição
// Contexto do usuário
actor: string; // ID do usuário/entidade
jwtClaims: Record<string, any>; // Claims do JWT
// Evento
action: string; // Ação executada
resource: string; // Recurso afetado
result: 'success' | 'error' | 'warning';
// Metadados
timestamp: Date; // Timestamp ISO 8601
duration?: number; // Duração em ms
metadata: Record<string, any>; // Metadados específicos
// Para mídias processadas
hashMedia?: string; // Hash SHA-256 da mídia
// Integridade
hash: string; // Hash SHA-256 do evento
signature?: string; // Assinatura digital (opcional)
}
class AuditSDK {
static async log(event: Partial<AuditEvent>): Promise<void>;
static async logManifestation(event: ManifestationAuditEvent): Promise<void>;
static async logTriage(event: TriageAuditEvent): Promise<void>;
static async logIntegration(event: IntegrationAuditEvent): Promise<void>;
static async logDataAccess(event: DataAccessAuditEvent): Promise<void>;
}
Eventos Específicos
interface ManifestationAuditEvent extends AuditEvent {
action: 'manifestation.created' | 'manifestation.updated' | 'manifestation.deleted';
resource: 'manifestation';
metadata: {
manifestationId: string;
tipo: string;
tenant: string;
conteudoHash: string;
mídiaHash?: string;
anonimizada: boolean;
};
}
interface TriageAuditEvent extends AuditEvent {
action: 'triage.assigned' | 'triage.completed' | 'triage.escalated';
resource: 'triage';
metadata: {
manifestationId: string;
analistaId: string;
prioridade: number;
motivoIA: string;
decisaoHumana: string;
tempoProcessamento: number;
};
}
interface IntegrationAuditEvent extends AuditEvent {
action: 'integration.sent' | 'integration.received' | 'integration.failed';
resource: 'integration';
metadata: {
sistemaExterno: string;
endpoint: string;
payloadHash: string;
responseCode: number;
tentativas: number;
};
}
interface DataAccessAuditEvent extends AuditEvent {
action: 'data.accessed' | 'data.exported' | 'data.deleted';
resource: 'data';
metadata: {
dataType: string;
recordId: string;
fieldsAccessed: string[];
purpose: string;
legalBasis: string;
};
}
2.2 Implementação do SDK
Middleware Express.js
import { AuditSDK } from '@aegistech/audit-sdk';
export function auditMiddleware(req: Request, res: Response, next: NextFunction) {
const startTime = Date.now();
const traceId = req.headers['x-trace-id'] as string;
const spanId = generateSpanId();
const requestId = req.headers['x-request-id'] as string;
// Log da requisição
AuditSDK.log({
traceId,
spanId,
requestId,
actor: req.user?.id || 'anonymous',
jwtClaims: req.user?.claims || {},
action: 'http.request',
resource: `${req.method} ${req.path}`,
result: 'success',
timestamp: new Date(),
metadata: {
method: req.method,
path: req.path,
userAgent: req.headers['user-agent'],
ip: req.ip,
tenant: req.headers['x-tenant-id']
}
});
// Interceptar resposta
const originalSend = res.send;
res.send = function(data) {
const duration = Date.now() - startTime;
AuditSDK.log({
traceId,
spanId,
requestId,
actor: req.user?.id || 'anonymous',
jwtClaims: req.user?.claims || {},
action: 'http.response',
resource: `${req.method} ${req.path}`,
result: res.statusCode >= 400 ? 'error' : 'success',
timestamp: new Date(),
duration,
metadata: {
statusCode: res.statusCode,
responseSize: data?.length || 0
}
});
return originalSend.call(this, data);
};
next();
}
3. Logs Estruturados
3.1 Formato Padrão
Estrutura JSON
logFormat:
timestamp:
type: string
format: "ISO 8601"
example: "2024-01-15T10:30:00.123Z"
level:
type: string
enum: ["DEBUG", "INFO", "WARN", "ERROR", "FATAL"]
service:
type: string
example: "manifestation-service"
version:
type: string
example: "1.0.0"
traceId:
type: string
format: "UUID"
example: "550e8400-e29b-41d4-a716-446655440000"
spanId:
type: string
example: "00f067aa0ba902b7"
requestId:
type: string
format: "UUID"
example: "550e8400-e29b-41d4-a716-446655440001"
userId:
type: string
example: "user-123"
tenant:
type: string
example: "mp-sp"
message:
type: string
example: "Manifestação processada com sucesso"
metadata:
type: object
additionalProperties: true
error:
type: object
properties:
name: string
message: string
stack: string
code: string
3.2 Campos Obrigatórios por Contexto
Logs de Aplicação
applicationLogs:
required:
- "timestamp"
- "level"
- "service"
- "traceId"
- "message"
optional:
- "spanId"
- "requestId"
- "userId"
- "tenant"
- "metadata"
- "error"
Logs de Auditoria
auditLogs:
required:
- "timestamp"
- "traceId"
- "spanId"
- "requestId"
- "actor"
- "action"
- "resource"
- "result"
- "jwtClaims"
- "hash"
optional:
- "duration"
- "metadata"
- "hashMedia"
- "signature"
3.3 Configuração de Logging
Winston Configuration
import winston from 'winston';
const logger = winston.createLogger({
level: process.env.LOG_LEVEL || 'info',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.errors({ stack: true }),
winston.format.json()
),
defaultMeta: {
service: process.env.SERVICE_NAME,
version: process.env.SERVICE_VERSION,
environment: process.env.NODE_ENV
},
transports: [
new winston.transports.Console({
format: winston.format.combine(
winston.format.colorize(),
winston.format.simple()
)
}),
new winston.transports.File({
filename: 'logs/error.log',
level: 'error',
maxsize: 5242880, // 5MB
maxFiles: 5
}),
new winston.transports.File({
filename: 'logs/combined.log',
maxsize: 5242880, // 5MB
maxFiles: 5
})
]
});
// Middleware para adicionar contexto
logger.addContext = (context: Record<string, any>) => {
return logger.child(context);
};
4. Métricas e KPIs
4.1 Métricas de Sistema
Métricas de Infraestrutura
infrastructureMetrics:
cpu:
- "cpu_usage_percent"
- "cpu_load_average"
- "cpu_cores_available"
memory:
- "memory_usage_bytes"
- "memory_usage_percent"
- "memory_available_bytes"
disk:
- "disk_usage_bytes"
- "disk_usage_percent"
- "disk_io_read_bytes"
- "disk_io_write_bytes"
network:
- "network_bytes_received"
- "network_bytes_sent"
- "network_connections_active"
Métricas de Aplicação
applicationMetrics:
http:
- "http_requests_total"
- "http_request_duration_seconds"
- "http_requests_in_flight"
- "http_requests_failed_total"
database:
- "db_connections_active"
- "db_connections_idle"
- "db_query_duration_seconds"
- "db_queries_total"
cache:
- "cache_hits_total"
- "cache_misses_total"
- "cache_operations_total"
- "cache_memory_usage_bytes"
4.2 KPIs de Negócio
Métricas de Processamento
businessKPIs:
manifestations:
- "manifestations_created_total"
- "manifestations_processed_total"
- "manifestations_triaged_total"
- "manifestations_resolved_total"
- "manifestation_processing_time_seconds"
triage:
- "triage_accuracy_percent"
- "triage_time_seconds"
- "human_override_rate_percent"
- "ai_confidence_score"
integration:
- "integrations_sent_total"
- "integrations_success_rate_percent"
- "integration_latency_seconds"
- "integration_retry_count"
compliance:
- "audit_events_total"
- "data_access_events_total"
- "consent_rate_percent"
- "data_retention_compliance_percent"
4.3 Configuração Prometheus
Custom Metrics
import { register, Counter, Histogram, Gauge } from 'prom-client';
// Contadores
const manifestationsCreated = new Counter({
name: 'manifestations_created_total',
help: 'Total number of manifestations created',
labelNames: ['tenant', 'type']
});
const manifestationsProcessed = new Counter({
name: 'manifestations_processed_total',
help: 'Total number of manifestations processed',
labelNames: ['tenant', 'status']
});
// Histogramas
const processingTime = new Histogram({
name: 'manifestation_processing_time_seconds',
help: 'Time taken to process manifestations',
labelNames: ['tenant', 'type'],
buckets: [0.1, 0.5, 1, 2, 5, 10, 30, 60]
});
// Gauges
const activeManifestations = new Gauge({
name: 'manifestations_active',
help: 'Number of active manifestations',
labelNames: ['tenant', 'status']
});
// Registro das métricas
register.registerMetric(manifestationsCreated);
register.registerMetric(manifestationsProcessed);
register.registerMetric(processingTime);
register.registerMetric(activeManifestations);
5. Traces Distribuídos
5.1 Configuração OpenTelemetry
Instrumentação Automática
import { NodeSDK } from '@opentelemetry/sdk-node';
import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';
import { JaegerExporter } from '@opentelemetry/exporter-jaeger';
import { Resource } from '@opentelemetry/resources';
import { SemanticResourceAttributes } from '@opentelemetry/semantic-conventions';
const sdk = new NodeSDK({
resource: new Resource({
[SemanticResourceAttributes.SERVICE_NAME]: 'aegistech-mvp',
[SemanticResourceAttributes.SERVICE_VERSION]: '1.0.0',
[SemanticResourceAttributes.DEPLOYMENT_ENVIRONMENT]: process.env.NODE_ENV,
}),
traceExporter: new JaegerExporter({
endpoint: process.env.JAEGER_ENDPOINT || 'http://localhost:14268/api/traces',
}),
instrumentations: [
getNodeAutoInstrumentations({
'@opentelemetry/instrumentation-fs': {
enabled: false, // Desabilitar instrumentação de arquivos
},
}),
],
});
sdk.start();
Instrumentação Customizada
import { trace, context, SpanStatusCode } from '@opentelemetry/api';
const tracer = trace.getTracer('aegistech-mvp');
export async function processManifestation(manifestationId: string) {
const span = tracer.startSpan('process_manifestation', {
attributes: {
'manifestation.id': manifestationId,
'manifestation.tenant': getTenantFromContext(),
},
});
try {
// Processamento OCR
const ocrSpan = tracer.startSpan('ocr_processing', {
parent: span,
});
const ocrResult = await performOCR(manifestationId);
ocrSpan.setAttributes({
'ocr.confidence': ocrResult.confidence,
'ocr.text_length': ocrResult.text.length,
});
ocrSpan.end();
// Processamento NLP
const nlpSpan = tracer.startSpan('nlp_processing', {
parent: span,
});
const nlpResult = await performNLP(ocrResult.text);
nlpSpan.setAttributes({
'nlp.entities_count': nlpResult.entities.length,
'nlp.classification_confidence': nlpResult.confidence,
});
nlpSpan.end();
// Triagem
const triageSpan = tracer.startSpan('triage_processing', {
parent: span,
});
const triageResult = await performTriage(nlpResult);
triageSpan.setAttributes({
'triage.priority_score': triageResult.priority,
'triage.ai_confidence': triageResult.confidence,
});
triageSpan.end();
span.setStatus({ code: SpanStatusCode.OK });
return triageResult;
} catch (error) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: error.message,
});
span.recordException(error);
throw error;
} finally {
span.end();
}
}
6. Cadeia de Custódia
6.1 Estrutura da Cadeia
Hash Chain
custodyChain:
structure:
- "event_hash"
- "previous_hash"
- "timestamp"
- "signature"
- "public_key"
algorithm: "SHA-256"
format: "Merkle Tree"
immutability: true
verification: "automatic"
Implementação
import crypto from 'crypto';
interface CustodyChainEntry {
eventHash: string;
previousHash: string;
timestamp: Date;
signature: string;
publicKey: string;
}
class CustodyChain {
private entries: CustodyChainEntry[] = [];
private previousHash: string = '0';
addEvent(event: AuditEvent): string {
const eventHash = this.calculateEventHash(event);
const timestamp = new Date();
const signature = this.signEvent(eventHash, timestamp);
const entry: CustodyChainEntry = {
eventHash,
previousHash: this.previousHash,
timestamp,
signature,
publicKey: this.getPublicKey(),
};
this.entries.push(entry);
this.previousHash = this.calculateEntryHash(entry);
return this.previousHash;
}
private calculateEventHash(event: AuditEvent): string {
const eventString = JSON.stringify(event, Object.keys(event).sort());
return crypto.createHash('sha256').update(eventString).digest('hex');
}
private calculateEntryHash(entry: CustodyChainEntry): string {
const entryString = JSON.stringify(entry, Object.keys(entry).sort());
return crypto.createHash('sha256').update(entryString).digest('hex');
}
private signEvent(eventHash: string, timestamp: Date): string {
const data = `${eventHash}:${timestamp.toISOString()}`;
const sign = crypto.createSign('SHA256');
sign.update(data);
return sign.sign(this.getPrivateKey(), 'hex');
}
verifyChain(): boolean {
for (let i = 1; i < this.entries.length; i++) {
const current = this.entries[i];
const previous = this.entries[i - 1];
if (current.previousHash !== this.calculateEntryHash(previous)) {
return false;
}
}
return true;
}
}
6.2 Integridade de Mídia
Hash de Mídia
interface MediaIntegrity {
fileId: string;
originalHash: string;
processedHash: string;
transformations: string[];
timestamp: Date;
signature: string;
}
class MediaIntegrityTracker {
async trackMediaProcessing(
fileId: string,
originalContent: Buffer,
processedContent: Buffer,
transformations: string[]
): Promise<MediaIntegrity> {
const originalHash = crypto.createHash('sha256').update(originalContent).digest('hex');
const processedHash = crypto.createHash('sha256').update(processedContent).digest('hex');
const integrity: MediaIntegrity = {
fileId,
originalHash,
processedHash,
transformations,
timestamp: new Date(),
signature: this.signIntegrity(fileId, originalHash, processedHash),
};
await this.storeIntegrity(integrity);
return integrity;
}
private signIntegrity(fileId: string, originalHash: string, processedHash: string): string {
const data = `${fileId}:${originalHash}:${processedHash}`;
const sign = crypto.createSign('SHA256');
sign.update(data);
return sign.sign(this.getPrivateKey(), 'hex');
}
}
7. Dashboards e Alertas
7.1 Dashboards Grafana
Dashboard de Sistema
systemDashboard:
panels:
- title: "CPU Usage"
type: "graph"
query: "rate(cpu_usage_percent[5m])"
threshold: 80
- title: "Memory Usage"
type: "graph"
query: "rate(memory_usage_bytes[5m])"
threshold: 85
- title: "Disk Usage"
type: "graph"
query: "rate(disk_usage_percent[5m])"
threshold: 90
- title: "Network Traffic"
type: "graph"
query: "rate(network_bytes_total[5m])"
Dashboard de Negócio
businessDashboard:
panels:
- title: "Manifestations Created"
type: "stat"
query: "sum(rate(manifestations_created_total[1h]))"
- title: "Processing Time"
type: "graph"
query: "histogram_quantile(0.95, rate(manifestation_processing_time_seconds_bucket[5m]))"
- title: "Triage Accuracy"
type: "stat"
query: "avg(triage_accuracy_percent)"
- title: "Integration Success Rate"
type: "stat"
query: "rate(integrations_success_total[1h]) / rate(integrations_sent_total[1h])"
7.2 Configuração de Alertas
Alertas de Sistema
systemAlerts:
highCpuUsage:
condition: "cpu_usage_percent > 80"
duration: "5m"
severity: "warning"
notification: ["slack", "email"]
highMemoryUsage:
condition: "memory_usage_percent > 85"
duration: "5m"
severity: "critical"
notification: ["pagerduty", "slack"]
diskSpaceLow:
condition: "disk_usage_percent > 90"
duration: "1m"
severity: "critical"
notification: ["pagerduty", "email"]
Alertas de Negócio
businessAlerts:
processingTimeHigh:
condition: "histogram_quantile(0.95, manifestation_processing_time_seconds) > 30"
duration: "10m"
severity: "warning"
notification: ["slack"]
triageAccuracyLow:
condition: "triage_accuracy_percent < 80"
duration: "30m"
severity: "warning"
notification: ["slack", "email"]
integrationFailureRate:
condition: "rate(integrations_failed_total[1h]) / rate(integrations_sent_total[1h]) > 0.1"
duration: "15m"
severity: "critical"
notification: ["pagerduty", "slack"]
7.3 Relatórios de Compliance
Relatório de Auditoria
auditReport:
frequency: "daily"
content:
- "Total de eventos auditados"
- "Eventos por tipo de ação"
- "Eventos por usuário"
- "Eventos por tenant"
- "Violações de segurança"
- "Integridade da cadeia de custódia"
metrics:
- "audit_events_total"
- "audit_events_by_action"
- "audit_events_by_user"
- "audit_events_by_tenant"
- "security_violations_total"
- "custody_chain_integrity_percent"
Relatório de Performance
performanceReport:
frequency: "weekly"
content:
- "Métricas de performance"
- "Tendências de uso"
- "Análise de gargalos"
- "Recomendações de otimização"
metrics:
- "response_time_p95"
- "throughput_rps"
- "error_rate_percent"
- "resource_utilization"