summaryrefslogtreecommitdiff
path: root/vendor/github.com/authzed/zed/pkg/backupformat/redaction.go
blob: c89c03fb55d3a6b984583b0cd1017a207f92460d (plain)
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
package backupformat

import (
	"fmt"
	"io"
	"strconv"

	v1 "github.com/authzed/authzed-go/proto/authzed/api/v1"
	"github.com/authzed/spicedb/pkg/namespace"
	core "github.com/authzed/spicedb/pkg/proto/core/v1"
	"github.com/authzed/spicedb/pkg/schemadsl/compiler"
	"github.com/authzed/spicedb/pkg/schemadsl/generator"
	"github.com/authzed/spicedb/pkg/schemadsl/input"
	"github.com/authzed/spicedb/pkg/spiceerrors"
	"github.com/authzed/spicedb/pkg/tuple"
)

// RedactionOptions are the options to use when redacting data.
type RedactionOptions struct {
	// RedactDefinitions will redact the definition names.
	RedactDefinitions bool

	// RedactRelations will redact the relation names.
	RedactRelations bool

	// RedactObjectIDs will redact the object IDs.
	RedactObjectIDs bool
}

// RedactionMap is the map of original names to their redacted names.
type RedactionMap struct {
	// Definitions is the map of original definition names to their redacted names.
	Definitions map[string]string

	// Caveats is the map of original caveat names to their redacted names.
	Caveats map[string]string

	// Relations is the map of original relation names to their redacted names.
	Relations map[string]string

	// ObjectIDs is the map of original object IDs to their redacted names.
	ObjectIDs map[string]string
}

// Invert returns the inverted redaction map, with the redacted names as the keys.
func (rm RedactionMap) Invert() RedactionMap {
	inverted := RedactionMap{
		Definitions: make(map[string]string),
		Caveats:     make(map[string]string),
		Relations:   make(map[string]string),
		ObjectIDs:   make(map[string]string),
	}

	for k, v := range rm.Definitions {
		inverted.Definitions[v] = k
	}

	for k, v := range rm.Caveats {
		inverted.Caveats[v] = k
	}

	for k, v := range rm.Relations {
		inverted.Relations[v] = k
	}

	for k, v := range rm.ObjectIDs {
		inverted.ObjectIDs[v] = k
	}

	return inverted
}

// NewRedactor creates a new redactor that will redact the data as it is written.
func NewRedactor(dec *Decoder, w io.Writer, opts RedactionOptions) (*Redactor, error) {
	// Rewrite the schema to redact as requested.
	redactedSchema, redactionMap, err := redactSchema(dec.Schema(), opts)
	if err != nil {
		return nil, err
	}

	// Create a new encoder with the redacted schema.
	token := dec.ZedToken()
	encoder, err := NewEncoder(w, redactedSchema, token)
	if err != nil {
		return nil, err
	}

	return &Redactor{dec, opts, encoder, redactionMap}, nil
}

type Redactor struct {
	dec          *Decoder
	opts         RedactionOptions
	enc          *Encoder
	redactionMap RedactionMap
}

// Next redacts the next record and writes it to the writer.
func (r *Redactor) Next() error {
	// Read the next record.
	rel, err := r.dec.Next()
	if err != nil {
		return err
	}

	if rel == nil {
		return io.EOF
	}

	// Redact the record.
	redactedRel, err := redactRelationship(rel, &r.redactionMap, r.opts)
	if err != nil {
		return err
	}

	// Write the redacted record.
	return r.enc.Append(redactedRel)
}

// RedactionMap returns the redaction map containing the original names and their redacted names.
func (r *Redactor) RedactionMap() RedactionMap {
	return r.redactionMap
}

func (r *Redactor) Close() error {
	if err := r.enc.Close(); err != nil {
		return err
	}

	return r.dec.Close()
}

func redactSchema(schema string, opts RedactionOptions) (string, RedactionMap, error) {
	// Parse the schema.
	compiled, err := compiler.Compile(compiler.InputSchema{
		Source:       input.Source("schema"),
		SchemaString: schema,
	}, compiler.AllowUnprefixedObjectType())
	if err != nil {
		return "", RedactionMap{}, err
	}

	// Create a new schema with the redacted fields.
	redactionMap := RedactionMap{
		Definitions: make(map[string]string),
		Caveats:     make(map[string]string),
		Relations:   make(map[string]string),
		ObjectIDs:   make(map[string]string),
	}

	redactionCount := 0

	// Redact namespace and caveat names.
	if opts.RedactDefinitions {
		for _, nsDef := range compiled.ObjectDefinitions {
			if opts.RedactDefinitions {
				redactionMap.Definitions[nsDef.Name] = "def" + strconv.Itoa(redactionCount)
				redactionCount++
				nsDef.Name = redactionMap.Definitions[nsDef.Name]
			}

			namespace.FilterUserDefinedMetadataInPlace(nsDef)
		}

		if len(compiled.CaveatDefinitions) > 0 {
			fmt.Println("WARNING: Caveat parameters and comments are not currently redacted.")
		}

		for _, caveatDef := range compiled.CaveatDefinitions {
			if opts.RedactDefinitions {
				redactionMap.Caveats[caveatDef.Name] = "cav" + strconv.Itoa(redactionCount)
				redactionCount++
				caveatDef.Name = redactionMap.Caveats[caveatDef.Name]
			}

			// TODO: Redact caveat parameters.
			// TODO: filter caveat metadata.
		}
	}

	// Redact relation names.
	if opts.RedactRelations {
		for _, nsDef := range compiled.ObjectDefinitions {
			for _, relDef := range nsDef.Relation {
				if existing, ok := redactionMap.Relations[relDef.Name]; ok {
					relDef.Name = existing
					continue
				}

				redactionMap.Relations[relDef.Name] = "rel" + strconv.Itoa(redactionCount)
				redactionCount++
				relDef.Name = redactionMap.Relations[relDef.Name]
			}
		}
	}

	// Redact type information.
	if opts.RedactDefinitions || opts.RedactRelations {
		for _, nsDef := range compiled.ObjectDefinitions {
			for _, relDef := range nsDef.Relation {
				if relDef.TypeInformation != nil {
					for _, allowedDirect := range relDef.TypeInformation.AllowedDirectRelations {
						if opts.RedactDefinitions {
							allowedDirect.Namespace = redactionMap.Definitions[allowedDirect.Namespace]

							if allowedDirect.RequiredCaveat != nil {
								allowedDirect.RequiredCaveat.CaveatName = redactionMap.Caveats[allowedDirect.RequiredCaveat.CaveatName]
							}
						}

						if opts.RedactRelations {
							switch t := allowedDirect.RelationOrWildcard.(type) {
							case *core.AllowedRelation_Relation:
								t.Relation = redactionMap.Relations[t.Relation]
							}
						}
					}
				}
			}
		}
	}

	// Redact within userset rewrites.
	if opts.RedactRelations {
		for _, nsDef := range compiled.ObjectDefinitions {
			for _, relDef := range nsDef.Relation {
				if relDef.UsersetRewrite != nil {
					err := redactUsersetRewrite(relDef.UsersetRewrite, &redactionMap)
					if err != nil {
						return "", RedactionMap{}, err
					}
				}
			}
		}
	}

	// Generate the schema string.
	generated, _, err := generator.GenerateSchema(compiled.OrderedDefinitions)
	return generated, redactionMap, err
}

