-
Notifications
You must be signed in to change notification settings - Fork 19
/
client_request_permissions.go
259 lines (217 loc) · 8.59 KB
/
client_request_permissions.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
package api
import (
"context"
"errors"
"fmt"
"time"
"code.vegaprotocol.io/vega/libs/jsonrpc"
"code.vegaprotocol.io/vega/wallet/api/session"
"code.vegaprotocol.io/vega/wallet/wallet"
"github.com/mitchellh/mapstructure"
)
var ErrCannotUpdatePermissionsWhileUsingLingLivingToken = errors.New("cannot update the permissions of the wallet connected with a long-living token")
type ClientRequestPermissionsParams struct {
Token string `json:"token"`
RequestedPermissions wallet.PermissionsSummary `json:"requestedPermissions"`
}
type ClientRequestPermissionsResult struct {
Permissions wallet.PermissionsSummary `json:"permissions"`
}
type ClientRequestPermissions struct {
walletStore WalletStore
interactor Interactor
sessions *session.Sessions
}
// Handle allows a third-party application to request permissions to access
// certain capabilities of the wallet.
//
// To update the permissions, the third-party application has to specify all
// the permissions it required, even those that are already active. This way the
// client get a full understanding of all the requested access, and is much more
// capable to evaluate abusive requests and applications. Any permission that is
// omitted is considered to be revoked.
//
// The client will be asked to review the permissions the third-party application
// is requesting. It has the possibility to approve or reject the request.
//
// Everytime the permissions are updated, the connected wallet resources are
// updated.
//
// Using this handler does not require permissions.
func (h *ClientRequestPermissions) Handle(ctx context.Context, rawParams jsonrpc.Params, metadata jsonrpc.RequestMetadata) (jsonrpc.Result, *jsonrpc.ErrorDetails) {
params, err := validateRequestPermissionsParams(rawParams)
if err != nil {
return nil, invalidParams(err)
}
perms, err := parsePermissions(params.RequestedPermissions)
if err != nil {
return nil, invalidParams(err)
}
connectedWallet, err := h.sessions.GetConnectedWallet(params.Token, time.Now())
if err != nil {
return nil, invalidParams(err)
}
if !connectedWallet.RequireInteraction() {
return nil, applicationError(ErrorCodeRequestNotPermitted, ErrCannotUpdatePermissionsWhileUsingLingLivingToken)
}
if err := h.interactor.NotifyInteractionSessionBegan(ctx, metadata.TraceID); err != nil {
return nil, internalError(err)
}
defer h.interactor.NotifyInteractionSessionEnded(ctx, metadata.TraceID)
approved, err := h.interactor.RequestPermissionsReview(ctx, metadata.TraceID, connectedWallet.Hostname, connectedWallet.Wallet.Name(), perms.Summary())
if err != nil {
if errDetails := handleRequestFlowError(ctx, metadata.TraceID, h.interactor, err); errDetails != nil {
return nil, errDetails
}
h.interactor.NotifyError(ctx, metadata.TraceID, InternalError, fmt.Errorf("requesting the permissions review failed: %w", err))
return nil, internalError(ErrCouldNotRequestPermissions)
}
if !approved {
return nil, userRejectionError()
}
var passphrase string
var walletFromStore wallet.Wallet
for {
if ctx.Err() != nil {
return nil, requestInterruptedError(ErrRequestInterrupted)
}
enteredPassphrase, err := h.interactor.RequestPassphrase(ctx, metadata.TraceID, connectedWallet.Wallet.Name())
if err != nil {
if errDetails := handleRequestFlowError(ctx, metadata.TraceID, h.interactor, err); errDetails != nil {
return nil, errDetails
}
h.interactor.NotifyError(ctx, metadata.TraceID, InternalError, fmt.Errorf("requesting the passphrase failed: %w", err))
return nil, internalError(ErrCouldNotRequestPermissions)
}
w, err := h.walletStore.GetWallet(ctx, connectedWallet.Wallet.Name(), enteredPassphrase)
if err != nil {
if errors.Is(err, wallet.ErrWrongPassphrase) {
h.interactor.NotifyError(ctx, metadata.TraceID, UserError, wallet.ErrWrongPassphrase)
continue
}
h.interactor.NotifyError(ctx, metadata.TraceID, InternalError, fmt.Errorf("could not retrieve the wallet: %w", err))
return nil, internalError(ErrCouldNotRequestPermissions)
}
passphrase = enteredPassphrase
walletFromStore = w
break
}
// We keep a reference to the in-memory wallet, it case we need to roll back.
previousWallet := connectedWallet.Wallet
// We update the wallet we just loaded from the wallet store to ensure
// we don't overwrite changes that could have been done outside the API.
if err := walletFromStore.UpdatePermissions(connectedWallet.Hostname, perms); err != nil {
h.interactor.NotifyError(ctx, metadata.TraceID, InternalError, fmt.Errorf("could not update the permissions: %w", err))
return nil, internalError(ErrCouldNotRequestPermissions)
}
// Then, we update the in-memory wallet with the updated wallet, before
// saving it, to ensure there is no problem with the resources reloading.
if err := connectedWallet.ReloadWithWallet(walletFromStore); err != nil {
h.interactor.NotifyError(ctx, metadata.TraceID, InternalError, fmt.Errorf("could not reload wallet's resources: %w", err))
return nil, internalError(ErrCouldNotRequestPermissions)
}
// And, to finish, we save the wallet loaded from the wallet store.
if err := h.walletStore.SaveWallet(ctx, walletFromStore, passphrase); err != nil {
// We ignore the error as we know the previous state worked so far.
// There is no sane reason it fails out of the blue.
_ = connectedWallet.ReloadWithWallet(previousWallet)
h.interactor.NotifyError(ctx, metadata.TraceID, InternalError, fmt.Errorf("could not save the wallet: %w", err))
return nil, internalError(ErrCouldNotRequestPermissions)
}
h.interactor.NotifySuccessfulRequest(ctx, metadata.TraceID, PermissionsSuccessfullyUpdated)
return ClientRequestPermissionsResult{
Permissions: perms.Summary(),
}, nil
}
func validateRequestPermissionsParams(rawParams jsonrpc.Params) (ClientRequestPermissionsParams, error) {
if rawParams == nil {
return ClientRequestPermissionsParams{}, ErrParamsRequired
}
params := ClientRequestPermissionsParams{}
if err := mapstructure.Decode(rawParams, ¶ms); err != nil {
return ClientRequestPermissionsParams{}, ErrParamsDoNotMatch
}
if params.Token == "" {
return ClientRequestPermissionsParams{}, ErrConnectionTokenIsRequired
}
if len(params.RequestedPermissions) == 0 {
return ClientRequestPermissionsParams{}, ErrRequestedPermissionsAreRequired
}
return params, nil
}
func NewRequestPermissions(
walletStore WalletStore,
interactor Interactor,
sessions *session.Sessions,
) *ClientRequestPermissions {
return &ClientRequestPermissions{
walletStore: walletStore,
interactor: interactor,
sessions: sessions,
}
}
func parsePermissions(permsSummary wallet.PermissionsSummary) (wallet.Permissions, error) {
for permission, mode := range permsSummary {
if !isSupportedPermissions(permission) {
return wallet.Permissions{}, fmt.Errorf("permission %q is not supported", permission)
}
if !isSupportedAccessMode(mode) {
return wallet.Permissions{}, fmt.Errorf("access mode %q is not supported", mode)
}
}
perms := wallet.Permissions{}
if err := extractPublicKeysPermission(&perms, permsSummary); err != nil {
return wallet.Permissions{}, err
}
return perms, nil
}
func extractPublicKeysPermission(detailedPerms *wallet.Permissions, permsSummary wallet.PermissionsSummary) error {
access, ok := permsSummary[wallet.PublicKeysPermissionLabel]
if !ok {
// If the public keys permissions is omitted, we revoke it.
detailedPerms.PublicKeys = wallet.NoPublicKeysPermission()
return nil
}
// The correctness of the access mode should be valid at this point, but
// we never know.
mode, err := wallet.ToAccessMode(access)
if err != nil {
return err
}
// An access explicitly set to none is understood as a revocation.
if mode == wallet.NoAccess {
detailedPerms.PublicKeys = wallet.NoPublicKeysPermission()
return nil
}
// TODO(valentin) Add future restricted key selection here
detailedPerms.PublicKeys = wallet.PublicKeysPermission{
Access: mode,
// We don't yet support restricting the list of keys a third-party application
// will have access to. Nil means access to all keys.
RestrictedKeys: nil,
}
return nil
}
var supportedPermissions = []string{
wallet.PublicKeysPermissionLabel,
}
func isSupportedPermissions(perm string) bool {
for _, supportedPermissions := range supportedPermissions {
if perm == supportedPermissions {
return true
}
}
return false
}
var supportedAccessMode = []string{
wallet.AccessModeToString(wallet.NoAccess),
wallet.AccessModeToString(wallet.ReadAccess),
}
func isSupportedAccessMode(mode string) bool {
for _, supportedMode := range supportedAccessMode {
if mode == supportedMode {
return true
}
}
return false
}