From 1eeb25f1aec791f42f2fb93ede2196b99f6f1893 Mon Sep 17 00:00:00 2001 From: Rafael Augusto Date: Sun, 8 Nov 2026 00:53:21 -0300 Subject: [PATCH 1/2] Add durable webhooks, idempotent connections and API key rotation --- .env.example | 7 + Makefile | 1 + README.md | 10 +- client.go | 30 ++ cmd/ranjit/cli.go | 8 +- cmd/ranjit/key.go | 47 ++++ cmd/ranjit/key_test.go | 47 ++++ cmd/ranjit/main.go | 12 +- cmd/ranjit/sync.go | 1 + compose.quick.yaml | 2 +- docs/api.md | 10 +- docs/architecture.md | 10 +- docs/backend-reliability.md | 86 ++++++ docs/openapi.json | 254 ++++++++++++++++- docs/operations.md | 14 +- docs/release-notes.md | 18 +- docs/server.md | 16 +- examples/connect/main.go | 8 +- examples/webhook/README.md | 22 ++ examples/webhook/main.go | 80 ++++++ examples/webhook/main_test.go | 56 ++++ internal/config/backend.go | 57 ++++ internal/config/backend_test.go | 41 +++ internal/config/config.go | 44 ++- internal/config/personal.go | 26 +- internal/httpapi/backend_test.go | 120 ++++++++ internal/httpapi/dashboard.go | 4 +- internal/httpapi/handlers.go | 28 +- internal/httpapi/server.go | 39 ++- internal/service/idempotency_test.go | 71 +++++ internal/service/service.go | 55 +++- internal/store/backend_test.go | 317 ++++++++++++++++++++++ internal/store/backup.go | 2 +- internal/store/connections.go | 6 + internal/store/data.go | 4 + internal/store/idempotency.go | 78 ++++++ internal/store/jobs.go | 42 ++- internal/store/maintenance_test.go | 5 + internal/store/migrations/007_backend.sql | 28 ++ internal/store/postgres/002_backend.sql | 28 ++ internal/store/store.go | 5 +- internal/store/webhooks.go | 135 +++++++++ internal/webhook/worker.go | 87 ++++++ internal/webhook/worker_test.go | 93 +++++++ model.go | 2 + scripts/server_smoke.py | 88 +++++- webhook.go | 82 ++++++ webhook_test.go | 51 ++++ 48 files changed, 2196 insertions(+), 81 deletions(-) create mode 100644 cmd/ranjit/key.go create mode 100644 cmd/ranjit/key_test.go create mode 100644 docs/backend-reliability.md create mode 100644 examples/webhook/README.md create mode 100644 examples/webhook/main.go create mode 100644 examples/webhook/main_test.go create mode 100644 internal/config/backend.go create mode 100644 internal/config/backend_test.go create mode 100644 internal/httpapi/backend_test.go create mode 100644 internal/service/idempotency_test.go create mode 100644 internal/store/backend_test.go create mode 100644 internal/store/idempotency.go create mode 100644 internal/store/migrations/007_backend.sql create mode 100644 internal/store/postgres/002_backend.sql create mode 100644 internal/store/webhooks.go create mode 100644 internal/webhook/worker.go create mode 100644 internal/webhook/worker_test.go create mode 100644 webhook.go create mode 100644 webhook_test.go diff --git a/.env.example b/.env.example index e6f3f27..7db46bf 100644 --- a/.env.example +++ b/.env.example @@ -56,3 +56,10 @@ RANJIT_SANTANDER_KEY_FILE=./secrets/santander-key.pem # Exactly 4 branch digits, a dot, then 12 account digits (including check digit). RANJIT_SANTANDER_ACCOUNT= RANJIT_SANTANDER_LOOKBACK_DAYS=7 + +# Optional backend notifications (HTTPS; HTTP only on loopback). +# RANJIT_WEBHOOK_URL=https://your-backend.example/webhooks/ranjit +# RANJIT_WEBHOOK_SECRET= +# Keep the previous API key temporarily while updating backend clients. +# RANJIT_API_KEY_PREVIOUS= +# RANJIT_API_KEY_PREVIOUS_EXPIRES_AT=2026-11-09T12:00:00Z diff --git a/Makefile b/Makefile index fdb52c8..4ec9d17 100644 --- a/Makefile +++ b/Makefile @@ -2,6 +2,7 @@ GO ?= go VERSION ?= dev -include .env +export RANJIT_API_KEY_PREVIOUS RANJIT_API_KEY_PREVIOUS_EXPIRES_AT RANJIT_WEBHOOK_URL RANJIT_WEBHOOK_SECRET export RANJIT_API_KEY RANJIT_ADDR RANJIT_BASE_URL RANJIT_DATABASE RANJIT_PROVIDER RANJIT_SYNC_INTERVAL export RANJIT_EFI_ENV RANJIT_EFI_CLIENT_ID RANJIT_EFI_CLIENT_SECRET_FILE RANJIT_EFI_CERT_FILE RANJIT_EFI_KEY_FILE RANJIT_EFI_LOOKBACK_DAYS export RANJIT_INTER_ENV RANJIT_INTER_CLIENT_ID RANJIT_INTER_CLIENT_SECRET_FILE RANJIT_INTER_CERT_FILE RANJIT_INTER_KEY_FILE RANJIT_INTER_ACCOUNT RANJIT_INTER_LOOKBACK_DAYS diff --git a/README.md b/README.md index ee96423..8bdae1b 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ As integrações diretas usam as credenciais da aplicação criada pelo titular Para começar localmente, instale o binário abaixo, rode `ranjit serve` e obtenha a chave com `ranjit key`. No seu backend: ```sh -go get github.com/getcortexlabs/ranjit@v0.3.0 +go get github.com/getcortexlabs/ranjit@v0.4.0 export RANJIT_URL=http://localhost:8080 # Configure RANJIT_API_KEY com a chave da sua instalação. ``` @@ -37,6 +37,8 @@ O SDK é um cliente HTTP: o Ranjit roda como processo separado do seu backend. A O [exemplo de backend Go](examples/backend/) importa um CSV e consulta transações sem precisar de acesso bancário. O [guia de instalação em servidor e Orbit](docs/server.md) cobre PostgreSQL, segredos e a configuração do SDK. O painel e os comandos locais continuam disponíveis como ferramentas de apoio. +Para repetir uma criação sem duplicar conexões, use `client.ConnectWithKey`. Webhooks assinados avisam quando a sincronização conclui ou falha definitivamente. A chave da API pode ser trocada com um prazo para migrar os consumidores. O [guia de integração confiável](docs/backend-reliability.md) traz configuração, exemplos e recuperação de falhas. + ## Instalar macOS e Linux, sem Go e sem Docker: @@ -210,13 +212,15 @@ O [exemplo Go](examples/connect/main.go) mostra o fluxo completo. O contrato HTT | `GET` | `/v1/connections/{id}` | Consultar estado e última sincronização | | `POST` | `/v1/connections/{id}/sync` | Enfileirar sincronização | | `GET` | `/v1/jobs/{id}` | Acompanhar execução e tentativas | +| `GET` | `/v1/webhooks/deliveries` | Inspecionar notificações e tentativas | +| `POST` | `/v1/webhooks/deliveries/{id}/retry` | Reenviar notificação que falhou | | `GET` | `/v1/connections/{id}/accounts` | Consultar contas e saldos | | `GET` | `/v1/accounts/{id}/transactions` | Consultar transações | | `DELETE` | `/v1/connections/{id}` | Revogar e remover dados normalizados | ## Decisões do projeto -Um binário, um banco e um worker. `net/http` faz o transporte; SQLite ou PostgreSQL guarda os dados e a fila; o provedor só entrega lotes normalizados. O painel usa HTML, CSS e JavaScript embutidos no executável, sem etapa de build do frontend. Não há Redis, ORM ou framework web. O driver SQLite funciona sem CGO. +Um binário, um banco e workers para sincronização e notificações. `net/http` faz o transporte; SQLite ou PostgreSQL guarda os dados e a fila; o provedor só entrega lotes normalizados. O painel usa HTML, CSS e JavaScript embutidos no executável, sem etapa de build do frontend. Não há Redis, ORM ou framework web. O driver SQLite funciona sem CGO. Os valores monetários usam centavos inteiros. As importações são atômicas e fazem upsert por identificador estável do provedor. As respostas de leitura já recebidas ficam temporariamente no banco de dados, vinculadas ao job. A retomada mantém o período solicitado e reaproveita essas respostas; tokens e headers não entram nesse armazenamento. Os registros temporários são removidos ao concluir, falhar definitivamente, expirar ou revogar. O resultado de uma tentativa antiga é rejeitado, mesmo se chegar depois da nova tentativa. @@ -233,6 +237,6 @@ make build # bin/ranjit, sem CGO Os testes usam SQLite em diretórios temporários e exercitam os handlers HTTP reais com transporte em memória. Cobrem consentimento, autenticação, paginação, isolamento dos IDs entre conexões, rollback, repetição de sincronização, concorrência, expiração e retomada após reinício. -Antes de operar fora da máquina local, leia [operação](docs/operations.md). A versão atual tem uma chave por instalação e banco sem criptografia em repouso. A configuração pessoal admite vários perfis; cada perfil direto acessa a conta vinculada às suas credenciais. O modo legado por variáveis de ambiente seleciona um provedor por processo. Webhooks, múltiplos operadores, outros produtos bancários e PostgreSQL ficam para mudanças com casos de uso definidos. +Antes de operar fora da máquina local, leia [operação](docs/operations.md). A versão atual tem um operador por instalação e permite trocar a chave com um período de sobreposição. O banco não tem criptografia em repouso. A configuração pessoal admite vários perfis; cada perfil direto acessa a conta vinculada às suas credenciais. O modo legado por variáveis de ambiente seleciona um provedor por processo. PostgreSQL, webhooks e idempotência estão disponíveis. Múltiplos operadores e outros produtos bancários ficam para mudanças com casos de uso definidos. Contribuições: [CONTRIBUTING.md](CONTRIBUTING.md). Licença: [MIT](LICENSE). diff --git a/client.go b/client.go index 7c3690e..5720d0a 100644 --- a/client.go +++ b/client.go @@ -195,6 +195,10 @@ func pageQuery(cursor string, limit int) url.Values { } func (c *Client) do(ctx context.Context, method, path string, input, output any) error { + return c.doWithKey(ctx, method, path, input, output, "") +} + +func (c *Client) doWithKey(ctx context.Context, method, path string, input, output any, key string) error { var body io.Reader if input != nil { data, err := json.Marshal(input) @@ -210,6 +214,9 @@ func (c *Client) do(ctx context.Context, method, path string, input, output any) if input != nil { req.Header.Set("Content-Type", "application/json") } + if key != "" { + req.Header.Set("Idempotency-Key", key) + } return c.send(req, output) } @@ -237,3 +244,26 @@ func (c *Client) send(req *http.Request, output any) error { } return decoder.Decode(output) } + +// ConnectWithKey retries a logical creation safely for 24 hours. Persist a random +// key per operation in your backend and reuse it with the same request on retry. +func (c *Client) ConnectWithKey(ctx context.Context, input ConnectRequest, key string) (ConnectResponse, error) { + var out ConnectResponse + if !ValidIdempotencyKey(key) { + return out, fmt.Errorf("%w: invalid idempotency key", ErrInvalid) + } + err := c.doWithKey(ctx, http.MethodPost, "/v1/connections", input, &out, key) + return out, err +} + +func ValidIdempotencyKey(key string) bool { + if len(key) < 16 || len(key) > 128 { + return false + } + for _, c := range key { + if c < 33 || c > 126 { + return false + } + } + return true +} diff --git a/cmd/ranjit/cli.go b/cmd/ranjit/cli.go index d6b6dee..a777cf9 100644 --- a/cmd/ranjit/cli.go +++ b/cmd/ranjit/cli.go @@ -43,6 +43,7 @@ Outros comandos: ranjit validate perfil Testar acesso e gerar relatório local ranjit revoke ID Revogar conexão e apagar seus dados ranjit key Mostrar chave da API local + ranjit key rotate --grace 24h Trocar chave com prazo para migração ranjit version Mostrar versão ranjit init Gerar .env para o fluxo com Make/Docker @@ -80,7 +81,12 @@ func (c cli) command(ctx context.Context, args []string) error { return c.doctor(ctx, args[1:]) case "import": return c.importFile(ctx, args[1:]) - case "status", "accounts", "transactions", "key", "revoke": + case "key": + if len(args) > 1 && args[1] == "rotate" { + return c.rotateKey(args[2:]) + } + return c.inspect(ctx, "key", args[1:]) + case "status", "accounts", "transactions", "revoke": return c.inspect(ctx, args[0], args[1:]) case "sync", "demo": return c.sync(ctx, args[0], args[1:]) diff --git a/cmd/ranjit/key.go b/cmd/ranjit/key.go new file mode 100644 index 0000000..1264343 --- /dev/null +++ b/cmd/ranjit/key.go @@ -0,0 +1,47 @@ +package main + +import ( + "crypto/rand" + "errors" + "fmt" + "time" + + "github.com/getcortexlabs/ranjit/internal/config" +) + +func (c cli) rotateKey(args []string) error { + f := c.flags("key rotate") + grace := f.Duration("grace", 24*time.Hour, "tempo para a chave anterior continuar válida (0 a 168h)") + if err := f.Parse(args); err != nil { + return err + } + if f.NArg() != 0 || *grace < 0 || *grace > 7*24*time.Hour { + return errors.New("use ranjit key rotate [--grace 24h]; máximo 168h") + } + cfg, err := localConfig(false) + if err != nil { + return err + } + if cfg.PersonalFile == "" { + return errors.New("configuração por ambiente: defina RANJIT_API_KEY_PREVIOUS e RANJIT_API_KEY_PREVIOUS_EXPIRES_AT, troque RANJIT_API_KEY e recrie o serviço") + } + p, err := config.ReadPersonal(cfg.PersonalFile) + if err != nil { + return err + } + now := time.Now().UTC() + if p.PreviousAPIKeyExpiresAt.After(now) && *grace > 0 { + return errors.New("há uma troca em andamento; aguarde a expiração ou use --grace 0 para invalidar as chaves anteriores") + } + p.PreviousAPIKey, p.PreviousAPIKeyExpiresAt = "", time.Time{} + if *grace > 0 { + p.PreviousAPIKey, p.PreviousAPIKeyExpiresAt = p.APIKey, now.Add(*grace) + } + p.APIKey = rand.Text() + rand.Text() + if err = config.SavePersonal(cfg.PersonalFile, p); err != nil { + return err + } + // stdout contains only the new key, so it can be redirected to a secret file. + _, err = fmt.Fprintln(c.out, p.APIKey) + return err +} diff --git a/cmd/ranjit/key_test.go b/cmd/ranjit/key_test.go new file mode 100644 index 0000000..66657cb --- /dev/null +++ b/cmd/ranjit/key_test.go @@ -0,0 +1,47 @@ +package main + +import ( + "bytes" + "context" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/getcortexlabs/ranjit/internal/config" +) + +func TestRotatePersonalKeyAndEndGrace(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.json") + t.Setenv("RANJIT_CONFIG", path) + t.Setenv("RANJIT_API_KEY", "") + t.Setenv("RANJIT_DATABASE_URL", "") + t.Setenv("RANJIT_PROFILES_JSON", "") + // Personal mode bypasses environment loading, including profile overrides. + p := config.NewPersonal() + if err := config.SavePersonal(path, p); err != nil { + t.Fatal(err) + } + var out bytes.Buffer + c := cli{out: &out} + if err := c.command(context.Background(), []string{"key", "rotate", "--grace", "1h"}); err != nil { + t.Fatal(err) + } + rotated, err := config.ReadPersonal(path) + if err != nil { + t.Fatal(err) + } + if rotated.APIKey == p.APIKey || rotated.PreviousAPIKey != p.APIKey || !rotated.PreviousAPIKeyExpiresAt.After(time.Now()) || strings.TrimSpace(out.String()) != rotated.APIKey { + t.Fatal("bad rotation") + } + if err = c.command(t.Context(), []string{"key", "rotate"}); err == nil { + t.Fatal("in-flight grace replaced") + } + if err = c.command(t.Context(), []string{"key", "rotate", "--grace", "0"}); err != nil { + t.Fatal(err) + } + rotated, err = config.ReadPersonal(path) + if err != nil || rotated.PreviousAPIKey != "" || !rotated.PreviousAPIKeyExpiresAt.IsZero() { + t.Fatal("old key retained", err) + } +} diff --git a/cmd/ranjit/main.go b/cmd/ranjit/main.go index 8641cdd..6a7ff38 100644 --- a/cmd/ranjit/main.go +++ b/cmd/ranjit/main.go @@ -19,6 +19,7 @@ import ( "github.com/getcortexlabs/ranjit/internal/httpapi" "github.com/getcortexlabs/ranjit/internal/service" "github.com/getcortexlabs/ranjit/internal/store" + "github.com/getcortexlabs/ranjit/internal/webhook" "github.com/getcortexlabs/ranjit/internal/worker" ) @@ -119,8 +120,9 @@ func run(logger *slog.Logger) error { logger.Warn("certificate needs attention", "profile", cert.Profile, "status", cert.Level, "days_remaining", cert.DaysRemaining) } } + db.EnableWebhooks(cfg.WebhookURL) svc := service.New(db, source, cfg.BaseURL) - server := &http.Server{Addr: cfg.Addr, Handler: httpapi.New(svc, cfg.APIKey, logger, httpapi.Diagnostics(func() any { + server := &http.Server{Addr: cfg.Addr, Handler: httpapi.New(svc, cfg.APIKey, logger, httpapi.APIKeys(cfg.APIKeys), httpapi.Diagnostics(func() any { return map[string]any{"version": version, "certificates": cfg.Certificates(time.Now()), "unavailable_profiles": unavailable} })), ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 10 * time.Second, WriteTimeout: 30 * time.Second, IdleTimeout: 60 * time.Second, MaxHeaderBytes: 16 << 10} listener, err := net.Listen("tcp", cfg.Addr) @@ -131,6 +133,14 @@ func run(logger *slog.Logger) error { defer cancelWorker() workerDone := make(chan struct{}) go func() { defer close(workerDone); worker.New(db, source, cfg.SyncInterval, logger).Run(workerCtx) }() + webhookDone := make(chan struct{}) + go func() { + defer close(webhookDone) + if cfg.WebhookURL != "" { + webhook.New(db, cfg.WebhookURL, cfg.WebhookSecret, logger).Run(workerCtx) + } + }() + defer func() { cancelWorker(); <-webhookDone }() serveErr := make(chan error, 1) go func() { serveErr <- server.Serve(listener) }() if ui { diff --git a/cmd/ranjit/sync.go b/cmd/ranjit/sync.go index 6d041f7..b93a9ca 100644 --- a/cmd/ranjit/sync.go +++ b/cmd/ranjit/sync.go @@ -80,6 +80,7 @@ func (c cli) sync(ctx context.Context, command string, args []string) error { return err } defer db.Close() + db.EnableWebhooks(cfg.WebhookURL) svc := service.New(db, source, cfg.BaseURL) connections, err := allConnections(ctx, db) if err != nil { diff --git a/compose.quick.yaml b/compose.quick.yaml index 7603e0e..45c73af 100644 --- a/compose.quick.yaml +++ b/compose.quick.yaml @@ -1,6 +1,6 @@ services: ranjit: - image: ghcr.io/getcortexlabs/ranjit:v0.3.0 + image: ghcr.io/getcortexlabs/ranjit:v0.4.0 pull_policy: never ports: - "127.0.0.1:8080:8080" diff --git a/docs/api.md b/docs/api.md index db9232e..5b9dd0c 100644 --- a/docs/api.md +++ b/docs/api.md @@ -18,7 +18,7 @@ Nos conectores diretos, `institution_id` é o nome do provedor selecionado: `efi `POST /v1/connections` recebe `customer_id` e `institution_id`. O primeiro é o ID interno da aplicação, com até 128 bytes. Use um identificador opaco. O segundo deve vir de `GET /v1/institutions`. -No sandbox, a resposta 201 contém `connection`, `authorization_url` e `authorization_expires_at`. O link é uma credencial temporária. Apenas a aplicação que criou a conexão e a pessoa autorizando devem recebê-lo. A criação não é idempotente: não repita automaticamente um POST cujo resultado ficou incerto; consulte as conexões do cliente antes de tentar novamente. +No sandbox, a resposta 201 contém `connection`, `authorization_url` e `authorization_expires_at`. O link é uma credencial temporária. Apenas a aplicação que criou a conexão e a pessoa autorizando devem recebê-lo. Envie `Idempotency-Key` (16–128 caracteres ASCII visíveis, sem espaços) para recuperar a mesma conexão em pedidos repetidos durante 24 horas. Outro conteúdo com a mesma chave retorna `409 idempotency_conflict`. Sem a chave, cada POST cria outra conexão. Veja o [contrato de repetição e recuperação do link](backend-reliability.md). `GET /sandbox/authorize?token=...` exibe a decisão. `POST /sandbox/authorize` recebe `token` e `decision=approve|deny` como `application/x-www-form-urlencoded`. O token dispensa a chave da API apenas nessa rota. Uma decisão bem-sucedida retorna a conexão em JSON. Reutilizar ou deixar vencer o link resulta em 410. @@ -82,6 +82,8 @@ Conexões diretas em `paused` ou `expired` permitem consultar o histórico, mas | 403 | `invalid_origin` | Origem do POST de autorização difere da URL configurada | | 404 | `not_found` | Recurso inexistente | | 409 | `inactive_connection` | Conexão sem consentimento ativo | +| 409 | `idempotency_conflict` | Chave de repetição usada com outro pedido | +| 409 | `webhook_not_retryable` | Entrega não está em falha ou pertence a outro destino | | 410 | `invalid_authorization` | Token inválido, consumido ou vencido | | 502 | `provider_credentials` | Credenciais, escopos ou vínculo da aplicação inválidos | | 502 | `provider_unavailable` | Banco temporariamente indisponível | @@ -109,3 +111,9 @@ CSV aceita `delimiter` (`,` / `;` / `tab`), `date_column`, `description_column`, `GET /v1/transactions?customer_id=personal&q=mercado&from=2026-11-01&through=2026-11-30` busca em todas as contas desse agrupamento; `account_id` restringe uma conta. Datas são inclusivas. A busca textual trata `%` e `_` como caracteres comuns; a conversão de caixa do SQLite é limitada a ASCII. A ordenação é por `posted_on` e ID, decrescente, com `limit` e `cursor`. `GET /v1/diagnostics` informa versão, perfis indisponíveis e validade de certificados. Não retorna caminhos, sujeitos dos certificados ou credenciais. A rota existe no servidor do binário; bibliotecas que montam seu próprio handler podem fornecê-la com `httpapi.Diagnostics`. + +## Notificações e rotação + +`GET /v1/webhooks/deliveries` lista eventos da URL configurada com a paginação padrão. `POST /v1/webhooks/deliveries/{id}/retry` reenfileira uma entrega em `failed` e responde `202`, sem corpo. O SDK oferece `WebhookDeliveries`, `RetryWebhook` e `VerifyWebhook`. + +A assinatura, os prazos de repetição e a troca de chave com sobreposição estão no [guia de integração confiável](backend-reliability.md). Esses recursos usam o mesmo banco e não exigem serviços adicionais. A revogação também apaga as entregas da conexão, sem desfazer requisições já enviadas. diff --git a/docs/architecture.md b/docs/architecture.md index 581f087..c55373e 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -45,7 +45,7 @@ O hash do Client ID e do ambiente vincula a conexão à aplicação Efí. No Int ## Sincronização -Um índice parcial permite no máximo um job `queued` ou `running` por conexão. Pedidos simultâneos de sincronização devolvem esse mesmo job. Criar conexões não é idempotente: uma repetição do POST cria outra conexão. +Um índice parcial permite no máximo um job `queued` ou `running` por conexão. Pedidos simultâneos de sincronização devolvem esse mesmo job. Criar conexões com `Idempotency-Key` recupera a mesma conexão durante 24 horas; sem esse cabeçalho, uma repetição do POST cria outra conexão. O worker verifica vencimentos, agenda conexões elegíveis e reivindica um job a cada passo. A reivindicação gera um token de execução e uma concessão de um minuto. A consulta ao provedor tem timeout de 20 segundos. Se o processo morrer, uma nova execução pode recuperar o job após esse minuto. Cada processo seleciona apenas conexões das instituições que conhece; adicionar um perfil pelo terminal exige reiniciar o servidor para disponibilizá-lo na API. @@ -89,3 +89,11 @@ Backups e restauração são feitos por PostgreSQL ou pela hospedagem. Os comand O painel é servido por `internal/httpapi` com `go:embed`, sem CDN ou dependências de frontend em produção. A API continua sendo a fronteira de dados. Sessões locais são mantidas em memória; mutações por cookie exigem origem correspondente. O comando `ui` usa um link descartável em fragmento para não colocar a chave do operador no navegador. `internal/autostart` renderiza serviços por usuário para os três sistemas suportados. `internal/updater` verifica assets estáveis do repositório e troca o executável mantendo a versão anterior. A camada de armazenamento coordena manutenção com locks compartilhados no uso normal e exclusivos em restauração/atualização. `VACUUM INTO` produz backups independentes do WAL; restauração valida, migra em arquivo temporário e publica apenas o resultado completo. Os testes de navegador ficam separados em `tests/browser`; Node e Playwright são dependências de desenvolvimento. + +## Repetição e entrega ao backend + +`connection_requests` vincula hashes da chave e do pedido a uma conexão por 24 horas. A criação da conexão, o primeiro job e esse vínculo são gravados juntos. Repetições retornam o estado atual; a aplicação não reabre um consentimento consumido. O token do sandbox pode ser derivado novamente apenas com a chave enviada pelo chamador; o banco mantém somente hashes. + +`webhook_deliveries` é a outbox de resultados de sincronização. `Complete` e as falhas terminais escrevem o evento na mesma transação da mudança do job. O worker de entrega usa leases com fencing, assinatura HMAC e backoff; não mantém uma transação aberta durante HTTP. Cada evento aceita até oito tentativas automáticas, com repetições possíveis. Não há garantia de entrega após o limite. O receptor deduplica o ID. O hash da URL associa a fila a um destinatário sem persistir o endereço; mudar a configuração não transfere eventos antigos para outra URL. + +A autenticação continua por instalação. Configuração por ambiente aceita chave atual e anterior com expiração. Configuração pessoal relê as chaves para observar substituições atômicas de `config.json`, negando autenticação por chave quando o arquivo não puder ser validado. diff --git a/docs/backend-reliability.md b/docs/backend-reliability.md new file mode 100644 index 0000000..5549ceb --- /dev/null +++ b/docs/backend-reliability.md @@ -0,0 +1,86 @@ +# Pedidos repetidos, notificações e troca de chaves + +## Criar uma conexão sem duplicar + +Crie uma chave aleatória por operação, salve-a no seu backend e reaproveite-a se a chamada perder a resposta: + +```go +result, err := client.ConnectWithKey(ctx, ranjit.ConnectRequest{ + CustomerID: authenticatedUserID, + InstitutionID: institutionID, +}, operationKey) // UUID ou outro valor aleatório persistido pela aplicação +``` + +Na API HTTP, envie `Idempotency-Key`. São aceitos de 16 a 128 caracteres ASCII visíveis, sem espaços. A chave vale por 24 horas desde a criação e pertence à instalação inteira: use um valor diferente por operação, inclusive entre usuários. O Ranjit armazena hashes da chave e do pedido. + +Mesmo pedido e chave retornam `201` com a mesma conexão e seu estado atual. Pedidos concorrentes só criam uma conexão e um primeiro job. Alterar `customer_id` ou `institution_id` usando a mesma chave retorna `409 idempotency_conflict`. Falhas antes do commit não reservam a chave. Depois de 24 horas, reutilizá-la pode criar outra conexão; guarde o ID recebido no seu backend. + +No sandbox, o mesmo link é recuperável enquanto estiver pendente e dentro dos dez minutos originais. O token é derivado da chave enviada e do ID da conexão; somente hashes são salvos. Aprovar, negar, revogar ou deixar vencer o link impede sua recuperação. Repetir a criação não renova consentimento nem reativa uma conexão. + +Sem o cabeçalho, `client.Connect` mantém o comportamento anterior: cada chamada cria uma conexão. O SDK não repete POSTs automaticamente. A idempotência descrita aqui se aplica apenas à criação de conexões; importações e solicitações de sincronização têm suas próprias regras de deduplicação. + +## Receber o resultado da sincronização + +Configure no serviço: + +```dotenv +RANJIT_WEBHOOK_URL=https://seu-backend.example/webhooks/ranjit +RANJIT_WEBHOOK_SECRET=seu-segredo-aleatorio-com-pelo-menos-32-caracteres +``` + +Use um segredo novo e diferente da chave da API. Para configuração pessoal em `config.json`, os campos são `webhook_url` e `webhook_secret`. Reinicie o serviço ao alterar essas opções. HTTP só é aceito em loopback para desenvolvimento; a URL não aceita credenciais, query ou fragmento. Docker exige um endereço alcançável de dentro do container. + +O Ranjit envia `sync.succeeded` após publicar o lote completo e `sync.failed` quando o job falha definitivamente. Tentativas intermediárias não geram eventos. Cancelamento, importação de arquivo e alteração de consentimento não geram notificações nesta versão. Habilitar webhooks não cria eventos retroativos. `ranjit sync` também grava os eventos quando configurado; `ranjit serve` precisa estar em execução para entregá-los. + +```json +{ + "id": "evt_...", + "type": "sync.succeeded", + "created_at": "2026-11-08T12:00:00Z", + "data": { + "job_id": "job_...", + "connection_id": "con_...", + "customer_id": "user-42" + } +} +``` + +Falhas incluem `data.error_code`. Não enviamos saldos, transações ou credenciais no evento. Consulte a API usando a chave do seu backend quando precisar dos dados. + +O cabeçalho `Ranjit-Event-ID` contém o ID. `Ranjit-Signature` usa `t=,v1=`, calculado sobre `timestamp + "." + corpo original`. Use `ranjit.VerifyWebhook(body, signature, secret, time.Now())`; não reconstrua o JSON antes de verificar. O verificador aceita até cinco minutos de diferença no relógio. Mantenha o relógio do servidor sincronizado e rejeite cabeçalhos de assinatura duplicados. + +O [receptor Go executável](../examples/webhook/) mostra assinatura, limite de corpo e deduplicação persistente. Responda com `2xx` depois de salvar o evento. Deduplicate pelo ID em uma restrição única no seu banco; a assinatura válida não impede uma segunda entrega legítima do mesmo evento. + +## Entregas e recuperação + +A fila fica no mesmo SQLite/PostgreSQL, gravada na mesma transação dos dados. O envio ocorre em um worker separado, com timeout de dez segundos. Redirecionamentos não são seguidos. Qualquer resposta fora de `2xx` ou erro de transporte agenda outra tentativa: até oito, com intervalos de 10, 20, 40, 80, 160, 320 e 640 segundos. Reinícios recuperam tentativas interrompidas após o lease de 30 segundos. Tentativas reclamadas depois de uma queda também contam no limite. + +A entrega pode se repetir e não tem garantia de ordem entre eventos. ID e corpo permanecem iguais; cada tentativa recebe uma assinatura com horário novo. A fila conserva registros por sete dias desde a última alteração. Trocar a URL não redireciona eventos antigos para o novo destinatário; eles ficam associados à URL original até expirar. Desabilitar webhooks pausa as entregas. Revogar uma conexão apaga seus registros de entrega, mas não desfaz uma requisição já enviada. + +```go +deliveries, err := client.WebhookDeliveries(ctx, "", 50) +// Depois de corrigir seu receptor, reenvie uma entrega com status failed: +err = client.RetryWebhook(ctx, eventID) +``` + +`GET /v1/webhooks/deliveries` usa `limit` e `cursor`, filtra pela URL configurada e mostra `queued`, `running`, `delivered` ou `failed`, tentativas, último status HTTP e próxima tentativa quando agendada. Não expõe URL nem segredo. `POST /v1/webhooks/deliveries/{id}/retry` retorna `202`, reinicia as tentativas e preserva o ID/corpo. Só aceita entregas `failed` da URL atual; caso contrário retorna `409 webhook_not_retryable`. Essas rotas exigem a chave da instalação. + +## Trocar a chave da API + +Na instalação pessoal ou no container instalado pelo script: + +```sh +ranjit key rotate --grace 24h +# Docker: docker compose exec ranjit /ranjit key rotate --grace 24h +``` + +O comando imprime apenas a nova chave. Guarde-a como segredo no backend. O servidor lê a mudança sem reiniciar e aceita a chave anterior durante o prazo informado, de zero a 168 horas. O padrão é 24 horas. Outra rotação durante esse prazo é recusada para não derrubar clientes ainda em migração. `--grace 0` invalida imediatamente as duas chaves anteriores. Se o arquivo ficar inválido ou ilegível, a autenticação por chave é negada até corrigir a configuração. Sessões já abertas do painel local continuam com sua validade original; a rotação atua nas chaves da API. + +Em instalações configuradas por ambiente, como o Orbit: + +1. Gere uma nova chave aleatória com pelo menos 32 caracteres. +2. Coloque a chave atual em `RANJIT_API_KEY_PREVIOUS`, defina `RANJIT_API_KEY_PREVIOUS_EXPIRES_AT` em RFC3339 UTC e a nova em `RANJIT_API_KEY`. Faça o deploy do Ranjit com as três alterações juntas. +3. Atualize `RANJIT_API_KEY` no backend consumidor e recrie seu cliente Go ou reinicie o backend. +4. Depois da migração, remova as duas variáveis da chave anterior. Ela deixa de funcionar no prazo configurado mesmo sem novo deploy. + +A configuração por ambiente é lida na inicialização. A janela de sobreposição permite migrar consumidores sem revogar a chave que eles ainda usam; não elimina a interrupção de um deploy com uma única réplica. O Ranjit continua representando um operador por instalação. A chave antiga e a nova têm as mesmas permissões. diff --git a/docs/openapi.json b/docs/openapi.json index ad07ca8..9242e9d 100644 --- a/docs/openapi.json +++ b/docs/openapi.json @@ -2,8 +2,8 @@ "openapi": "3.1.0", "info": { "title": "Ranjit API", - "version": "0.2.0", - "description": "Self-hosted financial data API with a local sandbox and direct Efí / Inter Empresas adapters. Bank account access requires credentials issued to the operator; coverage depends on the provider.", + "version": "0.4.0", + "description": "Self-hosted financial data API with SQLite or PostgreSQL, statement imports, a local sandbox and direct bank adapters. Includes idempotent connection creation and signed sync webhooks. Bank access requires operator-issued credentials; bank connectors remain experimental.", "license": { "name": "MIT", "identifier": "MIT" @@ -168,6 +168,9 @@ }, "502": { "$ref": "#/components/responses/Error502" + }, + "409": { + "$ref": "#/components/responses/Error409" } }, "requestBody": { @@ -180,7 +183,21 @@ } } }, - "description": "This operation is not idempotent. Repeating it creates another connection." + "description": "With Idempotency-Key, retries within 24 hours return the same connection in its current state (201). Reusing a key with different customer_id or institution_id returns 409. After 24 hours the key may create a new connection. Sandbox authorization_url is returned only while the original link is pending and unexpired. Requests without the header create a connection each time. The key is scoped to the installation; use a random key per operation and persist it in your backend.", + "parameters": [ + { + "name": "Idempotency-Key", + "in": "header", + "required": false, + "description": "Random operation key, reused for retries of the same request for 24 hours. No spaces.", + "schema": { + "type": "string", + "minLength": 16, + "maxLength": 128, + "pattern": "^[!-~]{16,128}$" + } + } + ] }, "get": { "operationId": "listConnections", @@ -1140,6 +1157,74 @@ } } } + }, + "/v1/webhooks/deliveries": { + "get": { + "operationId": "listWebhookDeliveries", + "summary": "List deliveries for the configured webhook URL", + "description": "Requires installation authentication. Records are retained for seven days after their last update. Changing the URL does not reassign existing deliveries. Revoking a connection deletes its delivery records. Empty when no webhook URL is configured.", + "parameters": [ + { + "$ref": "#/components/parameters/Limit" + }, + { + "$ref": "#/components/parameters/Cursor" + } + ], + "responses": { + "200": { + "description": "Delivery page", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WebhookDeliveryPage" + } + } + } + }, + "400": { + "$ref": "#/components/responses/Error400" + }, + "401": { + "$ref": "#/components/responses/Error401" + }, + "500": { + "$ref": "#/components/responses/Error500" + } + } + } + }, + "/v1/webhooks/deliveries/{id}/retry": { + "post": { + "operationId": "retryWebhookDelivery", + "summary": "Retry a failed webhook delivery", + "description": "Only failed events for the configured URL can be retried. Resets attempt count and keeps the event ID and body unchanged. Requires installation authentication.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "Event ID from the delivery list." + } + ], + "responses": { + "202": { + "description": "Queued, no response body" + }, + "401": { + "$ref": "#/components/responses/Error401" + }, + "409": { + "$ref": "#/components/responses/Error409" + }, + "500": { + "$ref": "#/components/responses/Error500" + } + } + } } }, "components": { @@ -1816,6 +1901,121 @@ "format": "date-time" } } + }, + "WebhookData": { + "type": "object", + "required": [ + "job_id", + "connection_id", + "customer_id" + ], + "properties": { + "job_id": { + "type": "string" + }, + "connection_id": { + "type": "string" + }, + "customer_id": { + "type": "string" + }, + "error_code": { + "type": "string" + } + } + }, + "WebhookEvent": { + "type": "object", + "required": [ + "id", + "type", + "created_at", + "data" + ], + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": [ + "sync.succeeded", + "sync.failed" + ] + }, + "created_at": { + "type": "string", + "format": "date-time" + }, + "data": { + "$ref": "#/components/schemas/WebhookData" + } + } + }, + "WebhookDelivery": { + "type": "object", + "required": [ + "event", + "status", + "attempts", + "updated_at" + ], + "properties": { + "event": { + "$ref": "#/components/schemas/WebhookEvent" + }, + "status": { + "type": "string", + "enum": [ + "queued", + "running", + "delivered", + "failed" + ] + }, + "attempts": { + "type": "integer", + "minimum": 0, + "maximum": 8, + "description": "Attempts since creation or manual retry, including reclaimed leases." + }, + "http_status": { + "type": "integer" + }, + "error_code": { + "type": "string", + "enum": [ + "transport_error", + "http_error", + "lease_exhausted" + ] + }, + "updated_at": { + "type": "string", + "format": "date-time" + }, + "next_attempt_at": { + "type": "string", + "format": "date-time" + } + } + }, + "WebhookDeliveryPage": { + "type": "object", + "required": [ + "data" + ], + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/WebhookDelivery" + } + }, + "next_cursor": { + "type": "string" + } + } } }, "responses": { @@ -1892,7 +2092,7 @@ } }, "Error409": { - "description": "Connection is not active", + "description": "Resource state conflict: inactive_connection, idempotency_conflict or webhook_not_retryable.", "headers": { "X-Request-ID": { "description": "Generated request identifier.", @@ -1956,5 +2156,51 @@ } } } + }, + "webhooks": { + "syncResult": { + "post": { + "operationId": "receiveSyncResult", + "summary": "Receive a terminal sync result at RANJIT_WEBHOOK_URL", + "description": "Configure a shared signing secret, at least 32 characters. Ranjit-Signature is t=,v1=. Verify before JSON decoding and enforce a five-minute timestamp tolerance. Deduplicate event.id durably. Retries keep the same ID/body with a fresh signature. Delivery is unordered and may repeat. Eight automatic attempts, ten-second timeout, redirects rejected. Events contain metadata only.", + "security": [], + "parameters": [ + { + "name": "Ranjit-Signature", + "in": "header", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "Ranjit-Event-ID", + "in": "header", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WebhookEvent" + } + } + } + }, + "responses": { + "2XX": { + "description": "Persisted; stop retries" + }, + "default": { + "description": "Retry, up to eight attempts" + } + } + } + } } } diff --git a/docs/operations.md b/docs/operations.md index 5ee19a1..fbb6b85 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -12,6 +12,12 @@ O servidor pode usar o sandbox local ou os conectores diretos Efí, Inter, Sicoo | `RANJIT_DATABASE` | `./data/ranjit.db` | Caminho do arquivo SQLite | | `RANJIT_PROVIDER` | `sandbox` | `sandbox`, `efi`, `inter`, `sicoob`, `c6` ou `santander` | | `RANJIT_SYNC_INTERVAL` | `1h` | Intervalo do agendador; mínimo `1m` | +| `RANJIT_DATABASE_URL` | — | PostgreSQL em vez de SQLite | +| `RANJIT_PROFILES_JSON` | — | Perfis em JSON; `[]` habilita apenas arquivos | +| `RANJIT_WEBHOOK_URL` | — | Endpoint para resultados da sincronização | +| `RANJIT_WEBHOOK_SECRET` | — | Segredo de assinatura, mínimo 32 caracteres | +| `RANJIT_API_KEY_PREVIOUS` | — | Chave anterior durante uma migração | +| `RANJIT_API_KEY_PREVIOUS_EXPIRES_AT` | — | Expiração obrigatória da chave anterior em RFC3339 | O binário usa `config.json` quando `RANJIT_CONFIG` está definido ou quando não há `RANJIT_API_KEY` no ambiente e existe configuração pessoal. O arquivo explicitamente selecionado tem precedência: não há mistura de credenciais entre arquivo e ambiente. Caminhos relativos no JSON são resolvidos a partir da pasta dele. No fluxo legado, o binário lê variáveis de ambiente. Quem carrega `.env` é o Makefile ou o Compose. Ao executar `bin/ranjit` diretamente, exporte as variáveis antes. `ranjit init` cria o arquivo sem sobrescrever outro existente; `ranjit version` imprime a versão; `ranjit healthcheck` verifica `/readyz` no endereço local. @@ -27,7 +33,7 @@ O processo cria novos diretórios com permissão `0700` e o arquivo com `0600`. Use `ranjit backup copia.db`, inclusive com o servidor ativo. O comando usa `VACUUM INTO`, confere integridade e publica uma cópia consistente sem sobrescrever um destino existente. Configuração, chave da API local e credenciais bancárias não entram nessa cópia. Ela contém dados financeiros e não é criptografada. Não copie apenas o arquivo principal enquanto existe escrita no WAL. -Para restaurar: `ranjit service stop` (ou encerre `serve`/`ui`) e `ranjit restore --replace copia.db`. Um lock exclusivo impede a restauração enquanto outro processo Ranjit usa esse banco. O comando valida a cópia, guarda o banco anterior ao lado do original e cancela jobs e links antigos. Conexões bancárias ficam pausadas; arquivos importados continuam disponíveis. Retome cada conexão com `ranjit renew ID`. Sem `--replace`, o destino precisa ser novo. Use discos locais que suportem hard links, como APFS, ext4 e NTFS. Processos SQLite externos não participam do lock de aplicação; encerre-os antes de restaurar. +Para restaurar: `ranjit service stop` (ou encerre `serve`/`ui`) e `ranjit restore --replace copia.db`. Um lock exclusivo impede a restauração enquanto outro processo Ranjit usa esse banco. O comando valida a cópia, guarda o banco anterior ao lado do original e cancela jobs e links antigos. A restauração também limpa a fila de webhooks para não reenviar eventos de uma cópia antiga. Conexões bancárias ficam pausadas; arquivos importados continuam disponíveis. Retome cada conexão com `ranjit renew ID`. Sem `--replace`, o destino precisa ser novo. Use discos locais que suportem hard links, como APFS, ext4 e NTFS. Processos SQLite externos não participam do lock de aplicação; encerre-os antes de restaurar. Revogação e expiração de consentimento simulado removem as linhas dos dados financeiros. Em conexões diretas, expiração e pausa preservam o histórico, mas não apagam retroativamente backups ou garantem eliminação de bytes antigos no disco. A política de retenção também deve considerar os metadados das conexões e o histórico de jobs, que crescem nesta versão. @@ -35,13 +41,13 @@ Revogação e expiração de consentimento simulado removem as linhas dos dados `/healthz` verifica o processo. `/readyz` verifica também a conexão SQL, sem afirmar que o provedor ou o worker estão saudáveis. Os logs são JSON e incluem IDs de requisição ou de job e códigos de erro. Não incluem URL, query, headers, corpos ou mensagens brutas do provedor. Proxies precisam de configuração equivalente para não registrar os tokens dos links. -SIGINT e SIGTERM encerram a aceitação de chamadas, aguardam as requisições por até dez segundos e cancelam o worker. Um job interrompido fica recuperável após a concessão de um minuto. Os adaptadores precisam respeitar cancelamento de contexto; um adaptador que ignora isso também prejudica o encerramento. +SIGINT e SIGTERM encerram a aceitação de chamadas, aguardam as requisições por até dez segundos e cancelam os workers. Entregas de webhook interrompidas ficam recuperáveis após 30 segundos. Um job interrompido fica recuperável após a concessão de um minuto. Os adaptadores precisam respeitar cancelamento de contexto; um adaptador que ignora isso também prejudica o encerramento. -Para trocar a chave da API, atualize a variável e reinicie o processo. Atualize os consumidores junto. Não há período de convivência de duas chaves. +Para trocar a chave da API com um período de convivência, use `ranjit key rotate --grace 24h` na configuração pessoal ou as variáveis de chave anterior/expiração no servidor. O [procedimento completo](backend-reliability.md) cobre a migração dos consumidores e a recuperação de webhooks. ## Verificação -`make check` valida código e comportamento sem exigir portas de rede. `make smoke` precisa de uma instância com o provedor `sandbox` rodando e testa o caminho HTTP por socket. O workflow de CI executa ambos e faz uma verificação de vulnerabilidades. A imagem Docker é construída e exercitada em um job separado. +`make check` valida código e comportamento; os testes de webhook abrem receptores HTTP em portas locais temporárias. Defina `RANJIT_TEST_POSTGRES_URL` para executar também os testes PostgreSQL, como no CI. `make smoke` precisa de uma instância com o provedor `sandbox` rodando e testa o caminho HTTP por socket. O workflow de CI executa ambos e faz uma verificação de vulnerabilidades. A imagem Docker é construída e exercitada em um job separado. Os cinco conectores usam respostas bancárias simuladas nos testes. A validação contra uma conta habilitada é uma etapa separada, descrita em [homologação](validation.md). Perfis distintos podem usar o mesmo SQLite: cada instituição contém o nome do perfil e cada conexão permanece vinculada ao hash da aplicação, ambiente e conta. Trocar credenciais que alterem essa identidade exige uma nova conexão. Não renomeie um perfil com conexões ativas sem planejar a reconexão. diff --git a/docs/release-notes.md b/docs/release-notes.md index 86a981f..3f5e233 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -1,13 +1,13 @@ -Ranjit como serviço para seu backend, com SDK Go e PostgreSQL. +Integrações de backend com recuperação de pedidos, notificações assinadas e troca de chaves. -- PostgreSQL para hospedagem, mantendo SQLite como padrão local. -- Configuração de vários perfis por `RANJIT_PROFILES_JSON` e credenciais por referências `env:NOME` aos segredos da plataforma. -- `ranjit.NewClientFromEnv()` e um exemplo de backend com importação e consulta de transações. -- Guia de instalação em servidor e receita preparada para o catálogo do Orbit. -- Testes com PostgreSQL real para concorrência, reinício, rollback, deduplicação e revogação; integração do SDK verificada contra o servidor em execução. +- `Idempotency-Key` e `client.ConnectWithKey`: pedidos repetidos recuperam a mesma conexão por 24 horas, inclusive depois de reiniciar. +- Webhooks `sync.succeeded` e `sync.failed` com HMAC-SHA256, fila persistente, oito tentativas automáticas e reenvio pela API/SDK. +- Rotação da chave com sobreposição: `ranjit key rotate --grace 24h` na configuração pessoal; chave anterior e expiração por ambiente em servidores. +- Receptor Go com verificação de assinatura e caixa de entrada SQLite que deduplica eventos. +- Contrato HTTP, exemplos e documentação de instalação atualizados. -A troca de SQLite para PostgreSQL não transfere o histórico automaticamente. Backups e atualização de uma instalação PostgreSQL ficam sob a hospedagem. A entrada no catálogo do Orbit depende da publicação da receita e do download anônimo da imagem no GHCR. +As novas tabelas são criadas automaticamente no SQLite ou PostgreSQL existente. Faça backup antes de atualizar; as migrações não têm downgrade automático. Webhooks são opcionais, sem eventos retroativos. Pedidos sem `Idempotency-Key` mantêm o comportamento anterior. -Os conectores bancários continuam experimentais e ainda não foram validados com uma conta real habilitada. A instalação começa com importação de extratos; conectar uma conta exige configurar o acesso à API correspondente. +Os conectores bancários continuam experimentais. A validação com uma conta real depende de acesso habilitado à API do banco. A integração com dados simulados e importação de extratos funciona sem essas credenciais. -Instalação e integração: https://github.com/getcortexlabs/ranjit/blob/main/docs/server.md +Configuração e exemplos: https://github.com/getcortexlabs/ranjit/blob/main/docs/backend-reliability.md diff --git a/docs/server.md b/docs/server.md index bc29eb2..be06bb1 100644 --- a/docs/server.md +++ b/docs/server.md @@ -15,7 +15,7 @@ Em outro terminal, `ranjit key` mostra a chave da instalação. Configure no amb ```sh export RANJIT_URL=http://localhost:8080 # RANJIT_API_KEY: chave mostrada por ranjit key -go get github.com/getcortexlabs/ranjit@v0.3.0 +go get github.com/getcortexlabs/ranjit@v0.4.0 ``` ```go @@ -80,22 +80,26 @@ Para habilitar uma integração existente, coloque os metadados em `RANJIT_PROFI ] ``` -Cadastre `BANK_CLIENT_SECRET`, `BANK_CERT_PEM` e `BANK_KEY_PEM` como **segredos** na hospedagem. PEM precisa conter as quebras de linha reais, incluindo BEGIN/END. A referência `env:NOME` é explícita; um caminho continua lendo um arquivo. Rotacionar o segredo exige reiniciar ou fazer um novo deploy do serviço. Para o Sicoob sandbox, `access_token_file` também aceita essa referência. Os campos exigidos por cada banco estão nos respectivos guias. +Cadastre `BANK_CLIENT_SECRET`, `BANK_CERT_PEM` e `BANK_KEY_PEM` como **segredos** na hospedagem. PEM precisa conter as quebras de linha reais, incluindo BEGIN/END. A referência `env:NOME` é explícita; um caminho continua lendo um arquivo. Rotacionar um segredo bancário exige reiniciar ou fazer um novo deploy do serviço. Para o Sicoob sandbox, `access_token_file` também aceita essa referência. Os campos exigidos por cada banco estão nos respectivos guias. Não combine `RANJIT_PROFILES_JSON` com `RANJIT_PROVIDER`. Este último permanece disponível para a configuração antiga de um único conector. Perfis indisponíveis não impedem a consulta do histórico; `ranjit doctor` ajuda a identificar configuração ou certificados inválidos. -Após configurar um perfil, consulte `client.Institutions(ctx)`, selecione o ID retornado e chame `client.Connect`. A conexão direta verifica as credenciais e agenda a primeira sincronização; acompanhe `client.Status` antes de assumir que os dados estão disponíveis. A autorização no navegador pertence ao sandbox simulado. Os conectores diretos acessam as contas cobertas pelas credenciais do operador; um `customer_id` diferente não concede acesso a outra conta bancária. Uma aplicação que recebe contas de terceiros precisa de uma operação de compartilhamento habilitada e do adaptador correspondente. +Após configurar um perfil, consulte `client.Institutions(ctx)`, selecione o ID retornado e chame `client.ConnectWithKey` com uma chave aleatória persistida para a operação. A conexão direta verifica as credenciais e agenda a primeira sincronização; acompanhe `client.Status` antes de assumir que os dados estão disponíveis. A autorização no navegador pertence ao sandbox simulado. Os conectores diretos acessam as contas cobertas pelas credenciais do operador; um `customer_id` diferente não concede acesso a outra conta bancária. Uma aplicação que recebe contas de terceiros precisa de uma operação de compartilhamento habilitada e do adaptador correspondente. ## Orbit -A receita preparada para o catálogo cria o serviço Ranjit, um PostgreSQL gerenciado e uma chave de API aleatória. A URL do banco entra por referência; a chave fica como segredo. O endereço HTTPS gerado é configurado em `RANJIT_BASE_URL` após o primeiro deploy. +A receita do catálogo cria o serviço Ranjit, um PostgreSQL gerenciado e uma chave de API aleatória. A URL do banco entra por referência; a chave fica como segredo. O endereço HTTPS gerado é configurado em `RANJIT_BASE_URL` após o primeiro deploy. Depois da instalação, configure a URL e a chave no seu backend. Comece importando um extrato; quando tiver acesso bancário habilitado, adicione os perfis e segredos nas variáveis do serviço e faça um novo deploy. O painel `/app/` permanece restrito ao uso local; a instalação hospedada é operada pela API, pelas variáveis e pelos logs do Orbit. -A entrada do catálogo só deve ser publicada quando a imagem versionada estiver disponível para download anônimo no GHCR. A receita usa `ghcr.io/getcortexlabs/ranjit:v0.3.0`. Enquanto a imagem estiver privada, o instalador local continua funcionando com os arquivos públicos da release, mas isso não habilita o pull automático do Orbit. +A receita usa a imagem pública `ghcr.io/getcortexlabs/ranjit:v0.3.0`, sem login no registry. A versão instalada depende da receita presente na sua versão do Orbit; atualizar o Ranjit exige alterar a tag e fazer um novo deploy. ## Backup e atualização Use os backups do PostgreSQL na hospedagem ou `pg_dump`/`pg_restore`. Inclua os segredos em uma política separada de recuperação. `ranjit backup`, `restore` e a atualização automática com backup SQLite recusam esse modo de servidor. -Antes de atualizar a imagem, faça um backup do banco. As migrações são aplicadas no início e não têm downgrade automático; voltar apenas à imagem anterior pode não reverter uma mudança de schema. Para restaurar um backup antigo, pare o serviço e revise conexões e jobs antes de retomar a coleta. O restore gerenciado do PostgreSQL não aplica as pausas automáticas do comando SQLite. +Antes de atualizar a imagem, faça um backup do banco. As migrações são aplicadas no início e não têm downgrade automático; voltar apenas à imagem anterior pode não reverter uma mudança de schema. Para restaurar um backup antigo, pare o serviço e revise conexões e jobs antes de retomar a coleta. O restore gerenciado do PostgreSQL não aplica as pausas automáticas nem limpa a fila de webhooks como o comando SQLite. Ao restaurar uma cópia antiga, revise essa fila antes de habilitar o envio; notificações antigas podem voltar a ser entregues. + +## Webhooks e continuidade da integração + +Você pode receber `sync.succeeded` e `sync.failed` no seu backend e trocar a chave da API com um prazo para atualizar os consumidores. Configure as variáveis pelo gerenciador de segredos da hospedagem e siga o [guia de integração confiável](backend-reliability.md). A fila de entrega usa o mesmo PostgreSQL/SQLite, sem Redis nem outro serviço. O receptor precisa estar acessível pelo Ranjit e salvar os eventos por ID antes de confirmar recebimento. diff --git a/examples/connect/main.go b/examples/connect/main.go index 738a30a..cc04bd4 100644 --- a/examples/connect/main.go +++ b/examples/connect/main.go @@ -36,7 +36,13 @@ func run() error { if len(institutions.Data) == 0 { return fmt.Errorf("no configured institution") } - result, err := client.Connect(ctx, ranjit.ConnectRequest{CustomerID: "local-user", InstitutionID: institutions.Data[0].ID}) + // Reuse RANJIT_OPERATION_KEY after a lost response. Production backends + // should persist one random key for each logical creation in their database. + operationKey := os.Getenv("RANJIT_OPERATION_KEY") + if operationKey == "" { + operationKey = ranjit.NewID("op") + } + result, err := client.ConnectWithKey(ctx, ranjit.ConnectRequest{CustomerID: "local-user", InstitutionID: institutions.Data[0].ID}, operationKey) if err != nil { return err } diff --git a/examples/webhook/README.md b/examples/webhook/README.md new file mode 100644 index 0000000..0c11cf6 --- /dev/null +++ b/examples/webhook/README.md @@ -0,0 +1,22 @@ +# Receber notificações no backend + +Este exemplo verifica a assinatura e grava cada evento uma única vez em SQLite antes de responder `204`. Reiniciar o exemplo preserva a caixa de entrada em `webhook-inbox.db`. Adapte a tabela ao banco do seu backend e processe os registros de forma transacional. Efeitos externos, como enviar outro pedido HTTP, precisam de sua própria chave de idempotência. + +Na raiz do repositório, com Go instalado: + +```sh +make setup +# Adicione ao .env: +# RANJIT_WEBHOOK_URL=http://127.0.0.1:8081/webhooks/ranjit +# RANJIT_WEBHOOK_SECRET= +set -a +. ./.env +set +a +go run ./examples/webhook +``` + +Em outro terminal, rode `make run`. Em um terceiro, `make example` cria uma conexão no sandbox. Abra o link exibido e aprove os dados fictícios. A primeira sincronização enviará `sync.succeeded` para o exemplo. Não é necessário habilitar um banco para esse teste. + +O endpoint pode receber o mesmo ID várias vezes, inclusive depois de responder com sucesso se a resposta se perder. A assinatura muda a cada tentativa; o ID e o corpo do evento permanecem iguais. O exemplo só recebe eventos, não consulta nem altera dados financeiros. Use `client.Accounts` e `client.Transactions` ao consumir a caixa de entrada se sua aplicação precisar atualizar seu próprio histórico. + +Em produção, sirva o endpoint por HTTPS e use o mesmo `RANJIT_WEBHOOK_SECRET` no Ranjit e no receptor. O segredo de assinatura é separado da chave da API. Veja [retries, inspeção e recuperação de entregas](../../docs/backend-reliability.md). diff --git a/examples/webhook/main.go b/examples/webhook/main.go new file mode 100644 index 0000000..b59e6dc --- /dev/null +++ b/examples/webhook/main.go @@ -0,0 +1,80 @@ +// This receiver commits authenticated events to an inbox before acknowledging +// delivery. Process the inbox in your backend, using event.id as a unique key. +package main + +import ( + "context" + "database/sql" + "io" + "log" + "net/http" + "os" + "time" + + "github.com/getcortexlabs/ranjit" + _ "modernc.org/sqlite" +) + +func main() { + secret := os.Getenv("RANJIT_WEBHOOK_SECRET") + if len(secret) < 32 { + log.Fatal("RANJIT_WEBHOOK_SECRET must contain at least 32 characters") + } + db, err := openInbox("webhook-inbox.db") + if err != nil { + log.Fatal(err) + } + defer db.Close() + server := &http.Server{Addr: "127.0.0.1:8081", Handler: receiver(db, secret), ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, IdleTimeout: time.Minute} + log.Print("webhook receiver listening on http://127.0.0.1:8081/webhooks/ranjit") + log.Fatal(server.ListenAndServe()) +} + +func openInbox(path string) (*sql.DB, error) { + db, err := sql.Open("sqlite", path) + if err != nil { + return nil, err + } + db.SetMaxOpenConns(1) + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + _, err = db.ExecContext(ctx, `PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA busy_timeout=5000; + CREATE TABLE IF NOT EXISTS webhook_inbox(id TEXT PRIMARY KEY,payload TEXT NOT NULL,received_at INTEGER NOT NULL);`) + if err != nil { + db.Close() + return nil, err + } + return db, nil +} + +func receiver(db *sql.DB, secret string) http.Handler { + mux := http.NewServeMux() + mux.HandleFunc("POST /webhooks/ranjit", func(w http.ResponseWriter, r *http.Request) { + r.Body = http.MaxBytesReader(w, r.Body, 16<<10) + defer r.Body.Close() + body, err := io.ReadAll(r.Body) + if err != nil { + http.Error(w, "body too large or unreadable", http.StatusBadRequest) + return + } + signatures := r.Header.Values("Ranjit-Signature") + if len(signatures) != 1 { + http.Error(w, "invalid signature", http.StatusUnauthorized) + return + } + event, err := ranjit.VerifyWebhook(body, signatures[0], secret, time.Now()) + if err != nil { + http.Error(w, "invalid signature", http.StatusUnauthorized) + return + } + // The primary key makes redelivery safe, including after a restart. + // Acknowledge only after commit; business work can consume this inbox. + _, err = db.ExecContext(r.Context(), `INSERT INTO webhook_inbox(id,payload,received_at) VALUES(?,?,?) ON CONFLICT(id) DO NOTHING`, event.ID, string(body), time.Now().UnixMilli()) + if err != nil { + http.Error(w, "inbox unavailable", http.StatusServiceUnavailable) + return + } + w.WriteHeader(http.StatusNoContent) + }) + return mux +} diff --git a/examples/webhook/main_test.go b/examples/webhook/main_test.go new file mode 100644 index 0000000..de8bd8c --- /dev/null +++ b/examples/webhook/main_test.go @@ -0,0 +1,56 @@ +package main + +import ( + "bytes" + "crypto/hmac" + "crypto/sha256" + "encoding/hex" + "fmt" + "net/http/httptest" + "path/filepath" + "strconv" + "strings" + "testing" + "time" +) + +func TestInboxAcknowledgesOnlyDurableUniqueEvents(t *testing.T) { + path := filepath.Join(t.TempDir(), "inbox.db") + db, err := openInbox(path) + if err != nil { + t.Fatal(err) + } + defer db.Close() + secret := strings.Repeat("s", 40) + body := []byte(fmt.Sprintf(`{"id":"evt-test","type":"sync.succeeded","created_at":%q,"data":{"job_id":"job-test","connection_id":"con-test","customer_id":"customer"}}`, time.Now().UTC().Format(time.RFC3339))) + ts := strconv.FormatInt(time.Now().Unix(), 10) + mac := hmac.New(sha256.New, []byte(secret)) + mac.Write([]byte(ts + ".")) + mac.Write(body) + signature := "t=" + ts + ",v1=" + hex.EncodeToString(mac.Sum(nil)) + deliver := func(signature string, want int) { + t.Helper() + req := httptest.NewRequest("POST", "/webhooks/ranjit", bytes.NewReader(body)) + req.Header.Set("Ranjit-Signature", signature) + w := httptest.NewRecorder() + receiver(db, secret).ServeHTTP(w, req) + if w.Code != want { + t.Fatal(w.Code, w.Body.String()) + } + } + deliver("invalid", 401) + deliver(signature, 204) + db.Close() + db, err = openInbox(path) + if err != nil { + t.Fatal(err) + } + defer db.Close() + deliver(signature, 204) + var count int + if err = db.QueryRow(`SELECT COUNT(*) FROM webhook_inbox`).Scan(&count); err != nil || count != 1 { + t.Fatal(count, err) + } + db.Close() + deliver(signature, 503) +} diff --git a/internal/config/backend.go b/internal/config/backend.go new file mode 100644 index 0000000..f39ec6b --- /dev/null +++ b/internal/config/backend.go @@ -0,0 +1,57 @@ +package config + +import ( + "errors" + "net" + "net/url" + "strings" + "time" +) + +func validatePrevious(current, previous string, expires time.Time) error { + if previous == "" && expires.IsZero() { + return nil + } + if len(previous) < 32 || strings.ContainsAny(previous, " \t\r\n") || previous == current || expires.IsZero() { + return errors.New("previous API key requires a distinct key of at least 32 bytes and an RFC3339 expiration") + } + return nil +} + +// APIKeys reads personal configuration on each authentication so atomic CLI +// rotations take effect without restarting. Read errors deliberately fail closed. +func (c Config) APIKeys(now time.Time) ([]string, error) { + current, previous, expires := c.APIKey, c.PreviousAPIKey, c.PreviousAPIKeyExpiresAt + if c.PersonalFile != "" { + p, err := ReadPersonal(c.PersonalFile) + if err != nil { + return nil, errors.New("cannot read API key configuration") + } + current, previous, expires = p.APIKey, p.PreviousAPIKey, p.PreviousAPIKeyExpiresAt + } + keys := []string{current} + if previous != "" && expires.After(now) { + keys = append(keys, previous) + } + return keys, nil +} + +func validateWebhook(destination, secret string) error { + if destination == "" && secret == "" { + return nil + } + if len(secret) < 32 || strings.ContainsAny(secret, " \t\r\n") { + return errors.New("webhook configuration requires a signing secret of at least 32 bytes without whitespace") + } + u, err := url.Parse(destination) + if err != nil || u.Hostname() == "" || u.User != nil || u.RawQuery != "" || u.ForceQuery || u.Fragment != "" || u.Scheme != "https" && u.Scheme != "http" { + return errors.New("webhook URL must use HTTPS without credentials, query or fragment (HTTP is allowed on loopback)") + } + if u.Scheme == "http" { + ip := net.ParseIP(u.Hostname()) + if u.Hostname() != "localhost" && (ip == nil || !ip.IsLoopback()) { + return errors.New("webhook URL requires HTTPS outside loopback") + } + } + return nil +} diff --git a/internal/config/backend_test.go b/internal/config/backend_test.go new file mode 100644 index 0000000..9bf9441 --- /dev/null +++ b/internal/config/backend_test.go @@ -0,0 +1,41 @@ +package config + +import ( + "strings" + "testing" + "time" +) + +func TestBackendEnvironmentValidation(t *testing.T) { + t.Setenv("RANJIT_CONFIG", "") + t.Setenv("RANJIT_API_KEY", strings.Repeat("k", 40)) + t.Setenv("RANJIT_PROVIDER", "sandbox") + t.Setenv("RANJIT_WEBHOOK_URL", "https://backend.example/webhooks/ranjit") + t.Setenv("RANJIT_WEBHOOK_SECRET", strings.Repeat("s", 40)) + t.Setenv("RANJIT_API_KEY_PREVIOUS", strings.Repeat("p", 40)) + t.Setenv("RANJIT_API_KEY_PREVIOUS_EXPIRES_AT", "2026-11-09T12:00:00Z") + cfg, err := Load() + if err != nil { + t.Fatal(err) + } + keys, err := cfg.APIKeys(time.Date(2026, 11, 9, 11, 59, 0, 0, time.UTC)) + if err != nil || len(keys) != 2 { + t.Fatal(err) + } + keys, err = cfg.APIKeys(time.Date(2026, 11, 9, 12, 0, 0, 0, time.UTC)) + if err != nil || len(keys) != 1 { + t.Fatal("expired key accepted", err) + } + for _, endpoint := range []string{"http://public.example/events", "https://user:password@example.com/events", "https://example.com/events?secret=bad", "https://example.com/events#fragment", "file:///tmp/events", ""} { + t.Run(endpoint, func(t *testing.T) { + t.Setenv("RANJIT_WEBHOOK_URL", endpoint) + if _, err := Load(); err == nil { + t.Fatal("invalid webhook accepted") + } + }) + } + t.Setenv("RANJIT_API_KEY_PREVIOUS_EXPIRES_AT", "") + if _, err = Load(); err == nil { + t.Fatal("unbounded previous key accepted") + } +} diff --git a/internal/config/config.go b/internal/config/config.go index 95d0cae..ae7c784 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -19,18 +19,23 @@ import ( ) type Config struct { - Profiles []Profile - Addr string - BaseURL string - APIKey string - Database string - SyncInterval time.Duration - Provider string - EFI efi.Config - Inter inter.Config - Sicoob sicoob.Config - Santander santander.Config - C6 c6.Config + PreviousAPIKey string + PreviousAPIKeyExpiresAt time.Time + PersonalFile string + WebhookURL string + WebhookSecret string + Profiles []Profile + Addr string + BaseURL string + APIKey string + Database string + SyncInterval time.Duration + Provider string + EFI efi.Config + Inter inter.Config + Sicoob sicoob.Config + Santander santander.Config + C6 c6.Config } func Load() (Config, error) { @@ -68,6 +73,21 @@ func Load() (Config, error) { } else if strings.Contains(c.Database, "://") { return c, fmt.Errorf("use RANJIT_DATABASE_URL for PostgreSQL; RANJIT_DATABASE is a SQLite file path") } + c.PreviousAPIKey = os.Getenv("RANJIT_API_KEY_PREVIOUS") + if value := os.Getenv("RANJIT_API_KEY_PREVIOUS_EXPIRES_AT"); value != "" { + var err error + c.PreviousAPIKeyExpiresAt, err = time.Parse(time.RFC3339, value) + if err != nil { + return c, fmt.Errorf("RANJIT_API_KEY_PREVIOUS_EXPIRES_AT must use RFC3339") + } + } + if err := validatePrevious(c.APIKey, c.PreviousAPIKey, c.PreviousAPIKeyExpiresAt); err != nil { + return c, err + } + c.WebhookURL, c.WebhookSecret = os.Getenv("RANJIT_WEBHOOK_URL"), os.Getenv("RANJIT_WEBHOOK_SECRET") + if err := validateWebhook(c.WebhookURL, c.WebhookSecret); err != nil { + return c, err + } c.Provider = env("RANJIT_PROVIDER", "sandbox") if hasProfiles { if os.Getenv("RANJIT_PROVIDER") != "" { diff --git a/internal/config/personal.go b/internal/config/personal.go index 90b921a..3b7faaa 100644 --- a/internal/config/personal.go +++ b/internal/config/personal.go @@ -28,13 +28,17 @@ type Profile struct { } type Personal struct { - Version int `json:"version"` - Database string `json:"database"` - APIKey string `json:"api_key"` - Addr string `json:"addr"` - BaseURL string `json:"base_url"` - SyncInterval string `json:"sync_interval"` - Profiles []Profile `json:"profiles"` + PreviousAPIKey string `json:"previous_api_key,omitempty"` + PreviousAPIKeyExpiresAt time.Time `json:"previous_api_key_expires_at,omitzero"` + WebhookURL string `json:"webhook_url,omitempty"` + WebhookSecret string `json:"webhook_secret,omitempty"` + Version int `json:"version"` + Database string `json:"database"` + APIKey string `json:"api_key"` + Addr string `json:"addr"` + BaseURL string `json:"base_url"` + SyncInterval string `json:"sync_interval"` + Profiles []Profile `json:"profiles"` } var profileName = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$`) @@ -94,6 +98,12 @@ func (c Personal) Validate() error { if d, err := time.ParseDuration(c.SyncInterval); err != nil || d < time.Minute { return errors.New("sync_interval must be at least 1m") } + if err := validatePrevious(c.APIKey, c.PreviousAPIKey, c.PreviousAPIKeyExpiresAt); err != nil { + return err + } + if err := validateWebhook(c.WebhookURL, c.WebhookSecret); err != nil { + return err + } return validateProfiles(c.Profiles) } @@ -163,5 +173,5 @@ func (c Personal) Runtime(path string) Config { p.AccessTokenFile = resolve(p.AccessTokenFile) } interval, _ := time.ParseDuration(c.SyncInterval) - return Config{Addr: c.Addr, BaseURL: c.BaseURL, APIKey: c.APIKey, Database: resolve(c.Database), SyncInterval: interval, Provider: "profiles", Profiles: profiles} + return Config{PersonalFile: path, PreviousAPIKey: c.PreviousAPIKey, PreviousAPIKeyExpiresAt: c.PreviousAPIKeyExpiresAt, WebhookURL: c.WebhookURL, WebhookSecret: c.WebhookSecret, Addr: c.Addr, BaseURL: c.BaseURL, APIKey: c.APIKey, Database: resolve(c.Database), SyncInterval: interval, Provider: "profiles", Profiles: profiles} } diff --git a/internal/httpapi/backend_test.go b/internal/httpapi/backend_test.go new file mode 100644 index 0000000..6b5a204 --- /dev/null +++ b/internal/httpapi/backend_test.go @@ -0,0 +1,120 @@ +package httpapi_test + +import ( + "errors" + "io" + "log/slog" + "net/http" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/getcortexlabs/ranjit" + "github.com/getcortexlabs/ranjit/internal/config" + "github.com/getcortexlabs/ranjit/internal/httpapi" +) + +func TestSDKConnectReplayDoesNotReopenConsent(t *testing.T) { + client, s, _, logs := setup(t) + input := ranjit.ConnectRequest{CustomerID: "private-customer", InstitutionID: "sandbox-bank"} + key := "persistent-operation-1234" + first, err := client.ConnectWithKey(t.Context(), input, key) + if err != nil { + t.Fatal(err) + } + next, err := client.ConnectWithKey(t.Context(), input, key) + if err != nil || next.Connection.ID != first.Connection.ID || next.AuthorizationURL != first.AuthorizationURL { + t.Fatal(next, err) + } + input.CustomerID = "another-customer" + _, err = client.ConnectWithKey(t.Context(), input, key) + var apiError *ranjit.APIError + if !errors.As(err, &apiError) || apiError.StatusCode != 409 || apiError.Code != "idempotency_conflict" { + t.Fatal(err) + } + if status, _ := decide(t, client, first, "approve", s.BaseURL); status != 200 { + t.Fatal(status) + } + input.CustomerID = "private-customer" + next, err = client.ConnectWithKey(t.Context(), input, key) + if err != nil || next.Connection.Status != "active" || next.AuthorizationURL != "" { + t.Fatal("consumed authorization replayed", next, err) + } + if strings.Contains(logs.String(), key) || strings.Contains(logs.String(), input.CustomerID) { + t.Fatal("request metadata leaked") + } +} + +func TestAPIKeysReloadAndExpireWithoutRestart(t *testing.T) { + _, s, _, _ := setup(t) + p := config.NewPersonal() + path := filepath.Join(t.TempDir(), "config.json") + if err := config.SavePersonal(path, p); err != nil { + t.Fatal(err) + } + cfg := p.Runtime(path) + transport := handlerTransport{handler: httpapi.New(s, p.APIKey, slog.New(slog.NewTextHandler(io.Discard, nil)), httpapi.APIKeys(cfg.APIKeys))} + check := func(key string, want int) { + t.Helper() + req, _ := http.NewRequest("GET", "http://localhost:8080/v1/institutions", nil) + req.Header.Set("Authorization", "Bearer "+key) + resp, err := transport.RoundTrip(req) + if err != nil { + t.Fatal(err) + } + resp.Body.Close() + if resp.StatusCode != want { + t.Fatalf("authentication status %d, want %d", resp.StatusCode, want) + } + } + old := p.APIKey + check(old, 200) + p.PreviousAPIKey, p.PreviousAPIKeyExpiresAt = old, s.Now().Add(time.Minute) + p.APIKey = strings.Repeat("n", 40) + if err := config.SavePersonal(path, p); err != nil { + t.Fatal(err) + } + check(old, 200) + check(p.APIKey, 200) + now := s.Now().Add(time.Minute) + s.Now = func() time.Time { return now } + check(old, 401) + check(p.APIKey, 200) + if err := os.WriteFile(path, []byte("broken"), 0600); err != nil { + t.Fatal(err) + } + check(p.APIKey, 401) + check(old, 401) +} + +func TestWebhookDeliverySDKAndAuthentication(t *testing.T) { + client, s, w, _ := setup(t) + s.Store.EnableWebhooks("https://backend.example/events") + result := connect(t, client, "customer") + if code, _ := decide(t, client, result, "approve", s.BaseURL); code != 200 { + t.Fatal(code) + } + if err := w.Step(t.Context()); err != nil { + t.Fatal(err) + } + page, err := client.WebhookDeliveries(t.Context(), "", 1) + if err != nil || len(page.Data) != 1 || page.Data[0].Event.Type != "sync.succeeded" { + t.Fatal(page, err) + } + err = client.RetryWebhook(t.Context(), page.Data[0].Event.ID) + var apiError *ranjit.APIError + if !errors.As(err, &apiError) || apiError.Code != "webhook_not_retryable" { + t.Fatal(err) + } + req, _ := http.NewRequest("GET", s.BaseURL+"/v1/webhooks/deliveries", nil) + resp, err := client.HTTPClient.Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + if resp.StatusCode != 401 { + t.Fatal("delivery metadata unauthenticated", resp.StatusCode) + } +} diff --git a/internal/httpapi/dashboard.go b/internal/httpapi/dashboard.go index 2dc9a78..3ccc5b9 100644 --- a/internal/httpapi/dashboard.go +++ b/internal/httpapi/dashboard.go @@ -3,7 +3,6 @@ package httpapi import ( "crypto/rand" "crypto/sha256" - "crypto/subtle" "embed" "io/fs" "net" @@ -134,8 +133,7 @@ func (h *Server) uiSession(w http.ResponseWriter, r *http.Request) { } valid := input.Token != "" && h.sessions.valid(input.Token, true) if input.Key != "" { - hash := sha256.Sum256([]byte(input.Key)) - valid = subtle.ConstantTimeCompare(hash[:], h.key[:]) == 1 + valid = h.validKey(input.Key) } if !valid { write(w, 401, map[string]any{"error": map[string]string{"message": "Acesso inválido ou expirado. Abra novamente com ranjit ui."}}) diff --git a/internal/httpapi/handlers.go b/internal/httpapi/handlers.go index ecbe5bb..90bf24c 100644 --- a/internal/httpapi/handlers.go +++ b/internal/httpapi/handlers.go @@ -9,12 +9,16 @@ import ( ) func (h *Server) connect(w http.ResponseWriter, r *http.Request) { + if values := r.Header.Values("Idempotency-Key"); len(values) > 1 || len(values) == 1 && !ranjit.ValidIdempotencyKey(values[0]) { + h.problem(w, fmt.Errorf("%w: invalid Idempotency-Key", ranjit.ErrInvalid)) + return + } var input ranjit.ConnectRequest if err := decode(r, &input); err != nil { h.problem(w, err) return } - result, err := h.service.Connect(r.Context(), input) + result, err := h.service.ConnectWithKey(r.Context(), input, r.Header.Get("Idempotency-Key")) if err != nil { h.problem(w, err) return @@ -136,3 +140,25 @@ func (h *Server) searchTransactions(w http.ResponseWriter, r *http.Request) { } write(w, 200, result) } + +func (h *Server) webhookDeliveries(w http.ResponseWriter, r *http.Request) { + cursor, limit, err := pagination(r) + if err != nil { + h.problem(w, err) + return + } + result, err := h.service.Store.WebhookDeliveries(r.Context(), cursor, limit) + if err != nil { + h.problem(w, err) + return + } + write(w, http.StatusOK, result) +} + +func (h *Server) retryWebhook(w http.ResponseWriter, r *http.Request) { + if err := h.service.Store.RetryWebhook(r.Context(), r.PathValue("id"), h.service.Now()); err != nil { + h.problem(w, err) + return + } + w.WriteHeader(http.StatusAccepted) +} diff --git a/internal/httpapi/server.go b/internal/httpapi/server.go index eefa611..5415a46 100644 --- a/internal/httpapi/server.go +++ b/internal/httpapi/server.go @@ -22,21 +22,21 @@ import ( type Server struct { sessions sessions service *service.Service - key [32]byte + keys func(time.Time) ([]string, error) logger *slog.Logger } -// Option adds authenticated operational information without exposing credentials. -type Option func(*http.ServeMux) +// Option configures authentication or operational routes. +type Option func(*Server, *http.ServeMux) func Diagnostics(fn func() any) Option { - return func(mux *http.ServeMux) { + return func(_ *Server, mux *http.ServeMux) { mux.HandleFunc("GET /v1/diagnostics", func(w http.ResponseWriter, r *http.Request) { write(w, 200, fn()) }) } } func New(s *service.Service, apiKey string, logger *slog.Logger, options ...Option) http.Handler { - h := &Server{service: s, key: sha256.Sum256([]byte(apiKey)), logger: logger} + h := &Server{service: s, keys: func(time.Time) ([]string, error) { return []string{apiKey}, nil }, logger: logger} mux := http.NewServeMux() mux.HandleFunc("GET /app", h.dashboard) mux.HandleFunc("GET /app/", h.dashboard) @@ -57,8 +57,10 @@ func New(s *service.Service, apiKey string, logger *slog.Logger, options ...Opti mux.HandleFunc("POST /sandbox/authorize", h.decide) api := http.NewServeMux() for _, option := range options { - option(api) + option(h, api) } + api.HandleFunc("GET /v1/webhooks/deliveries", h.webhookDeliveries) + api.HandleFunc("POST /v1/webhooks/deliveries/{id}/retry", h.retryWebhook) api.HandleFunc("GET /v1/institutions", func(w http.ResponseWriter, r *http.Request) { write(w, http.StatusOK, ranjit.Page[ranjit.Institution]{Data: s.Source.Institutions()}) }) @@ -91,8 +93,7 @@ func (h *Server) authenticate(next http.Handler) http.Handler { } } prefix, token, ok := strings.Cut(r.Header.Get("Authorization"), " ") - got := sha256.Sum256([]byte(token)) - if !ok || !strings.EqualFold(prefix, "Bearer") || token == "" || subtle.ConstantTimeCompare(got[:], h.key[:]) != 1 { + if !ok || !strings.EqualFold(prefix, "Bearer") || token == "" || !h.validKey(token) { w.Header().Set("WWW-Authenticate", "Bearer") write(w, http.StatusUnauthorized, map[string]any{"error": map[string]string{"code": "unauthorized", "message": "a valid bearer token is required"}}) return @@ -191,6 +192,10 @@ func (h *Server) problem(w http.ResponseWriter, err error) { status, code, message = http.StatusNotFound, "not_found", "resource not found" case errors.Is(err, ranjit.ErrConsent): status, code, message = http.StatusGone, "invalid_authorization", ranjit.ErrConsent.Error() + case errors.Is(err, ranjit.ErrIdempotency): + status, code, message = http.StatusConflict, "idempotency_conflict", ranjit.ErrIdempotency.Error() + case errors.Is(err, ranjit.ErrWebhookState): + status, code, message = http.StatusConflict, "webhook_not_retryable", ranjit.ErrWebhookState.Error() case errors.Is(err, ranjit.ErrConflict): status, code, message = http.StatusConflict, "inactive_connection", ranjit.ErrConflict.Error() case errors.Is(err, ranjit.ErrInvalid): @@ -204,3 +209,21 @@ func (h *Server) problem(w http.ResponseWriter, err error) { } write(w, status, map[string]any{"error": map[string]string{"code": code, "message": message}}) } + +func APIKeys(source func(time.Time) ([]string, error)) Option { + return func(h *Server, _ *http.ServeMux) { h.keys = source } +} + +func (h *Server) validKey(token string) bool { + keys, err := h.keys(h.service.Now()) + if err != nil || token == "" { + return false + } + got := sha256.Sum256([]byte(token)) + matched := 0 + for _, key := range keys { + want := sha256.Sum256([]byte(key)) + matched |= subtle.ConstantTimeCompare(got[:], want[:]) + } + return matched == 1 +} diff --git a/internal/service/idempotency_test.go b/internal/service/idempotency_test.go new file mode 100644 index 0000000..39df5f8 --- /dev/null +++ b/internal/service/idempotency_test.go @@ -0,0 +1,71 @@ +package service + +import ( + "net/url" + "path/filepath" + "testing" + "time" + + "github.com/getcortexlabs/ranjit" + "github.com/getcortexlabs/ranjit/internal/provider/sandbox" + "github.com/getcortexlabs/ranjit/internal/store" +) + +func TestDirectReplayDoesNotVerifyAgain(t *testing.T) { + db, err := store.Open(t.Context(), filepath.Join(t.TempDir(), "db")) + if err != nil { + t.Fatal(err) + } + defer db.Close() + bank := &profileSource{key: "binding"} + svc := New(db, bank, "http://localhost:8080") + input := ranjit.ConnectRequest{CustomerID: "customer", InstitutionID: "inter"} + first, err := svc.ConnectWithKey(t.Context(), input, "operation-key-1234") + if err != nil { + t.Fatal(err) + } + // Even if the profile becomes unavailable, replay returns the existing grant. + svc.Source = sandbox.Source{} + again, err := svc.ConnectWithKey(t.Context(), input, "operation-key-1234") + if err != nil || again.Connection.ID != first.Connection.ID || bank.calls != 1 { + t.Fatal(again, err, bank.calls) + } +} + +func TestSandboxReplaySurvivesRestartButNotConsentExpiry(t *testing.T) { + path := filepath.Join(t.TempDir(), "db") + db, err := store.Open(t.Context(), path) + if err != nil { + t.Fatal(err) + } + now := time.Now().UTC().Truncate(time.Millisecond) + svc := New(db, sandbox.Source{}, "http://localhost:8080") + svc.Now = func() time.Time { return now } + input := ranjit.ConnectRequest{CustomerID: "customer", InstitutionID: "sandbox-bank"} + key := "operation-key-1234" + first, err := svc.ConnectWithKey(t.Context(), input, key) + if err != nil { + t.Fatal(err) + } + db.Close() + db, err = store.Open(t.Context(), path) + if err != nil { + t.Fatal(err) + } + defer db.Close() + svc = New(db, sandbox.Source{}, "http://localhost:8080") + svc.Now = func() time.Time { return now } + next, err := svc.ConnectWithKey(t.Context(), input, key) + if err != nil || next.AuthorizationURL != first.AuthorizationURL { + t.Fatal(next, err) + } + link, _ := url.Parse(next.AuthorizationURL) + if _, err = svc.Consent(t.Context(), link.Query().Get("token")); err != nil { + t.Fatal("recovered token rejected", err) + } + now = now.Add(AuthorizationTTL) + next, err = svc.ConnectWithKey(t.Context(), input, key) + if err != nil || next.AuthorizationURL != "" || next.Connection.Status != "expired" || next.Connection.ID != first.Connection.ID { + t.Fatal(next, err) + } +} diff --git a/internal/service/service.go b/internal/service/service.go index 567af19..dc48af2 100644 --- a/internal/service/service.go +++ b/internal/service/service.go @@ -2,9 +2,12 @@ package service import ( "context" + "crypto/hmac" "crypto/rand" "crypto/sha256" "encoding/hex" + "encoding/json" + "errors" "fmt" "net/url" "strings" @@ -30,6 +33,23 @@ func New(db *store.Store, source provider.Source, baseURL string) *Service { } func (s *Service) Connect(ctx context.Context, req ranjit.ConnectRequest) (ranjit.ConnectResponse, error) { + return s.ConnectWithKey(ctx, req, "") +} + +func (s *Service) ConnectWithKey(ctx context.Context, req ranjit.ConnectRequest, key string) (ranjit.ConnectResponse, error) { + if key != "" && !ranjit.ValidIdempotencyKey(key) { + return ranjit.ConnectResponse{}, fmt.Errorf("%w: Idempotency-Key must contain 16 to 128 printable ASCII characters without spaces", ranjit.ErrInvalid) + } + encoded, _ := json.Marshal(req) + fingerprint := tokenHash(string(encoded)) + keyHash := "" + if key != "" { + keyHash = tokenHash(key) + c, deadline, err := s.Store.ReplayConnection(ctx, keyHash, fingerprint, s.Now()) + if !errors.Is(err, ranjit.ErrNotFound) { + return s.connectResponse(c, deadline, key, ""), err + } + } if strings.TrimSpace(req.CustomerID) != req.CustomerID || req.CustomerID == "" || len(req.CustomerID) > 128 || strings.ContainsAny(req.CustomerID, "\x00\r\n") { return ranjit.ConnectResponse{}, fmt.Errorf("%w: customer_id must contain 1 to 128 bytes without surrounding whitespace", ranjit.ErrInvalid) } @@ -61,10 +81,8 @@ func (s *Service) Connect(ctx context.Context, req ranjit.ConnectRequest) (ranji } now := s.Now().UTC().Truncate(time.Millisecond) c := ranjit.Connection{ID: ranjit.NewID("con"), CustomerID: req.CustomerID, InstitutionID: institution.ID, Provider: institution.Provider, Status: "active", CreatedAt: now, ConsentExpiresAt: now.Add(ConsentTTL), AuthorizationMode: "api_credentials", CredentialID: source.CredentialID()} - if err := s.Store.CreateAuthorizedConnection(ctx, c); err != nil { - return ranjit.ConnectResponse{}, err - } - return ranjit.ConnectResponse{Connection: c}, nil + c, deadline, err := s.Store.CreateConnectionOnce(ctx, c, nil, time.Time{}, keyHash, fingerprint) + return s.connectResponse(c, deadline, key, ""), err } if institution.Provider != "sandbox" { return ranjit.ConnectResponse{}, ranjit.ErrInvalid @@ -72,11 +90,12 @@ func (s *Service) Connect(ctx context.Context, req ranjit.ConnectRequest) (ranji now := s.Now().UTC().Truncate(time.Millisecond) token := rand.Text() c := ranjit.Connection{ID: ranjit.NewID("con"), CustomerID: req.CustomerID, InstitutionID: req.InstitutionID, Provider: "sandbox", Status: "pending", CreatedAt: now, ConsentExpiresAt: now.Add(ConsentTTL), AuthorizationMode: "sandbox_consent"} - deadline := now.Add(AuthorizationTTL) - if err := s.Store.CreateConnection(ctx, c, tokenHash(token), deadline); err != nil { - return ranjit.ConnectResponse{}, err + if key != "" { + token = sandboxToken(key, c.ID) } - return ranjit.ConnectResponse{Connection: c, AuthorizationURL: s.BaseURL + "/sandbox/authorize?token=" + url.QueryEscape(token), AuthorizationExpiresAt: deadline}, nil + deadline := now.Add(AuthorizationTTL) + c, deadline, err := s.Store.CreateConnectionOnce(ctx, c, tokenHash(token), deadline, keyHash, fingerprint) + return s.connectResponse(c, deadline, key, token), err } func (s *Service) Consent(ctx context.Context, token string) (ranjit.Connection, error) { @@ -125,3 +144,23 @@ func (s *Service) Renew(ctx context.Context, id string) (ranjit.Connection, erro } return s.Store.Renew(ctx, id, c.CredentialID, s.Now().Add(ConsentTTL), s.Now()) } + +// The caller supplies the replay secret; only its hash is retained. Domain +// separation keeps this derivation specific to simulated consent links. +func sandboxToken(key, connectionID string) string { + mac := hmac.New(sha256.New, []byte(key)) + mac.Write([]byte("ranjit:sandbox-consent:v1:" + connectionID)) + return hex.EncodeToString(mac.Sum(nil)) +} + +func (s *Service) connectResponse(c ranjit.Connection, deadline time.Time, key, token string) ranjit.ConnectResponse { + out := ranjit.ConnectResponse{Connection: c} + if c.Status == "pending" && c.Provider == "sandbox" && deadline.After(s.Now()) { + if key != "" { + token = sandboxToken(key, c.ID) + } + out.AuthorizationURL = s.BaseURL + "/sandbox/authorize?token=" + url.QueryEscape(token) + out.AuthorizationExpiresAt = deadline + } + return out +} diff --git a/internal/store/backend_test.go b/internal/store/backend_test.go new file mode 100644 index 0000000..e34dfd9 --- /dev/null +++ b/internal/store/backend_test.go @@ -0,0 +1,317 @@ +package store + +import ( + "errors" + "path/filepath" + "sync" + "testing" + "time" + + "github.com/getcortexlabs/ranjit" + "github.com/getcortexlabs/ranjit/internal/provider/sandbox" +) + +func backendStores(t *testing.T, test func(*testing.T, *Store, string)) { + t.Helper() + t.Run("sqlite", func(t *testing.T) { + path := filepath.Join(t.TempDir(), "db.sqlite") + s, err := Open(t.Context(), path) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { s.Close() }) + test(t, s, path) + }) + t.Run("postgres", func(t *testing.T) { s, dsn := postgresFixture(t); test(t, s, dsn) }) +} + +func directGrant() ranjit.Connection { + return ranjit.Connection{ID: ranjit.NewID("con"), CustomerID: "backend-customer", InstitutionID: "efi", Provider: "efi", Status: "active", AuthorizationMode: "api_credentials", CredentialID: "binding", CreatedAt: testNow, ConsentExpiresAt: testNow.Add(90 * 24 * time.Hour)} +} + +func TestBackendMigrationPreservesExistingGrantAndJob(t *testing.T) { + backendStores(t, func(t *testing.T, s *Store, path string) { + c := directGrant() + if err := s.CreateAuthorizedConnection(t.Context(), c); err != nil { + t.Fatal(err) + } + migration := "007_backend.sql" + if s.db.postgres { + migration = "002_backend.sql" + } + if _, err := s.db.ExecContext(t.Context(), `DROP TABLE webhook_deliveries; DROP TABLE connection_requests;`); err != nil { + t.Fatal(err) + } + if _, err := s.db.ExecContext(t.Context(), `DELETE FROM schema_migrations WHERE name=?`, migration); err != nil { + t.Fatal(err) + } + s.Close() + s, err := Open(t.Context(), path) + if err != nil { + t.Fatal(err) + } + defer s.Close() + got, err := s.Connection(t.Context(), c.ID, testNow) + if err != nil || got.CredentialID != c.CredentialID || got.Status != "active" { + t.Fatal(got, err) + } + j, err := s.Claim(t.Context(), testNow, time.Minute) + if err != nil || j.ConnectionID != c.ID { + t.Fatal(j, err) + } + for _, table := range []string{"connection_requests", "webhook_deliveries"} { + var count int + if err = s.db.QueryRowContext(t.Context(), `SELECT COUNT(*) FROM `+table).Scan(&count); err != nil || count != 0 { + t.Fatal(table, count, err) + } + } + }) +} + +func TestIdempotentConnectionConcurrencyRestartAndExpiry(t *testing.T) { + backendStores(t, func(t *testing.T, s *Store, path string) { + var wg sync.WaitGroup + ids := make(chan string, 16) + errs := make(chan error, 16) + for range 16 { + wg.Go(func() { + c, _, err := s.CreateConnectionOnce(t.Context(), directGrant(), nil, time.Time{}, "key-hash", "request-hash") + ids <- c.ID + errs <- err + }) + } + wg.Wait() + id := <-ids + for range 16 { + if err := <-errs; err != nil { + t.Fatal(err) + } + } + for range 15 { + if next := <-ids; next != id { + t.Fatal("duplicate grant", next, id) + } + } + for _, table := range []string{"connections", "jobs", "connection_requests"} { + var count int + if err := s.db.QueryRowContext(t.Context(), `SELECT COUNT(*) FROM `+table).Scan(&count); err != nil || count != 1 { + t.Fatal(table, count, err) + } + } + if _, _, err := s.CreateConnectionOnce(t.Context(), directGrant(), nil, time.Time{}, "key-hash", "different"); !errors.Is(err, ranjit.ErrIdempotency) { + t.Fatal(err) + } + s.Close() + s, err := Open(t.Context(), path) + if err != nil { + t.Fatal(err) + } + defer s.Close() + c, _, err := s.ReplayConnection(t.Context(), "key-hash", "request-hash", testNow.Add(time.Hour)) + if err != nil || c.ID != id { + t.Fatal(c, err) + } + if err = s.Revoke(t.Context(), id, testNow); err != nil { + t.Fatal(err) + } + c, _, err = s.ReplayConnection(t.Context(), "key-hash", "request-hash", testNow) + if err != nil || c.Status != "revoked" { + t.Fatal(c, err) + } + next := directGrant() + next.CreatedAt = testNow.Add(IdempotencyTTL) + c, _, err = s.CreateConnectionOnce(t.Context(), next, nil, time.Time{}, "key-hash", "new-request") + if err != nil || c.ID == id { + t.Fatal(c, err) + } + }) +} + +func TestConnectionRequestRollsBackWithGrant(t *testing.T) { + backendStores(t, func(t *testing.T, s *Store, _ string) { + c := directGrant() + c.Provider = "unsupported" + if _, _, err := s.CreateConnectionOnce(t.Context(), c, nil, time.Time{}, "key", "request"); err == nil { + t.Fatal("invalid grant accepted") + } + if _, _, err := s.ReplayConnection(t.Context(), "key", "request", testNow); !errors.Is(err, ranjit.ErrNotFound) { + t.Fatal("failed request retained", err) + } + c = directGrant() + if _, _, err := s.CreateConnectionOnce(t.Context(), c, nil, time.Time{}, "key", "request"); err != nil { + t.Fatal(err) + } + }) +} + +func TestWebhookDeliveryRestartFencingRetryAndTarget(t *testing.T) { + backendStores(t, func(t *testing.T, s *Store, path string) { + target := "https://backend.example/webhooks" + s.EnableWebhooks(target) + c := directGrant() + if err := s.CreateAuthorizedConnection(t.Context(), c); err != nil { + t.Fatal(err) + } + j, err := s.Claim(t.Context(), testNow, time.Minute) + if err != nil { + t.Fatal(err) + } + batch, _ := (sandbox.Source{}).Fetch(t.Context(), c) + if err = s.Complete(t.Context(), j, batch, testNow); err != nil { + t.Fatal(err) + } + if err = s.Complete(t.Context(), j, batch, testNow); !errors.Is(err, ranjit.ErrLease) { + t.Fatal(err) + } + page, err := s.WebhookDeliveries(t.Context(), "", 100) + if err != nil || len(page.Data) != 1 { + t.Fatal(page, err) + } + event := page.Data[0].Event + if event.Type != "sync.succeeded" || event.Data.JobID != j.ID || event.Data.CustomerID != c.CustomerID { + t.Fatal(event) + } + old, err := s.ClaimWebhook(t.Context(), testNow) + if err != nil { + t.Fatal(err) + } + s.Close() + s, err = Open(t.Context(), path) + if err != nil { + t.Fatal(err) + } + defer s.Close() + s.EnableWebhooks("https://another.example/webhooks") + if _, err = s.ClaimWebhook(t.Context(), testNow.Add(time.Minute)); !errors.Is(err, ranjit.ErrNotFound) { + t.Fatal("wrong target claimed", err) + } + if err = s.RetryWebhook(t.Context(), old.ID, testNow); !errors.Is(err, ranjit.ErrWebhookState) { + t.Fatal(err) + } + s.EnableWebhooks(target) + if _, err = s.ClaimWebhook(t.Context(), testNow.Add(29*time.Second)); !errors.Is(err, ranjit.ErrNotFound) { + t.Fatal("active lease reclaimed", err) + } + now := testNow.Add(30 * time.Second) + attempt, err := s.ClaimWebhook(t.Context(), now) + if err != nil { + t.Fatal(err) + } + if attempt.ID != old.ID || string(attempt.Payload) != string(old.Payload) || attempt.LeaseToken == old.LeaseToken || attempt.Attempts != 2 { + t.Fatal(attempt) + } + if err = s.FinishWebhook(t.Context(), old, 200, now); !errors.Is(err, ranjit.ErrLease) { + t.Fatal("stale worker accepted", err) + } + for { + if err = s.FinishWebhook(t.Context(), attempt, 503, now); err != nil { + t.Fatal(err) + } + page, err = s.WebhookDeliveries(t.Context(), "", 100) + if err != nil { + t.Fatal(err) + } + d := page.Data[0] + if d.Status == "failed" { + if d.Attempts != WebhookMaxAttempts { + t.Fatal(d) + } + break + } + if _, err = s.ClaimWebhook(t.Context(), now); !errors.Is(err, ranjit.ErrNotFound) { + t.Fatal("backoff ignored", err) + } + now = *d.NextAttemptAt + attempt, err = s.ClaimWebhook(t.Context(), now) + if err != nil { + t.Fatal(err) + } + } + if err = s.RetryWebhook(t.Context(), event.ID, now); err != nil { + t.Fatal(err) + } + attempt, err = s.ClaimWebhook(t.Context(), now) + if err != nil || attempt.ID != event.ID || attempt.Attempts != 1 { + t.Fatal(attempt, err) + } + if err = s.FinishWebhook(t.Context(), attempt, 204, now); err != nil { + t.Fatal(err) + } + if err = s.RetryWebhook(t.Context(), event.ID, now); !errors.Is(err, ranjit.ErrWebhookState) { + t.Fatal("delivered retry", err) + } + if err = s.Revoke(t.Context(), c.ID, now); err != nil { + t.Fatal(err) + } + page, err = s.WebhookDeliveries(t.Context(), "", 100) + if err != nil || len(page.Data) != 0 { + t.Fatal("revoked metadata retained", err) + } + }) +} + +func TestWebhookFailureEventsAndOutboxRollback(t *testing.T) { + backendStores(t, func(t *testing.T, s *Store, _ string) { + s.EnableWebhooks("https://backend.example/webhooks") + c := directGrant() + if err := s.CreateAuthorizedConnection(t.Context(), c); err != nil { + t.Fatal(err) + } + j, err := s.Claim(t.Context(), testNow, time.Minute) + if err != nil { + t.Fatal(err) + } + if err = s.Fail(t.Context(), j, "provider_unavailable", testNow); err != nil { + t.Fatal(err) + } + page, err := s.WebhookDeliveries(t.Context(), "", 100) + if err != nil || len(page.Data) != 0 { + t.Fatal("nonterminal failure emitted", err) + } + j, err = s.Claim(t.Context(), testNow.Add(time.Minute), time.Minute) + if err != nil { + t.Fatal(err) + } + if err = s.Fail(t.Context(), j, "provider_credentials", testNow.Add(time.Minute)); err != nil { + t.Fatal(err) + } + page, err = s.WebhookDeliveries(t.Context(), "", 100) + if err != nil || len(page.Data) != 1 || page.Data[0].Event.Type != "sync.failed" || page.Data[0].Event.Data.ErrorCode != "provider_credentials" { + t.Fatal(page, err) + } + j = claim(t, s, c, testNow.Add(2*time.Minute)) + if _, err = s.db.ExecContext(t.Context(), `UPDATE jobs SET attempts=? WHERE id=?`, MaxAttempts, j.ID); err != nil { + t.Fatal(err) + } + if _, err = s.Claim(t.Context(), testNow.Add(4*time.Minute), time.Minute); !errors.Is(err, ranjit.ErrNotFound) { + t.Fatal(err) + } + page, err = s.WebhookDeliveries(t.Context(), "", 100) + if err != nil || len(page.Data) != 2 { + t.Fatal("exhausted lease missing", page, err) + } + + // A failed outbox insert must also roll back the financial snapshot. + ddl := `CREATE TRIGGER reject_webhook BEFORE INSERT ON webhook_deliveries BEGIN SELECT RAISE(ABORT,'test'); END` + if s.db.postgres { + ddl = `CREATE FUNCTION reject_webhook() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'test'; END; $$; CREATE TRIGGER reject_webhook BEFORE INSERT ON webhook_deliveries FOR EACH ROW EXECUTE FUNCTION reject_webhook();` + } + if _, err = s.db.ExecContext(t.Context(), ddl); err != nil { + t.Fatal(err) + } + now := testNow.Add(5 * time.Minute) + j = claim(t, s, c, now) + batch, _ := (sandbox.Source{}).Fetch(t.Context(), c) + if err = s.Complete(t.Context(), j, batch, now); err == nil { + t.Fatal("outbox failure ignored") + } + got, err := s.Job(t.Context(), j.ID) + if err != nil || got.Status != "running" { + t.Fatal(got, err) + } + var count int + if err = s.db.QueryRowContext(t.Context(), `SELECT COUNT(*) FROM accounts`).Scan(&count); err != nil || count != 0 { + t.Fatal("partial snapshot committed", count, err) + } + }) +} diff --git a/internal/store/backup.go b/internal/store/backup.go index 60129d8..e8b81bb 100644 --- a/internal/store/backup.go +++ b/internal/store/backup.go @@ -201,7 +201,7 @@ func Restore(ctx context.Context, source, destination string, replace bool) (str return rollback, err } // Never resurrect bank collection or outstanding consent links from a backup. - _, err = restored.db.ExecContext(ctx, `UPDATE jobs SET status='cancelled',lease_token='',lease_until=0 WHERE status IN ('queued','running'); DELETE FROM sync_responses; UPDATE connections SET status='paused',token_hash=NULL WHERE authorization_mode='api_credentials' AND status IN ('active','paused','expired'); UPDATE connections SET status='expired',token_hash=NULL WHERE provider='sandbox' AND status IN ('active','pending');`) + _, err = restored.db.ExecContext(ctx, `UPDATE jobs SET status='cancelled',lease_token='',lease_until=0 WHERE status IN ('queued','running'); DELETE FROM sync_responses; DELETE FROM webhook_deliveries; UPDATE connections SET status='paused',token_hash=NULL WHERE authorization_mode='api_credentials' AND status IN ('active','paused','expired'); UPDATE connections SET status='expired',token_hash=NULL WHERE provider='sandbox' AND status IN ('active','pending');`) if err == nil { err = restored.checkpoint(ctx) } diff --git a/internal/store/connections.go b/internal/store/connections.go index 319c5f6..128dc4a 100644 --- a/internal/store/connections.go +++ b/internal/store/connections.go @@ -123,6 +123,9 @@ func (s *Store) Revoke(ctx context.Context, id string, now time.Time) error { if err = changed(result, err, ranjit.ErrNotFound); err != nil { return err } + if _, err = tx.ExecContext(ctx, `DELETE FROM webhook_deliveries WHERE connection_id = ?`, id); err != nil { + return err + } if _, err = tx.ExecContext(ctx, `DELETE FROM accounts WHERE connection_id = ?`, id); err != nil { return err } @@ -139,6 +142,9 @@ func (s *Store) Expire(ctx context.Context, now time.Time) error { return err } defer tx.Rollback() + if _, err = tx.ExecContext(ctx, `DELETE FROM connection_requests WHERE expires_at<=?`, now.UnixMilli()); err != nil { + return err + } if _, err = tx.ExecContext(ctx, `UPDATE connections SET status = 'expired', token_hash = NULL WHERE (provider <> 'file' AND status = 'active' AND consent_expires_at <= ?) OR (status = 'pending' AND authorization_expires_at <= ?)`, now.UnixMilli(), now.UnixMilli()); err != nil { return err diff --git a/internal/store/data.go b/internal/store/data.go index 9ea3387..ef281d9 100644 --- a/internal/store/data.go +++ b/internal/store/data.go @@ -39,6 +39,10 @@ func (s *Store) Complete(ctx context.Context, j ranjit.Job, batch provider.Snaps if err = writeSnapshot(ctx, tx, j.ConnectionID, batch, now); err != nil { return err } + j.ErrorCode = "" + if err = s.queueWebhook(ctx, tx, j, "sync.succeeded", now); err != nil { + return err + } return tx.Commit() } diff --git a/internal/store/idempotency.go b/internal/store/idempotency.go new file mode 100644 index 0000000..2952ae2 --- /dev/null +++ b/internal/store/idempotency.go @@ -0,0 +1,78 @@ +package store + +import ( + "context" + "database/sql" + "errors" + "time" + + "github.com/getcortexlabs/ranjit" +) + +const IdempotencyTTL = 24 * time.Hour + +func replayConnection(ctx context.Context, tx *transaction, key, fingerprint string, now time.Time) (ranjit.Connection, time.Time, error) { + var id, stored string + err := tx.QueryRowContext(ctx, `SELECT connection_id, request_hash FROM connection_requests WHERE key_hash=? AND expires_at>?`, key, now.UnixMilli()).Scan(&id, &stored) + if errors.Is(err, sql.ErrNoRows) { + return ranjit.Connection{}, time.Time{}, ranjit.ErrNotFound + } + if err != nil { + return ranjit.Connection{}, time.Time{}, err + } + if stored != fingerprint { + return ranjit.Connection{}, time.Time{}, ranjit.ErrIdempotency + } + c, err := scanConnection(tx.QueryRowContext(ctx, `SELECT `+connectionColumns+` FROM connections WHERE id=?`, id)) + if err != nil { + return c, time.Time{}, err + } + var deadline int64 + err = tx.QueryRowContext(ctx, `SELECT authorization_expires_at FROM connections WHERE id=?`, id).Scan(&deadline) + if c.Status == "active" && !c.ConsentExpiresAt.After(now) || c.Status == "pending" && deadline <= now.UnixMilli() { + c.Status = "expired" + } + return c, instant(deadline), err +} + +func (s *Store) ReplayConnection(ctx context.Context, key, fingerprint string, now time.Time) (ranjit.Connection, time.Time, error) { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return ranjit.Connection{}, time.Time{}, err + } + defer tx.Rollback() + return replayConnection(ctx, tx, key, fingerprint, now) +} + +// CreateConnectionOnce commits the request identity, grant and initial job together. +// Concurrent callers may verify credentials, but only the winning grant is persisted. +func (s *Store) CreateConnectionOnce(ctx context.Context, c ranjit.Connection, tokenHash any, deadline time.Time, key, fingerprint string) (ranjit.Connection, time.Time, error) { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return c, deadline, err + } + defer tx.Rollback() + if key != "" { + prior, until, err := replayConnection(ctx, tx, key, fingerprint, c.CreatedAt) + if !errors.Is(err, ranjit.ErrNotFound) { + return prior, until, err + } + if _, err = tx.ExecContext(ctx, `DELETE FROM connection_requests WHERE expires_at<=?`, c.CreatedAt.UnixMilli()); err != nil { + return c, deadline, err + } + } + if err = insertConnection(ctx, tx, c, tokenHash, deadline); err != nil { + return c, deadline, err + } + if c.Status == "active" { + if _, err = enqueue(ctx, tx, c.ID, c.CreatedAt); err != nil { + return c, deadline, err + } + } + if key != "" { + if _, err = tx.ExecContext(ctx, `INSERT INTO connection_requests(key_hash,request_hash,connection_id,expires_at) VALUES (?,?,?,?)`, key, fingerprint, c.ID, c.CreatedAt.Add(IdempotencyTTL).UnixMilli()); err != nil { + return c, deadline, err + } + } + return c, deadline, tx.Commit() +} diff --git a/internal/store/jobs.go b/internal/store/jobs.go index bf355b6..a3606c1 100644 --- a/internal/store/jobs.go +++ b/internal/store/jobs.go @@ -130,10 +130,30 @@ func (s *Store) ClaimSelected(ctx context.Context, now time.Time, lease time.Dur return ranjit.Job{}, err } defer tx.Rollback() - if _, err = tx.ExecContext(ctx, `UPDATE jobs SET status = 'failed', error_code = 'lease_exhausted', updated_at = ?, lease_token = '' - WHERE status = 'running' AND lease_until <= ? AND attempts >= ?`, now.UnixMilli(), now.UnixMilli(), MaxAttempts); err != nil { + rows, err := tx.QueryContext(ctx, `UPDATE jobs SET status='failed',error_code='lease_exhausted',updated_at=?,lease_token='',lease_until=0 WHERE status='running' AND lease_until<=? AND attempts>=? RETURNING `+jobColumns, now.UnixMilli(), now.UnixMilli(), MaxAttempts) + if err != nil { + return ranjit.Job{}, err + } + var exhausted []ranjit.Job + for rows.Next() { + j, e := scanJob(rows) + if e != nil { + rows.Close() + return j, e + } + exhausted = append(exhausted, j) + } + err = rows.Err() + rows.Close() + if err != nil { return ranjit.Job{}, err } + for _, j := range exhausted { + if err = s.queueWebhook(ctx, tx, j, "sync.failed", now); err != nil { + return j, err + } + } + j, err := scanJob(tx.QueryRowContext(ctx, `UPDATE jobs SET status = 'running', attempts = attempts + 1, updated_at = ?, lease_until = ?, lease_token = ? WHERE id = ( SELECT j.id FROM jobs j JOIN connections c ON c.id = j.connection_id @@ -160,9 +180,23 @@ func (s *Store) FailAfter(ctx context.Context, j ranjit.Job, code string, now ti } delay := time.Duration(1< ?`, status, code, now.UnixMilli(), now.Add(delay).UnixMilli(), j.ID, j.LeaseToken, now.UnixMilli()) - return changed(result, err, ranjit.ErrLease) + if err = changed(result, err, ranjit.ErrLease); err != nil { + return err + } + if status == "failed" { + j.ErrorCode = code + if err = s.queueWebhook(ctx, tx, j, "sync.failed", now); err != nil { + return err + } + } + return tx.Commit() } // ConfiguredConnections excludes profiles absent from this process. A separate diff --git a/internal/store/maintenance_test.go b/internal/store/maintenance_test.go index 1097295..68161e0 100644 --- a/internal/store/maintenance_test.go +++ b/internal/store/maintenance_test.go @@ -68,6 +68,7 @@ func TestBackupRestoreLockRollbackAndIntegrity(t *testing.T) { func TestDirectHistoryRetainedPauseFencesAndRestorePauses(t *testing.T) { db, c, _ := fixture(t) + db.EnableWebhooks("https://backend.example/events") ctx := t.Context() batch, _ := (sandbox.Source{}).Fetch(ctx, c) c.ID = ranjit.NewID("con") @@ -127,6 +128,10 @@ func TestDirectHistoryRetainedPauseFencesAndRestorePauses(t *testing.T) { t.Fatal(err) } defer restored.Close() + var deliveries int + if err = restored.db.QueryRow(`SELECT COUNT(*) FROM webhook_deliveries`).Scan(&deliveries); err != nil || deliveries != 0 { + t.Fatal("restore resurrected deliveries", deliveries, err) + } s, err := restored.Status(ctx, c.ID, future) if err != nil || s.Connection.Status != "paused" || s.Transactions != 4 { t.Fatalf("restored access: %+v %v", s, err) diff --git a/internal/store/migrations/007_backend.sql b/internal/store/migrations/007_backend.sql new file mode 100644 index 0000000..dc34d87 --- /dev/null +++ b/internal/store/migrations/007_backend.sql @@ -0,0 +1,28 @@ +CREATE TABLE connection_requests ( + key_hash TEXT PRIMARY KEY, + request_hash TEXT NOT NULL, + connection_id TEXT NOT NULL REFERENCES connections(id) ON DELETE CASCADE, + expires_at INTEGER NOT NULL +); +CREATE INDEX connection_requests_expiry ON connection_requests(expires_at); + +CREATE TABLE webhook_deliveries ( + id TEXT PRIMARY KEY, + job_id TEXT NOT NULL REFERENCES jobs(id) ON DELETE CASCADE, + connection_id TEXT NOT NULL REFERENCES connections(id) ON DELETE CASCADE, + target_hash TEXT NOT NULL, + event_type TEXT NOT NULL, + payload TEXT NOT NULL, + status TEXT NOT NULL CHECK (status IN ('queued', 'running', 'delivered', 'failed')), + attempts INTEGER NOT NULL DEFAULT 0, + http_status INTEGER NOT NULL DEFAULT 0, + error_code TEXT NOT NULL DEFAULT '', + created_at INTEGER NOT NULL, + updated_at INTEGER NOT NULL, + available_at INTEGER NOT NULL, + lease_until INTEGER NOT NULL DEFAULT 0, + lease_token TEXT NOT NULL DEFAULT '', + UNIQUE(job_id, event_type) +); +CREATE INDEX webhook_deliveries_available ON webhook_deliveries(target_hash, status, available_at); +CREATE INDEX webhook_deliveries_expiry ON webhook_deliveries(updated_at); diff --git a/internal/store/postgres/002_backend.sql b/internal/store/postgres/002_backend.sql new file mode 100644 index 0000000..65d80ae --- /dev/null +++ b/internal/store/postgres/002_backend.sql @@ -0,0 +1,28 @@ +CREATE TABLE connection_requests ( + key_hash TEXT PRIMARY KEY, + request_hash TEXT NOT NULL, + connection_id TEXT NOT NULL REFERENCES connections(id) ON DELETE CASCADE, + expires_at BIGINT NOT NULL +); +CREATE INDEX connection_requests_expiry ON connection_requests(expires_at); + +CREATE TABLE webhook_deliveries ( + id TEXT PRIMARY KEY, + job_id TEXT NOT NULL REFERENCES jobs(id) ON DELETE CASCADE, + connection_id TEXT NOT NULL REFERENCES connections(id) ON DELETE CASCADE, + target_hash TEXT NOT NULL, + event_type TEXT NOT NULL, + payload TEXT NOT NULL, + status TEXT NOT NULL CHECK (status IN ('queued', 'running', 'delivered', 'failed')), + attempts BIGINT NOT NULL DEFAULT 0, + http_status BIGINT NOT NULL DEFAULT 0, + error_code TEXT NOT NULL DEFAULT '', + created_at BIGINT NOT NULL, + updated_at BIGINT NOT NULL, + available_at BIGINT NOT NULL, + lease_until BIGINT NOT NULL DEFAULT 0, + lease_token TEXT NOT NULL DEFAULT '', + UNIQUE(job_id, event_type) +); +CREATE INDEX webhook_deliveries_available ON webhook_deliveries(target_hash, status, available_at); +CREATE INDEX webhook_deliveries_expiry ON webhook_deliveries(updated_at); diff --git a/internal/store/store.go b/internal/store/store.go index b258396..4666778 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -21,8 +21,9 @@ import ( var migrations embed.FS type Store struct { - db *database - guard *filelock.Lock + webhookTarget string + db *database + guard *filelock.Lock } func Open(ctx context.Context, path string) (*Store, error) { diff --git a/internal/store/webhooks.go b/internal/store/webhooks.go new file mode 100644 index 0000000..c8b6da8 --- /dev/null +++ b/internal/store/webhooks.go @@ -0,0 +1,135 @@ +package store + +import ( + "context" + "crypto/sha256" + "database/sql" + "encoding/hex" + "encoding/json" + "errors" + "time" + + "github.com/getcortexlabs/ranjit" +) + +const WebhookMaxAttempts = 8 +const WebhookRetention = 7 * 24 * time.Hour + +// EnableWebhooks must be called before starting workers. A changed destination +// does not inherit deliveries containing another endpoint's customer metadata. +func (s *Store) EnableWebhooks(destination string) { + s.webhookTarget = "" + if destination != "" { + hash := sha256.Sum256([]byte(destination)) + s.webhookTarget = hex.EncodeToString(hash[:]) + } +} + +func (s *Store) queueWebhook(ctx context.Context, tx *transaction, j ranjit.Job, eventType string, now time.Time) error { + if s.webhookTarget == "" { + return nil + } + event := ranjit.WebhookEvent{ID: ranjit.NewID("evt"), Type: eventType, CreatedAt: now.UTC(), Data: ranjit.WebhookData{JobID: j.ID, ConnectionID: j.ConnectionID, ErrorCode: j.ErrorCode}} + if err := tx.QueryRowContext(ctx, `SELECT customer_id FROM connections WHERE id=?`, j.ConnectionID).Scan(&event.Data.CustomerID); err != nil { + return err + } + data, err := json.Marshal(event) + if err != nil { + return err + } + _, err = tx.ExecContext(ctx, `INSERT INTO webhook_deliveries(id,job_id,connection_id,target_hash,event_type,payload,status,created_at,updated_at,available_at) + VALUES (?,?,?,?,?,?,'queued',?,?,?) ON CONFLICT(job_id,event_type) DO NOTHING`, event.ID, j.ID, j.ConnectionID, s.webhookTarget, eventType, string(data), now.UnixMilli(), now.UnixMilli(), now.UnixMilli()) + return err +} + +type WebhookAttempt struct { + ID string + Payload []byte + Attempts int + LeaseToken string +} + +func (s *Store) ClaimWebhook(ctx context.Context, now time.Time) (WebhookAttempt, error) { + var out WebhookAttempt + if s.webhookTarget == "" { + return out, ranjit.ErrNotFound + } + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return out, err + } + defer tx.Rollback() + if _, err = tx.ExecContext(ctx, `DELETE FROM webhook_deliveries WHERE updated_at=?`, now.UnixMilli(), s.webhookTarget, now.UnixMilli(), WebhookMaxAttempts); err != nil { + return out, err + } + var payload string + err = tx.QueryRowContext(ctx, `UPDATE webhook_deliveries SET status='running',attempts=attempts+1,lease_until=?,lease_token=?,updated_at=? WHERE id=( + SELECT id FROM webhook_deliveries WHERE target_hash=? AND attempts= 300 { + status, code = "queued", "http_error" + if statusCode == 0 { + code = "transport_error" + } + if attempt.Attempts >= WebhookMaxAttempts { + status = "failed" + } + } + delay := min(10*time.Second*time.Duration(1<?`, status, code, statusCode, now.UnixMilli(), now.Add(delay).UnixMilli(), attempt.ID, s.webhookTarget, attempt.LeaseToken, now.UnixMilli()) + return changed(result, err, ranjit.ErrLease) +} + +func (s *Store) WebhookDeliveries(ctx context.Context, cursor string, limit int) (ranjit.Page[ranjit.WebhookDelivery], error) { + page := ranjit.Page[ranjit.WebhookDelivery]{Data: []ranjit.WebhookDelivery{}} + rows, err := s.db.QueryContext(ctx, `SELECT payload,status,attempts,http_status,error_code,updated_at,available_at FROM webhook_deliveries WHERE target_hash=? AND id>? ORDER BY id LIMIT ?`, s.webhookTarget, cursor, limit+1) + if err != nil { + return page, err + } + defer rows.Close() + for rows.Next() { + var d ranjit.WebhookDelivery + var payload string + var updated, available int64 + if err = rows.Scan(&payload, &d.Status, &d.Attempts, &d.HTTPStatus, &d.ErrorCode, &updated, &available); err != nil { + return page, err + } + if err = json.Unmarshal([]byte(payload), &d.Event); err != nil { + return page, err + } + d.UpdatedAt = instant(updated) + if d.Status == "queued" { + at := instant(available) + d.NextAttemptAt = &at + } + page.Data = append(page.Data, d) + } + if len(page.Data) > limit { + page.Data = page.Data[:limit] + page.NextCursor = page.Data[limit-1].Event.ID + } + return page, rows.Err() +} + +func (s *Store) RetryWebhook(ctx context.Context, id string, now time.Time) error { + result, err := s.db.ExecContext(ctx, `UPDATE webhook_deliveries SET status='queued',attempts=0,http_status=0,error_code='',updated_at=?,available_at=? WHERE id=? AND target_hash=? AND status='failed'`, now.UnixMilli(), now.UnixMilli(), id, s.webhookTarget) + return changed(result, err, ranjit.ErrWebhookState) +} diff --git a/internal/webhook/worker.go b/internal/webhook/worker.go new file mode 100644 index 0000000..a9ec23b --- /dev/null +++ b/internal/webhook/worker.go @@ -0,0 +1,87 @@ +package webhook + +import ( + "bytes" + "context" + "crypto/hmac" + "crypto/sha256" + "encoding/hex" + "errors" + "io" + "log/slog" + "net/http" + "strconv" + "time" + + "github.com/getcortexlabs/ranjit" + "github.com/getcortexlabs/ranjit/internal/store" +) + +type Worker struct { + Store *store.Store + URL string + Secret string + Client *http.Client + Now func() time.Time + Logger *slog.Logger +} + +func New(db *store.Store, destination, secret string, logger *slog.Logger) *Worker { + transport := http.DefaultTransport.(*http.Transport).Clone() + transport.Proxy = nil + return &Worker{Store: db, URL: destination, Secret: secret, Logger: logger, Now: time.Now, Client: &http.Client{Transport: transport, Timeout: 10 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}} +} + +func (w *Worker) Run(ctx context.Context) { + defer w.Client.CloseIdleConnections() + ticker := time.NewTicker(time.Second) + defer ticker.Stop() + for { + if err := w.Step(ctx); err != nil && ctx.Err() == nil { + w.Logger.Error("webhook delivery could not be recorded") + } + select { + case <-ctx.Done(): + return + case <-ticker.C: + } + } +} + +func (w *Worker) Step(ctx context.Context) error { + attempt, err := w.Store.ClaimWebhook(ctx, w.Now()) + if errors.Is(err, ranjit.ErrNotFound) { + return nil + } + if err != nil { + return err + } + req, err := http.NewRequestWithContext(ctx, http.MethodPost, w.URL, bytes.NewReader(attempt.Payload)) + if err != nil { + return err + } + timestamp := strconv.FormatInt(w.Now().Unix(), 10) + mac := hmac.New(sha256.New, []byte(w.Secret)) + mac.Write([]byte(timestamp + ".")) + mac.Write(attempt.Payload) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("User-Agent", "Ranjit-Webhook/1") + req.Header.Set("Ranjit-Event-ID", attempt.ID) + req.Header.Set("Ranjit-Signature", "t="+timestamp+",v1="+hex.EncodeToString(mac.Sum(nil))) + status := 0 + resp, err := w.Client.Do(req) + if err == nil { + status = resp.StatusCode + _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4096)) + resp.Body.Close() + } + // A shutdown leaves the lease recoverable instead of consuming another retry. + if ctx.Err() != nil { + return ctx.Err() + } + err = w.Store.FinishWebhook(ctx, attempt, status, w.Now()) + if errors.Is(err, ranjit.ErrLease) { + return nil + } + return err +} diff --git a/internal/webhook/worker_test.go b/internal/webhook/worker_test.go new file mode 100644 index 0000000..315a4eb --- /dev/null +++ b/internal/webhook/worker_test.go @@ -0,0 +1,93 @@ +package webhook + +import ( + "io" + "log/slog" + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/getcortexlabs/ranjit" + "github.com/getcortexlabs/ranjit/internal/provider/sandbox" + "github.com/getcortexlabs/ranjit/internal/service" + "github.com/getcortexlabs/ranjit/internal/store" + syncworker "github.com/getcortexlabs/ranjit/internal/worker" +) + +func TestSignedDeliveryRetriesAndRefusesRedirects(t *testing.T) { + now := time.Date(2026, 11, 8, 12, 0, 0, 0, time.UTC) + const secret = "webhook-test-secret-at-least-32-bytes" + var bodies, signatures []string + var unexpected int + sink := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { unexpected++; w.WriteHeader(204) })) + defer sink.Close() + receiver := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, err := io.ReadAll(r.Body) + if err != nil { + t.Error(err) + return + } + event, err := ranjit.VerifyWebhook(body, r.Header.Get("Ranjit-Signature"), secret, now) + if err != nil || event.Type != "sync.succeeded" || r.Header.Get("Ranjit-Event-ID") != event.ID { + t.Error("invalid delivered signature", err) + } + if strings.Contains(string(body), "amount_minor") || strings.Contains(string(body), "balance") { + t.Error("financial payload leaked") + } + bodies = append(bodies, string(body)) + signatures = append(signatures, r.Header.Get("Ranjit-Signature")) + switch len(bodies) { + case 1: + http.Redirect(w, r, sink.URL, http.StatusTemporaryRedirect) + case 2: + w.WriteHeader(http.StatusServiceUnavailable) + default: + w.WriteHeader(http.StatusNoContent) + } + })) + defer receiver.Close() + db, err := store.Open(t.Context(), filepath.Join(t.TempDir(), "db")) + if err != nil { + t.Fatal(err) + } + defer db.Close() + db.EnableWebhooks(receiver.URL) + source := sandbox.Source{} + svc := service.New(db, source, "http://localhost:8080") + svc.Now = func() time.Time { return now } + c := ranjit.Connection{ID: ranjit.NewID("con"), CustomerID: "test-customer", InstitutionID: "sandbox-bank", Provider: "sandbox", Status: "active", CreatedAt: now, ConsentExpiresAt: now.Add(time.Hour)} + if err = db.CreateConnection(t.Context(), c, "unused", now.Add(time.Minute)); err != nil { + t.Fatal(err) + } + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) + syncer := syncworker.New(db, source, time.Hour, logger) + syncer.Now = svc.Now + if err = syncer.Step(t.Context()); err != nil { + t.Fatal(err) + } + w := New(db, receiver.URL, secret, logger) + w.Now = svc.Now + defer w.Client.CloseIdleConnections() + for range 3 { + if err = w.Step(t.Context()); err != nil { + t.Fatal(err) + } + page, err := db.WebhookDeliveries(t.Context(), "", 100) + if err != nil || len(page.Data) != 1 { + t.Fatal(page, err) + } + if page.Data[0].NextAttemptAt != nil { + now = *page.Data[0].NextAttemptAt + } + } + if unexpected != 0 || len(bodies) != 3 || bodies[0] != bodies[2] || signatures[0] == signatures[2] { + t.Fatal("redirect followed, event changed or signature not renewed") + } + page, err := db.WebhookDeliveries(t.Context(), "", 100) + if err != nil || page.Data[0].Status != "delivered" || page.Data[0].Attempts != 3 { + t.Fatal(page, err) + } +} diff --git a/model.go b/model.go index bbd7af1..59d514e 100644 --- a/model.go +++ b/model.go @@ -11,6 +11,8 @@ import ( ) var ( + ErrWebhookState = errors.New("webhook is not failed or does not belong to the configured endpoint") + ErrIdempotency = errors.New("idempotency key was already used with a different request") ErrNotFound = errors.New("not found") ErrConflict = errors.New("connection is not active") ErrInvalid = errors.New("invalid input") diff --git a/scripts/server_smoke.py b/scripts/server_smoke.py index fc46eff..2b9fd79 100644 --- a/scripts/server_smoke.py +++ b/scripts/server_smoke.py @@ -1,15 +1,22 @@ #!/usr/bin/env python3 """Exercise the installed service and Go backend against a disposable PostgreSQL.""" +import hashlib +import hmac import json import os +import queue import secrets import subprocess import sys import time +import threading import urllib.error +import urllib.parse import urllib.request from contextlib import contextmanager +from datetime import datetime, timedelta, timezone +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer database = os.environ["RANJIT_TEST_POSTGRES_URL"] service_key, app_token = secrets.token_hex(32), secrets.token_hex(32) @@ -27,10 +34,11 @@ ) -def request(url, token=None, body=None): +def request(url, token=None, body=None, content_type="text/csv", extra_headers=None): headers = {"Authorization": "Bearer " + token} if token else {} if body is not None: - headers["Content-Type"] = "text/csv" + headers["Content-Type"] = content_type + headers.update(extra_headers or {}) req = urllib.request.Request(url, data=body, headers=headers) with urllib.request.urlopen(req, timeout=5) as response: return json.load(response) @@ -78,3 +86,79 @@ def process(command, ready_url, token=None): assert len(rows) == 2 assert sorted(row["amount"]["amount_minor"] for row in rows) == [-200, 1000] print("PostgreSQL service + Go SDK backend: import, authentication and restart passed") + + +# Verify the running binary wires its outbox worker, idempotency and key overlap. +webhook_secret = secrets.token_hex(32) +received = queue.Queue() + + +class Receiver(BaseHTTPRequestHandler): + def do_POST(self): + body = self.rfile.read(int(self.headers["Content-Length"])) + signature = self.headers["Ranjit-Signature"] + timestamp, digest = signature.split(",") + timestamp = timestamp.removeprefix("t=") + want = hmac.new(webhook_secret.encode(), timestamp.encode() + b"." + body, hashlib.sha256).hexdigest() + valid = hmac.compare_digest(digest, "v1=" + want) and abs(int(timestamp) - time.time()) < 300 + received.put((body, valid, signature)) + self.send_response(503 if received.qsize() == 1 else 204) + self.end_headers() + + def log_message(self, *_): + pass + + +receiver = ThreadingHTTPServer(("127.0.0.1", 0), Receiver) +thread = threading.Thread(target=receiver.serve_forever, daemon=True) +thread.start() +old_key = service_key +service_key = secrets.token_hex(32) +env.update( + RANJIT_API_KEY=service_key, + RANJIT_API_KEY_PREVIOUS=old_key, + RANJIT_API_KEY_PREVIOUS_EXPIRES_AT=(datetime.now(timezone.utc) + timedelta(hours=1)).isoformat(), + RANJIT_PROFILES_JSON='[{"name":"demo","provider":"sandbox"}]', + RANJIT_WEBHOOK_URL=f"http://127.0.0.1:{receiver.server_port}/webhooks/ranjit", + RANJIT_WEBHOOK_SECRET=webhook_secret, +) +operation_key = secrets.token_hex(16) +body = json.dumps({"customer_id":"webhook-customer","institution_id":"demo:sandbox-bank"}).encode() + + +def create_connection(): + return request(base + "/v1/connections", service_key, body, "application/json", {"Idempotency-Key":operation_key}) + + +def wait_delivery(status): + for _ in range(60): + deliveries = request(base + "/v1/webhooks/deliveries", service_key)["data"] + if deliveries and deliveries[0]["status"] == status and deliveries[0]["attempts"] > 0: + return deliveries[0] + time.sleep(0.5) + raise AssertionError("webhook did not reach expected status") + + +try: + with process([sys.argv[1], "serve"], base + "/readyz"): + assert request(base + "/v1/institutions", old_key)["data"] + first = create_connection() + assert create_connection()["authorization_url"] == first["authorization_url"] + link = urllib.parse.urlparse(first["authorization_url"]) + token = urllib.parse.parse_qs(link.query)["token"][0] + request(base + "/sandbox/authorize", body=urllib.parse.urlencode({"token":token,"decision":"approve"}).encode(), content_type="application/x-www-form-urlencoded") + assert wait_delivery("queued")["attempts"] == 1 + with process([sys.argv[1], "serve"], base + "/readyz"): + replay = create_connection() + assert replay["connection"]["id"] == first["connection"]["id"] + assert replay["connection"]["status"] == "active" and "authorization_url" not in replay + delivered = wait_delivery("delivered") + assert delivered["attempts"] == 2 + a, b = received.get(timeout=2), received.get(timeout=2) + assert a[0] == b[0] and a[1] and b[1] and a[2] != b[2] + assert json.loads(a[0])["data"]["connection_id"] == first["connection"]["id"] +finally: + receiver.shutdown() + receiver.server_close() + thread.join(timeout=5) +print("Idempotent creation + signed webhook retry across restart + API key overlap passed") diff --git a/webhook.go b/webhook.go new file mode 100644 index 0000000..542dbd0 --- /dev/null +++ b/webhook.go @@ -0,0 +1,82 @@ +package ranjit + +import ( + "context" + "crypto/hmac" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "net/http" + "net/url" + "strconv" + "strings" + "time" +) + +type WebhookEvent struct { + ID string `json:"id"` + Type string `json:"type"` + CreatedAt time.Time `json:"created_at"` + Data WebhookData `json:"data"` +} + +type WebhookData struct { + JobID string `json:"job_id"` + ConnectionID string `json:"connection_id"` + CustomerID string `json:"customer_id"` + ErrorCode string `json:"error_code,omitempty"` +} + +type WebhookDelivery struct { + Event WebhookEvent `json:"event"` + Status string `json:"status"` + Attempts int `json:"attempts"` + HTTPStatus int `json:"http_status,omitempty"` + ErrorCode string `json:"error_code,omitempty"` + UpdatedAt time.Time `json:"updated_at"` + NextAttemptAt *time.Time `json:"next_attempt_at,omitempty"` +} + +// VerifyWebhook authenticates the unmodified request body and rejects signatures +// older than five minutes. The receiver must also deduplicate event IDs durably. +func VerifyWebhook(body []byte, signature, secret string, now time.Time) (WebhookEvent, error) { + var event WebhookEvent + invalid := errors.New("invalid webhook signature or event") + if len(body) > 16<<10 || len(secret) < 32 { + return event, invalid + } + parts := strings.Split(signature, ",") + if len(parts) != 2 || !strings.HasPrefix(parts[0], "t=") || !strings.HasPrefix(parts[1], "v1=") { + return event, invalid + } + timestamp := strings.TrimPrefix(parts[0], "t=") + unix, err := strconv.ParseInt(timestamp, 10, 64) + if err != nil || timestamp != strconv.FormatInt(unix, 10) || unix < now.Add(-5*time.Minute).Unix() || unix > now.Add(5*time.Minute).Unix() { + return event, invalid + } + digest, err := hex.DecodeString(strings.TrimPrefix(parts[1], "v1=")) + if err != nil { + return event, invalid + } + mac := hmac.New(sha256.New, []byte(secret)) + mac.Write([]byte(timestamp + ".")) + mac.Write(body) + if !hmac.Equal(digest, mac.Sum(nil)) { + return event, invalid + } + if err := json.Unmarshal(body, &event); err != nil || event.ID == "" || event.Type == "" || event.CreatedAt.IsZero() || event.Data.JobID == "" || event.Data.ConnectionID == "" || event.Data.CustomerID == "" { + return WebhookEvent{}, invalid + } + return event, nil +} + +func (c *Client) WebhookDeliveries(ctx context.Context, cursor string, limit int) (Page[WebhookDelivery], error) { + var out Page[WebhookDelivery] + err := c.do(ctx, http.MethodGet, "/v1/webhooks/deliveries?"+pageQuery(cursor, limit).Encode(), nil, &out) + return out, err +} + +func (c *Client) RetryWebhook(ctx context.Context, eventID string) error { + return c.do(ctx, http.MethodPost, "/v1/webhooks/deliveries/"+url.PathEscape(eventID)+"/retry", nil, nil) +} diff --git a/webhook_test.go b/webhook_test.go new file mode 100644 index 0000000..7f2aff3 --- /dev/null +++ b/webhook_test.go @@ -0,0 +1,51 @@ +package ranjit + +import ( + "crypto/hmac" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "strconv" + "strings" + "testing" + "time" +) + +func TestVerifyWebhookRejectsTamperingAndReplay(t *testing.T) { + now := time.Date(2026, 11, 8, 12, 0, 0, 0, time.UTC) + secret := strings.Repeat("s", 40) + body, _ := json.Marshal(WebhookEvent{ID: "evt-test", Type: "sync.succeeded", CreatedAt: now, Data: WebhookData{JobID: "job-test", ConnectionID: "con-test", CustomerID: "customer"}}) + sign := func(body []byte, ts string) string { + mac := hmac.New(sha256.New, []byte(secret)) + mac.Write([]byte(ts + ".")) + mac.Write(body) + return "t=" + ts + ",v1=" + hex.EncodeToString(mac.Sum(nil)) + } + signature := sign(body, strconv.FormatInt(now.Unix(), 10)) + if _, err := VerifyWebhook(body, signature, secret, now); err != nil { + t.Fatal(err) + } + tests := []struct { + name string + body []byte + signature, secret string + now time.Time + }{ + {"altered body", append(append([]byte{}, body...), ' '), signature, secret, now}, + {"wrong secret", body, signature, strings.Repeat("x", 40), now}, + {"old", body, signature, secret, now.Add(5*time.Minute + time.Second)}, + {"future", body, signature, secret, now.Add(-5*time.Minute - time.Second)}, + {"duplicate", body, signature + ",v1=bad", secret, now}, + {"bad timestamp", body, sign(body, "not-a-time"), secret, now}, + {"overflow", body, sign(body, "9223372036854775807"), secret, now}, + {"oversized", []byte(strings.Repeat(" ", 16385)), signature, secret, now}, + {"empty event", []byte(`{}`), sign([]byte(`{}`), strconv.FormatInt(now.Unix(), 10)), secret, now}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if _, err := VerifyWebhook(tt.body, tt.signature, tt.secret, tt.now); err == nil { + t.Fatal("accepted") + } + }) + } +} From d656dc0d3a9338cf16407613a14f62d6586cb03a Mon Sep 17 00:00:00 2001 From: Rafael Augusto Date: Sun, 8 Nov 2026 00:56:06 -0300 Subject: [PATCH 2/2] Expire webhook metadata even when delivery is disabled --- internal/store/backend_test.go | 25 +++++++++++++++++++++++++ internal/store/connections.go | 4 ++++ 2 files changed, 29 insertions(+) diff --git a/internal/store/backend_test.go b/internal/store/backend_test.go index e34dfd9..03c6d77 100644 --- a/internal/store/backend_test.go +++ b/internal/store/backend_test.go @@ -315,3 +315,28 @@ func TestWebhookFailureEventsAndOutboxRollback(t *testing.T) { } }) } + +func TestWebhookRetentionWhileDeliveryDisabled(t *testing.T) { + backendStores(t, func(t *testing.T, s *Store, _ string) { + s.EnableWebhooks("https://backend.example/events") + c := directGrant() + if err := s.CreateAuthorizedConnection(t.Context(), c); err != nil { + t.Fatal(err) + } + j, err := s.Claim(t.Context(), testNow, time.Minute) + if err != nil { + t.Fatal(err) + } + if err = s.Fail(t.Context(), j, "provider_credentials", testNow); err != nil { + t.Fatal(err) + } + s.EnableWebhooks("") + if err = s.Expire(t.Context(), testNow.Add(WebhookRetention+time.Second)); err != nil { + t.Fatal(err) + } + var count int + if err = s.db.QueryRowContext(t.Context(), `SELECT COUNT(*) FROM webhook_deliveries`).Scan(&count); err != nil || count != 0 { + t.Fatal("delivery metadata retained", count, err) + } + }) +} diff --git a/internal/store/connections.go b/internal/store/connections.go index 128dc4a..f92ce33 100644 --- a/internal/store/connections.go +++ b/internal/store/connections.go @@ -145,6 +145,10 @@ func (s *Store) Expire(ctx context.Context, now time.Time) error { if _, err = tx.ExecContext(ctx, `DELETE FROM connection_requests WHERE expires_at<=?`, now.UnixMilli()); err != nil { return err } + // Retention still applies when delivery is disabled in the current configuration. + if _, err = tx.ExecContext(ctx, `DELETE FROM webhook_deliveries WHERE updated_at 'file' AND status = 'active' AND consent_expires_at <= ?) OR (status = 'pending' AND authorization_expires_at <= ?)`, now.UnixMilli(), now.UnixMilli()); err != nil { return err