/
client.go
349 lines (290 loc) · 8.04 KB
/
client.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
package entity
import (
"crypto/tls"
"fmt"
"net"
"reflect"
"strings"
"time"
"connectrpc.com/connect"
"github.com/common-fate/sdk/config"
"github.com/common-fate/sdk/eid"
entityv1alpha1 "github.com/common-fate/sdk/gen/commonfate/entity/v1alpha1"
"github.com/common-fate/sdk/gen/commonfate/entity/v1alpha1/entityv1alpha1connect"
"github.com/fatih/structtag"
"github.com/patrickmn/go-cache"
"github.com/pkg/errors"
"go.opentelemetry.io/otel"
"golang.org/x/net/http2"
"golang.org/x/oauth2"
)
type Client struct {
// Raw returns the underlying GRPC client.
// It can be used to call methods that we don't have wrappers for yet.
raw entityv1alpha1connect.EntityServiceClient
// A cache of recently seen entities. Used for retrieving long-lived
// attributes such as entity names.
cache *cache.Cache
}
type Opts struct {
HTTPClient connect.HTTPClient
BaseURL string
ClientOptions []connect.ClientOption
// AttrCacheExpiration defaults to 24h if not provided
AttrCacheExpiration time.Duration
// AttrCleanupInterval defaults to 48h if not provided
AttrCleanupInterval time.Duration
}
var insecureTransport = &http2.Transport{
AllowHTTP: true,
DialTLS: func(network, addr string, _ *tls.Config) (net.Conn, error) {
return net.Dial(network, addr)
},
}
var (
tracer = otel.Tracer("sdk_service_entity")
)
func NewClient(opts Opts) Client {
// client uses GRPC by default as the authz service does not support Buf Connect.
connectOpts := []connect.ClientOption{connect.WithGRPC()}
connectOpts = append(connectOpts, opts.ClientOptions...)
if opts.AttrCleanupInterval == 0 {
opts.AttrCleanupInterval = 48 * time.Hour
}
if opts.AttrCacheExpiration == 0 {
opts.AttrCacheExpiration = 24 * time.Hour
}
c := cache.New(opts.AttrCacheExpiration, opts.AttrCleanupInterval)
rawClient := entityv1alpha1connect.NewEntityServiceClient(opts.HTTPClient, opts.BaseURL, connectOpts...)
return Client{raw: rawClient, cache: c}
}
func NewFromConfig(cfg *config.Context) Client {
url := cfg.AuthzURL
if url == "" {
url = cfg.APIURL
}
connectOpts := []connect.ClientOption{connect.WithGRPC()}
// dereference the client to avoid mutating it for all services
// that share the config (this can cause HTTP2 issues in local dev)
httpclient := *cfg.HTTPClient
if strings.HasPrefix(url, "http://") {
httpclient.Transport = &oauth2.Transport{
Source: cfg.TokenSource,
Base: insecureTransport,
}
}
rawClient := entityv1alpha1connect.NewEntityServiceClient(&httpclient, url, connectOpts...)
c := cache.New(24*time.Hour, 48*time.Hour)
return Client{raw: rawClient, cache: c}
}
// Entities are objects that can be stored in the authz database.
type Entity interface {
EID() eid.EID
}
// Implementing the parent interface allows an entity to provide parents based on its attributes.
type Parenter interface {
Parents() []eid.EID
}
func Marshal(e Entity) (*entityv1alpha1.Entity, []*entityv1alpha1.ChildRelation, error) {
v := reflect.ValueOf(e)
if v.Kind() == reflect.Pointer {
v = reflect.Indirect(v)
}
if v.Kind() != reflect.Struct {
return nil, nil, fmt.Errorf("%s is not a struct", v.Type())
}
entity := entityv1alpha1.Entity{
Eid: e.EID().ToAPI(),
Attributes: []*entityv1alpha1.Attribute{},
}
var children []*entityv1alpha1.ChildRelation
p, ok := e.(Parenter)
if ok {
for _, parent := range p.Parents() {
err := parent.Valid()
if err != nil {
return nil, nil, errors.Wrapf(err, "parsing parents for entity %s", e.EID())
}
children = append(children, &entityv1alpha1.ChildRelation{
Parent: parent.ToAPI(),
Child: entity.Eid,
})
}
}
for i := 0; i < v.NumField(); i++ {
f := v.Type().Field(i)
key := parseTag(string(f.Tag))
if key == "" {
// can't parse the tag so continue on
continue
}
if key == "id" {
// don't put the ID in the attributes
continue
}
// try and parse as an attribute
attr, err := extractAttr(v.Field(i))
if err != nil {
return nil, nil, errors.Wrapf(err, "extracting attributes for entity %s: field %s", e.EID(), key)
}
entity.Attributes = append(entity.Attributes, &entityv1alpha1.Attribute{
Key: key,
Value: attr,
})
}
return &entity, children, nil
}
func extractAttr(val reflect.Value) (*entityv1alpha1.Value, error) {
switch val.Kind() {
case reflect.Struct:
// try and parse as an entity reference
eid, ok := val.Interface().(eid.EID)
if ok {
err := eid.Valid()
if err != nil {
return nil, err
}
return &entityv1alpha1.Value{
Value: &entityv1alpha1.Value_Entity{
Entity: eid.ToAPI(),
},
}, nil
}
// check if it's a timestamp
if val.Type() == reflect.TypeOf(time.Time{}) {
timeVal, ok := val.Interface().(time.Time)
if ok {
return &entityv1alpha1.Value{
Value: &entityv1alpha1.Value_Long{
Long: timeVal.UnixNano() / int64(time.Millisecond),
},
}, nil
}
}
// Handle the Record case
record := &entityv1alpha1.Record{
Attributes: []*entityv1alpha1.Attribute{},
}
for i := 0; i < val.NumField(); i++ {
field := val.Type().Field(i)
key := parseTag(string(field.Tag))
if key == "" {
continue
}
attr, err := extractAttr(val.Field(i))
if err != nil {
return nil, err
}
record.Attributes = append(record.Attributes, &entityv1alpha1.Attribute{
Key: key,
Value: attr,
})
}
return &entityv1alpha1.Value{
Value: &entityv1alpha1.Value_Record{
Record: record,
},
}, nil
case reflect.String:
return &entityv1alpha1.Value{
Value: &entityv1alpha1.Value_Str{
Str: val.String(),
},
}, nil
case reflect.Bool:
return &entityv1alpha1.Value{
Value: &entityv1alpha1.Value_Bool{
Bool: val.Bool(),
},
}, nil
case reflect.Int, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int8:
// check if it's a duration
if val.Type() == reflect.TypeOf(time.Duration(0)) {
durationVal, ok := val.Interface().(time.Duration)
if ok {
return &entityv1alpha1.Value{
Value: &entityv1alpha1.Value_Long{
Long: durationVal.Milliseconds(),
},
}, nil
}
}
return &entityv1alpha1.Value{
Value: &entityv1alpha1.Value_Long{
Long: val.Int(),
},
}, nil
case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint8:
return &entityv1alpha1.Value{
Value: &entityv1alpha1.Value_Long{
Long: int64(val.Uint()),
},
}, nil
case reflect.Slice:
// try and parse as set
set := &entityv1alpha1.Set{
Values: []*entityv1alpha1.Value{},
}
for i := 0; i < val.Len(); i++ {
attr, err := extractAttr(val.Index(i))
if err != nil {
return nil, err
}
set.Values = append(set.Values, attr)
}
return &entityv1alpha1.Value{
Value: &entityv1alpha1.Value_Set{
Set: set,
},
}, nil
case reflect.Pointer:
// Handle optional type (pointer)
if val.IsNil() {
// If the pointer is nil, return a nil value
return &entityv1alpha1.Value{
Value: nil,
}, nil
}
// Extract the value from the non-nil pointer
return extractAttr(val.Elem())
case reflect.Map:
if val.Type() != reflect.MapOf(reflect.TypeOf(""), reflect.TypeOf("")) {
return nil, fmt.Errorf("input is not a map[string]string")
}
record := &entityv1alpha1.Record{
Attributes: []*entityv1alpha1.Attribute{},
}
for _, keyVal := range val.MapKeys() {
key := keyVal.String()
value := val.MapIndex(keyVal)
// Assuming value is also a string
attr := value.String()
record.Attributes = append(record.Attributes, &entityv1alpha1.Attribute{
Key: key,
Value: &entityv1alpha1.Value{
Value: &entityv1alpha1.Value_Str{
Str: attr,
},
},
})
}
return &entityv1alpha1.Value{
Value: &entityv1alpha1.Value_Record{
Record: record,
},
}, nil
}
return nil, fmt.Errorf("extractAttr: unsupported attribute field type: %s", val.Kind())
}
// parseTag parses the 'authz' struct tag. It returns an empty string if the tag cannot be parsed
func parseTag(input string) string {
tags, err := structtag.Parse(input)
if err != nil {
return ""
}
authzTag, err := tags.Get("authz")
if err != nil {
return ""
}
return authzTag.Name
}