Skip to content

vynnydev/pix-banking-system-aws

Repository files navigation

🏦 PIX Banking System - AWS Cloud Infrastructure

Terraform AWS Kubernetes Python Docker

Sistema bancário completo para transferências PIX com arquitetura de microserviços na AWS

📋 Documentação🚀 Quick Start📊 Evidências💰 Custos


🌐 Rancher Dashboard

Rancher Dashboard

🔗 Acesso ao Rancher:
URL: https://a51ac781483a549b3b6937162f4eae27-440043048.us-east-1.elb.amazonaws.com/dashboard/home
Login: admin | Senha: Admin123!


📋 Índice


🏗️ Arquitetura

📐 Visão Geral da Arquitetura

💡 Dica: Importe o arquivo docs/architecture-diagram.xml no Draw.io para visualizar a arquitetura completa e interativa!

┌─────────────────────────────────────────────────────────────────────┐
│                          ☁️  AWS Cloud VPC                          │
│                         (10.0.0.0/16)                               │
├─────────────────────────────────────────────────────────────────────┤
│                                                                     │
│  ┌──────────────┐          ┌────────────────────────────────────┐ │
│  │   🌐 ALB     │  HTTP    │      🎯 EKS Cluster 1.28           │ │
│  │   Ingress    │─────────▶│                                    │ │
│  │  Controller  │          │  ┌──────────────────────────────┐  │ │
│  └──────────────┘          │  │  🐍 Auth Service             │  │ │
│         │                  │  │     (Python 3.11 + Flask)    │  │ │
│         │                  │  │     Replicas: 2              │  │ │
│         ▼                  │  └──────────────────────────────┘  │ │
│  ┌──────────────┐          │                                    │ │
│  │  📡 Route53  │          │  ┌──────────────────────────────┐  │ │
│  │    (DNS)     │          │  │  💸 Transaction Service      │  │ │
│  └──────────────┘          │  │     (Python 3.11 + Flask)    │  │ │
│                            │  │     Replicas: 2 (HPA 2-5)    │  │ │
│                            │  └──────────────────────────────┘  │ │
│                            │                                    │ │
│                            │  ┌──────────────────────────────┐  │ │
│                            │  │  ⚖️  Settlement Service      │  │ │
│                            │  │     (Python 3.11 + Flask)    │  │ │
│                            │  │     Replicas: 2              │  │ │
│                            │  │     CronJob: */6h            │  │ │
│                            │  └──────────────────────────────┘  │ │
│                            └────────────────────────────────────┘ │
│                                         │                          │
│                    ┌────────────────────┼────────────────────┐     │
│                    ▼                    ▼                    ▼     │
│         ┌──────────────────┐  ┌──────────────┐  ┌──────────────┐  │
│         │   📊 DynamoDB    │  │  📮 SNS      │  │  📬 SQS      │  │
│         │                  │  │  Topic       │  │  Queue       │  │
│         │  • users         │  │              │  │              │  │
│         │  • accounts      │  │  Pub/Sub     │  │  FIFO        │  │
│         │  • transactions  │  │  Notif.      │  │  Async       │  │
│         │  • pixkeys       │  └──────────────┘  └──────────────┘  │
│         │  • notifications │                                       │
│         └──────────────────┘                                       │
│                    │                                               │
│         ┌──────────┴──────────┐        ┌──────────────┐           │
│         ▼                     ▼        │   🐳 ECR     │           │
│  ┌──────────────┐    ┌──────────────┐  │              │           │
│  │ 🔥 ElastiCache│    │  🖼️  ECR     │  │  Repos: 3    │           │
│  │    Redis      │    │   Images     │  │  • auth      │           │
│  │  (t3.micro)   │    │              │  │  • trans.    │           │
│  │               │    │  Multi-Stage │  │  • settl.    │           │
│  │  Cache + Auth │    │  Dockerfile  │  └──────────────┘           │
│  └──────────────┘    └──────────────┘                             │
│                                                                     │
└─────────────────────────────────────────────────────────────────────┘

🔐 Segurança e Rede

📡 Internet Gateway
    │
    ▼
┌─────────────────────────────────┐
│    Public Subnets (2 AZs)       │
│  • NAT Gateway                  │
│  • Application Load Balancer    │
└─────────────────────────────────┘
    │
    ▼
