-
Notifications
You must be signed in to change notification settings - Fork 172
/
rest.go
341 lines (295 loc) · 9.88 KB
/
rest.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
/*
* Copyright (c) 2018. 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 rest provides a gateway to the underlying grpc service
package rest
import (
"context"
"fmt"
"github.com/emicklei/go-restful"
"github.com/golang/protobuf/ptypes"
"github.com/golang/protobuf/ptypes/any"
"github.com/micro/go-micro/errors"
"go.uber.org/zap"
"github.com/pborman/uuid"
"github.com/pydio/cells/common"
"github.com/pydio/cells/common/log"
"github.com/pydio/cells/common/micro"
"github.com/pydio/cells/common/proto/idm"
"github.com/pydio/cells/common/proto/rest"
service2 "github.com/pydio/cells/common/service"
"github.com/pydio/cells/common/service/proto"
"github.com/pydio/cells/common/service/resources"
)
// WorkspaceHandler defines the specific handler struc for workspace management.
type WorkspaceHandler struct {
resources.ResourceProviderHandler
}
// NewWorkspaceHandler simply creates and configures a handler.
func NewWorkspaceHandler() *WorkspaceHandler {
h := new(WorkspaceHandler)
h.ServiceName = common.ServiceWorkspace
h.ResourceName = "workspace"
h.PoliciesLoader = h.loadPoliciesForResource
return h
}
// SwaggerTags lists the names of the service tags declared in the swagger json implemented by this service.
func (h *WorkspaceHandler) SwaggerTags() []string {
return []string{"WorkspaceService"}
}
// Filter returns a function to filter the swagger path.
func (h *WorkspaceHandler) Filter() func(string) string {
return nil
}
func (h *WorkspaceHandler) PutWorkspace(req *restful.Request, rsp *restful.Response) {
ctx := req.Request.Context()
var inputWorkspace idm.Workspace
err := req.ReadEntity(&inputWorkspace)
if err != nil {
log.Logger(ctx).Error("cannot fetch idm.Workspace from request", zap.Error(err))
service2.RestError500(req, rsp, err)
return
}
log.Logger(req.Request.Context()).Debug("Received Workspace.Put API request", zap.Any("inputWorkspace", inputWorkspace))
cli := idm.NewWorkspaceServiceClient(common.ServiceGrpcNamespace_+common.ServiceWorkspace, defaults.NewClient())
update := false
if ws, _ := h.workspaceById(ctx, inputWorkspace.UUID, cli); ws != nil {
update = true
if !h.MatchPolicies(ctx, ws.UUID, ws.Policies, service.ResourcePolicyAction_WRITE) {
service2.RestError403(req, rsp, errors.Forbidden(common.ServiceWorkspace, "You are not allowed to edit this workspace"))
return
}
// Check that slug is not already in use
if ws.Slug != inputWorkspace.Slug {
h.deduplicateSlug(ctx, &inputWorkspace, cli)
}
} else {
// Create a new Uuid
if inputWorkspace.UUID == "" {
inputWorkspace.UUID = uuid.New()
}
// If Policies are empty, create default policies
if len(inputWorkspace.Policies) == 0 {
inputWorkspace.Policies = []*service.ResourcePolicy{
{Subject: "profile:standard", Action: service.ResourcePolicyAction_READ, Effect: service.ResourcePolicy_allow},
{Subject: "profile:" + common.PydioProfileAdmin, Action: service.ResourcePolicyAction_WRITE, Effect: service.ResourcePolicy_allow},
}
}
// Check that slug is not already in use
h.deduplicateSlug(ctx, &inputWorkspace, cli)
}
defaultRights, quotaValue := h.extractDefaultRights(ctx, &inputWorkspace)
response, er := cli.CreateWorkspace(req.Request.Context(), &idm.CreateWorkspaceRequest{
Workspace: &inputWorkspace,
})
if er != nil {
service2.RestError500(req, rsp, er)
return
}
if e := h.storeRootNodesAsACLs(ctx, &inputWorkspace, update); e != nil {
service2.RestError500(req, rsp, e)
return
}
if e := h.manageDefaultRights(ctx, &inputWorkspace, false, defaultRights, quotaValue); e != nil {
service2.RestError500(req, rsp, e)
return
}
u := response.Workspace
h.manageDefaultRights(ctx, u, true, "", "")
rsp.WriteEntity(u)
if update {
log.Auditer(ctx).Info(
fmt.Sprintf("Updated workspace [%s]", u.Slug),
log.GetAuditId(common.AuditWsUpdate),
u.ZapUuid(),
)
} else {
log.Auditer(ctx).Info(
fmt.Sprintf("Created workspace [%s]", u.Slug),
log.GetAuditId(common.AuditWsCreate),
u.ZapUuid(),
)
}
}
func (h *WorkspaceHandler) DeleteWorkspace(req *restful.Request, rsp *restful.Response) {
slug := req.PathParameter("Slug")
log.Logger(req.Request.Context()).Debug("Received Workspace.Delete API request", zap.String("Slug", slug))
singleQ := &idm.WorkspaceSingleQuery{}
singleQ.Slug = slug
query, _ := ptypes.MarshalAny(singleQ)
serviceQuery := &service.Query{SubQueries: []*any.Any{query}}
ctx := req.Request.Context()
cli := idm.NewWorkspaceServiceClient(common.ServiceGrpcNamespace_+common.ServiceWorkspace, defaults.NewClient())
if stream, e := cli.SearchWorkspace(ctx, &idm.SearchWorkspaceRequest{Query: serviceQuery}); e == nil {
defer stream.Close()
for {
resp, err := stream.Recv()
if err != nil {
break
}
if resp == nil {
continue
}
if !h.MatchPolicies(ctx, resp.Workspace.UUID, resp.Workspace.Policies, service.ResourcePolicyAction_WRITE) {
log.Auditer(ctx).Error(
fmt.Sprintf("Forbidden action could not delete workspace [%s]", slug),
log.GetAuditId(common.AuditWsDelete),
)
service2.RestError403(req, rsp, errors.Forbidden(common.ServiceWorkspace, "You are not allowed to edit this workspace!"))
return
}
}
}
n, e := cli.DeleteWorkspace(req.Request.Context(), &idm.DeleteWorkspaceRequest{Query: serviceQuery})
if e != nil {
service2.RestError500(req, rsp, e)
} else {
log.Auditer(ctx).Info(
fmt.Sprintf("Removed workspace [%s]", slug),
log.GetAuditId(common.AuditWsDelete),
)
rsp.WriteEntity(&rest.DeleteResponse{Success: true, NumRows: n.RowsDeleted})
}
}
func (h *WorkspaceHandler) SearchWorkspaces(req *restful.Request, rsp *restful.Response) {
ctx := req.Request.Context()
var restRequest rest.SearchWorkspaceRequest
err := req.ReadEntity(&restRequest)
if err != nil {
service2.RestError500(req, rsp, err)
return
}
// Transform to standard query
query := &service.Query{
Limit: restRequest.Limit,
Offset: restRequest.Offset,
GroupBy: restRequest.GroupBy,
Operation: restRequest.Operation,
}
for _, q := range restRequest.Queries {
anyfied, _ := ptypes.MarshalAny(q)
query.SubQueries = append(query.SubQueries, anyfied)
}
var er error
if query.ResourcePolicyQuery, er = h.RestToServiceResourcePolicy(ctx, restRequest.ResourcePolicyQuery); er != nil {
log.Logger(ctx).Error("403", zap.Error(er))
service2.RestError403(req, rsp, er)
return
}
cli := idm.NewWorkspaceServiceClient(common.ServiceGrpcNamespace_+common.ServiceWorkspace, defaults.NewClient())
streamer, err := cli.SearchWorkspace(ctx, &idm.SearchWorkspaceRequest{
Query: query,
})
if err != nil {
service2.RestError500(req, rsp, err)
return
}
defer streamer.Close()
collection := &rest.WorkspaceCollection{}
var uuids []string
wss := make(map[string]*idm.Workspace)
for {
resp, e := streamer.Recv()
if e != nil {
break
}
if resp == nil {
continue
}
resp.Workspace.PoliciesContextEditable = h.IsContextEditable(ctx, resp.Workspace.UUID, resp.Workspace.Policies)
uuids = append(uuids, resp.Workspace.UUID)
wss[resp.Workspace.UUID] = resp.Workspace
collection.Workspaces = append(collection.Workspaces, resp.Workspace)
collection.Total++
}
if len(collection.Workspaces) > 0 {
h.loadRootNodesForWorkspaces(ctx, uuids, wss)
h.bulkReadDefaultRights(ctx, uuids, wss)
}
rsp.WriteEntity(collection)
}
func (h *WorkspaceHandler) loadPoliciesForResource(ctx context.Context, resourceId string, resourceClient interface{}) (policies []*service.ResourcePolicy, e error) {
cli := (resourceClient).(idm.WorkspaceServiceClient)
ws, err := h.workspaceById(ctx, resourceId, cli)
if err != nil {
return nil, err
}
if ws == nil {
return
}
return ws.Policies, nil
}
func (h *WorkspaceHandler) workspaceById(ctx context.Context, wsId string, client idm.WorkspaceServiceClient) (*idm.Workspace, error) {
if wsId == "" {
return nil, nil
}
q, _ := ptypes.MarshalAny(&idm.WorkspaceSingleQuery{
Uuid: wsId,
})
if client, err := client.SearchWorkspace(ctx, &idm.SearchWorkspaceRequest{Query: &service.Query{SubQueries: []*any.Any{q}}}); err == nil {
defer client.Close()
for {
resp, e := client.Recv()
if e != nil {
break
}
if resp == nil {
continue
}
return resp.Workspace, nil
}
} else {
return nil, err
}
return nil, nil
}
func (h *WorkspaceHandler) deduplicateSlug(ctx context.Context, workspace *idm.Workspace, client idm.WorkspaceServiceClient) {
// Check that slug is not already in use
baseSlug := workspace.Slug
index := 0
for {
if existing, _ := h.workspaceBySlug(ctx, workspace.Slug, client); existing != nil {
index++
workspace.Slug = fmt.Sprintf("%s-%d", baseSlug, index)
} else {
break
}
}
}
func (h *WorkspaceHandler) workspaceBySlug(ctx context.Context, slug string, client idm.WorkspaceServiceClient) (*idm.Workspace, error) {
q, _ := ptypes.MarshalAny(&idm.WorkspaceSingleQuery{
Slug: slug,
})
if client, err := client.SearchWorkspace(ctx, &idm.SearchWorkspaceRequest{Query: &service.Query{SubQueries: []*any.Any{q}}}); err == nil {
defer client.Close()
for {
resp, e := client.Recv()
if e != nil {
break
}
if resp == nil {
continue
}
return resp.Workspace, nil
}
} else {
return nil, err
}
return nil, nil
}