-
Notifications
You must be signed in to change notification settings - Fork 113
/
appprovider.go
459 lines (396 loc) · 12.9 KB
/
appprovider.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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
// Copyright 2018-2021 CERN
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// In applying this license, CERN does not waive the privileges and immunities
// granted to it by virtue of its status as an Intergovernmental Organization
// or submit itself to any jurisdiction.
package appprovider
import (
"encoding/json"
"net/http"
"path"
appregistry "github.com/cs3org/go-cs3apis/cs3/app/registry/v1beta1"
gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1"
rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1"
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
typespb "github.com/cs3org/go-cs3apis/cs3/types/v1beta1"
"github.com/cs3org/reva/v2/internal/http/services/datagateway"
"github.com/cs3org/reva/v2/pkg/rgrpc/status"
"github.com/cs3org/reva/v2/pkg/rgrpc/todo/pool"
"github.com/cs3org/reva/v2/pkg/rhttp"
"github.com/cs3org/reva/v2/pkg/rhttp/global"
"github.com/cs3org/reva/v2/pkg/sharedconf"
"github.com/cs3org/reva/v2/pkg/storagespace"
"github.com/cs3org/reva/v2/pkg/utils"
"github.com/go-chi/chi"
ua "github.com/mileusna/useragent"
"github.com/mitchellh/mapstructure"
"github.com/pkg/errors"
"github.com/rs/zerolog"
)
func init() {
global.Register("appprovider", New)
}
// Config holds the config options for the HTTP appprovider service
type Config struct {
Prefix string `mapstructure:"prefix"`
GatewaySvc string `mapstructure:"gatewaysvc"`
Insecure bool `mapstructure:"insecure"`
}
func (c *Config) init() {
if c.Prefix == "" {
c.Prefix = "app"
}
c.GatewaySvc = sharedconf.GetGatewaySVC(c.GatewaySvc)
}
type svc struct {
conf *Config
router *chi.Mux
}
// New returns a new ocmd object
func New(m map[string]interface{}, log *zerolog.Logger) (global.Service, error) {
conf := &Config{}
if err := mapstructure.Decode(m, conf); err != nil {
return nil, err
}
conf.init()
r := chi.NewRouter()
s := &svc{
conf: conf,
router: r,
}
if err := s.routerInit(); err != nil {
return nil, err
}
return s, nil
}
func (s *svc) routerInit() error {
s.router.Get("/list", s.handleList)
s.router.Post("/new", s.handleNew)
s.router.Post("/open", s.handleOpen)
return nil
}
// Close performs cleanup.
func (s *svc) Close() error {
return nil
}
func (s *svc) Prefix() string {
return s.conf.Prefix
}
func (s *svc) Unprotected() []string {
return []string{"/list"}
}
func (s *svc) Handler() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
s.router.ServeHTTP(w, r)
})
}
func (s *svc) handleNew(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
client, err := pool.GetGatewayServiceClient(s.conf.GatewaySvc)
if err != nil {
writeError(w, r, appErrorServerError, "error getting grpc gateway client", err)
return
}
err = r.ParseForm()
if err != nil {
writeError(w, r, appErrorInvalidParameter, "parameters could not be parsed", nil)
}
if r.Form.Get("template") != "" {
// TODO in the future we want to create a file out of the given template
writeError(w, r, appErrorUnimplemented, "template is not implemented", nil)
return
}
parentContainerIDStr := r.Form.Get("parent_container_id")
if parentContainerIDStr == "" {
writeError(w, r, appErrorInvalidParameter, "missing parent container ID", nil)
return
}
parentContainerID, err := storagespace.ParseID(parentContainerIDStr)
if err != nil {
writeError(w, r, appErrorInvalidParameter, "invalid parent container ID", nil)
return
}
filename := r.Form.Get("filename")
if filename == "" {
writeError(w, r, appErrorInvalidParameter, "missing filename", nil)
return
}
dirPart, filePart := path.Split(filename)
if dirPart != "" || filePart != filename {
writeError(w, r, appErrorInvalidParameter, "the filename must not contain a path segment", nil)
return
}
statParentContainerReq := &provider.StatRequest{
Ref: &provider.Reference{
ResourceId: &parentContainerID,
},
}
parentContainer, err := client.Stat(ctx, statParentContainerReq)
if err != nil {
writeError(w, r, appErrorServerError, "error sending a grpc stat request", err)
return
}
if parentContainer.Status.Code != rpc.Code_CODE_OK {
writeError(w, r, appErrorNotFound, "the parent container is not accessible or does not exist", err)
return
}
if parentContainer.Info.Type != provider.ResourceType_RESOURCE_TYPE_CONTAINER {
writeError(w, r, appErrorInvalidParameter, "the parent container id does not point to a container", nil)
return
}
fileRef := &provider.Reference{
ResourceId: &parentContainerID,
Path: utils.MakeRelativePath(filename),
}
statFileReq := &provider.StatRequest{
Ref: fileRef,
}
statFileRes, err := client.Stat(ctx, statFileReq)
if err != nil {
writeError(w, r, appErrorServerError, "failed to stat the file", err)
return
}
if statFileRes.Status.Code != rpc.Code_CODE_NOT_FOUND {
if statFileRes.Status.Code == rpc.Code_CODE_OK {
writeError(w, r, appErrorAlreadyExists, "the file already exists", nil)
return
}
writeError(w, r, appErrorServerError, "statting the file returned unexpected status code", err)
return
}
// Create empty file via storageprovider
createReq := &provider.InitiateFileUploadRequest{
Ref: fileRef,
Opaque: &typespb.Opaque{
Map: map[string]*typespb.OpaqueEntry{
"Upload-Length": {
Decoder: "plain",
Value: []byte("0"),
},
},
},
}
// having a client.CreateFile() function would come in handy here...
createRes, err := client.InitiateFileUpload(ctx, createReq)
if err != nil {
writeError(w, r, appErrorServerError, "error calling InitiateFileUpload", err)
return
}
if createRes.Status.Code != rpc.Code_CODE_OK {
writeError(w, r, appErrorServerError, "error calling InitiateFileUpload", nil)
return
}
// Do a HTTP PUT with an empty body
var ep, token string
for _, p := range createRes.Protocols {
if p.Protocol == "simple" {
ep, token = p.UploadEndpoint, p.Token
}
}
httpReq, err := rhttp.NewRequest(ctx, http.MethodPut, ep, nil)
if err != nil {
writeError(w, r, appErrorServerError, "failed to create the file", err)
return
}
httpReq.Header.Set(datagateway.TokenTransportHeader, token)
httpRes, err := rhttp.GetHTTPClient(
rhttp.Context(ctx),
rhttp.Insecure(s.conf.Insecure),
).Do(httpReq)
if err != nil {
writeError(w, r, appErrorServerError, "failed to create the file", err)
return
}
defer httpRes.Body.Close()
if httpRes.StatusCode == http.StatusForbidden {
// the file upload was already finished since it is a zero byte file
// TODO: why do we get a 401 then!?
} else if httpRes.StatusCode != http.StatusOK {
writeError(w, r, appErrorServerError, "failed to create the file", nil)
return
}
// Stat the newly created file
statRes, err := client.Stat(ctx, statFileReq)
if err != nil {
writeError(w, r, appErrorServerError, "statting the created file failed", err)
return
}
if statRes.Status.Code != rpc.Code_CODE_OK {
writeError(w, r, appErrorServerError, "statting the created file failed", nil)
return
}
if statRes.Info.Type != provider.ResourceType_RESOURCE_TYPE_FILE {
writeError(w, r, appErrorInvalidParameter, "the given file id does not point to a file", nil)
return
}
js, err := json.Marshal(
map[string]interface{}{
"file_id": storagespace.FormatResourceID(*statRes.Info.Id),
},
)
if err != nil {
writeError(w, r, appErrorServerError, "error marshalling JSON response", err)
return
}
w.Header().Set("Content-Type", "application/json")
if _, err = w.Write(js); err != nil {
writeError(w, r, appErrorServerError, "error writing JSON response", err)
return
}
}
func (s *svc) handleList(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
client, err := pool.GetGatewayServiceClient(s.conf.GatewaySvc)
if err != nil {
writeError(w, r, appErrorServerError, "error getting grpc gateway client", err)
return
}
listRes, err := client.ListSupportedMimeTypes(ctx, &appregistry.ListSupportedMimeTypesRequest{})
if err != nil {
writeError(w, r, appErrorServerError, "error listing supported mime types", err)
return
}
if listRes.Status.Code != rpc.Code_CODE_OK {
writeError(w, r, appErrorServerError, "error listing supported mime types", nil)
return
}
res := filterAppsByUserAgent(listRes.MimeTypes, r.UserAgent())
js, err := json.Marshal(map[string]interface{}{"mime-types": res})
if err != nil {
writeError(w, r, appErrorServerError, "error marshalling JSON response", err)
return
}
w.Header().Set("Content-Type", "application/json")
if _, err = w.Write(js); err != nil {
writeError(w, r, appErrorServerError, "error writing JSON response", err)
return
}
}
func (s *svc) handleOpen(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
client, err := pool.GetGatewayServiceClient(s.conf.GatewaySvc)
if err != nil {
writeError(w, r, appErrorServerError, "Internal error with the gateway, please try again later", err)
return
}
err = r.ParseForm()
if err != nil {
writeError(w, r, appErrorInvalidParameter, "parameters could not be parsed", nil)
}
fileID := r.Form.Get("file_id")
if fileID == "" {
writeError(w, r, appErrorInvalidParameter, "missing file ID", nil)
return
}
resourceID, err := storagespace.ParseID(fileID)
if err != nil {
writeError(w, r, appErrorInvalidParameter, "invalid file ID", nil)
return
}
fileRef := &provider.Reference{
ResourceId: &resourceID,
Path: ".",
}
statRes, err := client.Stat(ctx, &provider.StatRequest{Ref: fileRef})
if err != nil {
writeError(w, r, appErrorServerError, "Internal error accessing the file, please try again later", err)
return
}
if statRes.Status.Code == rpc.Code_CODE_NOT_FOUND {
writeError(w, r, appErrorNotFound, "file does not exist", nil)
return
} else if statRes.Status.Code != rpc.Code_CODE_OK {
writeError(w, r, appErrorServerError, "failed to stat the file", nil)
return
}
if statRes.Info.Type != provider.ResourceType_RESOURCE_TYPE_FILE {
writeError(w, r, appErrorInvalidParameter, "the given file id does not point to a file", nil)
return
}
viewMode := getViewMode(statRes.Info, r.Form.Get("view_mode"))
if viewMode == gateway.OpenInAppRequest_VIEW_MODE_INVALID {
writeError(w, r, appErrorInvalidParameter, "invalid view mode", err)
return
}
openReq := gateway.OpenInAppRequest{
Ref: fileRef,
ViewMode: viewMode,
App: r.Form.Get("app_name"),
}
openRes, err := client.OpenInApp(ctx, &openReq)
if err != nil {
writeError(w, r, appErrorServerError,
"Error contacting the requested application, please use a different one or try again later", err)
return
}
if openRes.Status.Code != rpc.Code_CODE_OK {
if openRes.Status.Code == rpc.Code_CODE_NOT_FOUND {
writeError(w, r, appErrorNotFound, openRes.Status.Message, nil)
return
}
writeError(w, r, appErrorServerError, openRes.Status.Message,
status.NewErrorFromCode(openRes.Status.Code, "error calling OpenInApp"))
return
}
js, err := json.Marshal(openRes.AppUrl)
if err != nil {
writeError(w, r, appErrorServerError, "Internal error with JSON payload",
errors.Wrap(err, "error marshalling JSON response"))
return
}
w.Header().Set("Content-Type", "application/json")
if _, err = w.Write(js); err != nil {
writeError(w, r, appErrorServerError, "Internal error with JSON payload",
errors.Wrap(err, "error writing JSON response"))
return
}
}
func filterAppsByUserAgent(mimeTypes []*appregistry.MimeTypeInfo, userAgent string) []*appregistry.MimeTypeInfo {
ua := ua.Parse(userAgent)
res := []*appregistry.MimeTypeInfo{}
for _, m := range mimeTypes {
apps := []*appregistry.ProviderInfo{}
for _, p := range m.AppProviders {
p.Address = "" // address is internal only and not needed in the client
// apps are called by name, so if it has no name it cannot be called and should not be advertised
// also filter Desktop-only apps if ua is not Desktop
if p.Name != "" && (ua.Desktop || !p.DesktopOnly) {
apps = append(apps, p)
}
}
if len(apps) > 0 {
m.AppProviders = apps
res = append(res, m)
}
}
return res
}
func getViewMode(res *provider.ResourceInfo, vm string) gateway.OpenInAppRequest_ViewMode {
if vm != "" {
return utils.GetViewMode(vm)
}
var viewMode gateway.OpenInAppRequest_ViewMode
canEdit := res.PermissionSet.InitiateFileUpload
canView := res.PermissionSet.InitiateFileDownload
switch {
case canEdit && canView:
viewMode = gateway.OpenInAppRequest_VIEW_MODE_READ_WRITE
case canView:
viewMode = gateway.OpenInAppRequest_VIEW_MODE_READ_ONLY
default:
viewMode = gateway.OpenInAppRequest_VIEW_MODE_INVALID
}
return viewMode
}