diff --git a/CHANGELOG.md b/CHANGELOG.md index 6292f44..73edd39 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.0.17] - O Server conecta nos agentes +- **O Server conecta nos agentes:** o agente é cadastrado na interface com **nome, IP e porta** (assistente Novo agente), e a stack dele fica só com a porta publicada e o token. O Server disca cada agente, tenta de novo sozinho com espera crescente e mostra na tela por que não conectou (tempo esgotado, conexão recusada, autenticação recusada). +- **Segurança:** o agente só aceita a conexão de quem prova ser o seu Server (TLS 1.3 com o certificado fixado no token); o Server autentica o agente pelo token e depois pela credencial, como antes. A porta do agente deve ficar liberada só para o IP do Server. +- **Porta padrão do agente: `23847`**, sem uso por nenhum serviço registrado na IANA e fora das faixas de portas temporárias do Linux e do Windows. +- O Server não expõe mais porta para os agentes (o `8443` sai do compose do Server); a opção "Endereço para os agentes" saiu, porque não há mais comandos que apontem para o Server. +- **Atualização:** agentes já matriculados não precisam de token novo. Atualize a imagem, troque `CORUJA_SERVER` por `ports: ["23847:23847"]`, mantenha o volume e informe o IP e a porta do agente na interface (veja docs/OPERACAO.md). + ## [0.0.16] - Interface nova - **Interface nova:** menu lateral à esquerda, com ícones e grupos (Operação e Administração), que pode ser recolhido; no celular vira uma gaveta. Cartões, login e painel redesenhados. - **Ícones no lugar dos links** de ação (executar, histórico, editar, pausar, excluir, testar...), com dica ao passar o mouse ou focar pelo teclado. diff --git a/Dockerfile b/Dockerfile index 1ae9007..5009d66 100644 --- a/Dockerfile +++ b/Dockerfile @@ -12,7 +12,7 @@ RUN mkdir -p /src/internal/webui && npm run build # Os estágios web e gobuild rodam na plataforma nativa do runner (sem emulação); só o binário é cruzado. # --- binários Go ----------------------------------------------------------------------------------------------------- FROM --platform=$BUILDPLATFORM golang:1.26-alpine AS gobuild -ARG VERSION=0.0.16 +ARG VERSION=0.0.17 ARG TARGETOS ARG TARGETARCH WORKDIR /src @@ -32,7 +32,7 @@ RUN --mount=type=secret,id=google_client_secret --mount=type=secret,id=google_we # --- Server ------------------------------------------------------------------------------------------------------------ FROM alpine:3.21 AS server -ARG VERSION=0.0.16 +ARG VERSION=0.0.17 LABEL org.opencontainers.image.title="Coruja Backup Server" \ org.opencontainers.image.description="Backup centralizado: orquestração, agendamentos, nuvem e interface web" \ org.opencontainers.image.source="https://github.com/AprendendoLinux/corujabackup" \ @@ -42,13 +42,13 @@ COPY --from=gobuild /out/coruja-server /usr/local/bin/coruja-server RUN mkdir -p /data && chown coruja /data VOLUME /data USER coruja -EXPOSE 8080 8443 +EXPOSE 8080 HEALTHCHECK --interval=30s --timeout=5s --start-period=60s --retries=3 CMD ["/usr/local/bin/coruja-server", "-healthcheck"] ENTRYPOINT ["/usr/local/bin/coruja-server"] # --- Agente ------------------------------------------------------------------------------------------------------------ FROM alpine:3.21 AS agent -ARG VERSION=0.0.16 +ARG VERSION=0.0.17 LABEL org.opencontainers.image.title="Coruja Backup Agent" \ org.opencontainers.image.description="Agente leve do Coruja Backup (conecta ao Server por IP:porta)" \ org.opencontainers.image.source="https://github.com/AprendendoLinux/corujabackup" \ @@ -58,4 +58,5 @@ RUN apk add --no-cache ca-certificates tzdata mariadb-client postgresql17-client COPY --from=gobuild /out/coruja-agent /usr/local/bin/coruja-agent VOLUME /var/lib/coruja-agent # Roda como root: a Fase 2 precisa ler pastas do host (montadas somente leitura). +EXPOSE 23847 ENTRYPOINT ["/usr/local/bin/coruja-agent"] diff --git a/README.md b/README.md index ddcd7af..2d2a982 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ Sistema de backup **centralizado**, em Docker, gerenciado por **interface web**. Um **Server** orquestra tudo; **Agentes** leves rodam nos servidores de destino e se conectam a ele informando só **IP:porta + token**. -> **Versão 0.0.16** · [Changelog](CHANGELOG.md) · [Instalação](docs/INSTALACAO.md) · [Operação](docs/OPERACAO.md) · [Segurança](docs/SEGURANCA.md) · [FAQ](docs/FAQ.md) +> **Versão 0.0.17** · [Changelog](CHANGELOG.md) · [Instalação](docs/INSTALACAO.md) · [Operação](docs/OPERACAO.md) · [Segurança](docs/SEGURANCA.md) · [FAQ](docs/FAQ.md) ## O que faz @@ -21,17 +21,17 @@ nos servidores de destino e se conectam a ele informando só **IP:porta + token* ## Como funciona ``` - ┌────────────┐ gRPC/TLS 1.3 (agente → server) ┌───────────────────────┐ MySQL ┌────────┐ - │ Agente │ ────────────────────────────────▶ │ Server (UI + API) │ ────────▶ │ mysql │ - │ (cada host)│ IP:8443 + token │ agenda, orquestra │ └────────┘ + ┌────────────┐ gRPC/TLS 1.3 (server → agente) ┌───────────────────────┐ MySQL ┌────────┐ + │ Agente │ ◀──────────────────────────────── │ Server (UI + API) │ ────────▶ │ mysql │ + │ (cada host)│ IP:porta do agente + token │ agenda, orquestra │ └────────┘ └─────┬──────┘ └──────────┬────────────┘ │ envio direto (sessão emitida pelo Server) │ credenciais da nuvem ficam só aqui (cifradas) ▼ ▼ Drive · OneDrive · Dropbox e-mail · Telegram · Prometheus ``` -- O **Server** guarda configuração, histórico e credenciais (cifradas) e expõe duas portas: `8080` (interface/API) e `8443` (agentes). -- O **Agente** só faz conexões de saída, não abre portas, e executa apenas o que a política local permitir. +- O **Server** guarda configuração, histórico e credenciais (cifradas), expõe só a interface/API (`8080`) e **conecta em cada agente** pelo IP e pela porta cadastrados na interface. +- O **Agente** escuta numa porta (padrão `23847`), só aceita a conexão de quem prova ser o seu Server (certificado fixado no token) e executa apenas o que a política local permitir. - Tudo é configurado pela interface; as variáveis de ambiente dos compose são mínimas. ## Instalação rápida @@ -69,4 +69,4 @@ docker run --rm --network SUA_REDE -e CORUJA_TEST_DSN='usuario:senha@tcp(db:3306 ``` --- -Coruja Backup - Versão 0.0.16 - Desenvolvido por [Henrique Fagundes](https://henrique.tec.br) · Licença MIT +Coruja Backup - Versão 0.0.17 - Desenvolvido por [Henrique Fagundes](https://henrique.tec.br) · Licença MIT diff --git a/VERSION b/VERSION index e3b86dd..cd23180 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.0.16 +0.0.17 diff --git a/cmd/agent/main.go b/cmd/agent/main.go index 87312a8..661a5e6 100644 --- a/cmd/agent/main.go +++ b/cmd/agent/main.go @@ -19,12 +19,12 @@ import ( ) func main() { - server := flag.String("server", os.Getenv("CORUJA_SERVER"), "endereço do canal dos agentes no Server (IP:porta)") + listen := flag.String("listen", envOr("CORUJA_LISTEN", ":23847"), "porta onde o agente espera a conexão do Server") token := flag.String("token", os.Getenv("CORUJA_TOKEN"), "token de matrícula (gerado na interface web; uso único)") dataDir := flag.String("data", envOr("CORUJA_DATA_DIR", "/var/lib/coruja-agent"), "pasta onde o agente guarda a própria credencial e a fila local") - hostRoot := flag.String("host-root", envOr("CORUJA_HOST_ROOT", "/"), "raiz do servidor vista pelo agente (use /host se montar o host nesse caminho)") + hostRoot := flag.String("host-root", envOr("CORUJA_HOST_ROOT", "/"), "raiz da máquina vista pelo agente (use /host se montar a máquina nesse caminho)") backupDir := flag.String("backup-dir", envOr("CORUJA_BACKUP_DIR", "/backups"), "pasta onde os arquivos de backup são gravados") - hostWrite := flag.String("host-write", os.Getenv("CORUJA_HOST_WRITE"), "raiz gravável do servidor, só para a pasta de backup local escolhida na interface (padrão: /host-rw no contêiner)") + hostWrite := flag.String("host-write", os.Getenv("CORUJA_HOST_WRITE"), "raiz gravável da máquina, só para a pasta de backup local escolhida na interface (padrão: /host-rw no contêiner)") showVersion := flag.Bool("version", false, "mostra a versão e sai") flag.Parse() if *showVersion { @@ -34,29 +34,19 @@ func main() { log := slog.New(slog.NewTextHandler(os.Stdout, nil)) ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) defer stop() + if os.Getenv("CORUJA_SERVER") != "" { + log.Warn("CORUJA_SERVER é ignorada: desde a versão 0.0.17 é o Server que conecta no agente (pode remover da stack)") + } stPath := filepath.Join(*dataDir, "agent.json") st, err := agentcore.LoadCredentials(stPath) if err != nil { - if strings.TrimSpace(*server) == "" || strings.TrimSpace(*token) == "" { - log.Error("agente ainda não matriculado: informe --server IP:porta e --token (ou CORUJA_SERVER e CORUJA_TOKEN)") + st = nil + if strings.TrimSpace(*token) == "" { + log.Error("agente ainda não matriculado: informe o token gerado na interface (CORUJA_TOKEN)") os.Exit(2) } - st, err = agentcore.Enroll(ctx, log, *server, *token) - if err != nil { - log.Error("matrícula recusada", "erro", err.Error()) - os.Exit(1) - } - if err := agentcore.SaveCredentials(stPath, st); err != nil { - log.Error("não foi possível gravar a credencial (a pasta de dados é gravável?)", "pasta", *dataDir, "erro", err.Error()) - os.Exit(1) - } - log.Info("matrícula concluída", "agente", st.AgentID) - } else if s := strings.TrimSpace(*server); s != "" && s != st.Server { - st.Server = s // o Server mudou de endereço; a credencial e a impressão digital continuam valendo - _ = agentcore.SaveCredentials(stPath, st) } - log.Info("agente iniciado", "versão", version.Version, "server", st.Server, "agente", st.AgentID) local, err := agentcore.NewState(*dataDir) if err != nil { log.Error("não foi possível preparar a pasta de dados do agente", "erro", err.Error()) @@ -69,13 +59,21 @@ func main() { *hostWrite = "/host-rw" } } - core := agentcore.New(agentcore.Config{HostRoot: *hostRoot, HostWriteRoot: *hostWrite, BackupRoots: splitList(os.Getenv("CORUJA_BACKUP_ROOTS")), BackupDir: *backupDir, AllowedPaths: splitList(os.Getenv("CORUJA_ALLOWED_PATHS")), AllowedContainers: splitList(os.Getenv("CORUJA_ALLOWED_CONTAINERS")), DestDir: envOr("CORUJA_DEST_DIR", "/destinos")}, local, log) + core := agentcore.New(agentcore.Config{HostRoot: *hostRoot, HostWriteRoot: *hostWrite, BackupRoots: splitList(os.Getenv("CORUJA_BACKUP_ROOTS")), BackupDir: *backupDir, + AllowedPaths: splitList(os.Getenv("CORUJA_ALLOWED_PATHS")), AllowedContainers: splitList(os.Getenv("CORUJA_ALLOWED_CONTAINERS")), DestDir: envOr("CORUJA_DEST_DIR", "/destinos")}, local, log) if err := os.MkdirAll(*backupDir, 0o750); err != nil { log.Warn("a pasta de backups não está disponível (monte um volume gravável)", "pasta", *backupDir, "erro", err.Error()) } - log.Info("áreas de trabalho", "origem_do_host", *hostRoot, "pasta_de_backups", *backupDir) + id := int64(0) + if st != nil { + id = st.AgentID + } + log.Info("agente iniciado", "versão", version.Version, "agente", id, "origem_do_host", *hostRoot, "pasta_de_backups", *backupDir) go core.Run(ctx) - agentcore.Run(ctx, log, st, core) + if err := agentcore.Listen(ctx, log, agentcore.ListenConfig{Addr: *listen, Token: strings.TrimSpace(*token), StatePath: stPath}, st, core); err != nil { + log.Error("o agente não pôde iniciar", "erro", err.Error()) + os.Exit(1) + } log.Info("agente encerrado") } diff --git a/cmd/server/main.go b/cmd/server/main.go index d0444d5..9f919ef 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -99,9 +99,10 @@ func main() { hub.Box = box notifier := notify.New(st, box) hub.Notify = notifier - _, agentPort, _ := net.SplitHostPort(cfg.AgentListen) + dialer := agentsrv.NewDialer(st.DialTargets) // o Server conecta em cada agente cadastrado (host:porta) + hub.Dialer = dialer api := &httpapi.Server{DB: d, Store: st, Pinger: d, Agents: hub, Clouds: clouds, Box: box, Notifier: notifier, Started: time.Now(), Web: webui.Handler(), - Fingerprint: fp, AgentPort: agentPort, TrustProxy: cfg.TrustProxy} + Fingerprint: fp, TrustProxy: cfg.TrustProxy} if n, err := st.CountUsers(ctx); err == nil && n == 0 { code, _ := auth.RandomToken(9) api.SetupCode = code @@ -110,7 +111,12 @@ func main() { srv := &http.Server{Addr: cfg.Listen, Handler: api.Routes(), ReadHeaderTimeout: 10 * time.Second, IdleTimeout: 2 * time.Minute, MaxHeaderBytes: 64 << 10} errc := make(chan error, 2) - go func() { errc <- hub.Listen(ctx, cfg.AgentListen, cert) }() + go dialer.Run(ctx) + go func() { + if err := hub.Serve(ctx, dialer, cert); err != nil && ctx.Err() == nil && !errors.Is(err, net.ErrClosed) { + errc <- err + } + }() go func() { log.Info("interface web/API", "endereço", cfg.Listen, "https", cfg.TLSCert != "") var err error @@ -143,7 +149,7 @@ func main() { } } }() - log.Info("canal dos agentes (gRPC/TLS)", "endereço", cfg.AgentListen) + log.Info("canal dos agentes (gRPC/TLS): o Server conecta nos agentes cadastrados") select { case err := <-errc: diff --git a/deploy/docker-compose.agent.yml b/deploy/docker-compose.agent.yml index 1c88bd5..cf553a7 100644 --- a/deploy/docker-compose.agent.yml +++ b/deploy/docker-compose.agent.yml @@ -1,12 +1,14 @@ # Coruja Backup · Agente -# Informe o endereço do canal dos agentes do Server e o token gerado na interface (Agentes > Novo agente; vale uma vez). +# Cadastre o agente na interface (Agentes > Novo agente: nome, IP e porta). Ela gera o token (vale uma vez) e esta stack pronta. +# O Server conecta no agente pela porta publicada abaixo: libere-a só para o IP do Server. services: agent: - image: ghcr.io/aprendendolinux/corujabackup-agent:0.0.16 + image: ghcr.io/aprendendolinux/corujabackup-agent:0.0.17 container_name: corujabackup-agent restart: always + ports: + - "23847:23847" # o Server conecta aqui (a porta da esquerda é a cadastrada na interface) environment: - CORUJA_SERVER: "IP_DO_SERVER:8443" CORUJA_TOKEN: "TOKEN_GERADO_NA_INTERFACE" CORUJA_HOST_ROOT: "/host" # o servidor, como o agente o enxerga (veja o volume abaixo) # Defesa em profundidade (opcional, recomendado): o agente só executa o que estas listas permitirem, diff --git a/deploy/docker-compose.server.yml b/deploy/docker-compose.server.yml index fc6ff20..4b1fcfb 100644 --- a/deploy/docker-compose.server.yml +++ b/deploy/docker-compose.server.yml @@ -31,14 +31,14 @@ services: networks: [echelon] server: - image: ghcr.io/aprendendolinux/corujabackup-server:0.0.16 + image: ghcr.io/aprendendolinux/corujabackup-server:0.0.17 container_name: corujabackup-server restart: always depends_on: db: { condition: service_healthy } ports: - "8080:8080" # interface web e API (ponha atrás do seu proxy reverso com HTTPS) - - "8443:8443" # canal dos agentes (gRPC/TLS): é a porta que os agentes alcançam + # Não há porta para os agentes: é o Server quem conecta em cada agente (IP e porta cadastrados na interface). environment: CORUJA_DB_PASSWORD: "COLOQUE_UMA_SENHA_FORTE" # CORUJA_TRUST_PROXY: "true" diff --git a/docker-compose.dev.example.yml b/docker-compose.dev.example.yml index b5d121f..1669394 100644 --- a/docker-compose.dev.example.yml +++ b/docker-compose.dev.example.yml @@ -2,10 +2,10 @@ # docker compose -f docker-compose.dev.yml up -d --build -> http://187.110.161.52:8081 services: server: - build: { context: ., target: server, args: { VERSION: "0.0.16" } } + build: { context: ., target: server, args: { VERSION: "0.0.17" } } container_name: corujabackup-dev-server restart: unless-stopped - ports: ["8081:8080", "8444:8443"] # 8081 = interface web · 8444 = canal dos agentes + ports: ["8081:8080"] # interface web (o Server é quem conecta nos agentes) environment: CORUJA_DB_HOST: db-server CORUJA_DB_NAME: corujabackup_dev diff --git a/docs/ARQUITETURA.md b/docs/ARQUITETURA.md index 1657de8..a1a85e4 100644 --- a/docs/ARQUITETURA.md +++ b/docs/ARQUITETURA.md @@ -3,8 +3,8 @@ | Tema | Decisão | Motivo | | :--- | :--- | :--- | | Linguagem (Server e Agente) | Go, um módulo só | binário estático (~15 MB), pouca RAM no agente, concorrência nativa, fácil imagem mínima | -| Comunicação | gRPC em stream bidirecional sobre TLS, **iniciado pelo agente** | funciona atrás de NAT/firewall; comandos e progresso tipados; um canal por agente | -| Portas | `8080` (interface + API REST, atrás de proxy reverso/HTTPS) e `8443` (canal gRPC/TLS dos agentes) | o canal dos agentes tem TLS próprio e fixado por impressão digital; a UI pode ficar atrás do proxy | +| Comunicação | gRPC em stream bidirecional sobre TLS; **o Server abre a conexão TCP** com cada agente (IP:porta cadastrados na interface) e, sobre ela, continua sendo o lado servidor do TLS e do gRPC | toda a configuração fica na interface; a stack do agente só publica a porta e leva o token. O agente confere a impressão digital do Server antes de qualquer coisa; comandos e progresso tipados; um canal por agente | +| Portas | Server: `8080` (interface + API REST, atrás de proxy reverso/HTTPS). Agente: `23847` (padrão), alcançável só pelo Server | o canal tem TLS próprio e fixado por impressão digital; o Server não expõe porta para os agentes | | Interface | React + TypeScript + Vite + Tailwind, embutida (`go:embed`) | sem contêiner extra; temas = variáveis CSS; logo por upload | | Banco do Server | MySQL (`mysql:latest`; recomendado fixar `8.4`) | pedido do projeto; `db` no compose de produção, `db-server` no desenvolvimento | | Caminho dos dados | **agente → nuvem direto**, com sessão de upload emitida pelo Server | credenciais ficam só no Server; o tráfego pesado não passa por ele | diff --git a/docs/FAQ.md b/docs/FAQ.md index 95540e9..5ec2f53 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -1,6 +1,6 @@ # Perguntas frequentes -**Preciso abrir portas nos servidores com agente?** Não. O agente só faz conexões de saída para o Server (`8443`). +**Preciso abrir portas nos servidores com agente?** Sim, uma: a porta do agente (padrão `23847`), **só para o IP do Server**. É o Server quem conecta no agente. O agente recusa qualquer conexão que não prove ser o seu Server (o certificado do Server é fixado no token de matrícula). Agentes atrás de NAT precisam de um redirecionamento dessa porta ou de uma VPN até o Server. **O arquivo de backup passa pelo Server?** Não. O agente envia direto à nuvem por uma sessão emitida pelo Server; as credenciais da nuvem ficam só no Server. diff --git a/docs/INSTALACAO.md b/docs/INSTALACAO.md index 992015e..7460102 100644 --- a/docs/INSTALACAO.md +++ b/docs/INSTALACAO.md @@ -2,7 +2,7 @@ ## Requisitos - Docker 24+ com Compose v2 no servidor do **Server** e nos servidores dos **agentes**. -- O Server precisa de um MySQL 8.x (o compose já traz um). Os agentes só precisam alcançar o Server na porta `8443`. +- O Server precisa de um MySQL 8.x (o compose já traz um). O **Server precisa alcançar cada agente** na porta dele (padrão `23847`). - Arquiteturas: `amd64` e `arm64`. ## 1. Server @@ -25,7 +25,7 @@ O compose usa a rede Docker externa `echelon`; crie-a (`docker network create ec | Porta | Para quê | Quem deve alcançar | | :--- | :--- | :--- | | `8080` | Interface web e API | Administradores (de preferência atrás de HTTPS) | -| `8443` | Canal gRPC/TLS dos agentes | Os servidores com agente | +| `23847` (na máquina de cada **agente**) | Canal gRPC/TLS: o Server conecta no agente | Só o IP do Server | ### HTTPS Escolha **uma** opção: @@ -43,7 +43,7 @@ location / { proxy_read_timeout 1h; } ``` -Não publique o canal dos agentes (`8443`) pelo proxy HTTP: ele tem TLS próprio e é fixado por impressão digital. +O canal dos agentes não passa pelo proxy HTTP: o Server conecta direto em cada agente, com TLS próprio fixado por impressão digital. **B) HTTPS direto no Server.** Monte um certificado e uma chave PEM e defina `CORUJA_TLS_CERT` e `CORUJA_TLS_KEY`. @@ -51,11 +51,11 @@ Não publique o canal dos agentes (`8443`) pelo proxy HTTP: ele tem TLS próprio Defina `CORUJA_DB_HOST`, `CORUJA_DB_NAME`, `CORUJA_DB_USER`, `CORUJA_DB_PASSWORD` e, se não estiver na mesma rede Docker, `CORUJA_DB_TLS=true` (ou `skip-verify`). ## 2. Agente -Na interface: **Agentes > Novo agente** gera o comando pronto (com o token de uso único). Em resumo: +Na interface: **Agentes > Novo agente** pede o nome, o **IP e a porta** da máquina do agente e gera a stack pronta (com o token de uso único). Depois que o agente sobe, o Server conecta nele sozinho. Em resumo: ```bash -docker run -d --name corujabackup-agent --restart always \ - -e CORUJA_SERVER=IP_DO_SERVER:8443 -e CORUJA_TOKEN=cb1.... -e CORUJA_HOST_ROOT=/host \ +docker run -d --name corujabackup-agent --restart always -p 23847:23847 \ + -e CORUJA_TOKEN=cb1.... -e CORUJA_HOST_ROOT=/host \ -v coruja-agent-data:/var/lib/coruja-agent -v /:/host:ro -v /:/host-rw -v /srv/coruja-backups:/backups \ ghcr.io/aprendendolinux/corujabackup-agent:latest ``` @@ -64,6 +64,7 @@ docker run -d --name corujabackup-agent --restart always \ - `/host-rw` permite escolher no painel a **pasta do backup local** em qualquer disco do servidor, vendo o espaço livre. Ele dá ao agente permissão de gravação no servidor (veja [Segurança](SEGURANCA.md)). `/backups` é a pasta padrão do agente. - **Docker socket** (`-v /var/run/docker.sock:/var/run/docker.sock`): só para jobs de banco em contêineres. Dá ao agente controle total do Docker do servidor. - **Restrinja o agente** (recomendado): `CORUJA_ALLOWED_PATHS=/etc,/srv,/home` e `CORUJA_ALLOWED_CONTAINERS=db-*,mongo`. +- **Firewall:** libere a porta publicada (`23847` no exemplo) **só para o IP do Server**. - O arquivo `deploy/docker-compose.agent.yml` traz tudo isso, com `cap_drop: ALL` e só as capacidades necessárias. ## 3. Primeiros passos @@ -81,7 +82,6 @@ docker run -d --name corujabackup-agent --restart always \ | `CORUJA_DB_HOST` / `PORT` / `NAME` / `USER` | `db` / `3306` / `corujabackup` / `corujabackup` | Conexão com o MySQL | | `CORUJA_DB_TLS` | vazio | `true`, `skip-verify` ou `preferred` (TLS com o MySQL) | | `CORUJA_LISTEN` | `:8080` | Interface web/API | -| `CORUJA_AGENT_LISTEN` | `:8443` | Canal dos agentes | | `CORUJA_DATA_DIR` | `/data` | Certificado do canal dos agentes e chave de criptografia | | `CORUJA_TRUST_PROXY` | `false` | Confiar em `X-Forwarded-*` (só atrás de proxy confiável) | | `CORUJA_TLS_CERT` / `CORUJA_TLS_KEY` | vazio | HTTPS direto na interface | @@ -89,7 +89,7 @@ docker run -d --name corujabackup-agent --restart always \ ### Agente | Variável | Padrão | Descrição | | :--- | :--- | :--- | -| `CORUJA_SERVER` | — | `IP:8443` do Server | +| `CORUJA_LISTEN` | `:23847` | Porta onde o agente espera a conexão do Server (publique-a na stack) | | `CORUJA_TOKEN` | — | Token de matrícula (uso único; depois o agente guarda a própria credencial) | | `CORUJA_HOST_ROOT` | `/` | Onde o servidor está montado dentro do contêiner | | `CORUJA_BACKUP_DIR` | `/backups` | Onde os arquivos de backup são gravados | diff --git a/docs/OPERACAO.md b/docs/OPERACAO.md index e207114..db08fe6 100644 --- a/docs/OPERACAO.md +++ b/docs/OPERACAO.md @@ -22,6 +22,12 @@ As imagens oficiais embutem o aplicativo do Google do projeto: o ID do cliente Enquanto a marca do aplicativo não estiver verificada pelo Google, o app aceita até 100 usuários no total. +## Migração para a 0.0.17 (o Server conecta nos agentes) +Os agentes já matriculados **não precisam de token novo**: a credencial e o certificado fixado continuam valendo. +1. Atualize o Server. A porta dos agentes no compose do Server deixa de ser usada (pode remover o `8443`). +2. Em cada agente: imagem `0.0.17` ou mais nova, troque `CORUJA_SERVER` por `ports: ["23847:23847"]` e recrie o contêiner **mantendo o volume de dados**. +3. Na interface, em **Agentes**, use o ícone de endereço para informar o **IP e a porta** de cada agente. O Server conecta em poucos segundos. + ## Atualização ```bash docker compose -f docker-compose.server.yml pull && docker compose -f docker-compose.server.yml up -d @@ -52,8 +58,9 @@ A nova senha é lida do terminal (ou de `CORUJA_NEW_PASSWORD`). Todas as sessõe ## Solução de problemas | Sintoma | Causa provável | O que fazer | | :--- | :--- | :--- | -| Os comandos de **Novo agente** mostram a porta errada | o canal está publicado em outra porta ou nome (ex.: `8444:8443`) | em **Agentes**, ajuste **Endereço para os agentes** | -| Agente "offline" | rede/porta `8443` bloqueada, token já usado, agente revogado | `docker logs corujabackup-agent`; libere a porta; gere novo token | +| Agente "offline" com **tempo esgotado** | firewall bloqueando a porta do agente, IP errado ou máquina desligada | libere a porta do agente para o IP do Server; confira o endereço em **Agentes** (ícone de endereço) | +| Agente "offline" com **conexão recusada** | o agente não está rodando ou a porta não foi publicada na stack | `docker ps`, `docker logs corujabackup-agent`; confira o `ports:` da stack | +| "o agente aceitou a conexão, mas não concluiu a autenticação" | token errado ou já usado, ou o certificado do Server mudou (volume `/data` recriado) | gere um novo agente na interface e use o token novo; se o Server foi reinstalado, apague o volume do agente e matricule de novo | | "o certificado do Server não confere" | o volume `/data` do Server foi recriado | restaure `tls/` ou matricule os agentes de novo | | Backup "Perdido" | agente parado/offline no horário | veja o log do agente; o agente recupera horários perdidos em até 6 h | | "o envio para a nuvem falhou" | token revogado, cota cheia, rede | página Nuvem (Testar conexão); depois **Reenviar** no detalhe da execução | diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 0472806..e95f21f 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -15,6 +15,7 @@ - [x] **Pasta local pelo painel (0.0.14):** servidor inteiro visível, pasta do backup local escolhida na interface com o espaço livre, e o que é do agente (backups, destinos e credenciais) fora dos backups. - [x] **Clareza da interface (0.0.15):** a máquina do backup é sempre chamada de agente; pastas, arquivos, atalhos e padrões identificados nas listas. - [x] **Interface nova (0.0.16):** menu lateral, ícones, modais próprios, assistentes de job e agente, execução ao vivo, temas só por pacote com modo claro e escuro, créditos configuráveis e foto do usuário. +- [x] **Conexão invertida (0.0.17):** o Server conecta nos agentes (cadastro com IP e porta; porta padrão 23847); a stack do agente só publica a porta e leva o token. - [ ] **Fase 9, parte 3:** vários destinos por job; compatíveis com S3; SharePoint. - [ ] **Fase 10 – Full/Incremental e MikroTik (versão seguinte):** motor `tar.gz` em blocos com índice e catálogo; agenda full + incrementais; retenção por cadeia; jobs de MikroTik (SSH: `.rsc` e `.backup`). - [ ] **Fase 11 – Restauração inteligente (versão posterior):** árvore de arquivos, linha do tempo de versões, restauração de arquivos selecionados e de bancos pela interface. diff --git a/docs/SEGURANCA.md b/docs/SEGURANCA.md index 2fb1211..dbd51b1 100644 --- a/docs/SEGURANCA.md +++ b/docs/SEGURANCA.md @@ -26,7 +26,7 @@ ## Checklist de endurecimento - [ ] HTTPS na interface (proxy reverso com `CORUJA_TRUST_PROXY=true`, ou `CORUJA_TLS_CERT/KEY`). -- [ ] Porta `8080` acessível só a quem administra; `8443` só aos servidores com agente (firewall). +- [ ] Porta `8080` acessível só a quem administra; a porta de cada agente (padrão `23847`) acessível só ao IP do Server (firewall). - [ ] 2FA ativo e **exigido** (Segurança > Exigir 2FA); sessão curta (ex.: 8 h). - [ ] Backup do banco **e** do volume `/data` guardados **fora** do servidor (veja Operação). - [ ] Agentes com `CORUJA_ALLOWED_PATHS` / `CORUJA_ALLOWED_CONTAINERS` e `/host` montado só com o necessário. @@ -62,3 +62,10 @@ Para a **pasta do backup local** ser escolhida no painel, o agente precisa grava A pasta de dados do agente guarda a credencial dele e a definição dos jobs, que pode conter senhas de bancos e de destinos de rede (arquivos com permissão 600). Ela **nunca entra na origem de um backup**, mesmo quando o `/` inteiro é selecionado. Consequência: para recuperar um agente perdido, matricule-o de novo com um token novo. Isso vale só para essa pasta. Um backup de pastas do sistema continua levando os outros segredos do servidor que estiverem nelas (inclusive o arquivo da stack, se tiver senhas ou token); trate o destino como um local confidencial. + +## Conexão do Server com os agentes +Desde a 0.0.17 é o Server quem abre a conexão TCP com cada agente, no IP e na porta cadastrados na interface. O resto não mudou: +- **O agente confere o Server primeiro:** antes de qualquer outra coisa, ele faz o handshake TLS 1.3 como cliente e exige o certificado cuja impressão digital veio no token de matrícula. Quem não tiver a chave privada do Server não passa daí (testado com um "Server" impostor). Um ataque de interceptação na rede também não. +- **O Server confere o agente:** na primeira conexão, pelo token de uso único; depois, pela credencial do agente (o Server guarda só o hash). +- **Porta aberta no agente:** é uma superfície nova. O agente limita os handshakes simultâneos, derruba conexões que não concluem o TLS em 15 s e não registra no log cada tentativa estranha. Mesmo assim, **libere a porta só para o IP do Server**. +- **Quem cadastra o endereço:** Operador ou Administrador. O Server só tenta um handshake TLS nesse endereço; não envia dados a quem não for o agente. diff --git a/internal/agentcore/client.go b/internal/agentcore/client.go index c2475ad..94d2184 100644 --- a/internal/agentcore/client.go +++ b/internal/agentcore/client.go @@ -3,19 +3,23 @@ package agentcore import ( "bufio" "context" + "crypto/tls" "encoding/json" + "errors" "fmt" "log/slog" + "net" "os" "path/filepath" "runtime" "strconv" "strings" "sync" + "sync/atomic" "time" "google.golang.org/grpc" - "google.golang.org/grpc/credentials" + "google.golang.org/grpc/credentials/insecure" "google.golang.org/grpc/keepalive" "google.golang.org/grpc/metadata" @@ -27,74 +31,162 @@ import ( // Credentials é o que o agente guarda depois de matriculado (arquivo agent.json, permissão 600). type Credentials struct { - Server string `json:"server"` + Server string `json:"server,omitempty"` // só de versões antigas (antes da 0.0.17 o agente discava o Server) Fingerprint string `json:"fingerprint"` AgentID int64 `json:"agent_id"` Credential string `json:"credential"` } -func Dial(addr, fp string) (*grpc.ClientConn, error) { - return grpc.NewClient(addr, - grpc.WithTransportCredentials(credentials.NewTLS(tlsutil.PinnedConfig(fp))), - grpc.WithKeepaliveParams(keepalive.ClientParameters{Time: 30 * time.Second, Timeout: 10 * time.Second, PermitWithoutStream: true}), - ) +// ListenConfig descreve como o agente espera o Server: ele escuta numa porta e o Server conecta nele. +type ListenConfig struct { + Addr string // ex.: ":23847" + Token string // token de matrícula (só na primeira vez) + StatePath string // onde a credencial fica gravada } -func Enroll(ctx context.Context, log *slog.Logger, server, tokenStr string) (*Credentials, error) { - tk, err := enroll.Parse(tokenStr) - if err != nil { - return nil, err +// oneShot entrega ao gRPC a conexão já aberta pelo Server (uma única vez: sem ela, a sessão termina). +func oneShot(c net.Conn) func(context.Context, string) (net.Conn, error) { + var used atomic.Bool + return func(context.Context, string) (net.Conn, error) { + if used.Swap(true) { + return nil, errors.New("conexão encerrada: aguardando o Server conectar de novo") + } + return c, nil } - conn, err := Dial(server, tk.Fingerprint) - if err != nil { - return nil, err +} + +// Listen recebe as conexões do Server. Cada uma só vira sessão se o TLS provar que do outro lado está o Server certo +// (impressão digital fixada, vinda do token de matrícula). A primeira conexão faz a matrícula; as seguintes usam a +// credencial gravada. Uma conexão nova substitui a anterior. +func Listen(ctx context.Context, log *slog.Logger, cfg ListenConfig, st *Credentials, core *Core) error { + var fp string + if st != nil { + fp = st.Fingerprint + } else { + tk, err := enroll.Parse(cfg.Token) + if err != nil { + return err + } + fp = tk.Fingerprint } - defer conn.Close() - host, _ := os.Hostname() - cctx, cancel := context.WithTimeout(ctx, 20*time.Second) - defer cancel() - resp, err := pb.NewAgentServiceClient(conn).Enroll(cctx, &pb.EnrollRequest{ - Token: tokenStr, Hostname: host, Os: runtime.GOOS, Arch: runtime.GOARCH, AgentVersion: version.Version}) + ln, err := net.Listen("tcp", cfg.Addr) if err != nil { - return nil, err + return fmt.Errorf("não foi possível escutar em %s: %w", cfg.Addr, err) } - return &Credentials{Server: server, Fingerprint: tk.Fingerprint, AgentID: resp.AgentId, Credential: resp.Credential}, nil -} + go func() { <-ctx.Done(); _ = ln.Close() }() + log.Info("aguardando o Server conectar", "porta", cfg.Addr) -// run mantém o canal aberto, reconectando com espera crescente (1s até 30s). -func Run(ctx context.Context, log *slog.Logger, st *Credentials, core *Core) { - backoff := time.Second - for ctx.Err() == nil { - start := time.Now() - revoked, err := session(ctx, log, st, core) - if revoked { - log.Error("este agente foi revogado no Server; ficando ocioso (remova-o ou matricule de novo com um token novo)") - <-ctx.Done() - return - } - if err != nil && ctx.Err() == nil { - log.Warn("canal encerrado", "erro", err.Error(), "nova_tentativa_em", backoff.String()) - } - if time.Since(start) > 2*time.Minute { - backoff = time.Second + var mu sync.Mutex + cur := st + var stopCur context.CancelFunc + revoked := false + slots := make(chan struct{}, 4) // limita handshakes simultâneos (conexões de estranhos não esgotam o agente) + lastWarn := time.Time{} + for { + raw, err := ln.Accept() + if err != nil { + if ctx.Err() != nil { + return nil + } + time.Sleep(200 * time.Millisecond) + continue } select { - case <-ctx.Done(): - return - case <-time.After(backoff): - } - if backoff < 30*time.Second { - backoff *= 2 + case slots <- struct{}{}: + default: + _ = raw.Close() + continue } + go func() { + defer func() { <-slots }() + mu.Lock() + pin, isRevoked := fp, revoked + mu.Unlock() + if isRevoked { + _ = raw.Close() + return + } + _ = raw.SetDeadline(time.Now().Add(15 * time.Second)) + tc := tls.Client(raw, tlsutil.PinnedConfig(pin)) + if err := tc.HandshakeContext(ctx); err != nil { + _ = raw.Close() + mu.Lock() + if time.Since(lastWarn) > time.Minute { // conexões de estranhos não enchem o log + lastWarn = time.Now() + log.Warn("conexão recusada: não é o Server deste agente (ou o certificado do Server mudou)", "de", raw.RemoteAddr().String(), "erro", err.Error()) + } + mu.Unlock() + return + } + _ = raw.SetDeadline(time.Time{}) + cc, err := grpc.NewClient("passthrough:///coruja-server", + grpc.WithTransportCredentials(insecure.NewCredentials()), // o TLS (com pinning) já foi feito acima, nesta mesma conexão + grpc.WithContextDialer(oneShot(tc)), + grpc.WithKeepaliveParams(keepalive.ClientParameters{Time: 30 * time.Second, Timeout: 10 * time.Second, PermitWithoutStream: true})) + if err != nil { + _ = tc.Close() + return + } + defer cc.Close() + mu.Lock() + creds := cur + mu.Unlock() + if creds == nil { + nc, err := enrollOver(ctx, cc, cfg.Token, pin) + if err != nil { + log.Error("matrícula recusada", "erro", err.Error()) + return + } + if err := SaveCredentials(cfg.StatePath, nc); err != nil { + log.Error("não foi possível gravar a credencial (a pasta de dados é gravável?)", "erro", err.Error()) + return + } + log.Info("matrícula concluída", "agente", nc.AgentID) + mu.Lock() + if cur == nil { + cur = nc + } + creds = cur + mu.Unlock() + } + sctx, cancel := context.WithCancel(ctx) + mu.Lock() + if stopCur != nil { + stopCur() // a conexão nova substitui a anterior + } + stopCur = cancel + mu.Unlock() + defer cancel() + wasRevoked, err := session(sctx, ctx, log, creds, core, cc) + if wasRevoked { + mu.Lock() + revoked = true + mu.Unlock() + log.Error("este agente foi revogado no Server; recusando novas conexões (remova-o ou matricule de novo com um token novo)") + return + } + if err != nil && sctx.Err() == nil { + log.Warn("canal encerrado; aguardando o Server conectar de novo", "erro", err.Error()) + } + }() } } -func session(ctx context.Context, log *slog.Logger, st *Credentials, core *Core) (revoked bool, err error) { - conn, err := Dial(st.Server, st.Fingerprint) +func enrollOver(ctx context.Context, cc *grpc.ClientConn, token, fp string) (*Credentials, error) { + host, _ := os.Hostname() + cctx, cancel := context.WithTimeout(ctx, 20*time.Second) + defer cancel() + resp, err := pb.NewAgentServiceClient(cc).Enroll(cctx, &pb.EnrollRequest{ + Token: token, Hostname: host, Os: runtime.GOOS, Arch: runtime.GOARCH, AgentVersion: version.Version}) if err != nil { - return false, err + return nil, err } - defer conn.Close() + return &Credentials{Fingerprint: fp, AgentID: resp.AgentId, Credential: resp.Credential}, nil +} + +// session conduz um canal. ctx termina com o canal; base é o contexto do agente (ações e consultas em andamento não +// são interrompidas quando o Server reconecta). +func session(ctx, base context.Context, log *slog.Logger, st *Credentials, core *Core, conn *grpc.ClientConn) (revoked bool, err error) { sctx, cancel := context.WithCancel(metadata.AppendToOutgoingContext(ctx, "authorization", fmt.Sprintf("Bearer %d.%s", st.AgentID, st.Credential))) defer cancel() stream, err := pb.NewAgentServiceClient(conn).Connect(sctx) @@ -152,10 +244,10 @@ func session(ctx context.Context, log *slog.Logger, st *Credentials, core *Core) case m.GetCancelRun() != nil: core.Cancel(m.GetCancelRun().RunUid) case m.GetAction() != nil: - core.HandleAction(ctx, m.GetAction()) + core.HandleAction(base, m.GetAction()) case m.GetRpc() != nil: rpc := m.GetRpc() - go func() { _ = safeSend(core.HandleRPC(ctx, rpc)) }() + go func() { _ = safeSend(core.HandleRPC(base, rpc)) }() case m.GetUploadSession() != nil: core.OnUploadSession(m.GetUploadSession()) case m.GetUploadVerdict() != nil: diff --git a/internal/agentsrv/agentsrv.go b/internal/agentsrv/agentsrv.go index 6fd9b43..f2f9c2b 100644 --- a/internal/agentsrv/agentsrv.go +++ b/internal/agentsrv/agentsrv.go @@ -66,6 +66,7 @@ type Server struct { Store *store.Store ServerVersion string Limiter *ratelimit.Limiter // freia tentativas de matrícula por IP + Dialer *Dialer // conexões abertas pelo Server com os agentes mu sync.Mutex online map[int64]*conn @@ -225,6 +226,7 @@ func (s *Server) Serve(ctx context.Context, lis net.Listener, cert tls.Certifica gs := grpc.NewServer( grpc.Creds(credentials.NewTLS(&tls.Config{Certificates: []tls.Certificate{cert}, MinVersion: tls.VersionTLS13})), grpc.MaxRecvMsgSize(1<<20), + grpc.ConnectionTimeout(20*time.Second), // o handshake TLS de uma conexão discada não pode ficar pendurado grpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{MinTime: 10 * time.Second, PermitWithoutStream: true}), ) pb.RegisterAgentServiceServer(gs, s) @@ -241,6 +243,18 @@ func (s *Server) Serve(ctx context.Context, lis net.Listener, cert tls.Certifica return gs.Serve(lis) } +// markConnected avisa o discador que a conexão deste contexto virou uma sessão autenticada. +func (s *Server) markConnected(ctx context.Context) { + if s.Dialer == nil { + return + } + if p, ok := peer.FromContext(ctx); ok { + if da, ok := p.Addr.(*DialedAddr); ok { + s.Dialer.connected(da.Target) + } + } +} + func peerIP(ctx context.Context) string { if p, ok := peer.FromContext(ctx); ok { if h, _, err := net.SplitHostPort(p.Addr.String()); err == nil { @@ -340,6 +354,7 @@ func (s *Server) Connect(stream pb.AgentService_ConnectServer) error { if h == nil { return status.Error(codes.InvalidArgument, "a primeira mensagem deve ser Hello") } + s.markConnected(ctx) _ = s.Store.TouchAgent(ctx, a.ID, clip(h.Hostname, 255), clip(h.Os, 40), clip(h.Arch, 20), clip(h.AgentVersion, 40), h.DockerAvailable, ip) if n, err := s.Store.FailStaleRuns(ctx, a.ID, h.ActiveRuns); err == nil && n > 0 { diff --git a/internal/agentsrv/reverse.go b/internal/agentsrv/reverse.go new file mode 100644 index 0000000..12ee1d5 --- /dev/null +++ b/internal/agentsrv/reverse.go @@ -0,0 +1,258 @@ +package agentsrv + +// Conexão invertida: é o Server quem abre a conexão TCP com cada agente (no host:porta cadastrado na interface). Sobre +// ela, os papéis continuam os mesmos de antes: o Server é o lado servidor do TLS e do gRPC (o agente confere a impressão +// digital do certificado do Server) e o agente se autentica com o token de matrícula ou a credencial dele. Assim o +// protocolo, a autenticação e a fila de resultados não mudam; só muda quem disca. + +import ( + "context" + "errors" + "log/slog" + "net" + "sync" + "syscall" + "time" + + "github.com/AprendendoLinux/corujabackup/internal/store" +) + +// LinkState é a situação da conexão com um endereço. +type LinkState struct { + Address string `json:"address"` + State string `json:"state"` // connecting | connected | error + Error string `json:"error,omitempty"` + Since time.Time `json:"since"` + NextTry time.Time `json:"next_try,omitempty"` +} + +// Dialer mantém uma conexão aberta com cada endereço cadastrado e entrega as conexões ao servidor gRPC como se fossem +// conexões recebidas (implementa net.Listener). +type Dialer struct { + Targets func(ctx context.Context) ([]store.DialTarget, error) + Dial func(ctx context.Context, address string) (net.Conn, error) + Every time.Duration // intervalo entre as varreduras (padrão 3 s) + + conns chan net.Conn + closed chan struct{} + once sync.Once + + mu sync.Mutex + links map[string]*LinkState + active map[string]bool + fails map[string]int + wake chan struct{} +} + +func NewDialer(targets func(ctx context.Context) ([]store.DialTarget, error)) *Dialer { + d := &Dialer{Targets: targets, conns: make(chan net.Conn), closed: make(chan struct{}), links: map[string]*LinkState{}, + active: map[string]bool{}, fails: map[string]int{}, wake: make(chan struct{}, 1)} + d.Dial = func(ctx context.Context, address string) (net.Conn, error) { + nd := net.Dialer{Timeout: 10 * time.Second, KeepAlive: 30 * time.Second} + return nd.DialContext(ctx, "tcp", address) + } + return d +} + +// Accept entrega a próxima conexão aberta pelo Server (para o servidor gRPC). +func (d *Dialer) Accept() (net.Conn, error) { + select { + case c := <-d.conns: + return c, nil + case <-d.closed: + return nil, net.ErrClosed + } +} + +func (d *Dialer) Close() error { d.once.Do(func() { close(d.closed) }); return nil } +func (d *Dialer) Addr() net.Addr { return &net.TCPAddr{} } + +// Wake faz uma varredura imediata (ex.: logo depois de cadastrar um agente). +func (d *Dialer) Wake() { + select { + case d.wake <- struct{}{}: + default: + } +} + +// Links devolve a situação de cada endereço conhecido. +func (d *Dialer) Links() map[string]LinkState { + d.mu.Lock() + defer d.mu.Unlock() + out := make(map[string]LinkState, len(d.links)) + for k, v := range d.links { + out[k] = *v + } + return out +} + +func backoff(fails int) time.Duration { + // curta de propósito: quem acabou de subir o agente não deve esperar; uma tentativa a cada 15 s é custo desprezível + b := 3 * time.Second << min(fails, 3) + return min(b, 15*time.Second) +} + +// Run varre os endereços e disca os que estão sem conexão, respeitando uma espera crescente após falhas. +func (d *Dialer) Run(ctx context.Context) { + every := d.Every + if every <= 0 { + every = 3 * time.Second + } + t := time.NewTicker(every) + defer t.Stop() + for { + d.scan(ctx) + select { + case <-ctx.Done(): + _ = d.Close() + return + case <-t.C: + case <-d.wake: + } + } +} + +func (d *Dialer) scan(ctx context.Context) { + targets, err := d.Targets(ctx) + if err != nil { + return + } + want := map[string]bool{} + now := time.Now() + d.mu.Lock() + for _, tg := range targets { + want[tg.Address] = true + if d.active[tg.Address] { + continue + } + l := d.links[tg.Address] + if l != nil && now.Before(l.NextTry) { + continue + } + if l == nil { + l = &LinkState{Address: tg.Address, Since: now} + d.links[tg.Address] = l + } + if l.State != "error" { + l.State, l.Since = "connecting", now + } + d.active[tg.Address] = true + go d.dialOne(ctx, tg.Address) + } + for a := range d.links { // endereços que saíram do cadastro + if !want[a] && !d.active[a] { + delete(d.links, a) + delete(d.fails, a) + } + } + d.mu.Unlock() +} + +func (d *Dialer) dialOne(ctx context.Context, address string) { + c, err := d.Dial(ctx, address) + d.mu.Lock() + l := d.links[address] + if l == nil { + l = &LinkState{Address: address} + d.links[address] = l + } + if err != nil { + d.active[address] = false + d.fails[address]++ + msg := describeDialErr(err) + if l.State != "error" || l.Error != msg { + slog.Warn("não foi possível conectar no agente", "endereço", address, "erro", msg) + l.Since = time.Now() + } + l.State, l.Error, l.NextTry = "error", msg, time.Now().Add(backoff(d.fails[address])) + d.mu.Unlock() + return + } + d.mu.Unlock() + tc := &trackedConn{Conn: c, remote: &DialedAddr{Target: address, Addr: c.RemoteAddr()}, done: func(ok bool) { d.released(address, ok) }} + select { + case d.conns <- tc: + case <-d.closed: + _ = c.Close() + } +} + +// connected é chamado pelo servidor quando a sessão do agente nesta conexão foi autenticada. +func (d *Dialer) connected(address string) { + d.mu.Lock() + defer d.mu.Unlock() + if l := d.links[address]; l != nil { + l.State, l.Error, l.Since = "connected", "", time.Now() + } + d.fails[address] = 0 +} + +func (d *Dialer) released(address string, _ bool) { + d.mu.Lock() + defer d.mu.Unlock() + d.active[address] = false + if l := d.links[address]; l != nil && l.State == "connected" { + l.State, l.Since, l.NextTry = "connecting", time.Now(), time.Now().Add(time.Second) + return + } + // a conexão abriu, mas a sessão não se estabeleceu (TLS ou autenticação recusados): espera antes de tentar de novo + d.fails[address]++ + if l := d.links[address]; l != nil { + if l.State != "error" { + l.State, l.Error, l.Since = "error", "o agente aceitou a conexão, mas não concluiu a autenticação (token ou impressão digital do Server não conferem?)", time.Now() + } + l.NextTry = time.Now().Add(backoff(d.fails[address])) + } +} + +func describeDialErr(err error) string { + var ne net.Error + switch { + case errors.As(err, &ne) && ne.Timeout(): + return "tempo esgotado: o agente não respondeu (firewall bloqueando a porta, endereço errado ou máquina desligada)" + case errors.Is(err, syscall.ECONNREFUSED): + return "conexão recusada: nada escutando nessa porta (o agente está rodando e com a porta publicada?)" + } + var dnsErr *net.DNSError + if errors.As(err, &dnsErr) { + return "nome não encontrado: " + dnsErr.Name + } + return err.Error() +} + +// DialedAddr é o endereço remoto de uma conexão aberta pelo Server: guarda também o endereço cadastrado (que pode ser um +// nome) para a sessão saber de qual cadastro ela veio. +type DialedAddr struct { + Target string + net.Addr +} + +type trackedConn struct { + net.Conn + remote *DialedAddr + once sync.Once + done func(ok bool) +} + +func (c *trackedConn) RemoteAddr() net.Addr { return c.remote } + +func (c *trackedConn) Close() error { + err := c.Conn.Close() + c.once.Do(func() { c.done(true) }) + return err +} + +// Links devolve a situação das conexões abertas pelo Server (vazio sem discador). +func (s *Server) Links() map[string]LinkState { + if s.Dialer == nil { + return map[string]LinkState{} + } + return s.Dialer.Links() +} + +// Wake pede uma tentativa de conexão imediata (ex.: logo depois de cadastrar ou mudar o endereço de um agente). +func (s *Server) Wake() { + if s.Dialer != nil { + s.Dialer.Wake() + } +} diff --git a/internal/config/config.go b/internal/config/config.go index 9fa4525..9c63ec9 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -9,35 +9,33 @@ import ( ) type Config struct { - Listen string // interface web e API REST, padrão ":8080" (fica atrás do proxy reverso, se houver) - AgentListen string // canal gRPC/TLS dos agentes, padrão ":8443" - DataDir string // certificado TLS e dados locais, padrão "/data" - TrustProxy bool // confiar em X-Forwarded-For/Proto (só atrás de proxy reverso confiável) - TLSCert string // HTTPS direto na interface (opcional): caminho do certificado PEM - TLSKey string // e da chave privada PEM - DBTLS string // TLS com o MySQL: vazio/false = sem TLS; true = com validação; skip-verify; preferred - DBHost string - DBPort string - DBName string - DBUser string - DBPassword string + Listen string // interface web e API REST, padrão ":8080" (fica atrás do proxy reverso, se houver) + DataDir string // certificado TLS e dados locais, padrão "/data" + TrustProxy bool // confiar em X-Forwarded-For/Proto (só atrás de proxy reverso confiável) + TLSCert string // HTTPS direto na interface (opcional): caminho do certificado PEM + TLSKey string // e da chave privada PEM + DBTLS string // TLS com o MySQL: vazio/false = sem TLS; true = com validação; skip-verify; preferred + DBHost string + DBPort string + DBName string + DBUser string + DBPassword string } // Load lê o ambiente. Só CORUJA_DB_PASSWORD é obrigatória. func Load(getenv func(string) string) (Config, error) { c := Config{ - Listen: or(getenv("CORUJA_LISTEN"), ":8080"), - AgentListen: or(getenv("CORUJA_AGENT_LISTEN"), ":8443"), - DataDir: or(getenv("CORUJA_DATA_DIR"), "/data"), - TrustProxy: strings.EqualFold(getenv("CORUJA_TRUST_PROXY"), "true"), - TLSCert: strings.TrimSpace(getenv("CORUJA_TLS_CERT")), - TLSKey: strings.TrimSpace(getenv("CORUJA_TLS_KEY")), - DBTLS: strings.ToLower(strings.TrimSpace(getenv("CORUJA_DB_TLS"))), - DBHost: or(getenv("CORUJA_DB_HOST"), "db"), - DBPort: or(getenv("CORUJA_DB_PORT"), "3306"), - DBName: or(getenv("CORUJA_DB_NAME"), "corujabackup"), - DBUser: or(getenv("CORUJA_DB_USER"), "corujabackup"), - DBPassword: getenv("CORUJA_DB_PASSWORD"), + Listen: or(getenv("CORUJA_LISTEN"), ":8080"), + DataDir: or(getenv("CORUJA_DATA_DIR"), "/data"), + TrustProxy: strings.EqualFold(getenv("CORUJA_TRUST_PROXY"), "true"), + TLSCert: strings.TrimSpace(getenv("CORUJA_TLS_CERT")), + TLSKey: strings.TrimSpace(getenv("CORUJA_TLS_KEY")), + DBTLS: strings.ToLower(strings.TrimSpace(getenv("CORUJA_DB_TLS"))), + DBHost: or(getenv("CORUJA_DB_HOST"), "db"), + DBPort: or(getenv("CORUJA_DB_PORT"), "3306"), + DBName: or(getenv("CORUJA_DB_NAME"), "corujabackup"), + DBUser: or(getenv("CORUJA_DB_USER"), "corujabackup"), + DBPassword: getenv("CORUJA_DB_PASSWORD"), } if strings.TrimSpace(c.DBPassword) == "" { return c, fmt.Errorf("a variável CORUJA_DB_PASSWORD é obrigatória") diff --git a/internal/config/config_test.go b/internal/config/config_test.go index ebaf394..0931a3b 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -18,7 +18,7 @@ func TestPadroes(t *testing.T) { if err != nil { t.Fatal(err) } - if c.Listen != ":8080" || c.AgentListen != ":8443" || c.DataDir != "/data" || c.DBHost != "db" || c.DBName != "corujabackup" || c.DBUser != "corujabackup" || c.DBPort != "3306" { + if c.Listen != ":8080" || c.DataDir != "/data" || c.DBHost != "db" || c.DBName != "corujabackup" || c.DBUser != "corujabackup" || c.DBPort != "3306" { t.Fatalf("padrões inesperados: %+v", c) } } diff --git a/internal/db/migrations/008_conexao_invertida.sql b/internal/db/migrations/008_conexao_invertida.sql new file mode 100644 index 0000000..a566a8c --- /dev/null +++ b/internal/db/migrations/008_conexao_invertida.sql @@ -0,0 +1,3 @@ +-- Coruja Backup · migração 008: o Server conecta nos agentes (endereço host:porta de cada agente e de cada token pendente) +ALTER TABLE agents ADD COLUMN address VARCHAR(300) NOT NULL DEFAULT ''; +ALTER TABLE enrollment_tokens ADD COLUMN address VARCHAR(300) NOT NULL DEFAULT ''; diff --git a/internal/e2e/e2e_test.go b/internal/e2e/e2e_test.go index 349b40b..91e6f60 100644 --- a/internal/e2e/e2e_test.go +++ b/internal/e2e/e2e_test.go @@ -69,22 +69,24 @@ func newRig(t *testing.T, ep cloudmgr.Endpoints) *rig { srv := agentsrv.New(st, "teste") srv.Cloud = mgr srv.Box = box - lis, _ := net.Listen("tcp", "127.0.0.1:0") ctx, cancel := context.WithCancel(context.Background()) t.Cleanup(cancel) - go srv.Serve(ctx, lis, cert) - + // conexão invertida: o Server disca o endereço cadastrado do agente + dialer := agentsrv.NewDialer(st.DialTargets) + dialer.Every = 200 * time.Millisecond + srv.Dialer = dialer + go dialer.Run(ctx) + go srv.Serve(ctx, dialer, cert) + + probe, _ := net.Listen("tcp", "127.0.0.1:0") + agentAddr := probe.Addr().String() + probe.Close() fp := tlsutil.Fingerprint(cert) tok, _ := enroll.New(fp) pt, _ := enroll.Parse(tok) - if err := st.CreateEnrollToken(ctx, pt.Hash(), "srv-e2e", 0, time.Now().Add(time.Hour)); err != nil { + if err := st.CreateEnrollTokenAt(ctx, pt.Hash(), "srv-e2e", agentAddr, 0, time.Now().Add(time.Hour)); err != nil { t.Fatal(err) } - cr, err := agentcore.Enroll(ctx, slog.New(slog.NewTextHandler(io.Discard, nil)), lis.Addr().String(), tok) - if err != nil { - t.Fatal(err) - } - a, _ := st.AgentByID(ctx, cr.AgentID) host, bk := t.TempDir(), t.TempDir() for name, content := range map[string]string{"srv/app/index.html": "olá mundo", "srv/app/dados.bin": strings.Repeat("0123456789", 50000), "etc/app.conf": "conf"} { @@ -97,8 +99,24 @@ func newRig(t *testing.T, ep cloudmgr.Endpoints) *rig { core := agentcore.New(agentcore.Config{HostRoot: host, BackupDir: bk, DestDir: destDir}, local, slog.New(slog.NewTextHandler(io.Discard, nil))) core.SetUploadOptions(uploader.Options{Retries: 2, Sleep: func(context.Context, time.Duration) {}}) go core.Run(ctx) - go agentcore.Run(ctx, slog.New(slog.NewTextHandler(io.Discard, nil)), cr, core) - + statePath := filepath.Join(t.TempDir(), "agent.json") + go agentcore.Listen(ctx, slog.New(slog.NewTextHandler(io.Discard, nil)), agentcore.ListenConfig{Addr: agentAddr, Token: tok, StatePath: statePath}, nil, core) + + var a *store.Agent + for deadline := time.Now().Add(15 * time.Second); time.Now().Before(deadline) && a == nil; time.Sleep(100 * time.Millisecond) { + ags, _ := st.ListAgents(ctx) + for i := range ags { + if ags[i].Name == "srv-e2e" { + a = &ags[i] + } + } + } + if a == nil { + t.Fatal("o agente não foi matriculado pela conexão invertida") + } + if a.Address != agentAddr { + t.Fatalf("o endereço do token deveria passar para o agente: %q", a.Address) + } r := &rig{t: t, st: st, srv: srv, mgr: mgr, core: core, agent: a, hostDir: host, bkDir: bk, destDir: destDir, cancel: cancel} r.waitOnline() return r diff --git a/internal/e2e/reverse_test.go b/internal/e2e/reverse_test.go new file mode 100644 index 0000000..156be25 --- /dev/null +++ b/internal/e2e/reverse_test.go @@ -0,0 +1,150 @@ +package e2e + +import ( + "context" + "io" + "log/slog" + "net" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/AprendendoLinux/corujabackup/internal/agentcore" + "github.com/AprendendoLinux/corujabackup/internal/agentsrv" + "github.com/AprendendoLinux/corujabackup/internal/enroll" + "github.com/AprendendoLinux/corujabackup/internal/store" + "github.com/AprendendoLinux/corujabackup/internal/testutil" + "github.com/AprendendoLinux/corujabackup/internal/tlsutil" +) + +func freeAddr(t *testing.T) string { + t.Helper() + l, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer l.Close() + return l.Addr().String() +} + +func quiet() *slog.Logger { return slog.New(slog.NewTextHandler(io.Discard, nil)) } + +// startServer sobe um Server (só o canal dos agentes) que disca os endereços cadastrados no banco. +func startServer(t *testing.T, ctx context.Context, st *store.Store) (*agentsrv.Server, *agentsrv.Dialer, string) { + t.Helper() + cert, err := tlsutil.LoadOrCreate(t.TempDir()) + if err != nil { + t.Fatal(err) + } + srv := agentsrv.New(st, "teste") + d := agentsrv.NewDialer(st.DialTargets) + d.Every = 150 * time.Millisecond + srv.Dialer = d + go d.Run(ctx) + go srv.Serve(ctx, d, cert) + return srv, d, tlsutil.Fingerprint(cert) +} + +func waitFor(t *testing.T, what string, cond func() bool) { + t.Helper() + for deadline := time.Now().Add(15 * time.Second); time.Now().Before(deadline); time.Sleep(100 * time.Millisecond) { + if cond() { + return + } + } + t.Fatal("tempo esgotado esperando: " + what) +} + +func agentNamed(st *store.Store, name string) *store.Agent { + ags, _ := st.ListAgents(context.Background()) + for i := range ags { + if ags[i].Name == name { + return &ags[i] + } + } + return nil +} + +func TestConexaoInvertidaImpostorEReinicio(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + st := store.New(testutil.DB(t)) + _, _, fp := startServer(t, ctx, st) + + // 1) Um "Server" impostor, com outro certificado, conhece o endereço do agente e o disca primeiro: o agente recusa, + // porque a impressão digital fixada no token é a do Server verdadeiro. + agentAddr := freeAddr(t) + impCtx, stopImp := context.WithCancel(ctx) + impStore := store.New(testutil.DB(t)) + impSrv, _, impFP := startServer(t, impCtx, impStore) + impTok, _ := enroll.New(impFP) + ip, _ := enroll.Parse(impTok) + if err := impStore.CreateEnrollTokenAt(ctx, ip.Hash(), "isca", agentAddr, 0, time.Now().Add(time.Hour)); err != nil { + t.Fatal(err) + } + + tok, _ := enroll.New(fp) + pt, _ := enroll.Parse(tok) + statePath := filepath.Join(t.TempDir(), "agent.json") + local, _ := agentcore.NewState(t.TempDir()) + core := agentcore.New(agentcore.Config{HostRoot: t.TempDir(), BackupDir: t.TempDir()}, local, quiet()) + go core.Run(ctx) + agentCtx, stopAgent := context.WithCancel(ctx) + go agentcore.Listen(agentCtx, quiet(), agentcore.ListenConfig{Addr: agentAddr, Token: tok, StatePath: statePath}, nil, core) + + time.Sleep(1500 * time.Millisecond) // o impostor tenta várias vezes + if len(impSrv.Online()) != 0 || agentNamed(impStore, "isca") != nil { + t.Fatal("o agente aceitou um Server com outro certificado") + } + if _, err := agentcore.LoadCredentials(statePath); err == nil { + t.Fatal("o agente não deveria ter credencial antes do Server verdadeiro conectar") + } + stopImp() + + // 2) O Server verdadeiro tem o token com o endereço: conecta, matricula e o agente fica online + if err := st.CreateEnrollTokenAt(ctx, pt.Hash(), "srv-inv", agentAddr, 0, time.Now().Add(time.Hour)); err != nil { + t.Fatal(err) + } + waitFor(t, "matrícula", func() bool { return agentNamed(st, "srv-inv") != nil }) + a := agentNamed(st, "srv-inv") + cr, err := agentcore.LoadCredentials(statePath) + if err != nil || cr.AgentID != a.ID || cr.Server != "" { + t.Fatalf("credencial gravada: %v %+v", err, cr) + } + + // 3) O agente reinicia (sem token, só com a credencial gravada): o Server reconecta sozinho + stopAgent() + time.Sleep(300 * time.Millisecond) + agentCtx2, stopAgent2 := context.WithCancel(ctx) + defer stopAgent2() + go agentcore.Listen(agentCtx2, quiet(), agentcore.ListenConfig{Addr: agentAddr, StatePath: statePath}, cr, core) + waitFor(t, "reconexão", func() bool { + g, _ := st.AgentByID(ctx, a.ID) + return g.LastSeenAt != nil && time.Since(*g.LastSeenAt) < 3*time.Second && g.Address == agentAddr + }) +} + +func TestDiscadorInformaPortaFechadaETempoEsgotado(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + st := store.New(testutil.DB(t)) + _, d, fp := startServer(t, ctx, st) + closed := freeAddr(t) // ninguém escutando + tok, _ := enroll.New(fp) + pt, _ := enroll.Parse(tok) + if err := st.CreateEnrollTokenAt(ctx, pt.Hash(), "srv-fechado", closed, 0, time.Now().Add(time.Hour)); err != nil { + t.Fatal(err) + } + waitFor(t, "estado de erro", func() bool { return d.Links()[closed].State == "error" }) + if l := d.Links()[closed]; !strings.Contains(l.Error, "recusada") || l.NextTry.IsZero() { + t.Fatalf("mensagem: %+v", l) + } + // o token excluído some da lista de conexões + _ = st.DeleteToken(ctx, 1) + ts, _ := st.ListPendingTokens(ctx) + for _, x := range ts { + _ = st.DeleteToken(ctx, x.ID) + } + waitFor(t, "endereço removido", func() bool { _, ok := d.Links()[closed]; return !ok }) +} diff --git a/internal/httpapi/handlers_admin.go b/internal/httpapi/handlers_admin.go index 2072daf..8a18172 100644 --- a/internal/httpapi/handlers_admin.go +++ b/internal/httpapi/handlers_admin.go @@ -2,6 +2,7 @@ package httpapi import ( "errors" + "github.com/AprendendoLinux/corujabackup/internal/agentsrv" "net/http" "regexp" "strconv" @@ -176,8 +177,14 @@ func (s *Server) audit(w http.ResponseWriter, r *http.Request, _ *ctxUser) { type agentView struct { store.Agent - Online bool `json:"online"` - ConnectedAt *time.Time `json:"connected_at"` + Online bool `json:"online"` + ConnectedAt *time.Time `json:"connected_at"` + Link *agentsrv.LinkState `json:"link,omitempty"` // situação da conexão do Server com o agente (quando offline) +} + +type pendingView struct { + store.PendingToken + Link *agentsrv.LinkState `json:"link,omitempty"` } func (s *Server) listAgents(w http.ResponseWriter, r *http.Request, _ *ctxUser) { @@ -190,22 +197,38 @@ func (s *Server) listAgents(w http.ResponseWriter, r *http.Request, _ *ctxUser) if s.Agents != nil { online = s.Agents.Online() } + links := map[string]agentsrv.LinkState{} + if s.Agents != nil { + links = s.Agents.Links() + } out := make([]agentView, 0, len(ags)) for _, a := range ags { v := agentView{Agent: a} if t, ok := online[a.ID]; ok && a.RevokedAt == nil { v.Online, v.ConnectedAt = true, &t } + if l, ok := links[a.Address]; ok && a.RevokedAt == nil && !v.Online { + v.Link = &l + } out = append(out, v) } tokens, _ := s.Store.ListPendingTokens(r.Context()) - writeJSON(w, 200, map[string]any{"agents": out, "pending_tokens": tokens}) + pending := make([]pendingView, 0, len(tokens)) + for _, t := range tokens { + p := pendingView{PendingToken: t} + if l, ok := links[t.Address]; ok { + p.Link = &l + } + pending = append(pending, p) + } + writeJSON(w, 200, map[string]any{"agents": out, "pending_tokens": pending}) } func (s *Server) createToken(w http.ResponseWriter, r *http.Request, cu *ctxUser) { var in struct { Name string `json:"name"` TTLHours int `json:"ttl_hours"` + Address string `json:"address"` } if !decodeLoose(w, r, &in) { return @@ -215,6 +238,11 @@ func (s *Server) createToken(w http.ResponseWriter, r *http.Request, cu *ctxUser writeErr(w, 400, "nome inválido: use 2 a 100 caracteres (letras, números, ponto, hífen ou sublinhado)") return } + addr, ok := parseAgentAddress(in.Address) + if !ok || addr == "" { + writeErr(w, 400, "informe o endereço do agente: IP ou nome e a porta (ex.: 192.0.2.10:23847)") + return + } if in.TTLHours <= 0 { in.TTLHours = 24 } @@ -228,7 +256,7 @@ func (s *Server) createToken(w http.ResponseWriter, r *http.Request, cu *ctxUser } parsed, _ := enroll.Parse(tok) exp := s.clock().Add(time.Duration(in.TTLHours) * time.Hour) - if err := s.Store.CreateEnrollToken(r.Context(), parsed.Hash(), in.Name, cu.User.ID, exp); err != nil { + if err := s.Store.CreateEnrollTokenAt(r.Context(), parsed.Hash(), in.Name, addr, cu.User.ID, exp); err != nil { if errors.Is(err, store.ErrDuplicate) { writeErr(w, 409, "já existe um agente com esse nome") return @@ -236,8 +264,11 @@ func (s *Server) createToken(w http.ResponseWriter, r *http.Request, cu *ctxUser writeErr(w, 500, "erro interno") return } - s.Store.Audit(r.Context(), cu.User.ID, cu.User.Username, "agent.token_created", in.Name, s.clientIP(r)) - writeJSON(w, 201, map[string]any{"token": tok, "expires_at": exp, "name": in.Name}) // o token só aparece agora + s.Store.Audit(r.Context(), cu.User.ID, cu.User.Username, "agent.token_created", in.Name+" "+addr, s.clientIP(r)) + if s.Agents != nil { + s.Agents.Wake() + } + writeJSON(w, 201, map[string]any{"token": tok, "expires_at": exp, "name": in.Name, "address": addr}) // o token só aparece agora } func (s *Server) deleteToken(w http.ResponseWriter, r *http.Request, cu *ctxUser) { @@ -252,16 +283,47 @@ func (s *Server) deleteToken(w http.ResponseWriter, r *http.Request, cu *ctxUser func (s *Server) renameAgent(w http.ResponseWriter, r *http.Request, cu *ctxUser) { id, ok := pathID(r) - var in struct{ Name string } + var in struct { + Name *string `json:"name"` + Address *string `json:"address"` + } if !ok || !decodeLoose(w, r, &in) { return } - in.Name = strings.TrimSpace(in.Name) - if !agentNameRE.MatchString(in.Name) { + if in.Address != nil { + addr, ok := parseAgentAddress(*in.Address) + if !ok || addr == "" { + writeErr(w, 400, "endereço inválido: use IP ou nome e a porta (ex.: 192.0.2.10:23847)") + return + } + if err := s.Store.SetAgentAddress(r.Context(), id, addr); err != nil { + if errors.Is(err, store.ErrNotFound) { + writeErr(w, 404, "agente não encontrado") + return + } + writeErr(w, 500, "erro interno") + return + } + s.Store.Audit(r.Context(), cu.User.ID, cu.User.Username, "agent.address", addr, s.clientIP(r)) + if s.Agents != nil { + s.Agents.Wake() + } + if in.Name == nil { + writeJSON(w, 200, map[string]bool{"ok": true}) + return + } + } + if in.Name == nil { + writeErr(w, 400, "nada para alterar") + return + } + name := strings.TrimSpace(*in.Name) + if !agentNameRE.MatchString(name) { writeErr(w, 400, "nome inválido") return } - if err := s.Store.RenameAgent(r.Context(), id, in.Name); err != nil { + in.Name = &name + if err := s.Store.RenameAgent(r.Context(), id, name); err != nil { if errors.Is(err, store.ErrDuplicate) { writeErr(w, 409, "já existe um agente com esse nome") return @@ -269,7 +331,7 @@ func (s *Server) renameAgent(w http.ResponseWriter, r *http.Request, cu *ctxUser writeErr(w, 500, "erro interno") return } - s.Store.Audit(r.Context(), cu.User.ID, cu.User.Username, "agent.renamed", in.Name, s.clientIP(r)) + s.Store.Audit(r.Context(), cu.User.ID, cu.User.Username, "agent.renamed", name, s.clientIP(r)) writeJSON(w, 200, map[string]bool{"ok": true}) } diff --git a/internal/httpapi/handlers_browse.go b/internal/httpapi/handlers_browse.go index 9561b50..c48fb37 100644 --- a/internal/httpapi/handlers_browse.go +++ b/internal/httpapi/handlers_browse.go @@ -94,9 +94,7 @@ func (s *Server) destFolders(w http.ResponseWriter, r *http.Request, _ *ctxUser) writeJSON(w, 200, map[string]any{"folders": slices.Compact(out)}) } -const settingAgentAddress = "agent_address" - -// parseAgentAddress valida "host:porta" (o texto vai para dentro dos comandos de instalação, então é restrito). +// parseAgentAddress valida o endereço "host:porta" onde o Server conecta no agente. func parseAgentAddress(v string) (string, bool) { v = strings.TrimSpace(v) if v == "" { @@ -112,23 +110,3 @@ func parseAgentAddress(v string) (string, bool) { } return net.JoinHostPort(host, strconv.Itoa(n)), true } - -func (s *Server) saveAgentAddress(w http.ResponseWriter, r *http.Request, cu *ctxUser) { - var in struct { - Address string `json:"address"` - } - if !decode(w, r, &in) { - return - } - addr, ok := parseAgentAddress(in.Address) - if !ok { - writeErr(w, 400, "informe no formato endereço:porta (ex.: backup.exemplo.com:8443 ou 203.0.113.10:8444), sem http://") - return - } - if err := s.Store.SetSetting(r.Context(), settingAgentAddress, addr); err != nil { - writeErr(w, 500, "erro interno") - return - } - s.Store.Audit(r.Context(), cu.User.ID, cu.User.Username, "system.agent_address", addr, s.clientIP(r)) - writeJSON(w, 200, map[string]string{"agent_address": addr}) -} diff --git a/internal/httpapi/httpapi.go b/internal/httpapi/httpapi.go index 3e48a1d..310772d 100644 --- a/internal/httpapi/httpapi.go +++ b/internal/httpapi/httpapi.go @@ -14,6 +14,7 @@ import ( "sync/atomic" "time" + "github.com/AprendendoLinux/corujabackup/internal/agentsrv" "github.com/AprendendoLinux/corujabackup/internal/cloud" "github.com/AprendendoLinux/corujabackup/internal/cloudmgr" "github.com/AprendendoLinux/corujabackup/internal/netdest" @@ -37,6 +38,8 @@ type AgentHub interface { CancelRun(agentID int64, runUID string) error Call(ctx context.Context, agentID int64, kind string, payload []byte, timeout time.Duration) ([]byte, error) Action(agentID int64, act *pb.AgentAction) error + Links() map[string]agentsrv.LinkState + Wake() } // CloudAdmin é o que a API precisa do gerenciador de contas de nuvem (cloudmgr.Manager). @@ -67,7 +70,6 @@ type Server struct { Started time.Time Web http.Handler Fingerprint string // impressão digital do certificado do canal dos agentes - AgentPort string TrustProxy bool SetupCode string // código de uma execução, mostrado nos logs, exigido na configuração inicial @@ -137,7 +139,6 @@ func (s *Server) Routes() http.Handler { mux.HandleFunc("DELETE /api/agents/{id}", s.authed(roleOperator, s.deleteAgent)) mux.HandleFunc("GET /api/agents/{id}/containers", s.authed(roleOperator, s.agentContainers)) mux.HandleFunc("GET /api/agents/{id}/browse", s.authed(roleOperator, s.agentBrowse)) - mux.HandleFunc("PUT /api/system/agent-address", s.authed(roleAdmin, s.saveAgentAddress)) mux.HandleFunc("POST /api/agents/{id}/db-test", s.authed(roleOperator, s.dbTest)) mux.HandleFunc("GET /api/notifications/channels", s.authed(roleAdmin, s.listChannels)) mux.HandleFunc("POST /api/notifications/channels", s.authed(roleAdmin, s.createChannel)) @@ -257,12 +258,7 @@ func (s *Server) version(w http.ResponseWriter, r *http.Request) { } func (s *Server) system(w http.ResponseWriter, r *http.Request, _ *ctxUser) { - set, err := s.Store.GetSettings(r.Context(), settingAgentAddress) - if err != nil { - writeErr(w, 500, "erro interno") - return - } - writeJSON(w, 200, map[string]any{"version": version.Version, "agent_port": s.AgentPort, "agent_address": set[settingAgentAddress], "fingerprint": s.Fingerprint}) + writeJSON(w, 200, map[string]any{"version": version.Version, "fingerprint": s.Fingerprint}) } func writeJSON(w http.ResponseWriter, code int, v any) { diff --git a/internal/httpapi/httpapi_test.go b/internal/httpapi/httpapi_test.go index 4219d6b..4b9a189 100644 --- a/internal/httpapi/httpapi_test.go +++ b/internal/httpapi/httpapi_test.go @@ -40,6 +40,7 @@ type fakeHub struct { actions []*pb.AgentAction callOut []byte callErr error + wakes int } func (f *fakeHub) Online() map[int64]time.Time { return map[int64]time.Time{} } @@ -53,6 +54,10 @@ func (f *fakeHub) RunNow(_, jobID int64, uid string) error { return nil } func (f *fakeHub) CancelRun(int64, string) error { return nil } +func (f *fakeHub) Links() map[string]agentsrv.LinkState { + return map[string]agentsrv.LinkState{"10.0.0.9:8443": {Address: "10.0.0.9:8443", State: "error", Error: "conexão recusada"}} +} +func (f *fakeHub) Wake() { f.wakes++ } func (f *fakeHub) Action(_ int64, a *pb.AgentAction) error { if f.offline { return agentsrv.ErrOffline @@ -121,7 +126,7 @@ func newEnv(t *testing.T) *env { d := testutil.DB(t) e := &env{t: t, hub: &fakeHub{}, now: time.Now().UTC().Truncate(time.Second)} box, _ := secrets.Open(t.TempDir()) - e.api = &Server{DB: d, Store: store.New(d), Box: box, Pinger: d, Agents: e.hub, Started: time.Now(), Fingerprint: strings.Repeat("ab", 32), AgentPort: "8443", + e.api = &Server{DB: d, Store: store.New(d), Box: box, Pinger: d, Agents: e.hub, Started: time.Now(), Fingerprint: strings.Repeat("ab", 32), LoginLimiter: ratelimit.New(5, 15*time.Minute), now: func() time.Time { return e.now }} e.srv = httptest.NewServer(e.api.Routes()) t.Cleanup(e.srv.Close) @@ -239,7 +244,7 @@ func TestSessaoLogoutEPermissoes(t *testing.T) { if code, _ := o.do("GET", "/api/users", nil); code != 403 { t.Fatalf("operador não administra usuários: %d", code) } - if code, _ := o.do("POST", "/api/agents/tokens", map[string]any{"name": "srv-1"}); code != 201 { + if code, _ := o.do("POST", "/api/agents/tokens", map[string]any{"name": "srv-1", "address": "10.0.0.5:8443"}); code != 201 { t.Fatalf("operador deveria criar token: %d", code) } adm.mustOK("POST", "/api/logout", nil) @@ -345,10 +350,19 @@ func TestUltimoAdminProtegidoESenha(t *testing.T) { func TestTokensDeMatriculaEAgentes(t *testing.T) { e := newEnv(t) c := setupAdmin(e) - if code, _ := c.do("POST", "/api/agents/tokens", map[string]any{"name": "a"}); code != 400 { + if code, _ := c.do("POST", "/api/agents/tokens", map[string]any{"name": "a", "address": "10.0.0.9:8443"}); code != 400 { t.Fatalf("nome curto: %d", code) } - tk := c.mustOK("POST", "/api/agents/tokens", map[string]any{"name": "umami-server2", "ttl_hours": 9999}) + // o endereço onde o Server conecta no agente é obrigatório e validado + for _, bad := range []string{"", "semporta", "http://x:8443", "x:0", "x:70000", "x y:1", `x";rm -rf /:1`, "$(id):8443", "x:abc"} { + if code, _ := c.do("POST", "/api/agents/tokens", map[string]any{"name": "umami-server2", "address": bad}); code != 400 { + t.Errorf("endereço %q deveria ser recusado: %d", bad, code) + } + } + tk := c.mustOK("POST", "/api/agents/tokens", map[string]any{"name": "umami-server2", "ttl_hours": 9999, "address": " 10.0.0.9:8443 "}) + if tk["address"] != "10.0.0.9:8443" || e.hub.wakes != 1 { + t.Fatalf("endereço normalizado e conexão imediata: %v %d", tk["address"], e.hub.wakes) + } if !strings.HasPrefix(tk["token"].(string), "cb1."+strings.Repeat("ab", 16)+".") { t.Fatalf("token deveria carregar a impressão digital: %v", tk["token"]) } @@ -356,15 +370,28 @@ func TestTokensDeMatriculaEAgentes(t *testing.T) { if len(list["pending_tokens"].([]any)) != 1 || strings.Contains(jsonString(list), "cb1.") { t.Fatalf("o token em si nunca deve ser listado: %v", list) } + if p := list["pending_tokens"].([]any)[0].(map[string]any); p["address"] != "10.0.0.9:8443" || p["link"].(map[string]any)["error"] != "conexão recusada" { + t.Fatalf("o token pendente deve mostrar o endereço e a situação da conexão: %v", p) + } // agente criado direto no banco para testar renomear/revogar/excluir a, err := e.api.Store.Enroll(context.Background(), enrollHashOf(t, c, e), "host", "linux", "amd64", "0.0.1", "10.0.0.1", auth.SHA256Hex("cred")) if err != nil { t.Fatal(err) } - if code, _ := c.do("POST", "/api/agents/tokens", map[string]any{"name": "umami-server2"}); code != 409 { + if a.Address != "10.0.0.9:8443" { + t.Fatalf("o agente herda o endereço do token: %q", a.Address) + } + if code, _ := c.do("POST", "/api/agents/tokens", map[string]any{"name": "umami-server2", "address": "10.0.0.8:8443"}); code != 409 { t.Fatalf("nome de agente existente: %d", code) } c.mustOK("PATCH", "/api/agents/"+itoa(int(a.ID)), map[string]string{"name": "umami-s2"}) + if code, _ := c.do("PATCH", "/api/agents/"+itoa(int(a.ID)), map[string]string{"address": "sem-porta"}); code != 400 { + t.Fatalf("endereço inválido: %d", code) + } + c.mustOK("PATCH", "/api/agents/"+itoa(int(a.ID)), map[string]string{"address": "[2001:db8::1]:9443"}) + if g, _ := e.api.Store.AgentByID(context.Background(), a.ID); g.Address != "[2001:db8::1]:9443" || g.Name != "umami-s2" { + t.Fatalf("endereço: %+v", g) + } c.mustOK("POST", "/api/agents/"+itoa(int(a.ID))+"/revoke", nil) if len(e.hub.revoked) != 1 || e.hub.revoked[0] != a.ID { t.Fatalf("revogar deveria derrubar o canal: %v", e.hub.revoked) @@ -833,23 +860,7 @@ func TestSeletorDePastasEEnderecoDosAgentes(t *testing.T) { t.Fatalf("'..' deveria ser recusado: %d", code) } - // endereço dos agentes - if r = adm.mustOK("GET", "/api/system", nil); r["agent_address"] != "" { - t.Fatalf("padrão deveria ser vazio: %v", r) - } - for _, bad := range []string{"semporta", "http://x:8443", "x:0", "x:70000", "x y:1", `x";rm -rf /:1`, "$(id):8443", "x:abc"} { - if code, _ := adm.do("PUT", "/api/system/agent-address", map[string]string{"address": bad}); code != 400 { - t.Errorf("%q deveria ser recusado: %d", bad, code) - } - } - for _, good := range []string{"backup.exemplo.com:8443", "203.0.113.10:8444", "[2001:db8::1]:8443", ""} { - adm.mustOK("PUT", "/api/system/agent-address", map[string]string{"address": " " + good + " "}) - if r = adm.mustOK("GET", "/api/system", nil); r["agent_address"] != good { - t.Errorf("gravou %v, esperado %q", r["agent_address"], good) - } - } - - // permissões: só leitura não navega; operador navega, mas não muda o endereço + // permissões: só leitura não navega; operador navega for name, role := range map[string]string{"leitor3": "viewer", "oper3": "operator"} { adm.mustOK("POST", "/api/users", map[string]string{"username": name, "password": pw, "role": role}) u := e.client() @@ -864,9 +875,6 @@ func TestSeletorDePastasEEnderecoDosAgentes(t *testing.T) { if code, _ := u.do("GET", "/api/clouds/1/folders", nil); code != want { t.Errorf("%s listando destino: %d", role, code) } - if code, _ := u.do("PUT", "/api/system/agent-address", map[string]string{"address": "x:1"}); code != 403 { - t.Errorf("%s não pode mudar o endereço: %d", role, code) - } } if code, _ := e.client().do("GET", browse+"?area=host", nil); code != 401 { t.Errorf("sem login: %d", code) diff --git a/internal/store/agents.go b/internal/store/agents.go index 05b893b..3c7b353 100644 --- a/internal/store/agents.go +++ b/internal/store/agents.go @@ -20,14 +20,15 @@ type Agent struct { CreatedAt time.Time `json:"created_at"` LastSeenAt *time.Time `json:"last_seen_at"` RevokedAt *time.Time `json:"revoked_at"` + Address string `json:"address"` // host:porta onde o Server conecta no agente } -const agentCols = "id, name, hostname, os, arch, agent_version, docker_available, ip, credential_hash, created_at, last_seen_at, revoked_at" +const agentCols = "id, name, hostname, os, arch, agent_version, docker_available, ip, credential_hash, created_at, last_seen_at, revoked_at, address" func scanAgent(r interface{ Scan(...any) error }) (*Agent, error) { var a Agent var ls, rv sql.NullTime - if err := r.Scan(&a.ID, &a.Name, &a.Hostname, &a.OS, &a.Arch, &a.AgentVersion, &a.DockerAvailable, &a.IP, &a.CredentialHash, &a.CreatedAt, &ls, &rv); err != nil { + if err := r.Scan(&a.ID, &a.Name, &a.Hostname, &a.OS, &a.Arch, &a.AgentVersion, &a.DockerAvailable, &a.IP, &a.CredentialHash, &a.CreatedAt, &ls, &rv, &a.Address); err != nil { if errors.Is(err, sql.ErrNoRows) { return nil, ErrNotFound } @@ -46,6 +47,11 @@ func scanAgent(r interface{ Scan(...any) error }) (*Agent, error) { // CreateEnrollToken registra (só o hash de) um token de matrícula de uso único. func (s *Store) CreateEnrollToken(ctx context.Context, tokenHash, name string, createdBy int64, expires time.Time) error { + return s.CreateEnrollTokenAt(ctx, tokenHash, name, "", createdBy, expires) +} + +// CreateEnrollTokenAt registra o token junto com o endereço (host:porta) onde o Server vai conectar no novo agente. +func (s *Store) CreateEnrollTokenAt(ctx context.Context, tokenHash, name, address string, createdBy int64, expires time.Time) error { var by any if createdBy > 0 { by = createdBy @@ -57,7 +63,7 @@ func (s *Store) CreateEnrollToken(ctx context.Context, tokenHash, name string, c if n > 0 { return ErrDuplicate } - _, err := s.DB.ExecContext(ctx, "INSERT INTO enrollment_tokens (token_hash, name, created_by, expires_at) VALUES (?,?,?,?)", tokenHash, name, by, expires.UTC()) + _, err := s.DB.ExecContext(ctx, "INSERT INTO enrollment_tokens (token_hash, name, address, created_by, expires_at) VALUES (?,?,?,?,?)", tokenHash, name, address, by, expires.UTC()) return err } @@ -66,10 +72,11 @@ type PendingToken struct { Name string `json:"name"` CreatedAt time.Time `json:"created_at"` ExpiresAt time.Time `json:"expires_at"` + Address string `json:"address"` } func (s *Store) ListPendingTokens(ctx context.Context) ([]PendingToken, error) { - rows, err := s.DB.QueryContext(ctx, "SELECT id, name, created_at, expires_at FROM enrollment_tokens WHERE used_at IS NULL AND expires_at > UTC_TIMESTAMP() ORDER BY id DESC") + rows, err := s.DB.QueryContext(ctx, "SELECT id, name, created_at, expires_at, address FROM enrollment_tokens WHERE used_at IS NULL AND expires_at > UTC_TIMESTAMP() ORDER BY id DESC") if err != nil { return nil, err } @@ -77,7 +84,7 @@ func (s *Store) ListPendingTokens(ctx context.Context) ([]PendingToken, error) { out := []PendingToken{} for rows.Next() { var t PendingToken - if err := rows.Scan(&t.ID, &t.Name, &t.CreatedAt, &t.ExpiresAt); err != nil { + if err := rows.Scan(&t.ID, &t.Name, &t.CreatedAt, &t.ExpiresAt, &t.Address); err != nil { return nil, err } out = append(out, t) @@ -99,16 +106,16 @@ func (s *Store) Enroll(ctx context.Context, tokenHash, hostname, os_, arch, vers } defer tx.Rollback() var tokID int64 - var name string - err = tx.QueryRowContext(ctx, "SELECT id, name FROM enrollment_tokens WHERE token_hash=? AND used_at IS NULL AND expires_at > UTC_TIMESTAMP() FOR UPDATE", tokenHash).Scan(&tokID, &name) + var name, address string + err = tx.QueryRowContext(ctx, "SELECT id, name, address FROM enrollment_tokens WHERE token_hash=? AND used_at IS NULL AND expires_at > UTC_TIMESTAMP() FOR UPDATE", tokenHash).Scan(&tokID, &name, &address) if errors.Is(err, sql.ErrNoRows) { return nil, ErrNotFound } if err != nil { return nil, err } - res, err := tx.ExecContext(ctx, "INSERT INTO agents (name, hostname, os, arch, agent_version, ip, credential_hash, last_seen_at) VALUES (?,?,?,?,?,?,?, UTC_TIMESTAMP())", - name, hostname, os_, arch, version, ip, credHash) + res, err := tx.ExecContext(ctx, "INSERT INTO agents (name, hostname, os, arch, agent_version, ip, credential_hash, last_seen_at, address) VALUES (?,?,?,?,?,?,?, UTC_TIMESTAMP(), ?)", + name, hostname, os_, arch, version, ip, credHash, address) if err != nil { if isDup(err) { return nil, ErrDuplicate @@ -175,3 +182,43 @@ func (s *Store) DeleteAgent(ctx context.Context, id int64) error { _, err := s.DB.ExecContext(ctx, "DELETE FROM agents WHERE id=?", id) return err } + +// SetAgentAddress muda o endereço (host:porta) onde o Server conecta no agente. +func (s *Store) SetAgentAddress(ctx context.Context, id int64, address string) error { + res, err := s.DB.ExecContext(ctx, "UPDATE agents SET address=? WHERE id=?", address, id) + if err != nil { + return err + } + if n, _ := res.RowsAffected(); n == 0 { + if _, err := s.AgentByID(ctx, id); err != nil { + return err + } + } + return nil +} + +// DialTarget é um endereço que o Server deve manter conectado: um agente ativo ou um token ainda não usado. +type DialTarget struct { + Address string + AgentID int64 // 0 = token pendente + Name string +} + +// DialTargets lista os endereços que o Server deve conectar (agentes não revogados e tokens pendentes que têm endereço). +func (s *Store) DialTargets(ctx context.Context) ([]DialTarget, error) { + rows, err := s.DB.QueryContext(ctx, `SELECT address, id, name FROM agents WHERE revoked_at IS NULL AND address <> '' + UNION ALL SELECT address, 0, name FROM enrollment_tokens WHERE used_at IS NULL AND expires_at > UTC_TIMESTAMP() AND address <> ''`) + if err != nil { + return nil, err + } + defer rows.Close() + var out []DialTarget + for rows.Next() { + var t DialTarget + if err := rows.Scan(&t.Address, &t.AgentID, &t.Name); err != nil { + return nil, err + } + out = append(out, t) + } + return out, rows.Err() +} diff --git a/internal/version/version.go b/internal/version/version.go index 18e1a86..1c79179 100644 --- a/internal/version/version.go +++ b/internal/version/version.go @@ -2,6 +2,6 @@ package version // Version é sobrescrita no build: -ldflags "-X github.com/AprendendoLinux/corujabackup/internal/version.Version=1.2.3". -var Version = "0.0.16" +var Version = "0.0.17" const Name = "Coruja Backup" diff --git a/scripts/release.sh b/scripts/release.sh index 04508a7..f31895e 100755 --- a/scripts/release.sh +++ b/scripts/release.sh @@ -1,8 +1,8 @@ #!/bin/sh # Publicação manual das imagens multi-arquitetura (o fluxo normal é o workflow "Release", disparado pela tag vX.Y.Z). -# Uso: ./scripts/release.sh 0.0.16 (precisa de "docker login ghcr.io" e do buildx) +# Uso: ./scripts/release.sh 0.0.17 (precisa de "docker login ghcr.io" e do buildx) set -e -V="${1:?informe a versão, ex.: 0.0.16}" +V="${1:?informe a versão, ex.: 0.0.17}" OWNER="${OWNER:-aprendendolinux}" cd "$(dirname "$0")/.." # Segredo do app OAuth padrão do Google (opcional): GOOGLE_CLIENT_SECRET_FILE=/caminho/arquivo ./scripts/release.sh X.Y.Z diff --git a/web/package.json b/web/package.json index d7c8c47..d842fe1 100644 --- a/web/package.json +++ b/web/package.json @@ -1,7 +1,7 @@ { "name": "coruja-backup-web", "private": true, - "version": "0.0.16", + "version": "0.0.17", "type": "module", "scripts": { "dev": "vite", diff --git a/web/src/App.tsx b/web/src/App.tsx index 7615c69..e46486f 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -48,7 +48,7 @@ export default function App() { const [brand, setBrand] = useState({ name: 'Coruja Backup', theme: 'coruja', themes: [], has_logo: false }) const [phase, setPhase] = useState('loading') const [me, setMe] = useState(null) - const [version, setVersion] = useState('0.0.16') + const [version, setVersion] = useState('0.0.17') const [drawer, setDrawer] = useState(false) const [collapsed, setCollapsed] = useState(readCollapsed) const route = useRoute() diff --git a/web/src/api.ts b/web/src/api.ts index 5172277..4b0aec8 100644 --- a/web/src/api.ts +++ b/web/src/api.ts @@ -31,9 +31,11 @@ export type User = { export type Agent = { id: number; name: string; hostname: string; os: string; arch: string; agent_version: string docker_available: boolean; ip: string; created_at: string; last_seen_at: string | null - revoked_at: string | null; online: boolean + revoked_at: string | null; online: boolean; address: string; link?: LinkState } -export type PendingToken = { id: number; name: string; created_at: string; expires_at: string } +/** Situação da conexão do Server com o endereço de um agente. */ +export type LinkState = { address: string; state: 'connecting' | 'connected' | 'error'; error?: string; since: string; next_try?: string } +export type PendingToken = { id: number; name: string; created_at: string; expires_at: string; address: string; link?: LinkState } export type AuditEntry = { id: number; at: string; username: string; action: string; detail: string; ip: string } export const ROLE_LABEL = { admin: 'Administrador', operator: 'Operador', viewer: 'Somente leitura' } as const diff --git a/web/src/pages/Agents.tsx b/web/src/pages/Agents.tsx index f93f884..de79ba4 100644 --- a/web/src/pages/Agents.tsx +++ b/web/src/pages/Agents.tsx @@ -1,15 +1,28 @@ -import { FormEvent, useCallback, useEffect, useState } from 'react' -import { Agent, PendingToken, User, api, ApiError, fmtDate } from '../api' +import { useCallback, useEffect, useState } from 'react' +import { Agent, LinkState, PendingToken, User, api, ApiError, fmtDate } from '../api' import { Actions, Badge, Button, Card, CopyBox, ErrorBox, Field, IconButton, Input, Modal, Spinner } from '../ui' import { Wizard } from '../Wizard' import { confirmar, perguntar } from '../Dialogs' -type Sys = { agent_port: string; agent_address: string; version: string } +const DEFAULT_PORT = 23847 + +/** Explica, em linguagem simples, por que o Server ainda não conectou no agente. */ +function LinkInfo({ link }: { link?: LinkState }) { + if (!link) return aguardando a primeira tentativa… + if (link.state === 'connecting') return conectando… + if (link.state === 'error') return {link.error} + return null +} + +function splitAddress(a: string): { host: string; port: string } { + const m = a.match(/^\[(.+)\]:(\d+)$/) ?? a.match(/^(.+):(\d+)$/) + return m ? { host: m[1], port: m[2] } : { host: a, port: String(DEFAULT_PORT) } +} +const joinAddress = (host: string, port: string | number) => (host.includes(':') ? `[${host}]:${port}` : `${host}:${port}`) export default function Agents({ me }: { me: User }) { const [agents, setAgents] = useState([]) const [pending, setPending] = useState([]) - const [sys, setSys] = useState(null) const [err, setErr] = useState('') const [modal, setModal] = useState(false) const canEdit = me.role !== 'viewer' @@ -19,20 +32,23 @@ export default function Agents({ me }: { me: User }) { .then((r) => { setAgents(r.agents); setPending(r.pending_tokens); setErr('') }) .catch((x) => setErr((x as ApiError).message)) }, []) - useEffect(() => { load(); const t = setInterval(load, 10000); return () => clearInterval(t) }, [load]) - useEffect(() => { api('GET', '/api/system').then(setSys).catch(() => {}) }, []) + const waiting = agents.some((a) => !a.online && !a.revoked_at) || pending.length > 0 + useEffect(() => { load() }, [load]) + useEffect(() => { const t = setInterval(load, waiting ? 3000 : 10000); return () => clearInterval(t) }, [load, waiting]) async function act(fn: () => Promise) { try { await fn(); load() } catch (x) { setErr((x as ApiError).message) } } - const defaultAddress = `${window.location.hostname}:${sys?.agent_port ?? '8443'}` - const address = sys?.agent_address || defaultAddress - const rename = async (a: Agent) => { const n = await perguntar({ title: 'Renomear agente', label: 'Novo nome', value: a.name, confirmLabel: 'Renomear' }) if (n && n !== a.name) act(() => api('PATCH', `/api/agents/${a.id}`, { name: n })) } - const revoke = async (a: Agent) => await confirmar({ title: `Revogar "${a.name}"?`, message: 'Ele é desconectado na hora e só volta com uma nova matrícula.', confirmLabel: 'Revogar', danger: true, icon: 'revogar' }) && act(() => api('POST', `/api/agents/${a.id}/revoke`)) + const readdress = async (a: Agent) => { + const n = await perguntar({ title: `Endereço de ${a.name}`, label: 'IP ou nome e porta', value: a.address || `:${DEFAULT_PORT}`, confirmLabel: 'Salvar', icon: 'agentes', + hint: 'Onde o Server conecta no agente, por exemplo 192.0.2.10:23847. A porta é a publicada na stack do agente.' }) + if (n && n !== a.address) act(() => api('PATCH', `/api/agents/${a.id}`, { address: n.trim() })) + } + const revoke = async (a: Agent) => await confirmar({ title: `Revogar "${a.name}"?`, message: 'O Server deixa de conectar nele, e ele recusa novas conexões. Para voltar, é preciso uma nova matrícula.', confirmLabel: 'Revogar', danger: true, icon: 'revogar' }) && act(() => api('POST', `/api/agents/${a.id}/revoke`)) const remove = async (a: Agent) => await confirmar({ title: `Excluir "${a.name}"?`, message: 'O agente é removido definitivamente do painel.', danger: true }) && act(() => api('DELETE', `/api/agents/${a.id}`)) return ( @@ -40,30 +56,33 @@ export default function Agents({ me }: { me: User }) {

