-
Notifications
You must be signed in to change notification settings - Fork 56
/
accesscontroller_orbitdb.go
286 lines (227 loc) · 7.44 KB
/
accesscontroller_orbitdb.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
package orbitdb
import (
"context"
"encoding/json"
"sync"
logac "berty.tech/go-ipfs-log/accesscontroller"
"berty.tech/go-ipfs-log/identityprovider"
"berty.tech/go-orbit-db/accesscontroller"
"berty.tech/go-orbit-db/accesscontroller/utils"
"berty.tech/go-orbit-db/address"
"berty.tech/go-orbit-db/events"
"berty.tech/go-orbit-db/iface"
"berty.tech/go-orbit-db/stores"
cid "github.com/ipfs/go-cid"
"github.com/pkg/errors"
"go.uber.org/zap"
)
// CreateDBOptions An alias for iface.CreateDBOptions
type CreateDBOptions = iface.CreateDBOptions
// EventUpdated An event sent when the access controller has been updated
type EventUpdated struct{}
type orbitDBAccessController struct {
events.EventEmitter
orbitdb iface.OrbitDB
kvStore iface.KeyValueStore
options accesscontroller.ManifestParams
lock sync.RWMutex
logger *zap.Logger
}
func (o *orbitDBAccessController) SetLogger(logger *zap.Logger) {
o.lock.Lock()
defer o.lock.Unlock()
o.logger = logger
}
func (o *orbitDBAccessController) Logger() *zap.Logger {
o.lock.RLock()
defer o.lock.RUnlock()
return o.logger
}
func (o *orbitDBAccessController) Type() string {
return "orbitdb"
}
func (o *orbitDBAccessController) Address() address.Address {
return o.kvStore.Address()
}
func (o *orbitDBAccessController) GetAuthorizedByRole(role string) ([]string, error) {
authorizations, err := o.getAuthorizations()
if err != nil {
return nil, errors.Wrap(err, "unable to get authorizations")
}
return authorizations[role], nil
}
func (o *orbitDBAccessController) getAuthorizations() (map[string][]string, error) {
authorizations := map[string]map[string]struct{}{}
if o.kvStore == nil {
return map[string][]string{}, nil
}
for role, keyBytes := range o.kvStore.All() {
var authorizedKeys []string
authorizations[role] = map[string]struct{}{}
if err := json.Unmarshal(keyBytes, &authorizedKeys); err != nil {
return nil, errors.Wrap(err, "unable to unmarshal json")
}
for _, key := range authorizedKeys {
authorizations[role][key] = struct{}{}
}
}
if _, ok := authorizations["write"]; ok {
if _, ok := authorizations["admin"]; !ok {
authorizations["admin"] = map[string]struct{}{}
}
for authorized := range authorizations["write"] {
authorizations["admin"][authorized] = struct{}{}
}
}
authorizationsLists := map[string][]string{}
for permissionName, authorizationMap := range authorizations {
authorizationsLists[permissionName] = []string{}
for authorized := range authorizationMap {
authorizationsLists[permissionName] = append(authorizationsLists[permissionName], authorized)
}
}
return authorizationsLists, nil
}
func (o *orbitDBAccessController) CanAppend(entry logac.LogEntry, p identityprovider.Interface, additionalContext accesscontroller.CanAppendAdditionalContext) error {
writeAccess, err := o.GetAuthorizedByRole("write")
if err != nil {
return errors.Wrap(err, "unable to get keys with write access")
}
adminAccess, err := o.GetAuthorizedByRole("admin")
if err != nil {
return errors.Wrap(err, "unable to get keys with admin access")
}
access := append(writeAccess, adminAccess...)
for _, k := range access {
if k == entry.GetIdentity().ID || k == "*" {
return p.VerifyIdentity(entry.GetIdentity())
}
}
return errors.New("unauthorized")
}
func (o *orbitDBAccessController) Grant(ctx context.Context, capability string, keyID string) error {
capabilities, err := o.GetAuthorizedByRole(capability)
if err != nil {
return errors.Wrap(err, "unable to fetch capabilities")
}
capabilities = append(capabilities, keyID)
capabilitiesJSON, err := json.Marshal(capabilities)
if err != nil {
return errors.Wrap(err, "unable to marshal capabilities")
}
_, err = o.kvStore.Put(ctx, capability, capabilitiesJSON)
if err != nil {
return errors.Wrap(err, "unable to put data in store")
}
return nil
}
func (o *orbitDBAccessController) Revoke(ctx context.Context, capability string, keyID string) error {
capabilities, err := o.GetAuthorizedByRole(capability)
if err != nil {
return errors.Wrap(err, "unable to get capability")
}
for idx, existingKeyID := range capabilities {
if existingKeyID == keyID {
capabilities = append(capabilities[:idx], capabilities[idx+1:]...)
break
}
}
if len(capabilities) > 0 {
capabilitiesJSON, err := json.Marshal(capabilities)
if err != nil {
return errors.Wrap(err, "unable to marshal capabilities")
}
_, err = o.kvStore.Put(ctx, capability, capabilitiesJSON)
if err != nil {
return errors.Wrap(err, "unable to persist capabilities")
}
} else {
_, err := o.kvStore.Delete(ctx, capability)
if err != nil {
return errors.Wrap(err, "unable to remove capabilities")
}
}
return nil
}
func (o *orbitDBAccessController) Load(ctx context.Context, address string) error {
if o.kvStore != nil {
err := o.kvStore.Close()
if err != nil {
return errors.Wrap(err, "unable to close opened store")
}
}
// Force '<address>/_access' naming for the database
writeAccess := o.options.GetAccess("admin")
if len(writeAccess) == 0 {
writeAccess = []string{o.orbitdb.Identity().ID}
}
ipfsAccessController := accesscontroller.NewManifestParams(cid.Cid{}, true, "ipfs")
ipfsAccessController.SetAccess("write", writeAccess)
store, err := o.orbitdb.KeyValue(ctx, utils.EnsureAddress(address), &CreateDBOptions{
AccessController: ipfsAccessController,
})
if err != nil {
return errors.Wrap(err, "unable to open key value store for access controller")
}
o.kvStore = store
sub := o.kvStore.Subscribe(ctx)
go func() {
for e := range sub {
switch e.(type) {
case stores.EventReady, stores.EventWrite, stores.EventReplicated:
o.onUpdate(ctx)
}
}
}()
err = o.kvStore.Load(ctx, -1)
if err != nil {
return errors.Wrap(err, "unable to fetch store data")
}
return nil
}
func (o *orbitDBAccessController) Save(ctx context.Context) (accesscontroller.ManifestParams, error) {
return accesscontroller.NewManifestParams(o.kvStore.Address().GetRoot(), false, "orbitdb"), nil
}
func (o *orbitDBAccessController) Close() error {
if err := o.kvStore.Close(); err != nil {
return errors.Wrap(err, "error while closing store")
}
return nil
}
func (o *orbitDBAccessController) onUpdate(ctx context.Context) {
o.Emit(ctx, &EventUpdated{})
}
// NewIPFSAccessController Returns a default access controller for OrbitDB database
func NewOrbitDBAccessController(ctx context.Context, db iface.BaseOrbitDB, params accesscontroller.ManifestParams, options ...accesscontroller.Option) (accesscontroller.Interface, error) {
if db == nil {
return &orbitDBAccessController{}, errors.New("an OrbitDB instance is required")
}
kvDB, ok := db.(iface.OrbitDBKVStoreProvider)
if !ok {
return &orbitDBAccessController{}, errors.New("the OrbitDB instance must provide a key value store")
}
addr := "default-access-controller"
if params.GetAddress().Defined() {
addr = params.GetAddress().String()
} else if params.GetName() != "" {
addr = params.GetName()
}
kvStore, err := kvDB.KeyValue(ctx, addr, nil)
if err != nil {
return nil, errors.Wrap(err, "unable to init key value store")
}
controller := &orbitDBAccessController{
kvStore: kvStore,
options: params,
}
for _, o := range options {
o(controller)
}
for _, writeAccess := range params.GetAccess("write") {
if err := controller.Grant(ctx, "write", writeAccess); err != nil {
return nil, errors.Wrap(err, "unable to grant write access")
}
}
return controller, nil
}
var _ accesscontroller.Interface = &orbitDBAccessController{}