func redactUsersetRewrite(usersetRewrite *core.UsersetRewrite, redactionMap *RedactionMap) error {
	switch t := usersetRewrite.RewriteOperation.(type) {
	case *core.UsersetRewrite_Union:
		return redactRewriteChildren(t.Union.Child, redactionMap)

	case *core.UsersetRewrite_Intersection:
		return redactRewriteChildren(t.Intersection.Child, redactionMap)

	case *core.UsersetRewrite_Exclusion:
		return redactRewriteChildren(t.Exclusion.Child, redactionMap)

	default:
		return spiceerrors.MustBugf("unknown userset rewrite type: %T", t)
	}
}

func redactRewriteChildren(children []*core.SetOperation_Child, redactionMap *RedactionMap) error {
	for _, child := range children {
		switch t := child.ChildType.(type) {
		case *core.SetOperation_Child_ComputedUserset:
			t.ComputedUserset.Relation = redactionMap.Relations[t.ComputedUserset.Relation]

		case *core.SetOperation_Child_UsersetRewrite:
			err := redactUsersetRewrite(t.UsersetRewrite, redactionMap)
			if err != nil {
				return err
			}

		case *core.SetOperation_Child_TupleToUserset:
			t.TupleToUserset.Tupleset.Relation = redactionMap.Relations[t.TupleToUserset.Tupleset.Relation]
			t.TupleToUserset.ComputedUserset.Relation = redactionMap.Relations[t.TupleToUserset.ComputedUserset.Relation]

		case *core.SetOperation_Child_XNil:
			// nothing to do

		case *core.SetOperation_Child_XThis:
			// nothing to do

		default:
			return spiceerrors.MustBugf("unknown child type: %T", t)
		}
	}

	return nil
}

func redactRelationship(rel *v1.Relationship, redactionMap *RedactionMap, opts RedactionOptions) (*v1.Relationship, error) {
	redactedRel := rel.CloneVT()

	// Redact the resource.
	if opts.RedactDefinitions {
		redactedRel.Resource.ObjectType = redactionMap.Definitions[redactedRel.Resource.ObjectType]
		redactedRel.Subject.Object.ObjectType = redactionMap.Definitions[redactedRel.Subject.Object.ObjectType]

		if rel.OptionalCaveat != nil {
			redactedRel.OptionalCaveat.CaveatName = redactionMap.Caveats[redactedRel.OptionalCaveat.CaveatName]
		}
	}

	// Redact the relation.
	if opts.RedactRelations {
		redactedRel.Relation = redactionMap.Relations[redactedRel.Relation]

		if rel.Subject.OptionalRelation != "" {
			redactedRel.Subject.OptionalRelation = redactionMap.Relations[redactedRel.Subject.OptionalRelation]
		}
	}

	// Redact the object IDs.
	if opts.RedactObjectIDs {
		redactionMap.ObjectIDs[tuple.PublicWildcard] = tuple.PublicWildcard // wilcards are not redacted
		if _, ok := redactionMap.ObjectIDs[redactedRel.Resource.ObjectId]; !ok {
			if redactedRel.Resource.ObjectId != tuple.PublicWildcard {
				redactionMap.ObjectIDs[redactedRel.Resource.ObjectId] = "obj" + strconv.Itoa(len(redactionMap.ObjectIDs))
			}
		}

		redactedRel.Resource.ObjectId = redactionMap.ObjectIDs[redactedRel.Resource.ObjectId]

		if _, ok := redactionMap.ObjectIDs[redactedRel.Subject.Object.ObjectId]; !ok {
			redactionMap.ObjectIDs[redactedRel.Subject.Object.ObjectId] = "obj" + strconv.Itoa(len(redactionMap.ObjectIDs))
		}

		redactedRel.Subject.Object.ObjectId = redactionMap.ObjectIDs[redactedRel.Subject.Object.ObjectId]
	}

	return redactedRel, nil
}