┌─────────────────────────────────┐
│   Private Subnets (2 AZs)       │
│  • EKS Worker Nodes             │
│  • Microservices Pods           │
│  • Network Policies (Isolation) │
└─────────────────────────────────┘
    │
    ▼
┌─────────────────────────────────┐
│   AWS Managed Services          │
│  • DynamoDB (VPC Endpoint)      │
│  • ElastiCache (Private)        │
│  • SNS/SQS                      │
└─────────────────────────────────┘

🛠️ Tecnologias

☁️ Cloud & Infrastructure

  • Terraform Terraform - IaC
  • AWS AWS - Cloud Provider
  • Kubernetes EKS - Container Orchestration
  • Docker Docker - Containerization

🗄️ Databases & Storage

  • DynamoDB DynamoDB - NoSQL
  • Redis ElastiCache - In-Memory Cache

💬 Messaging & Events

  • SNS SNS - Pub/Sub
  • SQS SQS - Message Queue

🐍 Backend

  • Python Python - Language
  • Flask Flask - Web Framework
  • Boto3 Boto3 - AWS SDK

🔧 DevOps

  • Helm Helm - K8s Package Manager
  • Rancher Rancher - K8s Management

📦 Infraestrutura AWS

📊 Recursos Provisionados

🏗️ Categoria 📦 Recurso 🔢 Quantidade 📝 Descrição
🌐 Networking VPC 1 Rede privada (10.0.0.0/16)
Subnets Privadas 2 Workloads (us-east-1a, us-east-1b)
Subnets Públicas 2 ALB + NAT Gateway
NAT Gateway 2 Conectividade internet (HA)
⚙️ Compute EKS Cluster 1 Kubernetes 1.28
EC2 Worker Nodes 2-3 t3.small (auto-scaling)
🗄️ Database DynamoDB Tables 5 users, accounts, transactions, pixkeys, notifications
ElastiCache Redis 1 t3.micro (cache + sessions)
📬 Messaging SNS Topic 1 Notificações de transações
SQS Queue 1 Processamento assíncrono
🐳 Container ECR Repositories 3 Imagens Docker dos microserviços
ALB 1 Application Load Balancer

🚀 Microserviços

🏗️ Arquitetura de Microserviços

🎯 Serviço 📋 Detalhes

🔐 Auth Service

Porta: 3000
Réplicas: 2
HPA: Não configurado

📡 Endpoints:

  • GET /health - Health check
  • POST /api/auth/register - Cadastro de usuário + conta
  • POST /api/auth/login - Autenticação (JWT)
  • GET /api/auth/users/:id - Buscar usuário

🔗 Dependências:

  • 📊 DynamoDB: users, accounts
  • 🔥 Redis: Cache de tokens JWT

💸 Transaction Service

Porta: 3000
Réplicas: 2-5 (HPA)
Scaling: CPU > 70%

📡 Endpoints:

  • GET /health - Health check
  • POST /api/transactions - Criar transação PIX
  • GET /api/transactions/:id - Consultar transação

🔗 Dependências:

  • 📊 DynamoDB: transactions, accounts, pixkeys
  • 🔥 Redis: Cache de transações
  • 📮 SNS: Publicar notificações

⚖️ Settlement Service

Porta: 3000
Réplicas: 2
CronJob: */6h

📡 Endpoints:

  • GET /health - Health check
  • POST /api/settlement/process - Processar liquidação
  • GET /api/settlement/report - Relatório de transações

🔗 Dependências:

  • 📊 DynamoDB: transactions, accounts
  • 📬 SQS: Consumir fila de liquidação
  • 📮 SNS: Publicar status

⚙️ Deploy

🚀 Quick Start

📋 Pré-requisitos

# Ferramentas necessárias
✅ AWS CLI 2.x
✅ Terraform 1.5+
✅ kubectl 1.28+
✅ Docker 20.x+
✅ Helm 3.x+
✅ jq (opcional)

1️⃣ Provisionar Infraestrutura AWS

# Clonar repositório
git clone https://github.com/seu-usuario/pix-banking-system-aws.git
cd pix-banking-system-aws

# Configurar credenciais AWS
aws configure

# Navegar para o diretório do Terraform
cd infrastructure/terraform

# Inicializar Terraform
terraform init

# Planejar mudanças
terraform plan -out=tfplan