Agentes

-

Cada agente executa os backups da máquina em que está instalado e se conecta ao Server com IP:porta e um token de matrícula.

+

Cada agente executa os backups da máquina em que está instalado. O Server conecta nele pelo IP e pela porta cadastrados aqui.

{canEdit && }
- {sys && setSys({ ...sys, agent_address })} />} - - + - {agents.length === 0 && } + {agents.length === 0 && } {agents.map((a) => ( - + - - + + +
NomeEstadoHostVersãoVisto por último
NomeEstadoEndereçoMáquinaVersãoVisto por último
Nenhum agente ainda. Clique em “Novo agente”.
Nenhum agente ainda. Clique em “Novo agente”.
{a.name}{a.docker_available && 🐳}{a.revoked_at ? Revogado : a.online ? Online : Offline}{a.hostname || '—'}
{a.os}/{a.arch} · {a.ip}
+ {a.revoked_at ? Revogado : a.online ? Online : Offline} + {!a.online && !a.revoked_at &&
{a.address ? : sem endereço: cadastre o IP e a porta}
} +
{a.address || '—'}{a.hostname || '—'}
{a.os}/{a.arch}
{a.agent_version || '—'} {fmtDate(a.last_seen_at)} {canEdit && + {!a.revoked_at && readdress(a)} />} rename(a)} /> {!a.revoked_at && revoke(a)} />} remove(a)} /> @@ -77,12 +96,15 @@ export default function Agents({ me }: { me: User }) { {pending.length > 0 && ( -

Tokens aguardando matrícula

+

Aguardando a primeira conexão

    {pending.map((t) => ( -
  • - {t.name} · expira em {fmtDate(t.expires_at)} - {canEdit && act(() => api('DELETE', `/api/agents/tokens/${t.id}`))} />} +
  • +
    + {t.name} {t.address} · token vale até {fmtDate(t.expires_at)} +
    {t.address ? : token de uma versão anterior, sem endereço: cancele e cadastre o agente de novo}
    +
    + {canEdit && await confirmar({ title: `Cancelar "${t.name}"?`, message: 'O token deixa de valer e o Server para de tentar conectar.', confirmLabel: 'Cancelar o token', danger: true, icon: 'fechar' }) && act(() => api('DELETE', `/api/agents/tokens/${t.id}`))} />}
  • ))}
@@ -90,72 +112,42 @@ export default function Agents({ me }: { me: User }) { )} {modal && ( - setModal(false)}> - { setModal(false); load() }} /> + { setModal(false); load() }}> + { setModal(false); load() }} /> )} ) } -function AgentAddress({ current, fallback, canEdit, onSaved }: { current: string; fallback: string; canEdit: boolean; onSaved: (v: string) => void }) { - const [editing, setEditing] = useState(false) - const [value, setValue] = useState('') - const [err, setErr] = useState('') - async function save(e: FormEvent) { - e.preventDefault(); setErr('') - try { const r = await api<{ agent_address: string }>('PUT', '/api/system/agent-address', { address: value }); onSaved(r.agent_address); setEditing(false) } - catch (x) { setErr((x as ApiError).message) } - } - return ( - -
-
- Endereço para os agentes: {current || fallback} -
{current ? 'Definido por você.' : 'Automático (endereço desta página + porta interna do canal). Se você publica o canal em outra porta ou outro nome, altere.'} É o que vai nos comandos de instalação.
-
- {canEdit && !editing && } -
- {editing && ( -
-
-
setValue(e.target.value)} />
- - -
-

Formato endereço:porta. Deixe vazio para voltar ao automático. Isto só muda o texto dos comandos: a porta continua sendo publicada no Docker do Server.

- - - )} -
- ) -} - -type NewAgent = { token: string; name: string; expires_at: string } +type NewAgent = { token: string; name: string; expires_at: string; address: string } -/** Assistente: identificação → instalação (stack pronta) → conexão (espera o agente aparecer). */ -function AgentWizard({ addr, onChange, onClose }: { addr: string; onChange: () => void; onClose: () => void }) { +/** Assistente: identificação e endereço → instalação (stack pronta) → conexão (o Server conecta e mostra o resultado). */ +function AgentWizard({ onChange, onClose }: { onChange: () => void; onClose: () => void }) { const [step, setStep] = useState(0) const [name, setName] = useState('') + const [host, setHost] = useState('') + const [port, setPort] = useState(String(DEFAULT_PORT)) const [ttl, setTtl] = useState(24) const [err, setErr] = useState('') const [busy, setBusy] = useState(false) const [created, setCreated] = useState(null) const [online, setOnline] = useState(null) + const [link, setLink] = useState() const STEPS = [ - { title: 'Identificação', hint: 'Como o agente vai aparecer nos jobs, nos e-mails e nos relatórios.' }, + { title: 'Identificação', hint: 'Como o agente vai aparecer e onde o Server encontra a máquina dele.' }, { title: 'Instalação', hint: 'Suba o agente na máquina que será protegida, com a stack abaixo (Portainer ou docker compose).' }, - { title: 'Conexão', hint: 'Assim que o agente subir, ele aparece aqui sozinho.' }, + { title: 'Conexão', hint: 'O Server tenta conectar a cada poucos segundos. Assim que o agente estiver no ar, ele aparece aqui sozinho.' }, ] - // na etapa de conexão, consulta a cada 3 s até o agente se apresentar useEffect(() => { if (step !== 2 || !created || online) return - const look = () => api<{ agents: Agent[] }>('GET', '/api/agents').then((r) => { - const a = r.agents.find((x) => x.name === created.name && x.online) - if (a) { setOnline(a); onChange() } + const look = () => api<{ agents: Agent[]; pending_tokens: PendingToken[] }>('GET', '/api/agents').then((r) => { + const a = r.agents.find((x) => x.name === created.name) + if (a?.online) { setOnline(a); onChange(); return } + setLink(a?.link ?? r.pending_tokens.find((t) => t.name === created.name)?.link) }).catch(() => {}) look() - const t = setInterval(look, 3000) + const t = setInterval(look, 2000) return () => clearInterval(t) }, [step, created, online, onChange]) @@ -163,9 +155,13 @@ function AgentWizard({ addr, onChange, onClose }: { addr: string; onChange: () = setErr('') if (step === 0) { if (name.trim().length < 2) return setErr('Dê um nome ao agente (pelo menos 2 caracteres).') + const h = host.trim() + if (!h || /[\s/]/.test(h)) return setErr('Informe o IP ou o nome da máquina do agente (sem http:// e sem barras).') + const p = Number(port) + if (!Number.isInteger(p) || p < 1 || p > 65535) return setErr('Informe uma porta entre 1 e 65535.') if (!created) { setBusy(true) - try { setCreated(await api('POST', '/api/agents/tokens', { name: name.trim(), ttl_hours: ttl })); onChange() } + try { setCreated(await api('POST', '/api/agents/tokens', { name: name.trim(), ttl_hours: ttl, address: joinAddress(h, p) })); onChange() } catch (x) { return setErr((x as ApiError).message) } finally { setBusy(false) } } } @@ -176,13 +172,17 @@ function AgentWizard({ addr, onChange, onClose }: { addr: string; onChange: () = onNext={next} onFinish={onClose} nextLabel={step === 0 ? 'Gerar e avançar' : 'Avançar'} finishLabel={online ? 'Concluir' : 'Concluir depois'} busy={busy} err={err}> {step === 0 && (<> setName(e.target.value)} disabled={!!created} /> +
+ setHost(e.target.value)} disabled={!!created} /> + setPort(e.target.value)} disabled={!!created} /> +
)} - {step === 1 && created && } + {step === 1 && created && } {step === 2 && created && ( online ? (
@@ -194,8 +194,9 @@ function AgentWizard({ addr, onChange, onClose }: { addr: string; onChange: () = ) : (
- Aguardando o agente {created.name} se conectar… -

Pode levar alguns segundos depois de subir a stack. Se demorar, confira o log com docker logs corujabackup-agent e se a porta {addr.split(':').pop()} está liberada para a saída dele. Você pode fechar e voltar depois: o token continua valendo até {fmtDate(created.expires_at)}.

+ Conectando em {created.address}… + {link?.state === 'error' &&

Última tentativa: {link.error}

} +

Confira se a stack está no ar (docker logs corujabackup-agent) e se a porta {splitAddress(created.address).port} da máquina do agente aceita conexões vindas do Server. Você pode fechar e voltar depois: o token vale até {fmtDate(created.expires_at)}.

) )} @@ -203,14 +204,16 @@ function AgentWizard({ addr, onChange, onClose }: { addr: string; onChange: () = ) } -function Created({ c, addr }: { c: { token: string; name: string; expires_at: string }; addr: string }) { +function Created({ c }: { c: NewAgent }) { + const { port } = splitAddress(c.address) const compose = `services: agent: image: ghcr.io/aprendendolinux/corujabackup-agent:latest container_name: corujabackup-agent restart: always + ports: + - "${port}:23847" # o Server conecta aqui (libere só para o IP do Server) environment: - CORUJA_SERVER: "${addr}" CORUJA_TOKEN: "${c.token}" CORUJA_HOST_ROOT: "/host" volumes: @@ -221,8 +224,8 @@ function Created({ c, addr }: { c: { token: string; name: string; expires_at: st # - /var/run/docker.sock:/var/run/docker.sock # só para jobs de banco de dados em contêineres Docker volumes: agent-data:` - const run = `docker run -d --name corujabackup-agent --restart always \\ - -e CORUJA_SERVER="${addr}" -e CORUJA_TOKEN="${c.token}" -e CORUJA_HOST_ROOT=/host \\ + const run = `docker run -d --name corujabackup-agent --restart always -p ${port}:23847 \\ + -e CORUJA_TOKEN="${c.token}" -e CORUJA_HOST_ROOT=/host \\ -v coruja-agent-data:/var/lib/coruja-agent -v /:/host:ro -v /:/host-rw -v /srv/coruja-backups:/backups \\ ghcr.io/aprendendolinux/corujabackup-agent:latest` return ( @@ -232,14 +235,14 @@ volumes:
-
Opção 1 · docker run
- +
Opção 1 · docker-compose.yml (Portainer)
+
-
Opção 2 · docker-compose.yml
- +
Opção 2 · docker run
+
-

O agente se conecta de dentro para fora, em {addr} (porta do canal dos agentes). Libere essa porta para a saída do agente. A origem dos backups é lida em /host, somente leitura. A montagem /host-rw dá ao agente permissão de gravação em todo o sistema de arquivos dele, usada na pasta do backup local que você escolher no job.

+

O Server conecta no agente em {c.address}. Libere a porta {port} dessa máquina só para o IP do Server. O agente só aceita a conexão de quem prova ser este Server (pelo certificado). A origem dos backups é lida em /host, somente leitura; a montagem /host-rw dá ao agente permissão de gravação em todo o sistema de arquivos, usada na pasta do backup local escolhida no job.

) }