-
Notifications
You must be signed in to change notification settings - Fork 0
/
access.go
576 lines (555 loc) · 12.1 KB
/
access.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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
package sqlite
import (
"context"
"database/sql"
"errors"
"fmt"
"path/filepath"
"strings"
"time"
"github.com/imagvfx/forge"
)
func createAccessListTable(tx *sql.Tx) error {
// TODO: add group_id once groups table is created
// TODO: rename the table to access_list
_, err := tx.Exec(`
CREATE TABLE IF NOT EXISTS access_controls (
id INTEGER PRIMARY KEY,
entry_id INTEGER NOT NULL,
accessor_id INTEGER,
mode INTEGER NOT NULL,
updated_at TIMESTAMP,
FOREIGN KEY (accessor_id) REFERENCES accessors (id),
UNIQUE (entry_id, accessor_id)
)
`)
if err != nil {
return err
}
_, err = tx.Exec(`CREATE INDEX IF NOT EXISTS index_access_controls_entry_id ON access_controls (entry_id)`)
return err
}
func EntryAccessList(db *sql.DB, ctx context.Context, path string) ([]*forge.Access, error) {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return nil, err
}
defer tx.Rollback()
accs, err := entryAccessList(tx, ctx, path)
if err != nil {
return nil, err
}
err = tx.Commit()
if err != nil {
return nil, err
}
return accs, nil
}
func entryAccessList(tx *sql.Tx, ctx context.Context, path string) ([]*forge.Access, error) {
acm := make(map[string]*forge.Access)
for {
ent, err := getEntry(tx, ctx, path)
if err != nil {
return nil, err
}
as, err := findAccessList(tx, ctx, forge.AccessFinder{EntryPath: &path})
if err != nil {
return nil, err
}
for _, a := range as {
if acm[a.Name] != nil {
// Already found the accessor permission on a child entry.
continue
}
a.EntryPath = ent.Path
acm[a.Name] = a
}
if path == "/" {
break
}
path = filepath.Dir(path)
}
acs := make([]*forge.Access, 0)
for _, a := range acm {
acs = append(acs, a)
}
return acs, nil
}
func GetAccessList(db *sql.DB, ctx context.Context, path string) ([]*forge.Access, error) {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return nil, err
}
defer tx.Rollback()
accs, err := findAccessList(tx, ctx, forge.AccessFinder{EntryPath: &path})
if err != nil {
return nil, err
}
err = tx.Commit()
if err != nil {
return nil, err
}
return accs, nil
}
// when id is empty, it will find access controls of root.
func findAccessList(tx *sql.Tx, ctx context.Context, find forge.AccessFinder) ([]*forge.Access, error) {
keys := make([]string, 0)
vals := make([]any, 0)
if find.EntryPath != nil {
keys = append(keys, "entries.path=?")
vals = append(vals, *find.EntryPath)
}
if find.Name != nil {
keys = append(keys, "accessors.name=?")
vals = append(vals, *find.Name)
}
where := ""
if len(keys) != 0 {
where = "WHERE " + strings.Join(keys, " AND ")
}
rows, err := tx.QueryContext(ctx, `
SELECT
access_controls.id,
entries.path,
accessors.name,
accessors.is_group,
access_controls.mode,
access_controls.updated_at
FROM access_controls
LEFT JOIN entries ON access_controls.entry_id = entries.id
LEFT JOIN accessors ON access_controls.accessor_id = accessors.id
`+where,
vals...,
)
if err != nil {
return nil, err
}
defer rows.Close()
acss := make([]*forge.Access, 0)
for rows.Next() {
var isGroup bool
a := &forge.Access{}
err := rows.Scan(
&a.ID,
&a.EntryPath,
&a.Name,
&isGroup,
&a.RawValue,
&a.UpdatedAt,
)
if err != nil {
return nil, err
}
a.Type = "user"
if isGroup {
a.Type = "group"
}
a.Value = "r"
if a.RawValue == 1 {
a.Value = "rw"
}
acss = append(acss, a)
}
return acss, nil
}
func userEnabled(tx *sql.Tx, ctx context.Context, user string) (bool, error) {
u, err := getAccessor(tx, ctx, user)
if err != nil {
return false, err
}
if u.IsGroup {
return false, fmt.Errorf("accessor is a group: %v", user)
}
enabled := !u.Disabled
return enabled, nil
}
// userRead returns an error if the user cannot read the entry.
// It returns forge.NotFound error when the context user doesn't have read permission.
func userRead(tx *sql.Tx, ctx context.Context, path string) error {
user := forge.UserNameFromContext(ctx)
enabled, err := userEnabled(tx, ctx, user)
if err != nil {
return err
}
if !enabled {
return fmt.Errorf("user disabled: %v", user)
}
if path == "/" {
// Everyone should be able to access root.
return nil
}
mode, err := userAccessMode(tx, ctx, path)
if err != nil {
return err
}
if mode == nil {
// The entry should invisible to the user.
return forge.NotFound("cannot access to entry: %s", path)
}
return nil
}
// userWrite returns an error if the user cannot write the entry.
// It returns forge.NotFound error when the context user doesn't have read permission or
// returns forge.Unauthorized error when the context user doesn't have write permission.
func userWrite(tx *sql.Tx, ctx context.Context, path string) error {
user := forge.UserNameFromContext(ctx)
enabled, err := userEnabled(tx, ctx, user)
if err != nil {
return err
}
if !enabled {
return fmt.Errorf("user disabled: %v", user)
}
mode, err := userAccessMode(tx, ctx, path)
if err != nil {
return err
}
if mode == nil {
// The entry should invisible to the user.
return forge.NotFound("cannot access to entry: %s", path)
}
if *mode == "r" {
return forge.Unauthorized("entry modification not allowed: %s", path)
}
return nil
}
// userAccessMode returns the user's access control for an entry.
// It checks the parents recursively as access control inherits.
// It returns (nil, nil) when there is no access_control exists for the user.
func userAccessMode(tx *sql.Tx, ctx context.Context, path string) (*string, error) {
if path == "" {
return nil, fmt.Errorf("path should be specified for access check")
}
user := forge.UserNameFromContext(ctx)
if user == "" {
return nil, forge.Unauthorized("context user unspecified")
}
yes, err := isAdmin(tx, ctx, user)
if err != nil {
return nil, err
}
if yes {
// admins can read any entry.
rwMode := "rw"
return &rwMode, nil
}
for {
as, err := findAccessList(tx, ctx, forge.AccessFinder{EntryPath: &path})
if err != nil {
return nil, err
}
// Lower entry has precedence to higher entry.
// In a same entry, user accessor has precedence to group accessor.
for _, a := range as {
if a.Type == "user" && a.Name == user {
return &a.Value, nil
}
}
// a user can be a member of multiple groups,
// let's find most permissive
value := ""
for _, a := range as {
if a.Type == "user" {
continue
}
// groups
yes, err := isGroupMember(tx, ctx, a.Name, user)
if err != nil {
return nil, err
}
if yes {
if a.Value == "r" {
value = a.Value
continue
}
return &a.Value, nil
}
}
if value == "r" {
return &value, nil
}
if path == "/" {
break
}
path = filepath.Dir(path)
}
return nil, nil
}
func IsAdmin(db *sql.DB, ctx context.Context, user string) (bool, error) {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return false, err
}
defer tx.Rollback()
admin, err := isAdmin(tx, ctx, user)
if err != nil {
return false, err
}
err = tx.Commit()
if err != nil {
return false, err
}
return admin, nil
}
func isAdmin(tx *sql.Tx, ctx context.Context, user string) (bool, error) {
if user == "system" {
// system will be implictly treated as admin.
return true, nil
}
return isGroupMember(tx, ctx, "admin", user)
}
func GetAccess(db *sql.DB, ctx context.Context, path, name string) (*forge.Access, error) {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return nil, err
}
defer tx.Rollback()
acl, err := getAccess(tx, ctx, path, name)
if err != nil {
return nil, err
}
err = tx.Commit()
if err != nil {
return nil, err
}
return acl, nil
}
func getAccess(tx *sql.Tx, ctx context.Context, path, name string) (*forge.Access, error) {
as, err := findAccessList(tx, ctx, forge.AccessFinder{
EntryPath: &path,
Name: &name,
})
if err != nil {
return nil, err
}
if len(as) == 0 {
return nil, forge.NotFound("access control not found")
}
a := as[0]
return a, nil
}
func AddAccess(db *sql.DB, ctx context.Context, a *forge.Access) error {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
err = addAccess(tx, ctx, a)
if err != nil {
return err
}
err = tx.Commit()
if err != nil {
return err
}
return nil
}
func addAccess(tx *sql.Tx, ctx context.Context, a *forge.Access) error {
err := userWrite(tx, ctx, a.EntryPath)
if err != nil {
return err
}
ac, err := getAccessor(tx, ctx, a.Name)
if err != nil {
return err
}
a.RawValue = 0
if a.Value == "rw" {
a.RawValue = 1
}
entryID, err := getEntryID(tx, ctx, a.EntryPath)
if err != nil {
return err
}
result, err := tx.ExecContext(ctx, `
INSERT INTO access_controls (
entry_id,
accessor_id,
mode,
updated_at
)
VALUES (?, ?, ?, ?)
`,
entryID,
ac.ID,
a.RawValue,
time.Now().UTC(),
)
if err != nil {
return err
}
id, err := result.LastInsertId()
if err != nil {
return err
}
a.ID = int(id)
user := forge.UserNameFromContext(ctx)
if user == "" {
return forge.Unauthorized("context user unspecified")
}
err = addLog(tx, ctx, &forge.Log{
EntryPath: a.EntryPath,
User: user,
Action: "create",
Category: "access",
Name: a.Name,
Type: a.Type,
Value: a.Value,
})
if err != nil {
return err
}
return nil
}
func UpdateAccess(db *sql.DB, ctx context.Context, upd forge.AccessUpdater) error {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
err = updateAccess(tx, ctx, upd)
if err != nil {
return err
}
err = tx.Commit()
if err != nil {
return err
}
return nil
}
func updateAccess(tx *sql.Tx, ctx context.Context, upd forge.AccessUpdater) error {
err := userWrite(tx, ctx, upd.EntryPath)
if err != nil {
return err
}
a, err := getAccess(tx, ctx, upd.EntryPath, upd.Name)
if err != nil {
return err
}
keys := make([]string, 0)
vals := make([]any, 0)
if upd.Value != nil {
rawMode := 0
if *upd.Value == "rw" {
rawMode = 1
}
if rawMode != a.RawValue {
keys = append(keys, "mode=?")
vals = append(vals, rawMode)
a.Value = *upd.Value
}
}
if len(keys) == 0 {
return nil
}
keys = append(keys, "updated_at=?")
vals = append(vals, time.Now().UTC())
vals = append(vals, a.ID) // for where clause
result, err := tx.ExecContext(ctx, `
UPDATE access_controls
SET `+strings.Join(keys, ", ")+`
WHERE id=?
`,
vals...,
)
if err != nil {
return err
}
n, err := result.RowsAffected()
if err != nil {
return err
}
if n != 1 {
return fmt.Errorf("want 1 property affected, got %v", n)
}
user := forge.UserNameFromContext(ctx)
if user == "" {
return forge.Unauthorized("context user unspecified")
}
err = addLog(tx, ctx, &forge.Log{
EntryPath: a.EntryPath,
User: user,
Action: "update",
Category: "access",
Name: a.Name,
Type: a.Type,
Value: a.Value,
})
if err != nil {
return err
}
return nil
}
func DeleteAccess(db *sql.DB, ctx context.Context, path, name string) error {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
err = deleteAccess(tx, ctx, path, name)
if err != nil {
return err
}
err = tx.Commit()
if err != nil {
return err
}
return nil
}
func deleteAccess(tx *sql.Tx, ctx context.Context, path, name string) error {
err := userWrite(tx, ctx, path)
if err != nil {
return err
}
ent, err := getEntry(tx, ctx, path)
if err != nil {
return err
}
_, err = getDefaultAccess(tx, ctx, ent.Type, name)
if err == nil {
return fmt.Errorf("cannot delete default access of %q: %v", ent.Type, name)
}
if err != nil {
var e *forge.NotFoundError
if !errors.As(err, &e) {
return err
}
}
a, err := getAccess(tx, ctx, path, name)
if err != nil {
return err
}
result, err := tx.Exec(`
DELETE FROM access_controls
WHERE id=?
`,
a.ID,
)
if err != nil {
return err
}
n, err := result.RowsAffected()
if err != nil {
return err
}
if n != 1 {
return fmt.Errorf("want 1 access_control affected, got %v", n)
}
user := forge.UserNameFromContext(ctx)
if user == "" {
return forge.Unauthorized("context user unspecified")
}
err = addLog(tx, ctx, &forge.Log{
EntryPath: path,
User: user,
Action: "delete",
Category: "access",
Name: a.Name,
Type: a.Type,
Value: "",
})
if err != nil {
return nil
}
return nil
}