# Aplicar infraestrutura (⏱️ ~15-20 minutos)
terraform apply tfplan

# Salvar outputs importantes
terraform output > ../../terraform-outputs.txt

2️⃣ Configurar kubectl

# Configurar acesso ao cluster EKS
aws eks update-kubeconfig \
  --region us-east-1 \
  --name pix-banking-system-dev-eks

# Verificar conectividade
kubectl get nodes
kubectl cluster-info

3️⃣ Instalar ALB Ingress Controller

# Executar script de instalação
./scripts/04-install-alb-controller.sh

# Verificar instalação
kubectl get pods -n kube-system | grep aws-load-balancer-controller

4️⃣ Build e Push das Imagens Docker

# Alterar RM_ALUNO no script
export RM_ALUNO="RM555221"

# Executar build e push
./scripts/03-build-push-images.sh

# Verificar imagens no ECR
aws ecr list-images --repository-name pix-banking-system-dev-auth-service

5️⃣ Deploy dos Microserviços

# Aplicar todos os manifestos Kubernetes
./scripts/05-deploy-kubernetes.sh

# Ou aplicar manualmente
kubectl apply -f kubernetes/namespace/
kubectl apply -f kubernetes/configmap.yaml
kubectl apply -f kubernetes/secrets.yaml
kubectl apply -f kubernetes/rbac/
kubectl apply -f kubernetes/auth-service/
kubectl apply -f kubernetes/transaction-service/
kubectl apply -f kubernetes/settlement-service/
kubectl apply -f kubernetes/ingress/

6️⃣ Verificar Deploy

# Ver todos os pods
kubectl get pods -n pix-microservices

# Ver serviços
kubectl get svc -n pix-microservices

# Ver ingress e pegar URL do ALB
kubectl get ingress -n pix-microservices

# Health checks
ALB_URL=$(kubectl get ingress api-gateway -n pix-microservices -o jsonpath='{.status.loadBalancer.ingress[0].hostname}')
curl http://$ALB_URL/api/auth/health
curl http://$ALB_URL/api/transactions/health
curl http://$ALB_URL/api/settlement/health

📊 Evidências do Projeto

📸 Screenshots Organizadas por Etapa


🐳 Etapa 1: Docker e Imagem Segura (1,5 pts)

1.1 Build com Multi-Stage

Docker Build Auth

1.2 Docker Push com Tag Versionada

Docker Push

1.3 Docker Scout - Scan de Vulnerabilidades

Docker Scout Transaction Docker Scout Settlement

✅ Evidências coletadas:

  • ✅ Print do docker build mostrando multi-stage
  • ✅ Saída do docker push com tag v1.RM555221
  • ✅ Saída do docker scout cves sem vulnerabilidades críticas

🌐 Etapa 2: Rede, Comunicação e Segmentação (2,5 pts)

2.1 Network Policies Configuradas

Network Policies Network Policy Transaction Network Policy Settlement

2.2 Comunicação entre Pods

Pods Communication

2.3 Logs com Variáveis de Ambiente

Auth Logs Transaction Logs Dynamo Redis Common

✅ Evidências coletadas:

  • ✅ Network Policies isolando tráfego
  • ✅ Curl entre containers funcionando
  • ✅ Logs mostrando leitura de ConfigMaps

⚙️ Etapa 3: Kubernetes - Estrutura, Escala e Deploy (3,0 pts)

3.1 Pods com 2 Réplicas

All Pods

3.2 Scaling de Deployments

Scale Auth Scale Transaction Scale Settlement

3.3 Logs de Múltiplos Pods

Transaction Logs 1 Transaction Logs 2 Settlement Logs

3.4 CronJob Executado

CronJob Created CronJob Details

✅ Evidências coletadas:

  • kubectl get pods mostrando 2 réplicas
  • kubectl scale aumentando réplicas
  • ✅ Logs de pods diferentes
  • ✅ CronJob criado e executado

🔒 Etapa 4: Kubernetes - Segurança, Observação e Operação (2,0 pts)

4.1 Limites de CPU/Memória

Resource Limits

4.2 SecurityContext Configurado

Security Context Auth Security Context Transaction

4.3 Pod Inseguro Bloqueado

Insecure Pod

4.4 Permissões Restritas (RBAC)

Permissions No Permission

