From fb5b4a0a9fbf3b95a7a840a3027b8517b7dc7265 Mon Sep 17 00:00:00 2001 From: Henrique Fagundes Date: Thu, 26 Nov 2026 11:55:21 -0300 Subject: [PATCH 1/4] netdest: destinos SFTP, FTP/FTPS, SMB e pasta local, testados contra servidores reais Co-Authored-By: Claude Sonnet 5.5 --- go.mod | 13 + go.sum | 81 ++++++ internal/netdest/ftp.go | 122 +++++++++ internal/netdest/local.go | 100 +++++++ internal/netdest/netdest.go | 438 +++++++++++++++++++++++++++++++ internal/netdest/netdest_test.go | 181 +++++++++++++ internal/netdest/sftp.go | 139 ++++++++++ internal/netdest/smb.go | 113 ++++++++ scripts/test-netdest.sh | 19 ++ 9 files changed, 1206 insertions(+) create mode 100644 internal/netdest/ftp.go create mode 100644 internal/netdest/local.go create mode 100644 internal/netdest/netdest.go create mode 100644 internal/netdest/netdest_test.go create mode 100644 internal/netdest/sftp.go create mode 100644 internal/netdest/smb.go create mode 100755 scripts/test-netdest.sh diff --git a/go.mod b/go.mod index 81e0970..8e4ea7d 100644 --- a/go.mod +++ b/go.mod @@ -3,8 +3,11 @@ module github.com/AprendendoLinux/corujabackup go 1.26.0 require ( + github.com/cloudsoda/go-smb2 v0.0.0-20261105190815-95be04a983b8 github.com/go-pdf/fpdf v0.9.0 github.com/go-sql-driver/mysql v1.10.2 + github.com/jlaffaye/ftp v0.2.4 + github.com/pkg/sftp v1.13.13 github.com/robfig/cron/v3 v3.0.1 golang.org/x/crypto v0.59.0 google.golang.org/grpc v1.85.0 @@ -13,6 +16,16 @@ require ( require ( filippo.io/edwards25519 v1.2.0 // indirect + github.com/cloudsoda/sddl v0.0.0-20261105185302-1c8f96799263 // indirect + github.com/geoffgarside/ber v1.1.0 // indirect + github.com/hashicorp/go-uuid v1.0.3 // indirect + github.com/jcmturner/aescts/v2 v2.0.0 // indirect + github.com/jcmturner/dnsutils/v2 v2.0.0 // indirect + github.com/jcmturner/gofork v1.7.6 // indirect + github.com/jcmturner/goidentity/v6 v6.0.1 // indirect + github.com/jcmturner/gokrb5/v8 v8.4.4 // indirect + github.com/jcmturner/rpc/v2 v2.0.3 // indirect + github.com/kr/fs v0.1.0 // indirect golang.org/x/net v0.63.0 // indirect golang.org/x/sys v0.50.0 // indirect golang.org/x/text v0.44.0 // indirect diff --git a/go.sum b/go.sum index 68e680f..fd5be7d 100644 --- a/go.sum +++ b/go.sum @@ -1,5 +1,13 @@ filippo.io/edwards25519 v1.2.0 h1:crnVqOiS4jqYleHd9vaKZ+HKtHfllngJIiOpNpoJsjo= filippo.io/edwards25519 v1.2.0/go.mod h1:xzAOLCNug/yB62zG1bQ8uziwrIqIuxhctzJT18Q77mc= +github.com/cloudsoda/go-smb2 v0.0.0-20261105190815-95be04a983b8 h1:lBnZ8FJ6W+ftjYb3Exp5udAlHLLl5J3wO1nStg6abVI= +github.com/cloudsoda/go-smb2 v0.0.0-20261105190815-95be04a983b8/go.mod h1:LryNlMPoHo2c2K8tlyI/c0OH8yAryg9wPFvgRGmt2pA= +github.com/cloudsoda/sddl v0.0.0-20261105185302-1c8f96799263 h1:gua/EcVKg9gnxPrSrvHrz3jwrdnrYHKxmynexDwCrto= +github.com/cloudsoda/sddl v0.0.0-20261105185302-1c8f96799263/go.mod h1:uvR42Hb/t52HQd7x5/ZLzZEK8oihrFpgnodIJ1vte2E= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/geoffgarside/ber v1.1.0 h1:qTmFG4jJbwiSzSXoNJeHcOprVzZ8Ulde2Rrrifu5U9w= +github.com/geoffgarside/ber v1.1.0/go.mod h1:jVPKeCbj6MvQZhwLYsGwaGI52oUorHoHKNecGT85ZCc= github.com/go-pdf/fpdf v0.9.0 h1:PPvSaUuo1iMi9KkaAn90NuKi+P4gwMedWPHhj8YlJQw= github.com/go-pdf/fpdf v0.9.0/go.mod h1:oO8N111TkmKb9D7VvWGLvLJlaZUQVPM+6V42pp3iV4Y= github.com/go-sql-driver/mysql v1.10.2 h1:5TRvGvczDohUMOCRA5aCAXgfSZOo/oNDSFD/2RrChS0= @@ -8,16 +16,85 @@ github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/gorilla/securecookie v1.1.1 h1:miw7JPhV+b/lAHSXz4qd/nN9jRiAFV5FwjeKyCS8BvQ= +github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4= +github.com/gorilla/sessions v1.2.1 h1:DHd3rPN5lE3Ts3D8rKkQ8x/0kqfeNmBAaiSi+o7FsgI= +github.com/gorilla/sessions v1.2.1/go.mod h1:dk2InVEVJ0sfLlnXv9EAgkf6ecYs/i80K/zI+bUmuGM= +github.com/hashicorp/go-uuid v1.0.2/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= +github.com/hashicorp/go-uuid v1.0.3 h1:2gKiV6YVmrJ1i2CKKa9obLvRieoRGviZFL26PcT/Co8= +github.com/hashicorp/go-uuid v1.0.3/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= +github.com/jcmturner/aescts/v2 v2.0.0 h1:9YKLH6ey7H4eDBXW8khjYslgyqG2xZikXP0EQFKrle8= +github.com/jcmturner/aescts/v2 v2.0.0/go.mod h1:AiaICIRyfYg35RUkr8yESTqvSy7csK90qZ5xfvvsoNs= +github.com/jcmturner/dnsutils/v2 v2.0.0 h1:lltnkeZGL0wILNvrNiVCR6Ro5PGU/SeBvVO/8c/iPbo= +github.com/jcmturner/dnsutils/v2 v2.0.0/go.mod h1:b0TnjGOvI/n42bZa+hmXL+kFJZsFT7G4t3HTlQ184QM= +github.com/jcmturner/gofork v1.7.6 h1:QH0l3hzAU1tfT3rZCnW5zXl+orbkNMMRGJfdJjHVETg= +github.com/jcmturner/gofork v1.7.6/go.mod h1:1622LH6i/EZqLloHfE7IeZ0uEJwMSUyQ/nDd82IeqRo= +github.com/jcmturner/goidentity/v6 v6.0.1 h1:VKnZd2oEIMorCTsFBnJWbExfNN7yZr3EhJAxwOkZg6o= +github.com/jcmturner/goidentity/v6 v6.0.1/go.mod h1:X1YW3bgtvwAXju7V3LCIMpY0Gbxyjn/mY9zx4tFonSg= +github.com/jcmturner/gokrb5/v8 v8.4.4 h1:x1Sv4HaTpepFkXbt2IkL29DXRf8sOfZXo8eRKh687T8= +github.com/jcmturner/gokrb5/v8 v8.4.4/go.mod h1:1btQEpgT6k+unzCwX1KdWMEwPPkkgBtP+F6aCACiMrs= +github.com/jcmturner/rpc/v2 v2.0.3 h1:7FXXj8Ti1IaVFpSAziCZWNzbNuZmnvw/i6CqLNdWfZY= +github.com/jcmturner/rpc/v2 v2.0.3/go.mod h1:VUJYCIDm3PVOEHw8sgt091/20OJjskO/YJki3ELg/Hc= +github.com/jlaffaye/ftp v0.2.4 h1:JqI85DdkfZj8ntaHk8W9U2SC3jNfiPUU70+wtIWmlfE= +github.com/jlaffaye/ftp v0.2.4/go.mod h1:Y1ZnkzxownGIuX7xQ1mQzzkZ21+DbjVIyeKL/V+IIz4= +github.com/kr/fs v0.1.0 h1:Jskdu9ieNAYnjxsi0LbQp1ulIKZV1LAFgK1tWhpZgl8= +github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg= +github.com/pkg/sftp v1.13.13 h1:lfbNTnT3zEilT8XxmwBBb5sdqJJBTunll5OVNCZPwrs= +github.com/pkg/sftp v1.13.13/go.mod h1:uNkH9roSXglNJqM+glJJi+TQXQUm0fXFWqCFmT8hsN0= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs= github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= +github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw= +go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.6.0/go.mod h1:OFC/31mSvZgRz0V1QTNCzfAI1aIRzbiufJtkMIlEp58= golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c= golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= +golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.63.0 h1:HCoTmNh9EpD1PpK8gBNFY4gcTY4N+KQEO8ylfIKqFJ0= golang.org/x/net v0.63.0/go.mod h1:15JLg3IX1bLjHK264EZQEbIpTiR/KVLuo9CTRWd0pig= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs= golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= +golang.org/x/term v0.48.0 h1:G6UU1eiSB8nl3DzeUGt7Mg+2SctI8tPS6Z5/mBt6cOk= +golang.org/x/term v0.48.0/go.mod h1:BRDLHCZr2SUjIeBHHpRyQeC9xzSAVbzY2rvKgafnHf4= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo= golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4= gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E= google.golang.org/genproto/googleapis/rpc v0.0.0-20261123191846-1e707ab9fbc2 h1:FCWn4wv5of/ooWpbWDIeOXqI3+h2MGnV7SvvcJ8f+bQ= @@ -26,3 +103,7 @@ google.golang.org/grpc v1.85.0 h1:BPBCfuVRQ1qvBhKDOq9uvQllMvO59rKsYhXpp7Dd8vw= google.golang.org/grpc v1.85.0/go.mod h1:0rQrOD58yjal/0EaVbGBANindixsCZNQPDV3VKtaKuQ= google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc= google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/internal/netdest/ftp.go b/internal/netdest/ftp.go new file mode 100644 index 0000000..d47b7ef --- /dev/null +++ b/internal/netdest/ftp.go @@ -0,0 +1,122 @@ +package netdest + +import ( + "context" + "crypto/tls" + "errors" + "fmt" + "io" + "net/textproto" + "path" + "strings" + + "github.com/jlaffaye/ftp" +) + +type ftpConn struct { + cl *ftp.ServerConn + root string // pasta inicial do login + base string +} + +func dialFTP(ctx context.Context, c Config) (Conn, error) { + opts := []ftp.DialOption{ftp.DialWithContext(ctx), ftp.DialWithTimeout(dialTimeout)} + tc := &tls.Config{ServerName: c.Host, MinVersion: tls.VersionTLS12, InsecureSkipVerify: c.SkipVerify, //nolint:gosec // opção explícita do usuário + ClientSessionCache: tls.NewLRUClientSessionCache(16)} // vários servidores exigem reuso da sessão no canal de dados + switch c.TLS { + case TLSExplicit: + opts = append(opts, ftp.DialWithExplicitTLS(tc)) + case TLSImplicit: + opts = append(opts, ftp.DialWithTLS(tc)) + } + cl, err := ftp.Dial(c.address(), opts...) + if err != nil { + return nil, fmt.Errorf("não foi possível conectar em %s: %w", c.address(), err) + } + if err := cl.Login(c.User, c.Password); err != nil { + _ = cl.Quit() + return nil, fmt.Errorf("o servidor FTP recusou o login: %w", err) + } + root, err := cl.CurrentDir() + if err != nil { + _ = cl.Quit() + return nil, err + } + return &ftpConn{cl: cl, root: root, base: c.BasePath}, nil +} + +func (f *ftpConn) p(parts ...string) string { + return path.Join(append([]string{f.root, f.base}, parts...)...) +} + +func isFTPCode(err error, code int) bool { + var e *textproto.Error + return errors.As(err, &e) && e.Code == code +} + +func (f *ftpConn) MkdirAll(dir string) error { + cur := f.root + for _, seg := range strings.Split(path.Join(f.base, dir), "/") { + if seg == "" || seg == "." { + continue + } + cur = path.Join(cur, seg) + if err := f.cl.MakeDir(cur); err != nil { + // já existe? Confirma entrando na pasta (os códigos de erro variam entre servidores) + if cerr := f.cl.ChangeDir(cur); cerr != nil { + return err + } + if cerr := f.cl.ChangeDir(f.root); cerr != nil { + return cerr + } + } + } + return nil +} + +func (f *ftpConn) Write(_ context.Context, dir, name string, r io.Reader) error { + return f.cl.Stor(f.p(dir, name), r) +} + +func (f *ftpConn) Open(_ context.Context, dir, name string) (io.ReadCloser, error) { + return f.cl.Retr(f.p(dir, name)) +} + +func (f *ftpConn) Size(dir, name string) (int64, error) { + if n, err := f.cl.FileSize(f.p(dir, name)); err == nil { + return n, nil + } + files, err := f.List(dir) // servidores sem o comando SIZE + if err != nil { + return 0, err + } + for _, x := range files { + if x.Name == name { + return x.Size, nil + } + } + return 0, errors.New("arquivo não encontrado no destino") +} + +func (f *ftpConn) List(dir string) ([]File, error) { + es, err := f.cl.List(f.p(dir)) + if isFTPCode(err, ftp.StatusFileUnavailable) { + return nil, nil + } + if err != nil { + return nil, err + } + var out []File + for _, e := range es { + if e.Type == ftp.EntryTypeFile { + out = append(out, File{Name: path.Base(e.Name), Size: int64(e.Size), Modified: e.Time}) //nolint:gosec + } + } + return out, nil +} + +func (f *ftpConn) Rename(dir, from, to string) error { + return f.cl.Rename(f.p(dir, from), f.p(dir, to)) +} +func (f *ftpConn) Remove(dir, name string) error { return f.cl.Delete(f.p(dir, name)) } +func (f *ftpConn) Close() error { return f.cl.Quit() } diff --git a/internal/netdest/local.go b/internal/netdest/local.go new file mode 100644 index 0000000..9f5a20f --- /dev/null +++ b/internal/netdest/local.go @@ -0,0 +1,100 @@ +package netdest + +import ( + "context" + "errors" + "fmt" + "io" + "io/fs" + "os" + "path/filepath" +) + +// localConn grava numa pasta do próprio agente (um volume montado no host: NFS, iSCSI, disco USB...). Usa os.Root, que +// impede que qualquer caminho (inclusive por link simbólico) escape da raiz de destinos. +type localConn struct { + root *os.Root + base string +} + +func openLocal(c Config, env Env) (Conn, error) { + if env.LocalRoot == "" { + return nil, errors.New("este agente não tem uma raiz para destinos locais (CORUJA_DEST_DIR)") + } + r, err := os.OpenRoot(env.LocalRoot) + if err != nil { + return nil, fmt.Errorf("a raiz de destinos %s não existe no agente: monte o volume nela (veja a documentação): %w", env.LocalRoot, err) + } + return &localConn{root: r, base: c.BasePath}, nil +} + +func (l *localConn) p(parts ...string) string { + p := filepath.Join(append([]string{l.base}, parts...)...) + if p == "" { + return "." + } + return p +} + +func (l *localConn) MkdirAll(dir string) error { + p := l.p(dir) + if p == "." { + return nil + } + return l.root.MkdirAll(p, 0o750) +} + +func (l *localConn) Write(_ context.Context, dir, name string, r io.Reader) error { + f, err := l.root.OpenFile(l.p(dir, name), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o640) + if err != nil { + return err + } + _, err = io.Copy(f, r) + if serr := f.Sync(); err == nil { + err = serr + } + if cerr := f.Close(); err == nil { + err = cerr + } + return err +} + +func (l *localConn) Open(_ context.Context, dir, name string) (io.ReadCloser, error) { + return l.root.Open(l.p(dir, name)) +} + +func (l *localConn) Size(dir, name string) (int64, error) { + st, err := l.root.Stat(l.p(dir, name)) + if err != nil { + return 0, err + } + return st.Size(), nil +} + +func (l *localConn) List(dir string) ([]File, error) { + d, err := l.root.Open(l.p(dir)) + if errors.Is(err, fs.ErrNotExist) { + return nil, nil + } + if err != nil { + return nil, err + } + defer d.Close() + es, err := d.ReadDir(-1) + if err != nil { + return nil, err + } + var out []File + for _, e := range es { + if info, ierr := e.Info(); ierr == nil && info.Mode().IsRegular() { + out = append(out, File{Name: e.Name(), Size: info.Size(), Modified: info.ModTime()}) + } + } + return out, nil +} + +func (l *localConn) Rename(dir, from, to string) error { + return l.root.Rename(l.p(dir, from), l.p(dir, to)) +} +func (l *localConn) Remove(dir, name string) error { return l.root.Remove(l.p(dir, name)) } +func (l *localConn) Close() error { return l.root.Close() } diff --git a/internal/netdest/netdest.go b/internal/netdest/netdest.go new file mode 100644 index 0000000..caa85a3 --- /dev/null +++ b/internal/netdest/netdest.go @@ -0,0 +1,438 @@ +// Package netdest implementa os destinos "diretos do agente": SFTP, FTP/FTPS, SMB/CIFS e pasta local (volume montado no +// host, o que cobre NFS e iSCSI). Quem envia, confere e aplica a retenção é o AGENTE, que é quem alcança a rede onde o +// destino está. +package netdest + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "io" + "net" + "os" + "path" + "regexp" + "strconv" + "strings" + "time" + + "github.com/AprendendoLinux/corujabackup/internal/cloud" +) + +const ( + TypeSFTP = "sftp" + TypeFTP = "ftp" + TypeSMB = "smb" + TypeLocal = "local" + + // Modos de TLS do FTP. + TLSExplicit = "explicit" // FTPS (AUTH TLS), recomendado + TLSImplicit = "implicit" + TLSNone = "none" // senha e dados em texto puro + + VerifyFull = "full" // relê o arquivo do destino e compara o SHA-256 + VerifySize = "size" // só compara o tamanho (não relê) + + dialTimeout = 20 * time.Second + partSuffix = ".coruja-part" +) + +// Is informa se o tipo é um destino direto do agente. +func Is(typ string) bool { + return typ == TypeSFTP || typ == TypeFTP || typ == TypeSMB || typ == TypeLocal +} + +// Config descreve um destino. Viaja para o agente pelo canal TLS e fica cifrada no Server. +type Config struct { + Type string `json:"type"` + Host string `json:"host,omitempty"` + Port int `json:"port,omitempty"` + User string `json:"user,omitempty"` + Password string `json:"password,omitempty"` + PrivateKey string `json:"private_key,omitempty"` // SFTP (PEM), alternativa à senha + HostKey string `json:"host_key,omitempty"` // SFTP: impressão digital SHA256 fixada + TLS string `json:"tls,omitempty"` // FTP + SkipVerify bool `json:"skip_verify,omitempty"` // FTPS com certificado próprio + Share string `json:"share,omitempty"` // SMB + Domain string `json:"domain,omitempty"` // SMB + BasePath string `json:"base_path,omitempty"` // pasta base dentro do destino + Verify string `json:"verify,omitempty"` +} + +var ( + hostRE = regexp.MustCompile(`^[A-Za-z0-9]([A-Za-z0-9.\-]{0,251}[A-Za-z0-9])?$|^[0-9a-fA-F:]+$`) + shareRE = regexp.MustCompile(`^[^\\/:*?"<>|\x00]{1,80}$`) +) + +// DefaultPort devolve a porta padrão do protocolo. +func DefaultPort(c Config) int { + switch c.Type { + case TypeSFTP: + return 22 + case TypeFTP: + if c.TLS == TLSImplicit { + return 990 + } + return 21 + case TypeSMB: + return 445 + } + return 0 +} + +// CleanPath valida um caminho relativo (sem "..", sem barras invertidas). Vazio é permitido. +func CleanPath(p string) (string, error) { + p = strings.Trim(strings.TrimSpace(p), "/") + if p == "" { + return "", nil + } + for _, s := range strings.Split(p, "/") { + if s == "" || s == "." || s == ".." || len(s) > 200 || strings.ContainsAny(s, "\\\x00\r\n:*?\"<>|") { + return "", fmt.Errorf("caminho inválido: %q", p) + } + } + return p, nil +} + +// Normalize valida e completa a configuração. +func (c *Config) Normalize() error { + c.Host, c.User, c.Share, c.Domain = strings.TrimSpace(c.Host), strings.TrimSpace(c.User), strings.Trim(strings.TrimSpace(c.Share), `/\`), strings.TrimSpace(c.Domain) + abs := c.Type == TypeSFTP && strings.HasPrefix(strings.TrimSpace(c.BasePath), "/") + bp, err := CleanPath(c.BasePath) + if err != nil { + return err + } + if abs { + bp = "/" + bp // no SFTP, caminho começado por "/" é absoluto no servidor + } + c.BasePath = bp + if c.Verify == "" { + c.Verify = VerifyFull + } + if c.Verify != VerifyFull && c.Verify != VerifySize { + return errors.New("modo de conferência inválido") + } + if strings.ContainsAny(c.User+c.Password+c.Domain, "\r\n\x00") { + return errors.New("usuário ou senha com caracteres inválidos") + } + if c.Type == TypeLocal { + return nil + } + if !Is(c.Type) { + return fmt.Errorf("tipo de destino desconhecido: %q", c.Type) + } + if !hostRE.MatchString(c.Host) { + return errors.New("informe o endereço do servidor (nome ou IP, sem protocolo nem porta)") + } + if c.Type == TypeFTP { + if c.TLS == "" { + c.TLS = TLSExplicit + } + if c.TLS != TLSExplicit && c.TLS != TLSImplicit && c.TLS != TLSNone { + return errors.New("modo de TLS inválido") + } + } + if c.Port == 0 { + c.Port = DefaultPort(*c) + } + if c.Port < 1 || c.Port > 65535 { + return errors.New("porta inválida") + } + if c.User == "" { + return errors.New("informe o usuário") + } + if c.Type == TypeSFTP && c.Password == "" && c.PrivateKey == "" { + return errors.New("informe a senha ou a chave privada") + } + if c.Type == TypeSMB && !shareRE.MatchString(c.Share) { + return errors.New("informe o nome do compartilhamento SMB") + } + return nil +} + +// Label é um resumo legível (sem segredos). +func (c Config) Label() string { + switch c.Type { + case TypeLocal: + return "pasta /" + strings.TrimPrefix(c.BasePath, "/") + case TypeSMB: + return fmt.Sprintf(`//%s/%s (%s)`, c.Host, c.Share, c.User) + } + return fmt.Sprintf("%s@%s:%d", c.User, c.Host, c.Port) +} + +func (c Config) address() string { return net.JoinHostPort(c.Host, strconv.Itoa(c.Port)) } + +// File é um arquivo no destino. +type File struct { + Name string + Size int64 + Modified time.Time +} + +// Conn é uma conexão aberta com um destino. Os caminhos (dir) são relativos à pasta base. +type Conn interface { + MkdirAll(dir string) error + Write(ctx context.Context, dir, name string, r io.Reader) error + Open(ctx context.Context, dir, name string) (io.ReadCloser, error) + Size(dir, name string) (int64, error) + List(dir string) ([]File, error) // só arquivos; pasta inexistente = lista vazia + Rename(dir, from, to string) error + Remove(dir, name string) error + Close() error +} + +// Env é o contexto local do agente. +type Env struct { + LocalRoot string // raiz permitida para destinos "local" (ex.: /destinos) +} + +// Dial abre a conexão. Para SFTP sem impressão digital fixada, devolve a encontrada em seen (primeiro contato). +func Dial(ctx context.Context, c Config, env Env) (conn Conn, seen string, err error) { + if err = c.Normalize(); err != nil { + return nil, "", err + } + switch c.Type { + case TypeSFTP: + return dialSFTP(ctx, c) + case TypeFTP: + conn, err = dialFTP(ctx, c) + case TypeSMB: + conn, err = dialSMB(ctx, c) + case TypeLocal: + conn, err = openLocal(c, env) + } + return conn, "", err +} + +type ctxReader struct { + ctx context.Context + r io.Reader + n int64 + on func(int64) +} + +func (c *ctxReader) Read(p []byte) (int, error) { + if err := c.ctx.Err(); err != nil { + return 0, err + } + n, err := c.r.Read(p) + c.n += int64(n) + if c.on != nil && n > 0 { + c.on(c.n) + } + return n, err +} + +// Job é o que o agente precisa para enviar um backup. +type Job struct { + Folder string // pasta do job dentro do destino + LocalPath string // arquivo gerado pelo agente + Name string // nome final + SHA256 string // do arquivo local + Prefix string // prefixo dos arquivos do job (para a retenção) + Keep int + KeepDays int + Now time.Time +} + +// Result é o resultado de um envio conferido. +type Result struct { + Path string + Hash string + VerifiedBy string // sha256 | size + Retention []string +} + +// Send envia o arquivo com nome temporário, confere, renomeia e SÓ ENTÃO aplica a retenção. +func Send(ctx context.Context, c Config, env Env, j Job, progress func(sent, total int64)) (Result, error) { + var res Result + if err := c.Normalize(); err != nil { + return res, err + } + folder, err := CleanPath(j.Folder) + if err != nil { + return res, err + } + if c.Type == TypeSFTP && c.HostKey == "" { + return res, errors.New("destino SFTP sem impressão digital do servidor: teste e salve o destino de novo") + } + f, err := os.Open(j.LocalPath) + if err != nil { + return res, err + } + defer f.Close() + st, err := f.Stat() + if err != nil { + return res, err + } + total := st.Size() + conn, _, err := Dial(ctx, c, env) + if err != nil { + return res, err + } + defer conn.Close() + if err := conn.MkdirAll(folder); err != nil { + return res, fmt.Errorf("não foi possível criar a pasta no destino: %w", err) + } + part := j.Name + partSuffix + cleanup := func() { _ = conn.Remove(folder, part) } + rd := &ctxReader{ctx: ctx, r: f, on: func(n int64) { + if progress != nil { + progress(n, total) + } + }} + if err := conn.Write(ctx, folder, part, rd); err != nil { + cleanup() + return res, fmt.Errorf("falha ao gravar no destino: %w", err) + } + size, err := conn.Size(folder, part) + if err != nil { + cleanup() + return res, fmt.Errorf("não foi possível conferir o arquivo no destino: %w", err) + } + if size != total { + cleanup() + return res, fmt.Errorf("o destino guardou %d bytes, esperado %d (arquivo descartado)", size, total) + } + res.VerifiedBy = VerifySize + if c.Verify == VerifyFull { + sum, err := hashRemote(ctx, conn, folder, part) + if err != nil { + cleanup() + return res, fmt.Errorf("não foi possível reler o arquivo para conferir: %w", err) + } + if sum != j.SHA256 { + cleanup() + return res, errors.New("o SHA-256 relido do destino difere do arquivo enviado (arquivo descartado; os backups antigos foram preservados)") + } + res.Hash, res.VerifiedBy = sum, "sha256" + } + if err := conn.Rename(folder, part, j.Name); err != nil { + cleanup() + return res, fmt.Errorf("não foi possível dar o nome final ao arquivo: %w", err) + } + res.Path = path.Join(folder, j.Name) + files, err := conn.List(folder) + if err != nil { + res.Retention = append(res.Retention, "retenção ignorada: não foi possível listar a pasta: "+err.Error()) + return res, nil + } + remote := make([]cloud.RemoteFile, 0, len(files)) + for _, x := range files { + remote = append(remote, cloud.RemoteFile{Name: x.Name, Size: x.Size, Modified: x.Modified}) + } + for _, old := range cloud.Retention(remote, j.Prefix, j.Keep, j.KeepDays, j.Now) { + if old.Name == j.Name { + continue + } + if err := conn.Remove(folder, old.Name); err != nil { + res.Retention = append(res.Retention, "não foi possível apagar "+old.Name+": "+err.Error()) + continue + } + res.Retention = append(res.Retention, "removido do destino: "+old.Name) + } + return res, nil +} + +func hashRemote(ctx context.Context, conn Conn, dir, name string) (string, error) { + rc, err := conn.Open(ctx, dir, name) + if err != nil { + return "", err + } + h := sha256.New() + _, err = io.Copy(h, &ctxReader{ctx: ctx, r: rc}) + if cerr := rc.Close(); err == nil { + err = cerr + } + if err != nil { + return "", err + } + return hex.EncodeToString(h.Sum(nil)), nil +} + +// Fetch traz um arquivo do destino para localPath (restauração), conferindo o SHA-256 quando informado. +func Fetch(ctx context.Context, c Config, env Env, folder, name, localPath, wantSHA string) (int64, error) { + folder, err := CleanPath(folder) + if err != nil { + return 0, err + } + conn, _, err := Dial(ctx, c, env) + if err != nil { + return 0, err + } + defer conn.Close() + rc, err := conn.Open(ctx, folder, name) + if err != nil { + return 0, fmt.Errorf("não foi possível abrir o arquivo no destino: %w", err) + } + tmp := localPath + ".baixando" + out, err := os.OpenFile(tmp, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o600) + if err != nil { + rc.Close() + return 0, err + } + h := sha256.New() + n, err := io.Copy(io.MultiWriter(out, h), &ctxReader{ctx: ctx, r: rc}) + if cerr := rc.Close(); err == nil { + err = cerr + } + if cerr := out.Close(); err == nil { + err = cerr + } + if err == nil && wantSHA != "" && hex.EncodeToString(h.Sum(nil)) != wantSHA { + err = errors.New("o arquivo trazido do destino não confere com o SHA-256 do backup") + } + if err != nil { + _ = os.Remove(tmp) + return 0, err + } + return n, os.Rename(tmp, localPath) +} + +// TestResult é o resultado do teste de um destino. +type TestResult struct { + HostKey string `json:"host_key,omitempty"` // SFTP: impressão digital vista + Detail string `json:"detail"` +} + +// Test conecta, grava, relê e apaga um arquivo pequeno na pasta base: prova que o destino aceita tudo o que um backup precisa. +func Test(ctx context.Context, c Config, env Env) (TestResult, error) { + var out TestResult + conn, seen, err := Dial(ctx, c, env) + out.HostKey = seen + if err != nil { + return out, err + } + defer conn.Close() + if err := conn.MkdirAll(""); err != nil { + return out, fmt.Errorf("não foi possível criar a pasta base: %w", err) + } + name := fmt.Sprintf(".coruja-teste-%d", time.Now().UnixNano()) + data := []byte("teste de escrita do Coruja Backup\n") + defer func() { _ = conn.Remove("", name); _ = conn.Remove("", name+".2") }() + if err := conn.Write(ctx, "", name, strings.NewReader(string(data))); err != nil { + return out, fmt.Errorf("sem permissão para gravar: %w", err) + } + if err := conn.Rename("", name, name+".2"); err != nil { + return out, fmt.Errorf("não foi possível renomear: %w", err) + } + sum, err := hashRemote(ctx, conn, "", name+".2") + if err != nil { + return out, fmt.Errorf("não foi possível reler: %w", err) + } + if want := sha256.Sum256(data); sum != hex.EncodeToString(want[:]) { + return out, errors.New("o conteúdo relido não confere") + } + files, err := conn.List("") + if err != nil { + return out, fmt.Errorf("não foi possível listar: %w", err) + } + if err := conn.Remove("", name+".2"); err != nil { + return out, fmt.Errorf("não foi possível apagar (a retenção precisa disso): %w", err) + } + out.Detail = fmt.Sprintf("gravação, leitura, renomeação, listagem (%d arquivo(s)) e exclusão funcionando", len(files)) + return out, nil +} diff --git a/internal/netdest/netdest_test.go b/internal/netdest/netdest_test.go new file mode 100644 index 0000000..683a4c2 --- /dev/null +++ b/internal/netdest/netdest_test.go @@ -0,0 +1,181 @@ +package netdest + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "encoding/hex" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +func localFile(t *testing.T, n int) (string, string) { + t.Helper() + b := make([]byte, n) + _, _ = rand.Read(b) + p := filepath.Join(t.TempDir(), "arquivo") + if err := os.WriteFile(p, b, 0o600); err != nil { + t.Fatal(err) + } + s := sha256.Sum256(b) + return p, hex.EncodeToString(s[:]) +} + +// exercise valida o ciclo completo num destino real: teste, três envios com retenção, download conferido e limpeza. +func exercise(t *testing.T, c Config, env Env) { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + tr, err := Test(ctx, c, env) + if err != nil { + t.Fatalf("teste do destino: %v", err) + } + if c.Type == TypeSFTP { + if !strings.HasPrefix(tr.HostKey, "SHA256:") { + t.Fatalf("impressão digital: %q", tr.HostKey) + } + if _, err := Send(ctx, c, env, Job{Folder: "x", LocalPath: os.Args[0], Name: "a", Prefix: "a"}, nil); err == nil { + t.Fatal("SFTP sem chave fixada não pode enviar") + } + bad := c + bad.HostKey = "SHA256:outra" + if _, err := Test(ctx, bad, env); err == nil || !strings.Contains(err.Error(), "chave do servidor mudou") { + t.Fatalf("chave trocada deveria falhar: %v", err) + } + c.HostKey = tr.HostKey + } + folder := "Coruja Backup/servidor ção/job-" + c.Type + "-" + time.Now().Format("150405.000") + var last, lastSHA, lastPath string + for i, stamp := range []string{"20260101-010101", "20260102-010101", "20260103-010101"} { + src, sha := localFile(t, 3<<20+i*1000) + name := "web-" + stamp + ".tar.gz" + var sent int64 + res, err := Send(ctx, c, env, Job{Folder: folder, LocalPath: src, Name: name, SHA256: sha, Prefix: "web", Keep: 2, Now: time.Now()}, func(s, _ int64) { sent = s }) + if err != nil { + t.Fatalf("envio %d: %v", i, err) + } + if res.VerifiedBy != "sha256" || res.Hash != sha || sent == 0 || res.Path != folder+"/"+name { + t.Fatalf("resultado: %+v (enviado %d)", res, sent) + } + if i == 2 && (len(res.Retention) != 1 || !strings.Contains(res.Retention[0], "20260101")) { + t.Fatalf("a retenção deveria remover o mais antigo: %v", res.Retention) + } + last, lastSHA, lastPath = name, sha, src + } + _ = lastPath + conn, _, err := Dial(ctx, c, env) + if err != nil { + t.Fatal(err) + } + files, err := conn.List(folder) + if err != nil || len(files) != 2 { + t.Fatalf("lista: %v %+v", err, files) + } + if missing, err := conn.List(folder + "/nao-existe"); err != nil || len(missing) != 0 { + t.Fatalf("pasta inexistente deveria dar lista vazia: %v %v", missing, err) + } + conn.Close() + + // arquivo cujo conteúdo não confere é descartado e os antigos ficam + src, _ := localFile(t, 100000) + if _, err := Send(ctx, c, env, Job{Folder: folder, LocalPath: src, Name: "web-20260104-010101.tar.gz", SHA256: strings.Repeat("0", 64), Prefix: "web", Keep: 1, Now: time.Now()}, nil); err == nil || !strings.Contains(err.Error(), "descartado") { + t.Fatalf("deveria recusar o arquivo divergente: %v", err) + } + out := filepath.Join(t.TempDir(), "volta") + n, err := Fetch(ctx, c, env, folder, last, out, lastSHA) + if err != nil || n == 0 { + t.Fatalf("trazer de volta: %v (%d)", err, n) + } + if _, err := Fetch(ctx, c, env, folder, last, out+"2", strings.Repeat("f", 64)); err == nil { + t.Fatal("download com hash errado deveria falhar") + } + conn, _, err = Dial(ctx, c, env) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + files, _ = conn.List(folder) + if len(files) != 2 { + t.Fatalf("após a falha deveriam restar 2 arquivos: %+v", files) + } + for _, f := range files { + _ = conn.Remove(folder, f.Name) + } + + // senha errada tem mensagem clara + if c.Type != TypeLocal { + bad := c + bad.Password = "errada" + if _, err := Test(ctx, bad, env); err == nil { + t.Fatal("senha errada deveria falhar") + } + } +} + +func TestDestinoLocal(t *testing.T) { + root := t.TempDir() + exercise(t, Config{Type: TypeLocal, BasePath: "nfs/backups"}, Env{LocalRoot: root}) + // não escapa da raiz: nem com "..", nem por link simbólico + for _, p := range []string{"../fora", "a/../../fora"} { + if _, err := Test(context.Background(), Config{Type: TypeLocal, BasePath: p}, Env{LocalRoot: root}); err == nil { + t.Fatalf("%q deveria ser recusado", p) + } + } + outside := t.TempDir() + if err := os.Symlink(outside, filepath.Join(root, "atalho")); err != nil { + t.Fatal(err) + } + if _, err := Test(context.Background(), Config{Type: TypeLocal, BasePath: "atalho"}, Env{LocalRoot: root}); err == nil { + t.Fatal("link simbólico para fora da raiz deveria ser recusado") + } + if es, _ := os.ReadDir(outside); len(es) != 0 { + t.Fatalf("nada poderia ter sido escrito fora: %v", es) + } +} + +// Os testes abaixo usam servidores reais (veja scripts/test-netdest.sh). +func netHost(t *testing.T, env string) string { + h := os.Getenv(env) + if h == "" { + t.Skip("defina " + env + " (scripts/test-netdest.sh)") + } + return h +} + +func TestSFTPReal(t *testing.T) { + exercise(t, Config{Type: TypeSFTP, Host: netHost(t, "CORUJA_TEST_SFTP"), User: "coruja", Password: "s3nh@-forte", BasePath: "upload/base"}, Env{}) +} + +func TestFTPReal(t *testing.T) { + h := netHost(t, "CORUJA_TEST_FTP") + t.Run("ftps", func(t *testing.T) { + exercise(t, Config{Type: TypeFTP, Host: h, User: "coruja", Password: "s3nh@-forte", TLS: TLSExplicit, SkipVerify: true, BasePath: "base"}, Env{}) + if _, err := Test(context.Background(), Config{Type: TypeFTP, Host: h, User: "coruja", Password: "s3nh@-forte", TLS: TLSExplicit}, Env{}); err == nil { + t.Fatal("certificado autoassinado sem 'ignorar verificação' deveria falhar") + } + }) + t.Run("sem-tls", func(t *testing.T) { + exercise(t, Config{Type: TypeFTP, Host: h, User: "coruja", Password: "s3nh@-forte", TLS: TLSNone}, Env{}) + }) +} + +func TestSMBReal(t *testing.T) { + exercise(t, Config{Type: TypeSMB, Host: netHost(t, "CORUJA_TEST_SMB"), User: "coruja", Password: "s3nh@-forte", Share: "backups", BasePath: "base"}, Env{}) +} + +func TestNormalize(t *testing.T) { + bad := []Config{{Type: "x"}, {Type: TypeFTP, Host: "ftp://x", User: "a"}, {Type: TypeFTP, Host: "x", User: ""}, {Type: TypeSFTP, Host: "x", User: "a"}, + {Type: TypeSMB, Host: "x", User: "a", Share: "a/b"}, {Type: TypeFTP, Host: "x", User: "a\r\nDELE y"}, {Type: TypeLocal, BasePath: "../x"}} + for i, c := range bad { + if err := c.Normalize(); err == nil { + t.Errorf("caso %d deveria falhar: %+v", i, c) + } + } + c := Config{Type: TypeFTP, Host: "10.0.0.1", User: "a"} + if err := c.Normalize(); err != nil || c.TLS != TLSExplicit || c.Port != 21 || c.Verify != VerifyFull { + t.Fatalf("padrões: %v %+v", err, c) + } +} diff --git a/internal/netdest/sftp.go b/internal/netdest/sftp.go new file mode 100644 index 0000000..9963faf --- /dev/null +++ b/internal/netdest/sftp.go @@ -0,0 +1,139 @@ +package netdest + +import ( + "context" + "errors" + "fmt" + "io" + "io/fs" + "net" + "os" + "path" + + "github.com/pkg/sftp" + "golang.org/x/crypto/ssh" +) + +type sftpConn struct { + ssh *ssh.Client + cl *sftp.Client + base string + stop func() bool +} + +func dialSFTP(ctx context.Context, c Config) (Conn, string, error) { + var auth []ssh.AuthMethod + if c.PrivateKey != "" { + signer, err := ssh.ParsePrivateKey([]byte(c.PrivateKey)) + if err != nil { + return nil, "", errors.New("chave privada inválida (use PEM/OpenSSH sem senha)") + } + auth = append(auth, ssh.PublicKeys(signer)) + } + if c.Password != "" { + pw := c.Password + auth = append(auth, ssh.Password(pw), ssh.KeyboardInteractive(func(_, _ string, q []string, _ []bool) ([]string, error) { + a := make([]string, len(q)) + for i := range a { + a[i] = pw + } + return a, nil + })) + } + seen := "" + cfg := &ssh.ClientConfig{User: c.User, Auth: auth, Timeout: dialTimeout, + HostKeyCallback: func(_ string, _ net.Addr, key ssh.PublicKey) error { + seen = ssh.FingerprintSHA256(key) + if c.HostKey != "" && seen != c.HostKey { + return fmt.Errorf("a chave do servidor mudou (esperada %s, recebida %s): pode ser um ataque; se o servidor foi reinstalado, salve o destino de novo", c.HostKey, seen) + } + return nil + }} + d := net.Dialer{Timeout: dialTimeout} + raw, err := d.DialContext(ctx, "tcp", c.address()) + if err != nil { + return nil, "", fmt.Errorf("não foi possível conectar em %s: %w", c.address(), err) + } + cc, chans, reqs, err := ssh.NewClientConn(raw, c.address(), cfg) + if err != nil { + raw.Close() + return nil, seen, fmt.Errorf("falha no SSH: %w", err) + } + client := ssh.NewClient(cc, chans, reqs) + cl, err := sftp.NewClient(client, sftp.UseConcurrentWrites(true)) + if err != nil { + client.Close() + return nil, seen, fmt.Errorf("o servidor não aceitou SFTP: %w", err) + } + s := &sftpConn{ssh: client, cl: cl, base: c.BasePath} + s.stop = context.AfterFunc(ctx, func() { client.Close() }) // cancelamento interrompe transferências travadas + return s, seen, nil +} + +func (s *sftpConn) p(parts ...string) string { + p := path.Join(append([]string{s.base}, parts...)...) + if p == "" { + return "." + } + return p +} + +func (s *sftpConn) MkdirAll(dir string) error { return s.cl.MkdirAll(s.p(dir)) } + +func (s *sftpConn) Write(_ context.Context, dir, name string, r io.Reader) error { + f, err := s.cl.OpenFile(s.p(dir, name), os.O_WRONLY|os.O_CREATE|os.O_TRUNC) + if err != nil { + return err + } + _, err = io.Copy(f, r) + if cerr := f.Close(); err == nil { + err = cerr + } + return err +} + +func (s *sftpConn) Open(_ context.Context, dir, name string) (io.ReadCloser, error) { + return s.cl.Open(s.p(dir, name)) +} + +func (s *sftpConn) Size(dir, name string) (int64, error) { + st, err := s.cl.Stat(s.p(dir, name)) + if err != nil { + return 0, err + } + return st.Size(), nil +} + +func (s *sftpConn) List(dir string) ([]File, error) { + es, err := s.cl.ReadDir(s.p(dir)) + if errors.Is(err, fs.ErrNotExist) { + return nil, nil + } + if err != nil { + return nil, err + } + var out []File + for _, e := range es { + if e.Mode().IsRegular() { + out = append(out, File{Name: e.Name(), Size: e.Size(), Modified: e.ModTime()}) + } + } + return out, nil +} + +func (s *sftpConn) Rename(dir, from, to string) error { + a, b := s.p(dir, from), s.p(dir, to) + if err := s.cl.PosixRename(a, b); err == nil { + return nil + } + _ = s.cl.Remove(b) + return s.cl.Rename(a, b) +} + +func (s *sftpConn) Remove(dir, name string) error { return s.cl.Remove(s.p(dir, name)) } + +func (s *sftpConn) Close() error { + s.stop() + _ = s.cl.Close() + return s.ssh.Close() +} diff --git a/internal/netdest/smb.go b/internal/netdest/smb.go new file mode 100644 index 0000000..48af185 --- /dev/null +++ b/internal/netdest/smb.go @@ -0,0 +1,113 @@ +package netdest + +import ( + "context" + "errors" + "fmt" + "io" + "io/fs" + "net" + "os" + "path" + "strings" + + smb2 "github.com/cloudsoda/go-smb2" +) + +type smbConn struct { + sess *smb2.Session + share *smb2.Share + base string +} + +func dialSMB(ctx context.Context, c Config) (Conn, error) { + d := &smb2.Dialer{Initiator: &smb2.NTLMInitiator{User: c.User, Password: c.Password, Domain: c.Domain}} + dctx, cancel := context.WithTimeout(ctx, dialTimeout) + defer cancel() + nd := net.Dialer{} + raw, err := nd.DialContext(dctx, "tcp", c.address()) + if err != nil { + return nil, fmt.Errorf("não foi possível conectar em %s: %w", c.address(), err) + } + sess, err := d.DialConn(dctx, raw, c.address()) + if err != nil { + raw.Close() + return nil, fmt.Errorf("o servidor SMB recusou a conexão ou o login: %w", err) + } + share, err := sess.Mount(c.Share) + if err != nil { + _ = sess.Logoff() + return nil, fmt.Errorf("não foi possível abrir o compartilhamento %q: %w", c.Share, err) + } + return &smbConn{sess: sess, share: share.WithContext(ctx), base: c.BasePath}, nil +} + +// p monta o caminho no formato do SMB (relativo, com barras invertidas). +func (s *smbConn) p(parts ...string) string { + p := path.Join(append([]string{s.base}, parts...)...) + if p == "." { + p = "" + } + return strings.ReplaceAll(p, "/", `\`) +} + +func (s *smbConn) MkdirAll(dir string) error { + p := s.p(dir) + if p == "" { + return nil + } + return s.share.MkdirAll(p, 0o750) +} + +func (s *smbConn) Write(_ context.Context, dir, name string, r io.Reader) error { + f, err := s.share.OpenFile(s.p(dir, name), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o640) + if err != nil { + return err + } + _, err = io.CopyBuffer(struct{ io.Writer }{f}, r, make([]byte, 1<<20)) + if cerr := f.Close(); err == nil { + err = cerr + } + return err +} + +func (s *smbConn) Open(_ context.Context, dir, name string) (io.ReadCloser, error) { + return s.share.Open(s.p(dir, name)) +} + +func (s *smbConn) Size(dir, name string) (int64, error) { + st, err := s.share.Stat(s.p(dir, name)) + if err != nil { + return 0, err + } + return st.Size(), nil +} + +func (s *smbConn) List(dir string) ([]File, error) { + es, err := s.share.ReadDir(s.p(dir)) + if errors.Is(err, fs.ErrNotExist) || os.IsNotExist(err) { + return nil, nil + } + if err != nil { + return nil, err + } + var out []File + for _, e := range es { + if e.Mode().IsRegular() { + out = append(out, File{Name: e.Name(), Size: e.Size(), Modified: e.ModTime()}) + } + } + return out, nil +} + +func (s *smbConn) Rename(dir, from, to string) error { + _ = s.share.Remove(s.p(dir, to)) + return s.share.Rename(s.p(dir, from), s.p(dir, to)) +} + +func (s *smbConn) Remove(dir, name string) error { return s.share.Remove(s.p(dir, name)) } + +func (s *smbConn) Close() error { + _ = s.share.Umount() + return s.sess.Logoff() +} diff --git a/scripts/test-netdest.sh b/scripts/test-netdest.sh new file mode 100755 index 0000000..d72a047 --- /dev/null +++ b/scripts/test-netdest.sh @@ -0,0 +1,19 @@ +#!/bin/sh +# Sobe servidores reais de SFTP, FTP/FTPS e SMB em contêiner, roda os testes de internal/netdest e remove tudo. +set -e +cd "$(dirname "$0")/.." +NET=coruja-nettest +cleanup() { docker rm -f ct-sftp ct-ftp ct-smb >/dev/null 2>&1 || true; docker network rm $NET >/dev/null 2>&1 || true; } +trap cleanup EXIT +cleanup +docker network create $NET >/dev/null +docker run -d --name ct-sftp --network $NET atmoz/sftp:alpine 'coruja:s3nh@-forte:1001::upload' >/dev/null +docker run -d --name ct-ftp --network $NET -e PUBLICHOST=ct-ftp -e FTP_USER_NAME=coruja -e FTP_USER_PASS='s3nh@-forte' -e FTP_USER_HOME=/home/ftpusers/coruja \ + -e ADDED_FLAGS='--tls=1' -e TLS_CN=ct-ftp -e TLS_ORG=Coruja -e TLS_C=BR stilliard/pure-ftpd >/dev/null +docker run -d --name ct-smb --network $NET dperson/samba -u 'coruja;s3nh@-forte' -s 'backups;/share;yes;no;no;coruja' -p >/dev/null +docker exec ct-smb sh -c 'mkdir -p /share && chmod 777 /share' +# o Pure-FTPd gera parâmetros DH na primeira subida (pode levar alguns minutos): espera as portas abrirem +docker run --rm --network $NET alpine sh -c 'for h in ct-sftp:22 ct-ftp:21 ct-smb:445; do i=0; until nc -z -w 2 ${h%:*} ${h#*:}; do i=$((i+1)); [ $i -gt 200 ] && echo "sem resposta: $h" && exit 1; sleep 2; done; done' +sleep 2 +docker run --rm --network $NET -e CORUJA_TEST_SFTP=ct-sftp -e CORUJA_TEST_FTP=ct-ftp -e CORUJA_TEST_SMB=ct-smb \ + -v "$PWD":/src -v coruja-gomod126:/go/pkg/mod -w /src golang:1.26-alpine go test -count=1 ./internal/netdest "$@" From f3c4ff5ac7897b885b6e749bac43fd01ccd901de Mon Sep 17 00:00:00 2001 From: Henrique Fagundes Date: Thu, 26 Nov 2026 12:00:54 -0300 Subject: [PATCH 2/4] =?UTF-8?q?destinos=20de=20rede:=20agente=20envia/conf?= =?UTF-8?q?ere/ret=C3=A9m,=20API=20de=20teste=20e=20cria=C3=A7=C3=A3o,=20t?= =?UTF-8?q?razer=20do=20destino?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Sonnet 5.5 --- cmd/agent/main.go | 2 +- internal/agentcore/actions.go | 2 + internal/agentcore/core.go | 5 + internal/agentcore/dbjob.go | 14 ++ internal/agentcore/destjob.go | 86 ++++++++ internal/agentsrv/agentsrv.go | 13 ++ internal/cloudmgr/cloudmgr.go | 4 + internal/cloudmgr/destinations.go | 58 ++++++ internal/e2e/e2e_test.go | 73 ++++++- internal/httpapi/handlers_dest.go | 103 ++++++++++ internal/httpapi/handlers_restore.go | 4 + internal/httpapi/httpapi.go | 6 + internal/httpapi/httpapi_test.go | 7 +- internal/pb/agent.pb.go | 294 ++++++++++++++++++--------- proto/coruja/v1/agent.proto | 14 +- 15 files changed, 585 insertions(+), 100 deletions(-) create mode 100644 internal/agentcore/destjob.go create mode 100644 internal/cloudmgr/destinations.go create mode 100644 internal/httpapi/handlers_dest.go diff --git a/cmd/agent/main.go b/cmd/agent/main.go index 291dc1a..8c696d6 100644 --- a/cmd/agent/main.go +++ b/cmd/agent/main.go @@ -61,7 +61,7 @@ func main() { log.Error("não foi possível preparar a pasta de dados do agente", "erro", err.Error()) os.Exit(1) } - core := agentcore.New(agentcore.Config{HostRoot: *hostRoot, BackupDir: *backupDir, AllowedPaths: splitList(os.Getenv("CORUJA_ALLOWED_PATHS")), AllowedContainers: splitList(os.Getenv("CORUJA_ALLOWED_CONTAINERS"))}, local, log) + core := agentcore.New(agentcore.Config{HostRoot: *hostRoot, BackupDir: *backupDir, AllowedPaths: splitList(os.Getenv("CORUJA_ALLOWED_PATHS")), AllowedContainers: splitList(os.Getenv("CORUJA_ALLOWED_CONTAINERS")), DestDir: envOr("CORUJA_DEST_DIR", "/destinos")}, local, log) if err := os.MkdirAll(*backupDir, 0o750); err != nil { log.Warn("a pasta de backups não está disponível (monte um volume gravável)", "pasta", *backupDir, "erro", err.Error()) } diff --git a/internal/agentcore/actions.go b/internal/agentcore/actions.go index f81e85e..7b808cc 100644 --- a/internal/agentcore/actions.go +++ b/internal/agentcore/actions.go @@ -87,6 +87,8 @@ func (c *Core) HandleAction(parent context.Context, act *pb.AgentAction) { err = c.reupload(ctx, act, al) case "extract": err = c.extract(ctx, act, al) + case "fetch": + err = c.fetch(ctx, act, al) default: err = fmt.Errorf("ação desconhecida: %s", act.Kind) } diff --git a/internal/agentcore/core.go b/internal/agentcore/core.go index e5bdc53..7ac3ced 100644 --- a/internal/agentcore/core.go +++ b/internal/agentcore/core.go @@ -33,6 +33,8 @@ type Config struct { // peça outra coisa. Vazio = sem restrição. AllowedPaths []string // pastas que podem ser salvas (e tudo dentro delas) AllowedContainers []string // contêineres de banco em que o dump pode rodar (padrões com * e ?) + // DestDir é a única raiz onde destinos "pasta local" podem gravar (volumes montados: NFS, iSCSI, disco externo). + DestDir string } // Executor roda um job. Trocável nos testes. @@ -535,6 +537,9 @@ func (c *Core) uploadToCloud(ctx context.Context, spec *pb.JobSpec, runUID strin if res.OutputPath == "" { return info, errors.New("arquivo de backup não encontrado") } + if spec.Dest != nil { // destino de rede: quem envia, confere e aplica a retenção é este agente + return c.sendToDest(ctx, spec, res, h, progress) + } var up uploader.Result var sess *pb.UploadSession for attempt := 0; attempt < 2; attempt++ { // a segunda tentativa só acontece se a sessão expirar diff --git a/internal/agentcore/dbjob.go b/internal/agentcore/dbjob.go index 9a57a17..0794609 100644 --- a/internal/agentcore/dbjob.go +++ b/internal/agentcore/dbjob.go @@ -19,6 +19,7 @@ import ( "github.com/AprendendoLinux/corujabackup/internal/dbdump" "github.com/AprendendoLinux/corujabackup/internal/dockerapi" + "github.com/AprendendoLinux/corujabackup/internal/netdest" "github.com/AprendendoLinux/corujabackup/internal/pb" ) @@ -243,6 +244,19 @@ func (c *Core) rpc(ctx context.Context, m *pb.Rpc) ([]byte, error) { } sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name }) return json.Marshal(map[string]any{"containers": out}) + case "dest_test": + var cfg netdest.Config + if err := json.Unmarshal(m.Payload, &cfg); err != nil { + return nil, fmt.Errorf("pedido inválido: %w", err) + } + tctx, cancel := context.WithTimeout(ctx, 75*time.Second) + defer cancel() + r, err := netdest.Test(tctx, cfg, c.destEnv()) + if err != nil { + // a impressão digital vista ajuda a interface a explicar o problema + return nil, err + } + return json.Marshal(r) case "db_test": var d pb.DbSpec if err := json.Unmarshal(m.Payload, &d); err != nil { diff --git a/internal/agentcore/destjob.go b/internal/agentcore/destjob.go new file mode 100644 index 0000000..3fc35ae --- /dev/null +++ b/internal/agentcore/destjob.go @@ -0,0 +1,86 @@ +package agentcore + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "os" + "path" + "path/filepath" + + "github.com/AprendendoLinux/corujabackup/internal/netdest" + "github.com/AprendendoLinux/corujabackup/internal/pb" +) + +func (c *Core) destEnv() netdest.Env { return netdest.Env{LocalRoot: c.cfg.DestDir} } + +func destConfig(d *pb.DestSpec) (netdest.Config, error) { + var cfg netdest.Config + if d == nil { + return cfg, errors.New("este job não tem destino de rede configurado neste agente (aguarde a sincronização)") + } + if err := json.Unmarshal(d.Config, &cfg); err != nil { + return cfg, errors.New("configuração do destino ilegível") + } + return cfg, nil +} + +// sendToDest envia o backup a um destino de rede e devolve o resultado já conferido. +func (c *Core) sendToDest(ctx context.Context, spec *pb.JobSpec, res Result, h Hooks, progress func(pct int)) (CloudInfo, error) { + var info CloudInfo + cfg, err := destConfig(spec.Dest) + if err != nil { + return info, err + } + h.log("info", "conectando ao destino %s (%s)", cfg.Type, cfg.Label()) + r, err := netdest.Send(ctx, cfg, c.destEnv(), netdest.Job{Folder: spec.Dest.Folder, LocalPath: res.OutputPath, Name: res.OutputName, SHA256: res.SHA256, + Prefix: res.Prefix, Keep: int(spec.Dest.Keep), KeepDays: int(spec.Dest.KeepDays), Now: c.now().UTC()}, + func(sent, total int64) { + if total > 0 { + progress(int(sent * 100 / total)) + } + }) + if err != nil { + return info, err + } + return CloudInfo{Path: r.Path, Hash: r.Hash, VerifiedBy: r.VerifiedBy, Retention: r.Retention}, nil +} + +// fetch traz um backup do destino de rede de volta para a pasta de backups do agente (para extrair ou copiar). +func (c *Core) fetch(ctx context.Context, act *pb.AgentAction, al *actionLog) error { + c.mu.Lock() + spec := c.jobs[act.JobId] + c.mu.Unlock() + if spec == nil { + return errors.New("job desconhecido neste agente (aguarde a sincronização)") + } + cfg, err := destConfig(spec.Dest) + if err != nil { + return err + } + if !backupFileRE.MatchString(act.FileName) { + return errors.New("nome de arquivo de backup inválido") + } + dir, err := SafeSubdir(c.cfg.BackupDir, act.Subdir) + if err != nil { + return err + } + if err := os.MkdirAll(dir, 0o700); err != nil { + return err + } + local := filepath.Join(dir, act.FileName) + if _, err := os.Stat(local); err == nil { + al.flush("ok", "o arquivo já está neste agente", func(m *pb.ActionLog) { m.Path = local }) + return nil + } + al.logf("info", "trazendo %s do destino %s", path.Join(spec.Dest.Folder, act.FileName), cfg.Label()) + n, err := netdest.Fetch(ctx, cfg, c.destEnv(), spec.Dest.Folder, act.FileName, local, act.Sha256) + if err != nil { + return err + } + msg := fmt.Sprintf("%s trazido e conferido (%s)", act.FileName, HumanBytes(n)) + al.logf("info", "%s", msg) + al.flush("ok", msg, func(m *pb.ActionLog) { m.Path = local }) + return nil +} diff --git a/internal/agentsrv/agentsrv.go b/internal/agentsrv/agentsrv.go index 28b9f1a..6fd9b43 100644 --- a/internal/agentsrv/agentsrv.go +++ b/internal/agentsrv/agentsrv.go @@ -5,6 +5,7 @@ import ( "context" "crypto/subtle" "crypto/tls" + "encoding/json" "errors" "fmt" "log/slog" @@ -26,6 +27,7 @@ import ( "github.com/AprendendoLinux/corujabackup/internal/auth" "github.com/AprendendoLinux/corujabackup/internal/cloudmgr" "github.com/AprendendoLinux/corujabackup/internal/enroll" + "github.com/AprendendoLinux/corujabackup/internal/netdest" "github.com/AprendendoLinux/corujabackup/internal/pb" "github.com/AprendendoLinux/corujabackup/internal/ratelimit" "github.com/AprendendoLinux/corujabackup/internal/secrets" @@ -48,6 +50,7 @@ type conn struct { type CloudService interface { OpenUpload(ctx context.Context, j *store.Job, fileName string, size int64) (*cloudmgr.Upload, error) VerifyAndRetain(ctx context.Context, j *store.Job, fileName string, size int64, h cloudmgr.Hashes, now time.Time) cloudmgr.Verdict + DestConfig(ctx context.Context, accountID int64) (*netdest.Config, error) } // Notifier recebe o aviso de que uma execução terminou (para enviar notificações). @@ -85,6 +88,16 @@ func (s *Server) specFor(j store.Job) *pb.JobSpec { sp := SpecFromJob(j) if j.CloudAccountID != nil { sp.CloudAccountId = *j.CloudAccountID + if s.Cloud != nil { // destino de rede: o agente precisa da configuração (cifrada no Server, protegida pelo TLS) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if d, err := s.Cloud.DestConfig(ctx, *j.CloudAccountID); err != nil { + slog.Error("não foi possível ler o destino do job", "job", j.Name, "erro", err.Error()) + } else if d != nil { + b, _ := json.Marshal(d) + sp.Dest = &pb.DestSpec{Type: d.Type, Config: b, Folder: j.CloudFolder, Keep: int32(j.CloudKeep), KeepDays: int32(j.CloudKeepDays)} + } + } } if j.Kind == "database" { if cfg, err := j.OpenDB(s.Box); err == nil && cfg != nil { diff --git a/internal/cloudmgr/cloudmgr.go b/internal/cloudmgr/cloudmgr.go index 3ce4bef..e65ec6c 100644 --- a/internal/cloudmgr/cloudmgr.go +++ b/internal/cloudmgr/cloudmgr.go @@ -19,6 +19,7 @@ import ( "time" "github.com/AprendendoLinux/corujabackup/internal/cloud" + "github.com/AprendendoLinux/corujabackup/internal/netdest" "github.com/AprendendoLinux/corujabackup/internal/secrets" "github.com/AprendendoLinux/corujabackup/internal/slug" "github.com/AprendendoLinux/corujabackup/internal/store" @@ -290,6 +291,9 @@ func (m *Manager) Provider(ctx context.Context, id int64) (cloud.Provider, error if err != nil { return nil, err } + if netdest.Is(a.Type) { + return nil, ErrAgentDestination + } if a.Status != "connected" || a.Tokens == "" { return nil, ErrNotConnected } diff --git a/internal/cloudmgr/destinations.go b/internal/cloudmgr/destinations.go new file mode 100644 index 0000000..7d443ea --- /dev/null +++ b/internal/cloudmgr/destinations.go @@ -0,0 +1,58 @@ +package cloudmgr + +import ( + "context" + "encoding/json" + "errors" + + "github.com/AprendendoLinux/corujabackup/internal/netdest" +) + +// Destinos de rede (SFTP, FTP, SMB, pasta local) são guardados junto das contas de nuvem, com a configuração cifrada, mas +// quem os opera é o agente: o Server não os alcança necessariamente e não fala esses protocolos. + +// ErrAgentDestination: a operação pedida só pode ser feita pelo agente. +var ErrAgentDestination = errors.New("este destino é operado pelo agente (não há acesso a partir do Server)") + +// CreateDestination guarda um destino já testado por um agente. +func (m *Manager) CreateDestination(ctx context.Context, name string, cfg netdest.Config) (int64, error) { + if err := cfg.Normalize(); err != nil { + return 0, err + } + if cfg.Type == netdest.TypeSFTP && cfg.HostKey == "" { + return 0, errors.New("teste o destino antes de salvar: a impressão digital do servidor SFTP precisa ser confirmada") + } + b, err := json.Marshal(cfg) + if err != nil { + return 0, err + } + sealed, err := m.Box.Seal(string(b)) + if err != nil { + return 0, err + } + id, err := m.Store.CreateCloud(ctx, name, cfg.Type, sealed, "") + if err != nil { + return 0, err + } + return id, m.Store.SetCloudTokens(ctx, id, "", cfg.Label()) +} + +// DestConfig devolve a configuração de um destino de rede; (nil, nil) se a conta for uma nuvem. +func (m *Manager) DestConfig(ctx context.Context, id int64) (*netdest.Config, error) { + a, err := m.Store.GetCloud(ctx, id) + if err != nil { + return nil, err + } + if !netdest.Is(a.Type) { + return nil, nil + } + plain, err := m.Box.Open(a.Config) + if err != nil { + return nil, err + } + var c netdest.Config + if err := json.Unmarshal([]byte(plain), &c); err != nil { + return nil, err + } + return &c, nil +} diff --git a/internal/e2e/e2e_test.go b/internal/e2e/e2e_test.go index de7d275..349b40b 100644 --- a/internal/e2e/e2e_test.go +++ b/internal/e2e/e2e_test.go @@ -8,12 +8,15 @@ import ( "context" "crypto/sha256" "encoding/base64" + "encoding/hex" + "encoding/json" "errors" "io" "log/slog" "net" "net/url" "os" + "path" "path/filepath" "strings" "testing" @@ -27,6 +30,7 @@ import ( "github.com/AprendendoLinux/corujabackup/internal/cloudmgr" "github.com/AprendendoLinux/corujabackup/internal/dockerapi" "github.com/AprendendoLinux/corujabackup/internal/enroll" + "github.com/AprendendoLinux/corujabackup/internal/netdest" "github.com/AprendendoLinux/corujabackup/internal/pb" "github.com/AprendendoLinux/corujabackup/internal/secrets" "github.com/AprendendoLinux/corujabackup/internal/store" @@ -44,6 +48,7 @@ type rig struct { agent *store.Agent hostDir string bkDir string + destDir string cancel context.CancelFunc } @@ -88,12 +93,13 @@ func newRig(t *testing.T, ep cloudmgr.Endpoints) *rig { os.WriteFile(p, []byte(content), 0o644) } local, _ := agentcore.NewState(t.TempDir()) - core := agentcore.New(agentcore.Config{HostRoot: host, BackupDir: bk}, local, slog.New(slog.NewTextHandler(io.Discard, nil))) + destDir := t.TempDir() + core := agentcore.New(agentcore.Config{HostRoot: host, BackupDir: bk, DestDir: destDir}, local, slog.New(slog.NewTextHandler(io.Discard, nil))) core.SetUploadOptions(uploader.Options{Retries: 2, Sleep: func(context.Context, time.Duration) {}}) go core.Run(ctx) go agentcore.Run(ctx, slog.New(slog.NewTextHandler(io.Discard, nil)), cr, core) - r := &rig{t: t, st: st, srv: srv, mgr: mgr, core: core, agent: a, hostDir: host, bkDir: bk, cancel: cancel} + r := &rig{t: t, st: st, srv: srv, mgr: mgr, core: core, agent: a, hostDir: host, bkDir: bk, destDir: destDir, cancel: cancel} r.waitOnline() return r } @@ -758,3 +764,66 @@ func TestDropboxDePontaAPonta(t *testing.T) { t.Fatalf("as cópias antigas deveriam ficar: antes %v depois %v", before, after) } } + +// Destino de rede de ponta a ponta (pasta local do agente): o Server manda a configuração ao agente, que envia, confere +// relendo, aplica a retenção e relata; depois o arquivo é trazido de volta por uma ação. +func TestDestinoDeRedeDePontaAPonta(t *testing.T) { + r := newRig(t, cloudmgr.Endpoints{}) + ctx := context.Background() + id, err := r.mgr.CreateDestination(ctx, "NAS local", netdest.Config{Type: netdest.TypeLocal, BasePath: "nas"}) + if err != nil { + t.Fatal(err) + } + acc, _ := r.st.GetCloud(ctx, id) + if acc.Status != "connected" || acc.Type != "local" || acc.AccountLabel != "pasta /nas" { + t.Fatalf("destino: %+v", acc) + } + if _, err := r.mgr.Provider(ctx, id); !errors.Is(err, cloudmgr.ErrAgentDestination) { + t.Fatalf("o Server não opera destinos de rede: %v", err) + } + // teste pelo agente (RPC) + payload, _ := json.Marshal(netdest.Config{Type: netdest.TypeLocal, BasePath: "nas"}) + out, err := r.srv.Call(ctx, r.agent.ID, "dest_test", payload, 30*time.Second) + if err != nil || !strings.Contains(string(out), "funcionando") { + t.Fatalf("teste do destino: %v %s", err, out) + } + + jid := r.newJob("rede", id, 3, 2) + var run *store.Run + for i := 0; i < 3; i++ { + if i > 0 { + time.Sleep(1100 * time.Millisecond) + } + x := r.runNow(jid) + if x.Status != "ok" || x.CloudStatus != "ok" || x.CloudVerifiedBy != "sha256" { + t.Fatalf("execução %d: %+v\n%s", i, x, r.logs(x)) + } + run = x + } + dir := filepath.Join(r.destDir, "nas", filepath.FromSlash(path.Dir(run.CloudPath))) + es, err := os.ReadDir(dir) + if err != nil || len(es) != 2 { + t.Fatalf("a retenção deveria manter 2 no destino: %v %v (%s)", es, err, run.CloudPath) + } + // traz de volta o arquivo depois que a cópia local sumiu + local := filepath.Join(r.bkDir, "e2e", run.OutputName) + if err := os.Remove(local); err != nil { + t.Fatal(err) + } + if err := r.srv.Action(r.agent.ID, &pb.AgentAction{Kind: "fetch", RunUid: run.UID, JobId: jid, FileName: path.Base(run.CloudPath), Subdir: "e2e", Sha256: run.SHA256}); err != nil { + t.Fatal(err) + } + for i := 0; i < 100; i++ { + if _, err := os.Stat(local); err == nil { + break + } + time.Sleep(100 * time.Millisecond) + } + b, err := os.ReadFile(local) + if err != nil { + t.Fatalf("o arquivo deveria ter voltado: %v", err) + } + if sum := sha256.Sum256(b); hex.EncodeToString(sum[:]) != run.SHA256 { + t.Fatal("o arquivo trazido difere do backup") + } +} diff --git a/internal/httpapi/handlers_dest.go b/internal/httpapi/handlers_dest.go new file mode 100644 index 0000000..3239fc4 --- /dev/null +++ b/internal/httpapi/handlers_dest.go @@ -0,0 +1,103 @@ +package httpapi + +import ( + "encoding/json" + "errors" + "net/http" + "path" + "strings" + "time" + + "github.com/AprendendoLinux/corujabackup/internal/netdest" + "github.com/AprendendoLinux/corujabackup/internal/pb" + "github.com/AprendendoLinux/corujabackup/internal/store" +) + +// testDestination pede a um agente que teste o destino (é ele quem alcança a rede). Para um destino já salvo, informe id: +// a configuração guardada é usada e as credenciais não voltam para o navegador. +func (s *Server) testDestination(w http.ResponseWriter, r *http.Request, _ *ctxUser) { + var in struct { + AgentID int64 `json:"agent_id"` + ID int64 `json:"id"` + Config netdest.Config `json:"config"` + } + if !decode(w, r, &in) { + return + } + if in.AgentID <= 0 { + writeErr(w, 400, "escolha o agente que vai testar o destino") + return + } + cfg := in.Config + if in.ID > 0 { + if s.Clouds == nil { + writeErr(w, 503, "indisponível") + return + } + saved, err := s.Clouds.DestConfig(r.Context(), in.ID) + if err != nil || saved == nil { + writeErr(w, 404, "destino não encontrado") + return + } + cfg = *saved + } + if err := cfg.Normalize(); err != nil { + writeErr(w, 400, err.Error()) + return + } + payload, _ := json.Marshal(cfg) + s.agentCall(w, r, in.AgentID, "dest_test", payload, 85*time.Second) +} + +func (s *Server) createDestination(w http.ResponseWriter, r *http.Request, cu *ctxUser) { + if s.Clouds == nil { + writeErr(w, 503, "indisponível") + return + } + var in struct { + Name string `json:"name"` + Config netdest.Config `json:"config"` + } + if !decode(w, r, &in) { + return + } + in.Name = strings.TrimSpace(in.Name) + if !cloudNameRE.MatchString(in.Name) { + writeErr(w, 400, "nome inválido: use 2 a 100 caracteres (letras, números, espaço, ponto, hífen ou sublinhado)") + return + } + id, err := s.Clouds.CreateDestination(r.Context(), in.Name, in.Config) + if errors.Is(err, store.ErrDuplicate) { + writeErr(w, 409, "já existe um destino com esse nome") + return + } + if err != nil { + writeErr(w, 400, err.Error()) + return + } + s.Store.Audit(r.Context(), cu.User.ID, cu.User.Username, "destination.created", in.Name+" ("+in.Config.Type+")", s.clientIP(r)) + writeJSON(w, 201, map[string]any{"id": id}) +} + +// fetchRun pede ao agente que traga do destino de rede o arquivo de uma execução (para extrair ou copiar). +func (s *Server) fetchRun(w http.ResponseWriter, r *http.Request, cu *ctxUser) { + run, job, ok := s.runForAction(w, r) + if !ok { + return + } + if job.CloudAccountID == nil || s.Clouds == nil || run.CloudStatus != "ok" || run.CloudPath == "" { + writeErr(w, 409, "esta execução não tem cópia conferida no destino") + return + } + if d, err := s.Clouds.DestConfig(r.Context(), *job.CloudAccountID); err != nil || d == nil { + writeErr(w, 409, "o destino deste job não é um destino de rede") + return + } + _, name := path.Split(run.CloudPath) + err := s.Agents.Action(run.AgentID, &pb.AgentAction{Kind: "fetch", RunUid: run.UID, JobId: job.ID, FileName: name, Subdir: job.DestSubdir, Sha256: run.SHA256}) + if s.actionErr(w, err) { + return + } + s.Store.Audit(r.Context(), cu.User.ID, cu.User.Username, "run.fetch", run.JobName+" / "+name, s.clientIP(r)) + writeJSON(w, 202, map[string]bool{"ok": true}) +} diff --git a/internal/httpapi/handlers_restore.go b/internal/httpapi/handlers_restore.go index 24c4ff6..c82e10b 100644 --- a/internal/httpapi/handlers_restore.go +++ b/internal/httpapi/handlers_restore.go @@ -35,6 +35,10 @@ func (s *Server) downloadRun(w http.ResponseWriter, r *http.Request, cu *ctxUser writeErr(w, 409, "esta execução não tem cópia conferida na nuvem") return } + if d, err := s.Clouds.DestConfig(r.Context(), *job.CloudAccountID); err == nil && d != nil { + writeErr(w, 409, "este backup está num destino de rede, que o Server não acessa: use \"Trazer do destino\" para o agente buscar o arquivo") + return + } folder, name := path.Split(run.CloudPath) body, size, err := s.Clouds.Open(r.Context(), *job.CloudAccountID, strings.TrimSuffix(folder, "/"), name) if errors.Is(err, cloud.ErrNotFound) { diff --git a/internal/httpapi/httpapi.go b/internal/httpapi/httpapi.go index 161e4dc..873b90f 100644 --- a/internal/httpapi/httpapi.go +++ b/internal/httpapi/httpapi.go @@ -16,6 +16,7 @@ import ( "github.com/AprendendoLinux/corujabackup/internal/cloud" "github.com/AprendendoLinux/corujabackup/internal/cloudmgr" + "github.com/AprendendoLinux/corujabackup/internal/netdest" "github.com/AprendendoLinux/corujabackup/internal/pb" "github.com/AprendendoLinux/corujabackup/internal/ratelimit" "github.com/AprendendoLinux/corujabackup/internal/secrets" @@ -48,6 +49,8 @@ type CloudAdmin interface { BeginWeb(ctx context.Context, name, typ, origin string) (loginURL, state string, err error) BeginWebReauth(ctx context.Context, id int64, origin string) (loginURL, state string, err error) UsesPopup(ctx context.Context, id int64) bool + CreateDestination(ctx context.Context, name string, cfg netdest.Config) (int64, error) + DestConfig(ctx context.Context, id int64) (*netdest.Config, error) FinishWeb(ctx context.Context, state, code string) (int64, error) Open(ctx context.Context, accountID int64, folder, name string) (io.ReadCloser, int64, error) } @@ -146,6 +149,9 @@ func (s *Server) Routes() http.Handler { mux.HandleFunc("GET /api/reports/daily.pdf", s.authed(roleOperator, s.dailyPDF)) mux.HandleFunc("GET /api/clouds", s.authed(roleAny, s.listClouds)) mux.HandleFunc("POST /api/clouds", s.authed(roleAdmin, s.createCloud)) + mux.HandleFunc("POST /api/destinations/test", s.authed(roleAdmin, s.testDestination)) + mux.HandleFunc("POST /api/destinations", s.authed(roleAdmin, s.createDestination)) + mux.HandleFunc("POST /api/runs/{id}/fetch", s.authed(roleOperator, s.fetchRun)) mux.HandleFunc("POST /api/clouds/oauth/begin", s.authed(roleAdmin, s.beginCloudWeb)) mux.HandleFunc("POST /api/clouds/oauth/finish", s.authed(roleAdmin, s.finishCloudWeb)) mux.HandleFunc("POST /api/clouds/{id}/poll", s.authed(roleAdmin, s.pollCloud)) diff --git a/internal/httpapi/httpapi_test.go b/internal/httpapi/httpapi_test.go index 9c02135..93debbd 100644 --- a/internal/httpapi/httpapi_test.go +++ b/internal/httpapi/httpapi_test.go @@ -17,6 +17,7 @@ import ( "github.com/AprendendoLinux/corujabackup/internal/auth" "github.com/AprendendoLinux/corujabackup/internal/cloud" "github.com/AprendendoLinux/corujabackup/internal/cloudmgr" + "github.com/AprendendoLinux/corujabackup/internal/netdest" "github.com/AprendendoLinux/corujabackup/internal/pb" "github.com/AprendendoLinux/corujabackup/internal/ratelimit" "github.com/AprendendoLinux/corujabackup/internal/report" @@ -567,7 +568,11 @@ func (f *fakeClouds) BeginWeb(_ context.Context, name, typ, origin string) (stri func (f *fakeClouds) BeginWebReauth(_ context.Context, id int64, origin string) (string, string, error) { return "https://login.test/?re=1", "nonce.re", nil } -func (f *fakeClouds) UsesPopup(context.Context, int64) bool { return false } +func (f *fakeClouds) CreateDestination(context.Context, string, netdest.Config) (int64, error) { + return 77, nil +} +func (f *fakeClouds) DestConfig(context.Context, int64) (*netdest.Config, error) { return nil, nil } +func (f *fakeClouds) UsesPopup(context.Context, int64) bool { return false } func (f *fakeClouds) FinishWeb(_ context.Context, state, code string) (int64, error) { if code != "ok" { return 0, errors.New("código inválido") diff --git a/internal/pb/agent.pb.go b/internal/pb/agent.pb.go index 034381a..700aeef 100644 --- a/internal/pb/agent.pb.go +++ b/internal/pb/agent.pb.go @@ -67,7 +67,7 @@ func (x RunReport_State) Number() protoreflect.EnumNumber { // Deprecated: Use RunReport_State.Descriptor instead. func (RunReport_State) EnumDescriptor() ([]byte, []int) { - return file_coruja_v1_agent_proto_rawDescGZIP(), []int{15, 0} + return file_coruja_v1_agent_proto_rawDescGZIP(), []int{16, 0} } type EnrollRequest struct { @@ -896,6 +896,7 @@ type JobSpec struct { CloudAccountId int64 `protobuf:"varint,12,opt,name=cloud_account_id,json=cloudAccountId,proto3" json:"cloud_account_id,omitempty"` // 0 = sem nuvem (só cópia local) CloudFolder string `protobuf:"bytes,13,opt,name=cloud_folder,json=cloudFolder,proto3" json:"cloud_folder,omitempty"` // pasta na nuvem (informativo; quem decide é o Server) Db *DbSpec `protobuf:"bytes,14,opt,name=db,proto3" json:"db,omitempty"` // kind="database" + Dest *DestSpec `protobuf:"bytes,15,opt,name=dest,proto3" json:"dest,omitempty"` // destino "direto do agente" (SFTP, FTP, SMB, pasta local); ausente nas nuvens unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -1028,6 +1029,91 @@ func (x *JobSpec) GetDb() *DbSpec { return nil } +func (x *JobSpec) GetDest() *DestSpec { + if x != nil { + return x.Dest + } + return nil +} + +// DestSpec: o agente envia, confere e aplica a retenção. A configuração (com credenciais) viaja só pelo canal TLS e fica no +// disco do agente com permissão 600. +type DestSpec struct { + state protoimpl.MessageState `protogen:"open.v1"` + Type string `protobuf:"bytes,1,opt,name=type,proto3" json:"type,omitempty"` // "sftp" | "ftp" | "smb" | "local" + Config []byte `protobuf:"bytes,2,opt,name=config,proto3" json:"config,omitempty"` // netdest.Config em JSON + Folder string `protobuf:"bytes,3,opt,name=folder,proto3" json:"folder,omitempty"` + Keep int32 `protobuf:"varint,4,opt,name=keep,proto3" json:"keep,omitempty"` + KeepDays int32 `protobuf:"varint,5,opt,name=keep_days,json=keepDays,proto3" json:"keep_days,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *DestSpec) Reset() { + *x = DestSpec{} + mi := &file_coruja_v1_agent_proto_msgTypes[10] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *DestSpec) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*DestSpec) ProtoMessage() {} + +func (x *DestSpec) ProtoReflect() protoreflect.Message { + mi := &file_coruja_v1_agent_proto_msgTypes[10] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use DestSpec.ProtoReflect.Descriptor instead. +func (*DestSpec) Descriptor() ([]byte, []int) { + return file_coruja_v1_agent_proto_rawDescGZIP(), []int{10} +} + +func (x *DestSpec) GetType() string { + if x != nil { + return x.Type + } + return "" +} + +func (x *DestSpec) GetConfig() []byte { + if x != nil { + return x.Config + } + return nil +} + +func (x *DestSpec) GetFolder() string { + if x != nil { + return x.Folder + } + return "" +} + +func (x *DestSpec) GetKeep() int32 { + if x != nil { + return x.Keep + } + return 0 +} + +func (x *DestSpec) GetKeepDays() int32 { + if x != nil { + return x.KeepDays + } + return 0 +} + type SyncJobs struct { state protoimpl.MessageState `protogen:"open.v1"` Jobs []*JobSpec `protobuf:"bytes,1,rep,name=jobs,proto3" json:"jobs,omitempty"` @@ -1037,7 +1123,7 @@ type SyncJobs struct { func (x *SyncJobs) Reset() { *x = SyncJobs{} - mi := &file_coruja_v1_agent_proto_msgTypes[10] + mi := &file_coruja_v1_agent_proto_msgTypes[11] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1049,7 +1135,7 @@ func (x *SyncJobs) String() string { func (*SyncJobs) ProtoMessage() {} func (x *SyncJobs) ProtoReflect() protoreflect.Message { - mi := &file_coruja_v1_agent_proto_msgTypes[10] + mi := &file_coruja_v1_agent_proto_msgTypes[11] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1062,7 +1148,7 @@ func (x *SyncJobs) ProtoReflect() protoreflect.Message { // Deprecated: Use SyncJobs.ProtoReflect.Descriptor instead. func (*SyncJobs) Descriptor() ([]byte, []int) { - return file_coruja_v1_agent_proto_rawDescGZIP(), []int{10} + return file_coruja_v1_agent_proto_rawDescGZIP(), []int{11} } func (x *SyncJobs) GetJobs() []*JobSpec { @@ -1082,7 +1168,7 @@ type RunNow struct { func (x *RunNow) Reset() { *x = RunNow{} - mi := &file_coruja_v1_agent_proto_msgTypes[11] + mi := &file_coruja_v1_agent_proto_msgTypes[12] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1094,7 +1180,7 @@ func (x *RunNow) String() string { func (*RunNow) ProtoMessage() {} func (x *RunNow) ProtoReflect() protoreflect.Message { - mi := &file_coruja_v1_agent_proto_msgTypes[11] + mi := &file_coruja_v1_agent_proto_msgTypes[12] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1107,7 +1193,7 @@ func (x *RunNow) ProtoReflect() protoreflect.Message { // Deprecated: Use RunNow.ProtoReflect.Descriptor instead. func (*RunNow) Descriptor() ([]byte, []int) { - return file_coruja_v1_agent_proto_rawDescGZIP(), []int{11} + return file_coruja_v1_agent_proto_rawDescGZIP(), []int{12} } func (x *RunNow) GetJobId() int64 { @@ -1133,7 +1219,7 @@ type CancelRun struct { func (x *CancelRun) Reset() { *x = CancelRun{} - mi := &file_coruja_v1_agent_proto_msgTypes[12] + mi := &file_coruja_v1_agent_proto_msgTypes[13] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1145,7 +1231,7 @@ func (x *CancelRun) String() string { func (*CancelRun) ProtoMessage() {} func (x *CancelRun) ProtoReflect() protoreflect.Message { - mi := &file_coruja_v1_agent_proto_msgTypes[12] + mi := &file_coruja_v1_agent_proto_msgTypes[13] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1158,7 +1244,7 @@ func (x *CancelRun) ProtoReflect() protoreflect.Message { // Deprecated: Use CancelRun.ProtoReflect.Descriptor instead. func (*CancelRun) Descriptor() ([]byte, []int) { - return file_coruja_v1_agent_proto_rawDescGZIP(), []int{12} + return file_coruja_v1_agent_proto_rawDescGZIP(), []int{13} } func (x *CancelRun) GetRunUid() string { @@ -1177,7 +1263,7 @@ type ReportAck struct { func (x *ReportAck) Reset() { *x = ReportAck{} - mi := &file_coruja_v1_agent_proto_msgTypes[13] + mi := &file_coruja_v1_agent_proto_msgTypes[14] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1189,7 +1275,7 @@ func (x *ReportAck) String() string { func (*ReportAck) ProtoMessage() {} func (x *ReportAck) ProtoReflect() protoreflect.Message { - mi := &file_coruja_v1_agent_proto_msgTypes[13] + mi := &file_coruja_v1_agent_proto_msgTypes[14] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1202,7 +1288,7 @@ func (x *ReportAck) ProtoReflect() protoreflect.Message { // Deprecated: Use ReportAck.ProtoReflect.Descriptor instead. func (*ReportAck) Descriptor() ([]byte, []int) { - return file_coruja_v1_agent_proto_rawDescGZIP(), []int{13} + return file_coruja_v1_agent_proto_rawDescGZIP(), []int{14} } func (x *ReportAck) GetRunUid() string { @@ -1224,7 +1310,7 @@ type LogLine struct { func (x *LogLine) Reset() { *x = LogLine{} - mi := &file_coruja_v1_agent_proto_msgTypes[14] + mi := &file_coruja_v1_agent_proto_msgTypes[15] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1236,7 +1322,7 @@ func (x *LogLine) String() string { func (*LogLine) ProtoMessage() {} func (x *LogLine) ProtoReflect() protoreflect.Message { - mi := &file_coruja_v1_agent_proto_msgTypes[14] + mi := &file_coruja_v1_agent_proto_msgTypes[15] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1249,7 +1335,7 @@ func (x *LogLine) ProtoReflect() protoreflect.Message { // Deprecated: Use LogLine.ProtoReflect.Descriptor instead. func (*LogLine) Descriptor() ([]byte, []int) { - return file_coruja_v1_agent_proto_rawDescGZIP(), []int{14} + return file_coruja_v1_agent_proto_rawDescGZIP(), []int{15} } func (x *LogLine) GetSeq() int32 { @@ -1312,7 +1398,7 @@ type RunReport struct { func (x *RunReport) Reset() { *x = RunReport{} - mi := &file_coruja_v1_agent_proto_msgTypes[15] + mi := &file_coruja_v1_agent_proto_msgTypes[16] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1324,7 +1410,7 @@ func (x *RunReport) String() string { func (*RunReport) ProtoMessage() {} func (x *RunReport) ProtoReflect() protoreflect.Message { - mi := &file_coruja_v1_agent_proto_msgTypes[15] + mi := &file_coruja_v1_agent_proto_msgTypes[16] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1337,7 +1423,7 @@ func (x *RunReport) ProtoReflect() protoreflect.Message { // Deprecated: Use RunReport.ProtoReflect.Descriptor instead. func (*RunReport) Descriptor() ([]byte, []int) { - return file_coruja_v1_agent_proto_rawDescGZIP(), []int{15} + return file_coruja_v1_agent_proto_rawDescGZIP(), []int{16} } func (x *RunReport) GetRunUid() string { @@ -1507,7 +1593,7 @@ type UploadRequest struct { func (x *UploadRequest) Reset() { *x = UploadRequest{} - mi := &file_coruja_v1_agent_proto_msgTypes[16] + mi := &file_coruja_v1_agent_proto_msgTypes[17] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1519,7 +1605,7 @@ func (x *UploadRequest) String() string { func (*UploadRequest) ProtoMessage() {} func (x *UploadRequest) ProtoReflect() protoreflect.Message { - mi := &file_coruja_v1_agent_proto_msgTypes[16] + mi := &file_coruja_v1_agent_proto_msgTypes[17] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1532,7 +1618,7 @@ func (x *UploadRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use UploadRequest.ProtoReflect.Descriptor instead. func (*UploadRequest) Descriptor() ([]byte, []int) { - return file_coruja_v1_agent_proto_rawDescGZIP(), []int{16} + return file_coruja_v1_agent_proto_rawDescGZIP(), []int{17} } func (x *UploadRequest) GetRequestId() string { @@ -1588,7 +1674,7 @@ type UploadSession struct { func (x *UploadSession) Reset() { *x = UploadSession{} - mi := &file_coruja_v1_agent_proto_msgTypes[17] + mi := &file_coruja_v1_agent_proto_msgTypes[18] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1600,7 +1686,7 @@ func (x *UploadSession) String() string { func (*UploadSession) ProtoMessage() {} func (x *UploadSession) ProtoReflect() protoreflect.Message { - mi := &file_coruja_v1_agent_proto_msgTypes[17] + mi := &file_coruja_v1_agent_proto_msgTypes[18] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1613,7 +1699,7 @@ func (x *UploadSession) ProtoReflect() protoreflect.Message { // Deprecated: Use UploadSession.ProtoReflect.Descriptor instead. func (*UploadSession) Descriptor() ([]byte, []int) { - return file_coruja_v1_agent_proto_rawDescGZIP(), []int{17} + return file_coruja_v1_agent_proto_rawDescGZIP(), []int{18} } func (x *UploadSession) GetRequestId() string { @@ -1707,7 +1793,7 @@ type UploadDone struct { func (x *UploadDone) Reset() { *x = UploadDone{} - mi := &file_coruja_v1_agent_proto_msgTypes[18] + mi := &file_coruja_v1_agent_proto_msgTypes[19] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1719,7 +1805,7 @@ func (x *UploadDone) String() string { func (*UploadDone) ProtoMessage() {} func (x *UploadDone) ProtoReflect() protoreflect.Message { - mi := &file_coruja_v1_agent_proto_msgTypes[18] + mi := &file_coruja_v1_agent_proto_msgTypes[19] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1732,7 +1818,7 @@ func (x *UploadDone) ProtoReflect() protoreflect.Message { // Deprecated: Use UploadDone.ProtoReflect.Descriptor instead. func (*UploadDone) Descriptor() ([]byte, []int) { - return file_coruja_v1_agent_proto_rawDescGZIP(), []int{18} + return file_coruja_v1_agent_proto_rawDescGZIP(), []int{19} } func (x *UploadDone) GetRequestId() string { @@ -1841,7 +1927,7 @@ type UploadVerdict struct { func (x *UploadVerdict) Reset() { *x = UploadVerdict{} - mi := &file_coruja_v1_agent_proto_msgTypes[19] + mi := &file_coruja_v1_agent_proto_msgTypes[20] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1853,7 +1939,7 @@ func (x *UploadVerdict) String() string { func (*UploadVerdict) ProtoMessage() {} func (x *UploadVerdict) ProtoReflect() protoreflect.Message { - mi := &file_coruja_v1_agent_proto_msgTypes[19] + mi := &file_coruja_v1_agent_proto_msgTypes[20] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1866,7 +1952,7 @@ func (x *UploadVerdict) ProtoReflect() protoreflect.Message { // Deprecated: Use UploadVerdict.ProtoReflect.Descriptor instead. func (*UploadVerdict) Descriptor() ([]byte, []int) { - return file_coruja_v1_agent_proto_rawDescGZIP(), []int{19} + return file_coruja_v1_agent_proto_rawDescGZIP(), []int{20} } func (x *UploadVerdict) GetRequestId() string { @@ -1941,7 +2027,7 @@ type DbSpec struct { func (x *DbSpec) Reset() { *x = DbSpec{} - mi := &file_coruja_v1_agent_proto_msgTypes[20] + mi := &file_coruja_v1_agent_proto_msgTypes[21] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1953,7 +2039,7 @@ func (x *DbSpec) String() string { func (*DbSpec) ProtoMessage() {} func (x *DbSpec) ProtoReflect() protoreflect.Message { - mi := &file_coruja_v1_agent_proto_msgTypes[20] + mi := &file_coruja_v1_agent_proto_msgTypes[21] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1966,7 +2052,7 @@ func (x *DbSpec) ProtoReflect() protoreflect.Message { // Deprecated: Use DbSpec.ProtoReflect.Descriptor instead. func (*DbSpec) Descriptor() ([]byte, []int) { - return file_coruja_v1_agent_proto_rawDescGZIP(), []int{20} + return file_coruja_v1_agent_proto_rawDescGZIP(), []int{21} } func (x *DbSpec) GetEngine() string { @@ -2072,7 +2158,7 @@ type Rpc struct { func (x *Rpc) Reset() { *x = Rpc{} - mi := &file_coruja_v1_agent_proto_msgTypes[21] + mi := &file_coruja_v1_agent_proto_msgTypes[22] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2084,7 +2170,7 @@ func (x *Rpc) String() string { func (*Rpc) ProtoMessage() {} func (x *Rpc) ProtoReflect() protoreflect.Message { - mi := &file_coruja_v1_agent_proto_msgTypes[21] + mi := &file_coruja_v1_agent_proto_msgTypes[22] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2097,7 +2183,7 @@ func (x *Rpc) ProtoReflect() protoreflect.Message { // Deprecated: Use Rpc.ProtoReflect.Descriptor instead. func (*Rpc) Descriptor() ([]byte, []int) { - return file_coruja_v1_agent_proto_rawDescGZIP(), []int{21} + return file_coruja_v1_agent_proto_rawDescGZIP(), []int{22} } func (x *Rpc) GetId() string { @@ -2133,7 +2219,7 @@ type RpcResult struct { func (x *RpcResult) Reset() { *x = RpcResult{} - mi := &file_coruja_v1_agent_proto_msgTypes[22] + mi := &file_coruja_v1_agent_proto_msgTypes[23] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2145,7 +2231,7 @@ func (x *RpcResult) String() string { func (*RpcResult) ProtoMessage() {} func (x *RpcResult) ProtoReflect() protoreflect.Message { - mi := &file_coruja_v1_agent_proto_msgTypes[22] + mi := &file_coruja_v1_agent_proto_msgTypes[23] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2158,7 +2244,7 @@ func (x *RpcResult) ProtoReflect() protoreflect.Message { // Deprecated: Use RpcResult.ProtoReflect.Descriptor instead. func (*RpcResult) Descriptor() ([]byte, []int) { - return file_coruja_v1_agent_proto_rawDescGZIP(), []int{22} + return file_coruja_v1_agent_proto_rawDescGZIP(), []int{23} } func (x *RpcResult) GetId() string { @@ -2192,19 +2278,20 @@ func (x *RpcResult) GetPayload() []byte { type AgentAction struct { state protoimpl.MessageState `protogen:"open.v1"` Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` - Kind string `protobuf:"bytes,2,opt,name=kind,proto3" json:"kind,omitempty"` // "reupload" | "extract" + Kind string `protobuf:"bytes,2,opt,name=kind,proto3" json:"kind,omitempty"` // "reupload" | "extract" | "fetch" RunUid string `protobuf:"bytes,3,opt,name=run_uid,json=runUid,proto3" json:"run_uid,omitempty"` JobId int64 `protobuf:"varint,4,opt,name=job_id,json=jobId,proto3" json:"job_id,omitempty"` FileName string `protobuf:"bytes,5,opt,name=file_name,json=fileName,proto3" json:"file_name,omitempty"` // arquivo de backup (no padrão do job) na pasta de destino do agente Subdir string `protobuf:"bytes,6,opt,name=subdir,proto3" json:"subdir,omitempty"` Target string `protobuf:"bytes,7,opt,name=target,proto3" json:"target,omitempty"` // extract: nome da pasta em /restores/ + Sha256 string `protobuf:"bytes,8,opt,name=sha256,proto3" json:"sha256,omitempty"` // fetch: hash esperado do arquivo trazido do destino unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *AgentAction) Reset() { *x = AgentAction{} - mi := &file_coruja_v1_agent_proto_msgTypes[23] + mi := &file_coruja_v1_agent_proto_msgTypes[24] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2216,7 +2303,7 @@ func (x *AgentAction) String() string { func (*AgentAction) ProtoMessage() {} func (x *AgentAction) ProtoReflect() protoreflect.Message { - mi := &file_coruja_v1_agent_proto_msgTypes[23] + mi := &file_coruja_v1_agent_proto_msgTypes[24] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2229,7 +2316,7 @@ func (x *AgentAction) ProtoReflect() protoreflect.Message { // Deprecated: Use AgentAction.ProtoReflect.Descriptor instead. func (*AgentAction) Descriptor() ([]byte, []int) { - return file_coruja_v1_agent_proto_rawDescGZIP(), []int{23} + return file_coruja_v1_agent_proto_rawDescGZIP(), []int{24} } func (x *AgentAction) GetId() string { @@ -2281,6 +2368,13 @@ func (x *AgentAction) GetTarget() string { return "" } +func (x *AgentAction) GetSha256() string { + if x != nil { + return x.Sha256 + } + return "" +} + type ActionLog struct { state protoimpl.MessageState `protogen:"open.v1"` RunUid string `protobuf:"bytes,1,opt,name=run_uid,json=runUid,proto3" json:"run_uid,omitempty"` @@ -2299,7 +2393,7 @@ type ActionLog struct { func (x *ActionLog) Reset() { *x = ActionLog{} - mi := &file_coruja_v1_agent_proto_msgTypes[24] + mi := &file_coruja_v1_agent_proto_msgTypes[25] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2311,7 +2405,7 @@ func (x *ActionLog) String() string { func (*ActionLog) ProtoMessage() {} func (x *ActionLog) ProtoReflect() protoreflect.Message { - mi := &file_coruja_v1_agent_proto_msgTypes[24] + mi := &file_coruja_v1_agent_proto_msgTypes[25] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2324,7 +2418,7 @@ func (x *ActionLog) ProtoReflect() protoreflect.Message { // Deprecated: Use ActionLog.ProtoReflect.Descriptor instead. func (*ActionLog) Descriptor() ([]byte, []int) { - return file_coruja_v1_agent_proto_rawDescGZIP(), []int{24} + return file_coruja_v1_agent_proto_rawDescGZIP(), []int{25} } func (x *ActionLog) GetRunUid() string { @@ -2461,7 +2555,7 @@ const file_coruja_v1_agent_proto_rawDesc = "" + "\x03Ack\x12\x17\n" + "\aunix_ms\x18\x01 \x01(\x03R\x06unixMs\"!\n" + "\aRevoked\x12\x16\n" + - "\x06reason\x18\x01 \x01(\tR\x06reason\"\x83\x03\n" + + "\x06reason\x18\x01 \x01(\tR\x06reason\"\xac\x03\n" + "\aJobSpec\x12\x15\n" + "\x06job_id\x18\x01 \x01(\x03R\x05jobId\x12\x12\n" + "\x04name\x18\x02 \x01(\tR\x04name\x12\x12\n" + @@ -2478,7 +2572,14 @@ const file_coruja_v1_agent_proto_rawDesc = "" + "\aversion\x18\v \x01(\x05R\aversion\x12(\n" + "\x10cloud_account_id\x18\f \x01(\x03R\x0ecloudAccountId\x12!\n" + "\fcloud_folder\x18\r \x01(\tR\vcloudFolder\x12!\n" + - "\x02db\x18\x0e \x01(\v2\x11.coruja.v1.DbSpecR\x02db\"2\n" + + "\x02db\x18\x0e \x01(\v2\x11.coruja.v1.DbSpecR\x02db\x12'\n" + + "\x04dest\x18\x0f \x01(\v2\x13.coruja.v1.DestSpecR\x04dest\"\x7f\n" + + "\bDestSpec\x12\x12\n" + + "\x04type\x18\x01 \x01(\tR\x04type\x12\x16\n" + + "\x06config\x18\x02 \x01(\fR\x06config\x12\x16\n" + + "\x06folder\x18\x03 \x01(\tR\x06folder\x12\x12\n" + + "\x04keep\x18\x04 \x01(\x05R\x04keep\x12\x1b\n" + + "\tkeep_days\x18\x05 \x01(\x05R\bkeepDays\"2\n" + "\bSyncJobs\x12&\n" + "\x04jobs\x18\x01 \x03(\v2\x12.coruja.v1.JobSpecR\x04jobs\"8\n" + "\x06RunNow\x12\x15\n" + @@ -2602,7 +2703,7 @@ const file_coruja_v1_agent_proto_rawDesc = "" + "\x02id\x18\x01 \x01(\tR\x02id\x12\x0e\n" + "\x02ok\x18\x02 \x01(\bR\x02ok\x12\x14\n" + "\x05error\x18\x03 \x01(\tR\x05error\x12\x18\n" + - "\apayload\x18\x04 \x01(\fR\apayload\"\xae\x01\n" + + "\apayload\x18\x04 \x01(\fR\apayload\"\xc6\x01\n" + "\vAgentAction\x12\x0e\n" + "\x02id\x18\x01 \x01(\tR\x02id\x12\x12\n" + "\x04kind\x18\x02 \x01(\tR\x04kind\x12\x17\n" + @@ -2610,7 +2711,8 @@ const file_coruja_v1_agent_proto_rawDesc = "" + "\x06job_id\x18\x04 \x01(\x03R\x05jobId\x12\x1b\n" + "\tfile_name\x18\x05 \x01(\tR\bfileName\x12\x16\n" + "\x06subdir\x18\x06 \x01(\tR\x06subdir\x12\x16\n" + - "\x06target\x18\a \x01(\tR\x06target\"\xb1\x02\n" + + "\x06target\x18\a \x01(\tR\x06target\x12\x16\n" + + "\x06sha256\x18\b \x01(\tR\x06sha256\"\xb1\x02\n" + "\tActionLog\x12\x17\n" + "\arun_uid\x18\x01 \x01(\tR\x06runUid\x12\x12\n" + "\x04kind\x18\x02 \x01(\tR\x04kind\x12\x14\n" + @@ -2642,7 +2744,7 @@ func file_coruja_v1_agent_proto_rawDescGZIP() []byte { } var file_coruja_v1_agent_proto_enumTypes = make([]protoimpl.EnumInfo, 1) -var file_coruja_v1_agent_proto_msgTypes = make([]protoimpl.MessageInfo, 25) +var file_coruja_v1_agent_proto_msgTypes = make([]protoimpl.MessageInfo, 26) var file_coruja_v1_agent_proto_goTypes = []any{ (RunReport_State)(0), // 0: coruja.v1.RunReport.State (*EnrollRequest)(nil), // 1: coruja.v1.EnrollRequest @@ -2655,55 +2757,57 @@ var file_coruja_v1_agent_proto_goTypes = []any{ (*Ack)(nil), // 8: coruja.v1.Ack (*Revoked)(nil), // 9: coruja.v1.Revoked (*JobSpec)(nil), // 10: coruja.v1.JobSpec - (*SyncJobs)(nil), // 11: coruja.v1.SyncJobs - (*RunNow)(nil), // 12: coruja.v1.RunNow - (*CancelRun)(nil), // 13: coruja.v1.CancelRun - (*ReportAck)(nil), // 14: coruja.v1.ReportAck - (*LogLine)(nil), // 15: coruja.v1.LogLine - (*RunReport)(nil), // 16: coruja.v1.RunReport - (*UploadRequest)(nil), // 17: coruja.v1.UploadRequest - (*UploadSession)(nil), // 18: coruja.v1.UploadSession - (*UploadDone)(nil), // 19: coruja.v1.UploadDone - (*UploadVerdict)(nil), // 20: coruja.v1.UploadVerdict - (*DbSpec)(nil), // 21: coruja.v1.DbSpec - (*Rpc)(nil), // 22: coruja.v1.Rpc - (*RpcResult)(nil), // 23: coruja.v1.RpcResult - (*AgentAction)(nil), // 24: coruja.v1.AgentAction - (*ActionLog)(nil), // 25: coruja.v1.ActionLog + (*DestSpec)(nil), // 11: coruja.v1.DestSpec + (*SyncJobs)(nil), // 12: coruja.v1.SyncJobs + (*RunNow)(nil), // 13: coruja.v1.RunNow + (*CancelRun)(nil), // 14: coruja.v1.CancelRun + (*ReportAck)(nil), // 15: coruja.v1.ReportAck + (*LogLine)(nil), // 16: coruja.v1.LogLine + (*RunReport)(nil), // 17: coruja.v1.RunReport + (*UploadRequest)(nil), // 18: coruja.v1.UploadRequest + (*UploadSession)(nil), // 19: coruja.v1.UploadSession + (*UploadDone)(nil), // 20: coruja.v1.UploadDone + (*UploadVerdict)(nil), // 21: coruja.v1.UploadVerdict + (*DbSpec)(nil), // 22: coruja.v1.DbSpec + (*Rpc)(nil), // 23: coruja.v1.Rpc + (*RpcResult)(nil), // 24: coruja.v1.RpcResult + (*AgentAction)(nil), // 25: coruja.v1.AgentAction + (*ActionLog)(nil), // 26: coruja.v1.ActionLog } var file_coruja_v1_agent_proto_depIdxs = []int32{ 4, // 0: coruja.v1.AgentMessage.hello:type_name -> coruja.v1.Hello 5, // 1: coruja.v1.AgentMessage.heartbeat:type_name -> coruja.v1.Heartbeat - 16, // 2: coruja.v1.AgentMessage.run_report:type_name -> coruja.v1.RunReport - 17, // 3: coruja.v1.AgentMessage.upload_request:type_name -> coruja.v1.UploadRequest - 19, // 4: coruja.v1.AgentMessage.upload_done:type_name -> coruja.v1.UploadDone - 23, // 5: coruja.v1.AgentMessage.rpc_result:type_name -> coruja.v1.RpcResult - 25, // 6: coruja.v1.AgentMessage.action_log:type_name -> coruja.v1.ActionLog + 17, // 2: coruja.v1.AgentMessage.run_report:type_name -> coruja.v1.RunReport + 18, // 3: coruja.v1.AgentMessage.upload_request:type_name -> coruja.v1.UploadRequest + 20, // 4: coruja.v1.AgentMessage.upload_done:type_name -> coruja.v1.UploadDone + 24, // 5: coruja.v1.AgentMessage.rpc_result:type_name -> coruja.v1.RpcResult + 26, // 6: coruja.v1.AgentMessage.action_log:type_name -> coruja.v1.ActionLog 7, // 7: coruja.v1.ServerMessage.welcome:type_name -> coruja.v1.Welcome 8, // 8: coruja.v1.ServerMessage.ack:type_name -> coruja.v1.Ack 9, // 9: coruja.v1.ServerMessage.revoked:type_name -> coruja.v1.Revoked - 11, // 10: coruja.v1.ServerMessage.sync_jobs:type_name -> coruja.v1.SyncJobs - 12, // 11: coruja.v1.ServerMessage.run_now:type_name -> coruja.v1.RunNow - 13, // 12: coruja.v1.ServerMessage.cancel_run:type_name -> coruja.v1.CancelRun - 14, // 13: coruja.v1.ServerMessage.report_ack:type_name -> coruja.v1.ReportAck - 18, // 14: coruja.v1.ServerMessage.upload_session:type_name -> coruja.v1.UploadSession - 20, // 15: coruja.v1.ServerMessage.upload_verdict:type_name -> coruja.v1.UploadVerdict - 22, // 16: coruja.v1.ServerMessage.rpc:type_name -> coruja.v1.Rpc - 24, // 17: coruja.v1.ServerMessage.action:type_name -> coruja.v1.AgentAction - 21, // 18: coruja.v1.JobSpec.db:type_name -> coruja.v1.DbSpec - 10, // 19: coruja.v1.SyncJobs.jobs:type_name -> coruja.v1.JobSpec - 0, // 20: coruja.v1.RunReport.state:type_name -> coruja.v1.RunReport.State - 15, // 21: coruja.v1.RunReport.logs:type_name -> coruja.v1.LogLine - 15, // 22: coruja.v1.ActionLog.logs:type_name -> coruja.v1.LogLine - 1, // 23: coruja.v1.AgentService.Enroll:input_type -> coruja.v1.EnrollRequest - 3, // 24: coruja.v1.AgentService.Connect:input_type -> coruja.v1.AgentMessage - 2, // 25: coruja.v1.AgentService.Enroll:output_type -> coruja.v1.EnrollResponse - 6, // 26: coruja.v1.AgentService.Connect:output_type -> coruja.v1.ServerMessage - 25, // [25:27] is the sub-list for method output_type - 23, // [23:25] is the sub-list for method input_type - 23, // [23:23] is the sub-list for extension type_name - 23, // [23:23] is the sub-list for extension extendee - 0, // [0:23] is the sub-list for field type_name + 12, // 10: coruja.v1.ServerMessage.sync_jobs:type_name -> coruja.v1.SyncJobs + 13, // 11: coruja.v1.ServerMessage.run_now:type_name -> coruja.v1.RunNow + 14, // 12: coruja.v1.ServerMessage.cancel_run:type_name -> coruja.v1.CancelRun + 15, // 13: coruja.v1.ServerMessage.report_ack:type_name -> coruja.v1.ReportAck + 19, // 14: coruja.v1.ServerMessage.upload_session:type_name -> coruja.v1.UploadSession + 21, // 15: coruja.v1.ServerMessage.upload_verdict:type_name -> coruja.v1.UploadVerdict + 23, // 16: coruja.v1.ServerMessage.rpc:type_name -> coruja.v1.Rpc + 25, // 17: coruja.v1.ServerMessage.action:type_name -> coruja.v1.AgentAction + 22, // 18: coruja.v1.JobSpec.db:type_name -> coruja.v1.DbSpec + 11, // 19: coruja.v1.JobSpec.dest:type_name -> coruja.v1.DestSpec + 10, // 20: coruja.v1.SyncJobs.jobs:type_name -> coruja.v1.JobSpec + 0, // 21: coruja.v1.RunReport.state:type_name -> coruja.v1.RunReport.State + 16, // 22: coruja.v1.RunReport.logs:type_name -> coruja.v1.LogLine + 16, // 23: coruja.v1.ActionLog.logs:type_name -> coruja.v1.LogLine + 1, // 24: coruja.v1.AgentService.Enroll:input_type -> coruja.v1.EnrollRequest + 3, // 25: coruja.v1.AgentService.Connect:input_type -> coruja.v1.AgentMessage + 2, // 26: coruja.v1.AgentService.Enroll:output_type -> coruja.v1.EnrollResponse + 6, // 27: coruja.v1.AgentService.Connect:output_type -> coruja.v1.ServerMessage + 26, // [26:28] is the sub-list for method output_type + 24, // [24:26] is the sub-list for method input_type + 24, // [24:24] is the sub-list for extension type_name + 24, // [24:24] is the sub-list for extension extendee + 0, // [0:24] is the sub-list for field type_name } func init() { file_coruja_v1_agent_proto_init() } @@ -2739,7 +2843,7 @@ func file_coruja_v1_agent_proto_init() { GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_coruja_v1_agent_proto_rawDesc), len(file_coruja_v1_agent_proto_rawDesc)), NumEnums: 1, - NumMessages: 25, + NumMessages: 26, NumExtensions: 0, NumServices: 1, }, diff --git a/proto/coruja/v1/agent.proto b/proto/coruja/v1/agent.proto index b257e32..43951a5 100644 --- a/proto/coruja/v1/agent.proto +++ b/proto/coruja/v1/agent.proto @@ -90,6 +90,17 @@ message JobSpec { int64 cloud_account_id = 12; // 0 = sem nuvem (só cópia local) string cloud_folder = 13; // pasta na nuvem (informativo; quem decide é o Server) DbSpec db = 14; // kind="database" + DestSpec dest = 15; // destino "direto do agente" (SFTP, FTP, SMB, pasta local); ausente nas nuvens +} + +// DestSpec: o agente envia, confere e aplica a retenção. A configuração (com credenciais) viaja só pelo canal TLS e fica no +// disco do agente com permissão 600. +message DestSpec { + string type = 1; // "sftp" | "ftp" | "smb" | "local" + bytes config = 2; // netdest.Config em JSON + string folder = 3; + int32 keep = 4; + int32 keep_days = 5; } message SyncJobs { repeated JobSpec jobs = 1; } @@ -207,12 +218,13 @@ message RpcResult { string id = 1; bool ok = 2; string error = 3; bytes payload message AgentAction { string id = 1; - string kind = 2; // "reupload" | "extract" + string kind = 2; // "reupload" | "extract" | "fetch" string run_uid = 3; int64 job_id = 4; string file_name = 5; // arquivo de backup (no padrão do job) na pasta de destino do agente string subdir = 6; string target = 7; // extract: nome da pasta em /restores/ + string sha256 = 8; // fetch: hash esperado do arquivo trazido do destino } message ActionLog { From cb97872b1134d544fb307e84b166b01c297d77fc Mon Sep 17 00:00:00 2001 From: Henrique Fagundes Date: Thu, 26 Nov 2026 12:02:13 -0300 Subject: [PATCH 3/4] web e docs: destinos de rede (SFTP, FTP, SMB e pasta local) Co-Authored-By: Claude Sonnet 5.5 --- CHANGELOG.md | 4 + Dockerfile | 2 +- README.md | 2 + deploy/docker-compose.agent.yml | 2 + docs/DESTINOS.md | 43 ++++++++++ docs/SEGURANCA.md | 4 + internal/httpapi/handlers_jobs.go | 4 + web/src/App.tsx | 2 +- web/src/api.ts | 4 +- web/src/icons.tsx | 13 ++- web/src/pages/Clouds.tsx | 53 ++++++++++-- web/src/pages/Jobs.tsx | 14 ++-- web/src/pages/NetDestination.tsx | 132 ++++++++++++++++++++++++++++++ web/src/pages/Runs.tsx | 15 ++-- 14 files changed, 266 insertions(+), 28 deletions(-) create mode 100644 docs/DESTINOS.md create mode 100644 web/src/pages/NetDestination.tsx diff --git a/CHANGELOG.md b/CHANGELOG.md index e74b8da..4c46966 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## [Não publicado] +- **Destinos de rede:** SFTP (chave do servidor fixada), FTP/FTPS, SMB/CIFS e pasta local (NFS/iSCSI via volume montado em `/destinos`). O agente grava com nome temporário, confere relendo o arquivo (SHA-256) ou por tamanho, renomeia e só então aplica a retenção; "Trazer do destino" para restaurar. Testados contra servidores reais (`scripts/test-netdest.sh`). +- A página **Nuvem** passou a se chamar **Destinos**. + ## [0.0.11] - Temas: Clube Naval e ícone da aba - **Ícone da aba acompanha a logo** do tema ativo (ou a logo enviada em Aparência); sem logo própria, continua a coruja. - **Tema Clube Naval** em `themes/clube-naval` (botões no vermelho da âncora do brasão e dourado; escudo na interface e logo completa em e-mail e PDF). diff --git a/Dockerfile b/Dockerfile index 9ab4415..212ef00 100644 --- a/Dockerfile +++ b/Dockerfile @@ -54,7 +54,7 @@ LABEL org.opencontainers.image.title="Coruja Backup Agent" \ org.opencontainers.image.source="https://github.com/AprendendoLinux/corujabackup" \ org.opencontainers.image.version="${VERSION}" org.opencontainers.image.licenses="MIT" # Clientes de banco para o modo "rede" (no modo contêiner o dump roda com as ferramentas do próprio contêiner). -RUN apk add --no-cache ca-certificates tzdata mariadb-client postgresql17-client mongodb-tools && mkdir -p /var/lib/coruja-agent +RUN apk add --no-cache ca-certificates tzdata mariadb-client postgresql17-client mongodb-tools && mkdir -p /var/lib/coruja-agent /destinos COPY --from=gobuild /out/coruja-agent /usr/local/bin/coruja-agent VOLUME /var/lib/coruja-agent # Roda como root: a Fase 2 precisa ler pastas do host (montadas somente leitura). diff --git a/README.md b/README.md index fbbc19d..a85360b 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,7 @@ nos servidores de destino e se conectam a ele informando só **IP:porta + token* | Área | Recursos | | :--- | :--- | | **Backups** | Pastas/arquivos (`.tar.gz` com exclusões) e **bancos de dados** (MySQL, MariaDB, PostgreSQL, MongoDB). Agenda cron com fuso; o **agente agenda sozinho** e roda mesmo com o Server fora do ar. | +| **Destinos de rede** | **SFTP**, **FTP/FTPS**, **SMB/CIFS** e **pasta local** (NFS/iSCSI montados no host): o agente envia, confere relendo o arquivo e aplica a retenção. | | **Confiança** | Cada arquivo é conferido (SHA-256, gzip, estrutura) e há **teste de restauração real** de bancos num servidor descartável. A retenção só roda depois de verificar. Horários perdidos viram alerta. | | **Nuvem** | **Google Drive**, **OneDrive** e **Dropbox**, conectados com um clique (login por popup): o agente envia **direto** (envio retomável), conferência por hash do agente **e** do Server, retenção por quantidade/dias, exclusão definitiva (sem lixeira). | | **Restauração** | Baixar da nuvem, reenviar, extrair no agente (extração segura) e guia manual por tipo de backup. | @@ -50,6 +51,7 @@ O guia completo (HTTPS, proxy reverso, firewall, agentes, nuvem) está em [docs/ - [Instalação](docs/INSTALACAO.md) — Server, agentes, HTTPS/proxy, primeiros passos e referência de variáveis. - [Operação](docs/OPERACAO.md) — backup do próprio Server, atualização, recuperação de acesso, monitoramento, solução de problemas. - [Segurança](docs/SEGURANCA.md) — modelo de ameaças, o que protege, checklist de endurecimento. +- [Destinos de rede](docs/DESTINOS.md) — SFTP, FTP/FTPS, SMB e pasta local (NFS/iSCSI). - [Temas](docs/TEMAS.md) — pacotes `.zip` de identidade visual (interface, e-mail e PDF). - [Arquitetura](docs/ARQUITETURA.md) e [Roadmap](docs/ROADMAP.md) — decisões técnicas e fases. - [FAQ](docs/FAQ.md) · [Contribuindo](CONTRIBUTING.md) · [Política de segurança](SECURITY.md) diff --git a/deploy/docker-compose.agent.yml b/deploy/docker-compose.agent.yml index eabaaa0..1a95b8d 100644 --- a/deploy/docker-compose.agent.yml +++ b/deploy/docker-compose.agent.yml @@ -17,6 +17,8 @@ services: - agent-data:/var/lib/coruja-agent # credencial do agente, agenda local e fila de resultados - /:/host:ro # tudo o que o agente pode salvar, SOMENTE LEITURA (restrinja às pastas necessárias, se preferir) - /srv/coruja-backups:/backups # onde os arquivos de backup são gravados + # Destinos "pasta local" (NFS, iSCSI, disco externo): monte no host e exponha SOMENTE o que for destino em /destinos/... + # - /mnt/nas:/destinos/nas # Opcional (desligado por padrão): executar dumps DENTRO dos contêineres de banco e fazer o teste de restauração em # contêineres descartáveis. Dá ao agente controle total do Docker do servidor: habilite só se precisar. # - /var/run/docker.sock:/var/run/docker.sock diff --git a/docs/DESTINOS.md b/docs/DESTINOS.md new file mode 100644 index 0000000..737dfcc --- /dev/null +++ b/docs/DESTINOS.md @@ -0,0 +1,43 @@ +# Destinos de rede e pasta local + +Além das nuvens (Google Drive, OneDrive e Dropbox), o Coruja Backup grava em **SFTP**, **FTP/FTPS**, **SMB/CIFS** e numa **pasta local** do agente (que cobre **NFS** e **iSCSI** montados no host). + +## Quem faz o quê + +Um NAS ou servidor interno normalmente só é alcançado pela rede do agente. Por isso, nesses destinos **o agente** envia, confere e aplica a retenção. O Server guarda a configuração **cifrada** e a entrega ao agente pelo canal TLS (no agente ela fica em arquivo com permissão 600). Para o teste na tela **Destinos**, escolha o agente que vai acessar o destino. + +Cada envio segue a ordem: grava como `nome.coruja-part` → confere → renomeia → **só então** aplica a retenção (que nunca apaga o arquivo mais novo e só mexe nos arquivos do próprio job). + +| Conferência | O que faz | +| :--- | :--- | +| **Completa** (padrão) | Relê o arquivo do destino e compara o SHA-256. Dobra o tráfego. | +| **Rápida** | Compara só o tamanho. | + +## SFTP +- Senha ou chave privada (sem frase-senha). Caminho relativo à pasta do usuário; comece com `/` para um caminho absoluto. +- No primeiro teste, a **impressão digital** do servidor é mostrada para você confirmar e fica fixada. Se o servidor mudar de chave (reinstalação ou ataque), o envio é recusado; crie o destino de novo depois de conferir. + +## FTP / FTPS +- Padrão: **FTPS explícito**. Há também o implícito (porta 990) e o FTP sem criptografia, que envia **senha e arquivos em texto puro** (use apenas em rede isolada). +- "Aceitar certificado autoassinado" cifra o tráfego, mas não verifica a identidade do servidor. +- Usa modo passivo: o servidor precisa liberar as portas passivas para o agente. + +## SMB / CIFS +- SMB 2/3 com NTLM, direto do agente (não precisa montar nada nem de privilégios). Informe servidor, compartilhamento, usuário, senha e, se houver, domínio. + +## Pasta local (NFS, iSCSI, disco externo) +O agente **só grava dentro de `/destinos`** (mude com `CORUJA_DEST_DIR`), e não segue links simbólicos para fora dela. Monte o armazenamento **no host** e exponha só o que for destino: + +```yaml + volumes: + - /mnt/nas:/destinos/nas +``` + +- **NFS:** monte no host (`mount -t nfs servidor:/export /mnt/nas`, ou no `/etc/fstab` com `_netdev`). +- **iSCSI:** conecte o alvo no host (`open-iscsi`), formate e monte o dispositivo. +- Montar dentro do contêiner exigiria privilégios de administrador, o que o projeto evita de propósito. + +> Se o volume **não estiver montado** no host, o agente pode acabar gravando no disco do próprio host (na pasta vazia do ponto de montagem). Use uma subpasta que só exista dentro do volume montado como pasta base: se a montagem falhar, o teste acusa e você percebe. + +## Restauração +O Server não acessa destinos de rede, então não há download direto pelo navegador. Na execução, use **Trazer do destino para o agente** (o arquivo é conferido pelo SHA-256) e depois **Extrair no agente**, ou copie o arquivo. diff --git a/docs/SEGURANCA.md b/docs/SEGURANCA.md index 451b88e..7d7fd5b 100644 --- a/docs/SEGURANCA.md +++ b/docs/SEGURANCA.md @@ -39,3 +39,7 @@ Para relatar uma vulnerabilidade, veja [SECURITY.md](../SECURITY.md). ## Exceção do Dropbox No Google Drive e no OneDrive o agente recebe só o endereço de uma sessão de envio. O Dropbox não oferece isso para arquivos grandes, então o Server emite para o agente um **token de curta duração (cerca de 4 horas)** com o único escopo `files.content.write`, restrito à pasta do aplicativo. Esse escopo permite gravar e também **apagar** arquivos dessa pasta: um agente comprometido poderia remover backups da conta Dropbox durante a validade do token. Atenuantes: o Dropbox mantém os arquivos apagados recuperáveis por um período (conforme o plano da conta), e o token não lê o conteúdo nem alcança o restante do Dropbox. Se isso não for aceitável, use outro destino para esse job. + +## Destinos de rede + +Em SFTP, FTP, SMB e pasta local o **agente recebe as credenciais do destino** (exceção à regra de que credenciais ficam só no Server): sem isso ele não conseguiria gravar numa rede que o Server não alcança. Use uma conta exclusiva para backups, com acesso apenas à pasta de destino. Um agente comprometido pode ler, alterar e apagar o que essa conta alcança; se o armazenamento oferecer snapshots ou imutabilidade, habilite. Veja [DESTINOS.md](DESTINOS.md). diff --git a/internal/httpapi/handlers_jobs.go b/internal/httpapi/handlers_jobs.go index 07fe3e4..c7f552f 100644 --- a/internal/httpapi/handlers_jobs.go +++ b/internal/httpapi/handlers_jobs.go @@ -541,6 +541,10 @@ func (s *Server) getRun(w http.ResponseWriter, r *http.Request, _ *ctxUser) { info := map[string]any{} if j, err := s.Store.GetJob(r.Context(), run.JobID); err == nil { info = map[string]any{"kind": j.Kind, "has_cloud": j.CloudAccountID != nil, "keep": j.Keep} + if j.CloudAccountID != nil && s.Clouds != nil { + d, derr := s.Clouds.DestConfig(r.Context(), *j.CloudAccountID) + info["net_destination"] = derr == nil && d != nil + } if j.Kind == "database" { if cfg, err := j.OpenDB(s.Box); err == nil && cfg != nil { info["engine"] = cfg.Engine diff --git a/web/src/App.tsx b/web/src/App.tsx index 3e81a80..feeb31c 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -76,7 +76,7 @@ export default function App() { Painel Agentes Jobs - Nuvem + Destinos Histórico {me.user.role === 'admin' && Usuários} {me.user.role === 'admin' && Auditoria} diff --git a/web/src/api.ts b/web/src/api.ts index b7a3d50..5ee6ceb 100644 --- a/web/src/api.ts +++ b/web/src/api.ts @@ -67,11 +67,11 @@ export const ENGINE_LABEL: Record = { mysql: 'MySQL', mariadb: ' export const ENGINE_PORT: Record = { mysql: 3306, mariadb: 3306, postgres: 5432, mongodb: 27017 } export type CloudAccount = { - id: number; name: string; type: 'onedrive' | 'gdrive' | 'dropbox'; popup?: boolean; status: 'pending' | 'connected' | 'error'; account_label: string + id: number; name: string; type: 'onedrive' | 'gdrive' | 'dropbox' | 'sftp' | 'ftp' | 'smb' | 'local'; popup?: boolean; status: 'pending' | 'connected' | 'error'; account_label: string quota_total: number; quota_used: number; quota_checked_at: string | null; last_error: string; created_at: string; jobs: number } export type DeviceInfo = { user_code: string; verification_uri: string; expires_at: string; interval: number } -export const CLOUD_LABEL = { onedrive: 'OneDrive', gdrive: 'Google Drive', dropbox: 'Dropbox' } as const +export const CLOUD_LABEL = { onedrive: 'OneDrive', gdrive: 'Google Drive', dropbox: 'Dropbox', sftp: 'SFTP', ftp: 'FTP', smb: 'Pasta de rede (SMB)', local: 'Pasta local' } as const export const PHASE: Record = { archiving: 'Compactando', uploading: 'Enviando para a nuvem', verifying: 'Conferindo' } export const CRON_PRESETS: { label: string; cron: string }[] = [ diff --git a/web/src/icons.tsx b/web/src/icons.tsx index 5574ef3..82847ff 100644 --- a/web/src/icons.tsx +++ b/web/src/icons.tsx @@ -62,6 +62,17 @@ export const SmbIcon = ({ size = 40 }: P) => wrap(size, <> , 'Pasta de rede (SMB/NFS)') +export const FtpIcon = ({ size = 40 }: P) => wrap(size, <> + + +, 'FTP') + +export const LocalIcon = ({ size = 40 }: P) => wrap(size, <> + + + +, 'Pasta local ou volume montado') + export const CLOUD_ICON: Record ReactNode> = { - gdrive: GoogleDriveIcon, onedrive: OneDriveIcon, dropbox: DropboxIcon, s3: S3Icon, b2: B2Icon, box: BoxIcon, mega: MegaIcon, pcloud: PCloudIcon, sftp: SftpIcon, smb: SmbIcon, + gdrive: GoogleDriveIcon, onedrive: OneDriveIcon, dropbox: DropboxIcon, s3: S3Icon, b2: B2Icon, box: BoxIcon, mega: MegaIcon, pcloud: PCloudIcon, sftp: SftpIcon, ftp: FtpIcon, smb: SmbIcon, local: LocalIcon, } diff --git a/web/src/pages/Clouds.tsx b/web/src/pages/Clouds.tsx index f09d048..da19e88 100644 --- a/web/src/pages/Clouds.tsx +++ b/web/src/pages/Clouds.tsx @@ -2,6 +2,7 @@ import { FormEvent, useCallback, useEffect, useRef, useState } from 'react' import { CLOUD_LABEL, CloudAccount, DeviceInfo, User, api, ApiError, fmtBytes, fmtDate } from '../api' import { Badge, Button, Card, CopyBox, ErrorBox, Field, Input, Modal } from '../ui' import { CLOUD_ICON } from '../icons' +import NetDestination, { AgentSelect, NET_TYPES, useAgents } from './NetDestination' // Catálogo de destinos. ok = disponível; soon = em construção (colorido); off = previsto (cinza). type Prov = { id: string; label: string; hint: string; state: 'ok' | 'soon' | 'off' } @@ -17,8 +18,10 @@ const PROVIDERS: { group: string; items: Prov[] }[] = [ { id: 'pcloud', label: 'pCloud', hint: 'Armazenamento europeu', state: 'off' }, ] }, { group: 'Servidores e rede', items: [ - { id: 'sftp', label: 'SFTP', hint: 'Servidor por SSH', state: 'off' }, - { id: 'smb', label: 'Pasta de rede', hint: 'SMB, NFS, iSCSI', state: 'off' }, + { id: 'sftp', label: 'SFTP', hint: 'Servidor por SSH', state: 'ok' }, + { id: 'ftp', label: 'FTP', hint: 'FTPS ou FTP simples', state: 'ok' }, + { id: 'smb', label: 'Pasta de rede', hint: 'SMB / CIFS (Windows, NAS)', state: 'ok' }, + { id: 'local', label: 'Pasta local', hint: 'NFS, iSCSI ou disco montado', state: 'ok' }, ] }, ] type Defs = { gdrive?: boolean; gdrive_web?: boolean; onedrive_web?: boolean; dropbox_web?: boolean; broker?: string } @@ -57,6 +60,29 @@ function ProviderGrid({ onPick }: { onPick: (id: string) => void }) { ) } +// Teste de um destino de rede já salvo: quem testa é um agente. +function TestDestination({ account }: { account: CloudAccount }) { + const agents = useAgents() + const [agent, setAgent] = useState(0) + const [msg, setMsg] = useState('') + const [err, setErr] = useState('') + const [busy, setBusy] = useState(false) + async function run() { + setMsg(''); setErr(''); setBusy(true) + try { const r = await api<{ detail: string }>('POST', '/api/destinations/test', { agent_id: agent, id: account.id }); setMsg(`Funcionando: ${r.detail}.`) } + catch (x) { setErr((x as ApiError).message) } finally { setBusy(false) } + } + return ( +
+

Escolha o agente que vai acessar o destino ({account.account_label}).

+ + {msg &&
{msg}
} + + +
+ ) +} + // Login por popup: abre a janela já no clique (senão o navegador bloqueia), pede o endereço ao Server, espera o código que // a página de retorno entrega por postMessage (só aceita a origem do intermediário) e conclui no Server. async function popupLogin(body: Record, broker: string) { @@ -89,6 +115,7 @@ export default function Clouds({ me }: { me: User }) { const [info, setInfo] = useState('') const [defs, setDefs] = useState({}) const [wizard, setWizard] = useState<{ id?: number; device?: DeviceInfo; name?: string; type?: string } | null>(null) + const [testing, setTesting] = useState(null) const isAdmin = me.role === 'admin' const load = useCallback(() => { @@ -118,16 +145,16 @@ export default function Clouds({ me }: { me: User }) {
-

Nuvem

-

Contas onde os backups são guardados. As credenciais ficam só no Server (cifradas); o agente envia o arquivo direto para a nuvem.

+

Destinos

+

Onde os backups são guardados. Nas nuvens, as credenciais ficam só no Server; nos destinos de rede, quem acessa é o agente.

- {isAdmin && } + {isAdmin && }
{info &&
{info}
}
- {accounts.length === 0 &&

Nenhuma conta conectada ainda. Clique em “Conectar nuvem”.

} + {accounts.length === 0 &&

Nenhum destino ainda. Clique em “Novo destino”.

} {accounts.map((a) => { const pct = a.quota_total ? Math.min(100, Math.round((a.quota_used / a.quota_total) * 100)) : 0 return ( @@ -151,8 +178,9 @@ export default function Clouds({ me }: { me: User }) { )}
{a.jobs} job(s) usando - {me.role !== 'viewer' && a.status !== 'pending' && } - {isAdmin && } + {me.role !== 'viewer' && a.status !== 'pending' && !NET_TYPES.includes(a.type) && } + {isAdmin && NET_TYPES.includes(a.type) && } + {isAdmin && !NET_TYPES.includes(a.type) && } {isAdmin && }
@@ -160,10 +188,17 @@ export default function Clouds({ me }: { me: User }) { })}
- {wizard && { setWizard(null); load() }}> + {testing && setTesting(null)}>} + {wizard && { setWizard(null); load() }}> {wizard.device && wizard.id ? { setWizard(null); setInfo('Conta conectada com sucesso.'); load() }} /> : !wizard.type ? setWizard({ type })} /> + : NET_TYPES.includes(wizard.type) ? ( +
+ + { setWizard(null); setInfo('Destino salvo.'); load() }} /> +
+ ) : setWizard({})} defs={defs} onCreated={(id, device, name) => { setWizard({ id, device, name }); load() }} onConnected={() => { setWizard(null); setInfo('Conta conectada com sucesso.'); load() }} />}
}
diff --git a/web/src/pages/Jobs.tsx b/web/src/pages/Jobs.tsx index 57b870e..6d39d18 100644 --- a/web/src/pages/Jobs.tsx +++ b/web/src/pages/Jobs.tsx @@ -151,27 +151,27 @@ function JobForm({ job, agents, clouds, onDone }: { job: Job | null; agents: Age setF({ ...f, dest_subdir: e.target.value })} /> - + setF({ ...f, keep: Number(e.target.value) })} required />
- Enviar para a nuvem (opcional) - + Enviar para um destino (opcional) + {f.cloud_account_id !== 0 && (<> - + setF({ ...f, cloud_folder: e.target.value })} />
- setF({ ...f, cloud_keep: Number(e.target.value) })} /> - setF({ ...f, cloud_keep_days: Number(e.target.value) })} /> + setF({ ...f, cloud_keep: Number(e.target.value) })} /> + setF({ ...f, cloud_keep_days: Number(e.target.value) })} />
-

