forked from pydio/cells
-
Notifications
You must be signed in to change notification settings - Fork 0
/
remote.go
262 lines (236 loc) · 7.64 KB
/
remote.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
/*
* Copyright (c) 2019. Abstrium SAS <team (at) pydio.com>
* This file is part of Pydio Cells.
*
* Pydio Cells is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Pydio Cells is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Pydio Cells. If not, see <http://www.gnu.org/licenses/>.
*
* The latest code can be found at <https://pydio.com>.
*/
package cells
import (
"context"
"crypto/tls"
"crypto/x509"
"fmt"
"net"
"net/url"
"strings"
"time"
"github.com/micro/go-micro/client"
"github.com/micro/go-micro/metadata"
microgrpc "github.com/micro/go-plugins/client/grpc"
"github.com/pborman/uuid"
sdk "github.com/pydio/cells-sdk-go"
"github.com/pydio/cells-sdk-go/transport/mc"
"github.com/pydio/cells-sdk-go/transport/oidc"
"github.com/pydio/cells/common"
"github.com/pydio/cells/common/proto/tree"
servicecontext "github.com/pydio/cells/common/service/context"
"github.com/pydio/cells/common/sync/model"
)
// RemoteConfig is a dependency-free struct similar to SdkConfig
type RemoteConfig struct {
// Url stores domain name or IP & port to the server.
Url string `json:"url"`
// OIDC GrantPassword Flow
ClientKey string `json:"clientKey"`
ClientSecret string `json:"clientSecret"`
User string `json:"user"`
Password string `json:"password"`
// OIDC Code Flow
IdToken string `json:"id_token"`
RefreshToken string `json:"refresh_token"`
ExpiresAt int `json:"expires_at"`
// SkipVerify tells the transport to ignore expired or self-signed TLS certificates
SkipVerify bool `json:"skipVerify"`
CustomHeaders map[string]string `json:"-"`
}
// Remote connect to a remove Cells server using the GRPC gateway.
type Remote struct {
abstract
config *sdk.SdkConfig
session *tree.IndexationSession
sessionsCreates []*tree.CreateNodeRequest
}
// NewRemote creates a new Remote Endpoint
func NewRemote(config RemoteConfig, root string, options Options) *Remote {
useCache := true
if config.IdToken != "" {
useCache = false
}
sdkConfig := &sdk.SdkConfig{
Url: config.Url,
SkipVerify: config.SkipVerify,
// Password Flow
ClientKey: config.ClientKey,
ClientSecret: config.ClientSecret,
User: config.User,
Password: config.Password,
UseTokenCache: useCache,
// Code Flow
IdToken: config.IdToken,
RefreshToken: config.RefreshToken,
TokenExpiresAt: config.ExpiresAt,
CustomHeaders: config.CustomHeaders,
}
c := &Remote{
abstract: abstract{
root: strings.TrimLeft(root, "/"),
options: options,
clientUUID: uuid.New(),
},
config: sdkConfig,
}
c.factory = &remoteClientFactory{
config: sdkConfig,
registry: NewDynamicRegistry(sdkConfig),
}
c.source = c
logCtx := context.Background()
logCtx = servicecontext.WithServiceName(logCtx, "endpoint.cells.remote")
logCtx = servicecontext.WithServiceColor(logCtx, servicecontext.ServiceColorGrpc)
c.globalCtx = logCtx
return c
}
// RefreshRemoteConfig is used to refresh ID Token / Refresh Token from outside
func (c *Remote) RefreshRemoteConfig(config RemoteConfig) {
c.config.IdToken = config.IdToken
c.config.RefreshToken = config.RefreshToken
c.config.TokenExpiresAt = config.ExpiresAt
c.factory.(*remoteClientFactory).config = c.config
}
// GetEndpointInfo returns Endpoint information in standard format.
func (c *Remote) GetEndpointInfo() model.EndpointInfo {
return model.EndpointInfo{
URI: fmt.Sprintf("%s/%s", c.config.Url, c.root),
RequiresNormalization: false,
RequiresFoldersRescan: false,
IsAsynchronous: true,
Ignores: []string{common.PYDIO_SYNC_HIDDEN_FILE_META},
}
}
// remoteClientFactory implements the clientProviderFactory interface
type remoteClientFactory struct {
config *sdk.SdkConfig
registry *DynamicRegistry
}
func (f *remoteClientFactory) GetNodeProviderClient(ctx context.Context) (context.Context, tree.NodeProviderClient, error) {
ctx, cli, e := f.getClient(ctx)
if e != nil {
return nil, nil, e
}
return ctx, tree.NewNodeProviderClient(RemoteCellsServiceName, cli), nil
}
func (f *remoteClientFactory) GetNodeReceiverClient(ctx context.Context) (context.Context, tree.NodeReceiverClient, error) {
ctx, cli, e := f.getClient(ctx)
if e != nil {
return nil, nil, e
}
return ctx, tree.NewNodeReceiverClient(RemoteCellsServiceName, cli), nil
}
func (f *remoteClientFactory) GetNodeChangesStreamClient(ctx context.Context) (context.Context, tree.NodeChangesStreamerClient, error) {
ctx, cli, e := f.getClient(ctx)
if e != nil {
return nil, nil, e
}
return ctx, tree.NewNodeChangesStreamerClient(RemoteCellsServiceName, cli), nil
}
func (f *remoteClientFactory) GetNodeReceiverStreamClient(ctx context.Context) (context.Context, tree.NodeReceiverStreamClient, error) {
ctx, cli, e := f.getClient(ctx)
if e != nil {
return nil, nil, e
}
return ctx, tree.NewNodeReceiverStreamClient(RemoteCellsServiceName, cli), nil
}
func (f *remoteClientFactory) GetNodeProviderStreamClient(ctx context.Context) (context.Context, tree.NodeProviderStreamerClient, error) {
ctx, cli, e := f.getClient(ctx)
if e != nil {
return nil, nil, e
}
return ctx, tree.NewNodeProviderStreamerClient(RemoteCellsServiceName, cli), nil
}
func (f *remoteClientFactory) GetObjectsClient(ctx context.Context) (context.Context, objectsClient, error) {
return ctx, mc.NewS3Client(f.config), nil
}
func (f *remoteClientFactory) getClient(ctx context.Context) (context.Context, client.Client, error) {
jwt, err := oidc.RetrieveToken(f.config)
if err != nil {
return nil, nil, err
}
opts := []client.Option{
client.Registry(f.registry.Micro),
client.Wrap(func(i client.Client) client.Client {
return &RegistryRefreshClient{w: i, r: f.registry}
}),
}
u, _ := url.Parse(f.config.Url)
if u.Scheme == "https" {
if pool, err := f.serverCerts(); err == nil {
opts = append(opts, microgrpc.AuthTLS(&tls.Config{
InsecureSkipVerify: f.config.SkipVerify,
RootCAs: pool,
}))
}
}
microClient := microgrpc.NewClient(opts...)
var md metadata.Metadata
if m, ok := metadata.FromContext(ctx); ok {
md = m
} else {
md = metadata.Metadata{}
}
md["x-pydio-bearer"] = jwt
if f.config.CustomHeaders != nil {
if ua, ok := f.config.CustomHeaders["User-Agent"]; ok {
md["x-pydio-grpc-user-agent"] = ua
}
}
ctx = metadata.NewContext(ctx, md)
return ctx, microClient, nil
}
var memCerts map[string]*x509.CertPool
// serverCerts loads certificates from https served server to be set inside the client
func (f *remoteClientFactory) serverCerts() (*x509.CertPool, error) {
if memCerts == nil {
memCerts = make(map[string]*x509.CertPool)
}
if pool, ok := memCerts[f.config.Url]; ok {
return pool, nil
}
u, _ := url.Parse(f.config.Url)
d := &net.Dialer{
Timeout: time.Duration(1) * time.Second,
}
h := u.Host
if _, p, _ := net.SplitHostPort(u.Host); p == "" {
h += ":443"
}
conn, err := tls.DialWithDialer(d, "tcp", h, &tls.Config{
InsecureSkipVerify: f.config.SkipVerify,
})
if err != nil {
return nil, err
}
defer conn.Close()
cert := conn.ConnectionState().PeerCertificates
var pool *x509.CertPool
if pool, err = x509.SystemCertPool(); err != nil {
pool = x509.NewCertPool()
}
for _, c := range cert {
pool.AddCert(c)
}
memCerts[f.config.Url] = pool
return pool, nil
}