-
Notifications
You must be signed in to change notification settings - Fork 173
/
write.go
175 lines (146 loc) · 4.83 KB
/
write.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
package commands
import (
"context"
"errors"
"fmt"
openfgav1 "github.com/openfga/api/proto/openfga/v1"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
"github.com/openfga/openfga/internal/server/config"
"github.com/openfga/openfga/internal/validation"
"github.com/openfga/openfga/pkg/logger"
serverErrors "github.com/openfga/openfga/pkg/server/errors"
"github.com/openfga/openfga/pkg/storage"
tupleUtils "github.com/openfga/openfga/pkg/tuple"
"github.com/openfga/openfga/pkg/typesystem"
)
// WriteCommand is used to Write and Delete tuples. Instances may be safely shared by multiple goroutines.
type WriteCommand struct {
logger logger.Logger
datastore storage.OpenFGADatastore
conditionContextByteLimit int
}
type WriteCommandOption func(*WriteCommand)
func WithWriteCmdLogger(l logger.Logger) WriteCommandOption {
return func(wc *WriteCommand) {
wc.logger = l
}
}
func WithConditionContextByteLimit(limit int) WriteCommandOption {
return func(wc *WriteCommand) {
wc.conditionContextByteLimit = limit
}
}
// NewWriteCommand creates a WriteCommand with specified storage.OpenFGADatastore to use for storage.
func NewWriteCommand(datastore storage.OpenFGADatastore, opts ...WriteCommandOption) *WriteCommand {
cmd := &WriteCommand{
datastore: datastore,
logger: logger.NewNoopLogger(),
conditionContextByteLimit: config.DefaultWriteContextByteLimit,
}
for _, opt := range opts {
opt(cmd)
}
return cmd
}
// Execute deletes and writes the specified tuples. Deletes are applied first, then writes.
func (c *WriteCommand) Execute(ctx context.Context, req *openfgav1.WriteRequest) (*openfgav1.WriteResponse, error) {
if err := c.validateWriteRequest(ctx, req); err != nil {
return nil, err
}
err := c.datastore.Write(
ctx,
req.GetStoreId(),
req.GetDeletes().GetTupleKeys(),
req.GetWrites().GetTupleKeys(),
)
if err != nil {
return nil, handleError(err)
}
return &openfgav1.WriteResponse{}, nil
}
func (c *WriteCommand) validateWriteRequest(ctx context.Context, req *openfgav1.WriteRequest) error {
ctx, span := tracer.Start(ctx, "validateWriteRequest")
defer span.End()
store := req.GetStoreId()
modelID := req.GetAuthorizationModelId()
deletes := req.GetDeletes().GetTupleKeys()
writes := req.GetWrites().GetTupleKeys()
if len(deletes) == 0 && len(writes) == 0 {
return serverErrors.InvalidWriteInput
}
if len(writes) > 0 {
authModel, err := c.datastore.ReadAuthorizationModel(ctx, store, modelID)
if err != nil {
if errors.Is(err, storage.ErrNotFound) {
return serverErrors.AuthorizationModelNotFound(modelID)
}
return err
}
if !typesystem.IsSchemaVersionSupported(authModel.GetSchemaVersion()) {
return serverErrors.ValidationError(typesystem.ErrInvalidSchemaVersion)
}
typesys := typesystem.New(authModel)
for _, tk := range writes {
err := validation.ValidateTuple(typesys, tk)
if err != nil {
return serverErrors.ValidationError(err)
}
contextSize := proto.Size(tk.GetCondition().GetContext())
if contextSize > c.conditionContextByteLimit {
return serverErrors.ValidationError(&tupleUtils.InvalidTupleError{
Cause: fmt.Errorf("condition context size limit exceeded: %d bytes exceeds %d bytes", contextSize, c.conditionContextByteLimit),
TupleKey: tk,
})
}
}
}
for _, tk := range deletes {
if ok := tupleUtils.IsValidUser(tk.GetUser()); !ok {
return serverErrors.ValidationError(
&tupleUtils.InvalidTupleError{
Cause: fmt.Errorf("the 'user' field is malformed"),
TupleKey: tk,
},
)
}
}
if err := c.validateNoDuplicatesAndCorrectSize(deletes, writes); err != nil {
return err
}
return nil
}
// validateNoDuplicatesAndCorrectSize ensures the deletes and writes contain no duplicates and length fits.
func (c *WriteCommand) validateNoDuplicatesAndCorrectSize(
deletes []*openfgav1.TupleKeyWithoutCondition,
writes []*openfgav1.TupleKey,
) error {
tuples := map[string]struct{}{}
for _, tk := range deletes {
key := tupleUtils.TupleKeyToString(tk)
if _, ok := tuples[key]; ok {
return serverErrors.DuplicateTupleInWrite(tk)
}
tuples[key] = struct{}{}
}
for _, tk := range writes {
key := tupleUtils.TupleKeyToString(tk)
if _, ok := tuples[key]; ok {
return serverErrors.DuplicateTupleInWrite(tk)
}
tuples[key] = struct{}{}
}
if len(tuples) > c.datastore.MaxTuplesPerWrite() {
return serverErrors.ExceededEntityLimit("write operations", c.datastore.MaxTuplesPerWrite())
}
return nil
}
func handleError(err error) error {
if errors.Is(err, storage.ErrTransactionalWriteFailed) {
return status.Error(codes.Aborted, err.Error())
} else if errors.Is(err, storage.ErrInvalidWriteInput) {
return serverErrors.WriteFailedDueToInvalidInput(err)
}
return serverErrors.HandleError("", err)
}