✅ Evidências coletadas:

  • ✅ Recursos limitados (CPU/Memory)
  • ✅ SecurityContext com runAsNonRoot: true
  • ✅ Pod rodando como root (inseguro) vs non-root (seguro)
  • ✅ Permissões RBAC restritas

📁 Estrutura de Evidências

docs/
├── rancher.png
├── architecture-diagram.xml
├── first-stage/
│   ├── docker-auth-service.png
│   ├── docker-scout-auth-service.png
│   ├── docker-scout-transaction-service.png
│   └── docker-scout-settlement-service.png
├── second-stage/
│   ├── networkpolicy-auth-service.png
│   ├── networkpolicy-transaction-service.png
│   ├── networkpolicy-settlement-service.png
│   ├── comunicação-pods.png
│   ├── logs-dynamodb-redis-auth-service.png
│   ├── logs-dynamodb-redis-transaction-service.png
│   └── comun-dynamo-redis-auth-service.png
├── third-stage/
│   ├── todos-os-pods.png
│   ├── escalar-deployment-auth-service.png
│   ├── escalar-deployment-transaction-service.png
│   ├── escalar-deployment-settlement-service.png
│   ├── logs-leitura-escrita-transaction-service.png
│   ├── logs-leitura-escrita-settlement-service.png
│   ├── cronjob-criado-settlement-service.png
│   └── detalhes-cronjob-settlement-service.png
└── fourth-stage/
    ├── k8s-top-recursos-pods.png
    ├── security-context-auth-service.png
    ├── security-context-transaction-service.png
    ├── pod-inseguro-root.png
    ├── permissões.png
    └── transação-sem-permissão.png

💰 Estimativa de Custos

💵 Breakdown Mensal

🏷️ Recurso AWS ⚙️ Tipo/Tamanho 💰 Custo/Mês (USD)
🎯 EKS Control Plane Managed $72.00
🖥️ EC2 Worker Nodes 2x t3.small $30.00
🌐 NAT Gateway 2x AZ $32.00
⚖️ Application Load Balancer Internet-facing $16.00
🔥 ElastiCache Redis t3.micro $12.50
📊 DynamoDB On-Demand (5 tables) $5.00
📮 SNS + 📬 SQS Low traffic $1.00
🐳 ECR Storage 3 repos (~1GB) $0.12
💵 TOTAL ESTIMADO ~$168.62/mês

💡 Dicas para Reduzir Custos

💡 Dica 💰 Economia
🛑 Destruir cluster após testes ~$168/mês
🎯 Usar Spot Instances para workers ~$20/mês (70% off)
🌐 Remover 1 NAT Gateway (não HA) ~$16/mês
📊 DynamoDB Provisioned Capacity ~$3/mês
🔥 Usar Redis Spot ou t4g.micro ~$4/mês

🧹 Limpeza

⚠️ Destruir Infraestrutura

# 1. Deletar recursos Kubernetes primeiro
kubectl delete namespace pix-microservices
kubectl delete -f kubernetes/ingress/

# 2. Aguardar ALB ser deletado (~2 minutos)
kubectl get ingress --all-namespaces

# 3. Destruir infraestrutura Terraform
cd infrastructure/terraform
terraform destroy -auto-approve

# 4. Verificar recursos órfãos no AWS Console:
# - Load Balancers
# - Target Groups
# - Security Groups
# - ENIs (Network Interfaces)

👨‍💻 Autor

Vinicius Prudencio

RM: 555221
Instituição: FIAP - Faculdade de Informática e Administração Paulista
Curso: Cloud Computing & DevOps
Período: Novembro 2025

LinkedIn GitHub Email


📝 Licença

Este projeto está licenciado sob a MIT License - veja o arquivo LICENSE para detalhes.


🎯 Próximos Passos

  • 🔄 Implementar CI/CD com GitHub Actions
  • 🚀 Adicionar ArgoCD para GitOps
  • 🔒 Integrar Trivy para security scanning
  • 📊 Configurar SonarQube para análise de código
  • 📈 Implementar Prometheus + Grafana para observabilidade
  • 🕸️ Adicionar Istio service mesh
  • 🧪 Implementar testes automatizados (Jest + Pytest)
  • 📚 Adicionar documentação Swagger/OpenAPI

⭐ Se este projeto foi útil, deixe uma estrela!

Made with ❤️ by Vinicius Prudencio | © 2025

About

Pix banking platform system

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published