A retenção na nuvem só roda depois que o envio for conferido por hash, e o arquivo mais novo nunca é apagado.

+

A retenção no destino só roda depois que o envio for conferido, e o arquivo mais novo nunca é apagado.

)}
diff --git a/web/src/pages/NetDestination.tsx b/web/src/pages/NetDestination.tsx new file mode 100644 index 0000000..65e419b --- /dev/null +++ b/web/src/pages/NetDestination.tsx @@ -0,0 +1,132 @@ +import { FormEvent, useEffect, useState } from 'react' +import { Agent, api, ApiError } from '../api' +import { Button, ErrorBox, Field, Input } from '../ui' + +export const NET_TYPES = ['sftp', 'ftp', 'smb', 'local'] +const sel = 'w-full rounded-lg border border-border bg-surface px-3 py-2' + +type Cfg = { + type: string; host: string; port: number; user: string; password: string; private_key: string; host_key: string + tls: string; skip_verify: boolean; share: string; domain: string; base_path: string; verify: string +} + +export function useAgents() { + const [agents, setAgents] = useState([]) + useEffect(() => { + api<{ agents: Agent[] }>('GET', '/api/agents').then((r) => setAgents((r.agents ?? []).filter((a) => !a.revoked_at))).catch(() => setAgents([])) + }, []) + return agents +} + +export function AgentSelect({ agents, value, onChange }: { agents: Agent[]; value: number; onChange: (v: number) => void }) { + return ( + + ) +} + +export default function NetDestination({ type, onSaved }: { type: string; onSaved: () => void }) { + const agents = useAgents() + const [name, setName] = useState('') + const [agent, setAgent] = useState(0) + const [f, setF] = useState({ type, host: '', port: 0, user: '', password: '', private_key: '', host_key: '', tls: 'explicit', skip_verify: false, share: '', domain: '', base_path: '', verify: 'full' }) + const [useKey, setUseKey] = useState(false) + const [tested, setTested] = useState<{ detail: string; host_key?: string } | null>(null) + const [trusted, setTrusted] = useState(false) + const [err, setErr] = useState('') + const [busy, setBusy] = useState('') + useEffect(() => { const on = agents.find((a) => a.online); if (on && !agent) setAgent(on.id) }, [agents, agent]) + // qualquer mudança na configuração invalida o teste + const set = (p: Partial) => { setF((v) => ({ ...v, host_key: '', ...p })); setTested(null); setTrusted(false) } + const defPort = type === 'sftp' ? 22 : type === 'smb' ? 445 : f.tls === 'implicit' ? 990 : 21 + const cfg = () => ({ ...f, password: useKey ? '' : f.password, private_key: useKey ? f.private_key : '' }) + + async function test() { + setErr(''); setTested(null); setTrusted(false) + if (!agent) { setErr('Escolha um agente online: é ele que vai acessar o destino.'); return } + setBusy('test') + try { setTested(await api<{ detail: string; host_key?: string }>('POST', '/api/destinations/test', { agent_id: agent, config: cfg() })) } + catch (x) { setErr((x as ApiError).message) } finally { setBusy('') } + } + async function save(e: FormEvent) { + e.preventDefault(); setErr(''); setBusy('save') + try { await api('POST', '/api/destinations', { name, config: { ...cfg(), host_key: tested?.host_key ?? '' } }); onSaved() } + catch (x) { setErr((x as ApiError).message) } finally { setBusy('') } + } + const canSave = !!tested && !!name.trim() && (type !== 'sftp' || trusted) + + return ( +
+ setName(e.target.value)} required /> + + {type === 'local' && ( +
+ Grava numa pasta do próprio agente, dentro da raiz de destinos (/destinos). Para NFS, iSCSI ou um disco externo, monte-o no servidor e + adicione ao contêiner do agente um volume como - /mnt/nas:/destinos/nas. +
+ )} + {type !== 'local' && ( + <> + {type === 'ftp' && ( + + + + )} + {type === 'ftp' && f.tls === 'none' &&
Atenção: sem TLS, quem estiver na rede consegue ler a senha e o conteúdo dos backups. Use só numa rede isolada e confiável.
} +
+ set({ host: e.target.value })} placeholder="nas.empresa.local" required /> + set({ port: Number(e.target.value) })} /> +
+ {type === 'smb' && ( +
+ set({ share: e.target.value })} placeholder="backups" required /> + set({ domain: e.target.value })} /> +
+ )} +
+ set({ user: e.target.value })} required /> + {!useKey && set({ password: e.target.value })} />} +
+ {type === 'sftp' && ( + <> + + {useKey &&