-
Notifications
You must be signed in to change notification settings - Fork 476
/
sqlstore.go
4785 lines (4143 loc) · 133 KB
/
sqlstore.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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package sqlstore
import (
"bytes"
"context"
"crypto"
"crypto/x509"
"database/sql"
"errors"
"fmt"
"net/url"
"strconv"
"strings"
"sync"
"time"
"unicode"
"github.com/gofrs/uuid/v5"
"github.com/hashicorp/hcl"
"github.com/hashicorp/hcl/hcl/ast"
"github.com/hashicorp/hcl/hcl/printer"
"github.com/jinzhu/gorm"
"github.com/sirupsen/logrus"
"github.com/spiffe/go-spiffe/v2/spiffeid"
"github.com/spiffe/spire-api-sdk/proto/spire/api/types"
"github.com/spiffe/spire/pkg/common/bundleutil"
"github.com/spiffe/spire/pkg/common/cryptoutil"
"github.com/spiffe/spire/pkg/common/protoutil"
"github.com/spiffe/spire/pkg/common/telemetry"
"github.com/spiffe/spire/pkg/server/datastore"
"github.com/spiffe/spire/proto/private/server/journal"
"github.com/spiffe/spire/proto/spire/common"
"github.com/zeebo/errs"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
)
var sqlError = errs.Class("datastore-sql")
var validEntryIDChars = &unicode.RangeTable{
R16: []unicode.Range16{
{0x002d, 0x002e, 1}, // - | .
{0x0030, 0x0039, 1}, // [0-9]
{0x0041, 0x005a, 1}, // [A-Z]
{0x005f, 0x005f, 1}, // _
{0x0061, 0x007a, 1}, // [a-z]
},
LatinOffset: 5,
}
const (
PluginName = "sql"
// MySQL database type
MySQL = "mysql"
// PostgreSQL database type
PostgreSQL = "postgres"
// SQLite database type
SQLite = "sqlite3"
// MySQL database provided by an AWS service
AWSMySQL = "aws_mysql"
// PostgreSQL database type provided by an AWS service
AWSPostgreSQL = "aws_postgres"
// Maximum size for preallocation in a paginated request
maxResultPreallocation = 1000
)
// Configuration for the sql datastore implementation.
// Pointer values are used to distinguish between "unset" and "zero" values.
type configuration struct {
DatabaseTypeNode ast.Node `hcl:"database_type" json:"database_type"`
ConnectionString string `hcl:"connection_string" json:"connection_string"`
RoConnectionString string `hcl:"ro_connection_string" json:"ro_connection_string"`
RootCAPath string `hcl:"root_ca_path" json:"root_ca_path"`
ClientCertPath string `hcl:"client_cert_path" json:"client_cert_path"`
ClientKeyPath string `hcl:"client_key_path" json:"client_key_path"`
ConnMaxLifetime *string `hcl:"conn_max_lifetime" json:"conn_max_lifetime"`
MaxOpenConns *int `hcl:"max_open_conns" json:"max_open_conns"`
MaxIdleConns *int `hcl:"max_idle_conns" json:"max_idle_conns"`
DisableMigration bool `hcl:"disable_migration" json:"disable_migration"`
databaseTypeConfig *dbTypeConfig
// Undocumented flags
LogSQL bool `hcl:"log_sql" json:"log_sql"`
}
type dbTypeConfig struct {
AWSMySQL *awsConfig `hcl:"aws_mysql" json:"aws_mysql"`
AWSPostgres *awsConfig `hcl:"aws_postgres" json:"aws_postgres"`
databaseType string
}
type awsConfig struct {
Region string `hcl:"region"`
AccessKeyID string `hcl:"access_key_id"`
SecretAccessKey string `hcl:"secret_access_key"`
}
func (a *awsConfig) validate() error {
if a.Region == "" {
return sqlError.New("region must be specified")
}
return nil
}
type sqlDB struct {
databaseType string
connectionString string
raw *sql.DB
*gorm.DB
dialect dialect
stmtCache *stmtCache
supportsCTE bool
// this lock is only required for synchronized writes with "sqlite3". see
// the withTx() implementation for details.
opMu sync.Mutex
}
func (db *sqlDB) QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error) {
stmt, err := db.stmtCache.get(ctx, query)
if err != nil {
return nil, err
}
return stmt.QueryContext(ctx, args...)
}
// Plugin is a DataStore plugin implemented via a SQL database
type Plugin struct {
mu sync.Mutex
db *sqlDB
roDb *sqlDB
log logrus.FieldLogger
useServerTimestamps bool
}
// New creates a new sql plugin struct. Configure must be called
// in order to start the db.
func New(log logrus.FieldLogger) *Plugin {
return &Plugin{
log: log,
}
}
// CreateBundle stores the given bundle
func (ds *Plugin) CreateBundle(ctx context.Context, b *common.Bundle) (bundle *common.Bundle, err error) {
if err = ds.withWriteTx(ctx, func(tx *gorm.DB) (err error) {
bundle, err = createBundle(tx, b)
return err
}); err != nil {
return nil, err
}
return bundle, nil
}
// UpdateBundle updates an existing bundle with the given CAs. Overwrites any
// existing certificates.
func (ds *Plugin) UpdateBundle(ctx context.Context, b *common.Bundle, mask *common.BundleMask) (bundle *common.Bundle, err error) {
if err = ds.withReadModifyWriteTx(ctx, func(tx *gorm.DB) (err error) {
bundle, err = updateBundle(tx, b, mask)
return err
}); err != nil {
return nil, err
}
return bundle, nil
}
// SetBundle sets bundle contents. If no bundle exists for the trust domain, it is created.
func (ds *Plugin) SetBundle(ctx context.Context, b *common.Bundle) (bundle *common.Bundle, err error) {
if err = ds.withWriteTx(ctx, func(tx *gorm.DB) (err error) {
bundle, err = setBundle(tx, b)
return err
}); err != nil {
return nil, err
}
return bundle, nil
}
// AppendBundle append bundle contents to the existing bundle (by trust domain). If no existing one is present, create it.
func (ds *Plugin) AppendBundle(ctx context.Context, b *common.Bundle) (bundle *common.Bundle, err error) {
if err = ds.withReadModifyWriteTx(ctx, func(tx *gorm.DB) (err error) {
bundle, err = appendBundle(tx, b)
return err
}); err != nil {
return nil, err
}
return bundle, nil
}
// DeleteBundle deletes the bundle with the matching TrustDomain. Any CACert data passed is ignored.
func (ds *Plugin) DeleteBundle(ctx context.Context, trustDomainID string, mode datastore.DeleteMode) (err error) {
return ds.withWriteTx(ctx, func(tx *gorm.DB) (err error) {
err = deleteBundle(tx, trustDomainID, mode)
return err
})
}
// FetchBundle returns the bundle matching the specified Trust Domain.
func (ds *Plugin) FetchBundle(ctx context.Context, trustDomainID string) (resp *common.Bundle, err error) {
if err = ds.withReadTx(ctx, func(tx *gorm.DB) (err error) {
resp, err = fetchBundle(tx, trustDomainID)
return err
}); err != nil {
return nil, err
}
return resp, nil
}
// CountBundles can be used to count all existing bundles.
func (ds *Plugin) CountBundles(ctx context.Context) (count int32, err error) {
if err = ds.withReadTx(ctx, func(tx *gorm.DB) (err error) {
count, err = countBundles(tx)
return err
}); err != nil {
return 0, err
}
return count, nil
}
// ListBundles can be used to fetch all existing bundles.
func (ds *Plugin) ListBundles(ctx context.Context, req *datastore.ListBundlesRequest) (resp *datastore.ListBundlesResponse, err error) {
if err = ds.withReadTx(ctx, func(tx *gorm.DB) (err error) {
resp, err = listBundles(tx, req)
return err
}); err != nil {
return nil, err
}
return resp, nil
}
// PruneBundle removes expired certs and keys from a bundle
func (ds *Plugin) PruneBundle(ctx context.Context, trustDomainID string, expiresBefore time.Time) (changed bool, err error) {
if err = ds.withReadModifyWriteTx(ctx, func(tx *gorm.DB) (err error) {
changed, err = pruneBundle(tx, trustDomainID, expiresBefore, ds.log)
return err
}); err != nil {
return false, err
}
return changed, nil
}
// TaintX509CAByKey taints an X.509 CA signed using the provided public key
func (ds *Plugin) TaintX509CA(ctx context.Context, trustDoaminID string, publicKeyToTaint crypto.PublicKey) error {
return ds.withReadModifyWriteTx(ctx, func(tx *gorm.DB) (err error) {
return taintX509CA(tx, trustDoaminID, publicKeyToTaint)
})
}
// RevokeX509CA removes a Root CA from the bundle
func (ds *Plugin) RevokeX509CA(ctx context.Context, trustDoaminID string, publicKeyToRevoke crypto.PublicKey) error {
return ds.withReadModifyWriteTx(ctx, func(tx *gorm.DB) (err error) {
return revokeX509CA(tx, trustDoaminID, publicKeyToRevoke)
})
}
// TaintJWTKey taints a JWT Authority key
func (ds *Plugin) TaintJWTKey(ctx context.Context, trustDoaminID string, authorityID string) (*common.PublicKey, error) {
var taintedKey *common.PublicKey
if err := ds.withReadModifyWriteTx(ctx, func(tx *gorm.DB) (err error) {
taintedKey, err = taintJWTKey(tx, trustDoaminID, authorityID)
return err
}); err != nil {
return nil, err
}
return taintedKey, nil
}
// RevokeJWTAuthority removes JWT key from the bundle
func (ds *Plugin) RevokeJWTKey(ctx context.Context, trustDoaminID string, authorityID string) (*common.PublicKey, error) {
var revokedKey *common.PublicKey
if err := ds.withReadModifyWriteTx(ctx, func(tx *gorm.DB) (err error) {
revokedKey, err = revokeJWTKey(tx, trustDoaminID, authorityID)
return err
}); err != nil {
return nil, err
}
return revokedKey, nil
}
// CreateAttestedNode stores the given attested node
func (ds *Plugin) CreateAttestedNode(ctx context.Context, node *common.AttestedNode) (attestedNode *common.AttestedNode, err error) {
if node == nil {
return nil, sqlError.New("invalid request: missing attested node")
}
if err = ds.withWriteTx(ctx, func(tx *gorm.DB) (err error) {
attestedNode, err = createAttestedNode(tx, node)
if err != nil {
return err
}
return createAttestedNodeEvent(tx, node.SpiffeId)
}); err != nil {
return nil, err
}
return attestedNode, nil
}
// FetchAttestedNode fetches an existing attested node by SPIFFE ID
func (ds *Plugin) FetchAttestedNode(ctx context.Context, spiffeID string) (attestedNode *common.AttestedNode, err error) {
if err = ds.withReadTx(ctx, func(tx *gorm.DB) (err error) {
attestedNode, err = fetchAttestedNode(tx, spiffeID)
return err
}); err != nil {
return nil, err
}
return attestedNode, nil
}
// CountAttestedNodes counts all attested nodes
func (ds *Plugin) CountAttestedNodes(ctx context.Context, req *datastore.CountAttestedNodesRequest) (count int32, err error) {
if countAttestedNodesHasFilters(req) {
resp, err := countAttestedNodesWithFilters(ctx, ds.db, ds.log, req)
return resp, err
}
if err = ds.withReadTx(ctx, func(tx *gorm.DB) (err error) {
count, err = countAttestedNodes(tx)
return err
}); err != nil {
return 0, err
}
return count, nil
}
// ListAttestedNodes lists all attested nodes (pagination available)
func (ds *Plugin) ListAttestedNodes(ctx context.Context,
req *datastore.ListAttestedNodesRequest,
) (resp *datastore.ListAttestedNodesResponse, err error) {
if err = ds.withReadTx(ctx, func(tx *gorm.DB) (err error) {
resp, err = listAttestedNodes(ctx, ds.db, ds.log, req)
return err
}); err != nil {
return nil, err
}
return resp, nil
}
// UpdateAttestedNode updates the given node's cert serial and expiration.
func (ds *Plugin) UpdateAttestedNode(ctx context.Context, n *common.AttestedNode, mask *common.AttestedNodeMask) (node *common.AttestedNode, err error) {
if err = ds.withReadModifyWriteTx(ctx, func(tx *gorm.DB) (err error) {
node, err = updateAttestedNode(tx, n, mask)
if err != nil {
return err
}
return createAttestedNodeEvent(tx, n.SpiffeId)
}); err != nil {
return nil, err
}
return node, nil
}
// DeleteAttestedNode deletes the given attested node and the associated node selectors.
func (ds *Plugin) DeleteAttestedNode(ctx context.Context, spiffeID string) (attestedNode *common.AttestedNode, err error) {
if err = ds.withWriteTx(ctx, func(tx *gorm.DB) (err error) {
attestedNode, err = deleteAttestedNodeAndSelectors(tx, spiffeID)
if err != nil {
return err
}
return createAttestedNodeEvent(tx, spiffeID)
}); err != nil {
return nil, err
}
return attestedNode, nil
}
// ListAttestedNodesEvents lists all attested node events
func (ds *Plugin) ListAttestedNodesEvents(ctx context.Context, req *datastore.ListAttestedNodesEventsRequest) (resp *datastore.ListAttestedNodesEventsResponse, err error) {
if err = ds.withReadTx(ctx, func(tx *gorm.DB) (err error) {
resp, err = listAttestedNodesEvents(tx, req)
return err
}); err != nil {
return nil, err
}
return resp, nil
}
// PruneAttestedNodesEvents deletes all attested node events older than a specified duration (i.e. more than 24 hours old)
func (ds *Plugin) PruneAttestedNodesEvents(ctx context.Context, olderThan time.Duration) (err error) {
return ds.withWriteTx(ctx, func(tx *gorm.DB) (err error) {
err = pruneAttestedNodesEvents(tx, olderThan)
return err
})
}
// GetLatestAttestedNodeEventID get the id of the last event
func (ds *Plugin) GetLatestAttestedNodeEventID(ctx context.Context) (eventID uint, err error) {
if err = ds.withReadTx(ctx, func(tx *gorm.DB) (err error) {
eventID, err = getLatestAttestedNodeEventID(tx)
return err
}); err != nil {
return 0, err
}
return eventID, nil
}
// SetNodeSelectors sets node (agent) selectors by SPIFFE ID, deleting old selectors first
func (ds *Plugin) SetNodeSelectors(ctx context.Context, spiffeID string, selectors []*common.Selector) (err error) {
return ds.withWriteTx(ctx, func(tx *gorm.DB) (err error) {
err = setNodeSelectors(tx, spiffeID, selectors)
return err
})
}
// GetNodeSelectors gets node (agent) selectors by SPIFFE ID
func (ds *Plugin) GetNodeSelectors(ctx context.Context, spiffeID string,
dataConsistency datastore.DataConsistency,
) (selectors []*common.Selector, err error) {
if dataConsistency == datastore.TolerateStale && ds.roDb != nil {
return getNodeSelectors(ctx, ds.roDb, spiffeID)
}
return getNodeSelectors(ctx, ds.db, spiffeID)
}
// ListNodeSelectors gets node (agent) selectors by SPIFFE ID
func (ds *Plugin) ListNodeSelectors(ctx context.Context,
req *datastore.ListNodeSelectorsRequest,
) (resp *datastore.ListNodeSelectorsResponse, err error) {
if req.DataConsistency == datastore.TolerateStale && ds.roDb != nil {
return listNodeSelectors(ctx, ds.roDb, req)
}
return listNodeSelectors(ctx, ds.db, req)
}
// CreateRegistrationEntry stores the given registration entry
func (ds *Plugin) CreateRegistrationEntry(ctx context.Context,
entry *common.RegistrationEntry,
) (registrationEntry *common.RegistrationEntry, err error) {
out, _, err := ds.createOrReturnRegistrationEntry(ctx, entry)
return out, err
}
// CreateOrReturnRegistrationEntry stores the given registration entry. If an
// entry already exists with the same (parentID, spiffeID, selector) tuple,
// that entry is returned instead.
func (ds *Plugin) CreateOrReturnRegistrationEntry(ctx context.Context,
entry *common.RegistrationEntry,
) (registrationEntry *common.RegistrationEntry, existing bool, err error) {
return ds.createOrReturnRegistrationEntry(ctx, entry)
}
func (ds *Plugin) createOrReturnRegistrationEntry(ctx context.Context,
entry *common.RegistrationEntry,
) (registrationEntry *common.RegistrationEntry, existing bool, err error) {
// TODO: Validations should be done in the ProtoBuf level [https://github.com/spiffe/spire/issues/44]
if err = validateRegistrationEntry(entry); err != nil {
return nil, false, err
}
if err = ds.withWriteTx(ctx, func(tx *gorm.DB) (err error) {
registrationEntry, err = lookupSimilarEntry(ctx, ds.db, tx, entry)
if err != nil {
return err
}
if registrationEntry != nil {
existing = true
return nil
}
registrationEntry, err = createRegistrationEntry(tx, entry)
if err != nil {
return err
}
return createRegistrationEntryEvent(tx, registrationEntry.EntryId)
}); err != nil {
return nil, false, err
}
return registrationEntry, existing, nil
}
// FetchRegistrationEntry fetches an existing registration by entry ID
func (ds *Plugin) FetchRegistrationEntry(ctx context.Context,
entryID string,
) (*common.RegistrationEntry, error) {
return fetchRegistrationEntry(ctx, ds.db, entryID)
}
// CountRegistrationEntries counts all registrations (pagination available)
func (ds *Plugin) CountRegistrationEntries(ctx context.Context, req *datastore.CountRegistrationEntriesRequest) (count int32, err error) {
var actDb = ds.db
if req.DataConsistency == datastore.TolerateStale && ds.roDb != nil {
actDb = ds.roDb
}
resp, err := countRegistrationEntries(ctx, actDb, ds.log, req)
return resp, err
}
// ListRegistrationEntries lists all registrations (pagination available)
func (ds *Plugin) ListRegistrationEntries(ctx context.Context,
req *datastore.ListRegistrationEntriesRequest,
) (resp *datastore.ListRegistrationEntriesResponse, err error) {
if req.DataConsistency == datastore.TolerateStale && ds.roDb != nil {
return listRegistrationEntries(ctx, ds.roDb, ds.log, req)
}
return listRegistrationEntries(ctx, ds.db, ds.log, req)
}
// UpdateRegistrationEntry updates an existing registration entry
func (ds *Plugin) UpdateRegistrationEntry(ctx context.Context, e *common.RegistrationEntry, mask *common.RegistrationEntryMask) (entry *common.RegistrationEntry, err error) {
if err = ds.withReadModifyWriteTx(ctx, func(tx *gorm.DB) (err error) {
entry, err = updateRegistrationEntry(tx, e, mask)
if err != nil {
return err
}
return createRegistrationEntryEvent(tx, entry.EntryId)
}); err != nil {
return nil, err
}
return entry, nil
}
// DeleteRegistrationEntry deletes the given registration
func (ds *Plugin) DeleteRegistrationEntry(ctx context.Context,
entryID string,
) (registrationEntry *common.RegistrationEntry, err error) {
if err = ds.withWriteTx(ctx, func(tx *gorm.DB) (err error) {
registrationEntry, err = deleteRegistrationEntry(tx, entryID)
if err != nil {
return err
}
return createRegistrationEntryEvent(tx, entryID)
}); err != nil {
return nil, err
}
return registrationEntry, nil
}
// PruneRegistrationEntries takes a registration entry message, and deletes all entries which have expired
// before the date in the message
func (ds *Plugin) PruneRegistrationEntries(ctx context.Context, expiresBefore time.Time) (err error) {
return ds.withWriteTx(ctx, func(tx *gorm.DB) (err error) {
err = pruneRegistrationEntries(tx, expiresBefore, ds.log)
return err
})
}
// ListRegistrationEntriesEvents lists all registration entry events
func (ds *Plugin) ListRegistrationEntriesEvents(ctx context.Context, req *datastore.ListRegistrationEntriesEventsRequest) (resp *datastore.ListRegistrationEntriesEventsResponse, err error) {
if err = ds.withReadTx(ctx, func(tx *gorm.DB) (err error) {
resp, err = listRegistrationEntriesEvents(tx, req)
return err
}); err != nil {
return nil, err
}
return resp, nil
}
// PruneRegistrationEntriesEvents deletes all registration entry events older than a specified duration (i.e. more than 24 hours old)
func (ds *Plugin) PruneRegistrationEntriesEvents(ctx context.Context, olderThan time.Duration) (err error) {
return ds.withWriteTx(ctx, func(tx *gorm.DB) (err error) {
err = pruneRegistrationEntriesEvents(tx, olderThan)
return err
})
}
// GetLatestRegistrationEntryEventID get the id of the last event
func (ds *Plugin) GetLatestRegistrationEntryEventID(ctx context.Context) (eventID uint, err error) {
if err = ds.withReadTx(ctx, func(tx *gorm.DB) (err error) {
eventID, err = getLatestRegistrationEntryEventID(tx)
return err
}); err != nil {
return 0, err
}
return eventID, nil
}
// CreateJoinToken takes a Token message and stores it
func (ds *Plugin) CreateJoinToken(ctx context.Context, token *datastore.JoinToken) (err error) {
if token == nil || token.Token == "" || token.Expiry.IsZero() {
return errors.New("token and expiry are required")
}
return ds.withWriteTx(ctx, func(tx *gorm.DB) (err error) {
err = createJoinToken(tx, token)
return err
})
}
// FetchJoinToken takes a Token message and returns one, populating the fields
// we have knowledge of
func (ds *Plugin) FetchJoinToken(ctx context.Context, token string) (resp *datastore.JoinToken, err error) {
if err = ds.withReadTx(ctx, func(tx *gorm.DB) (err error) {
resp, err = fetchJoinToken(tx, token)
return err
}); err != nil {
return nil, err
}
return resp, nil
}
// DeleteJoinToken deletes the given join token
func (ds *Plugin) DeleteJoinToken(ctx context.Context, token string) (err error) {
return ds.withWriteTx(ctx, func(tx *gorm.DB) (err error) {
err = deleteJoinToken(tx, token)
return err
})
}
// PruneJoinTokens takes a Token message, and deletes all tokens which have expired
// before the date in the message
func (ds *Plugin) PruneJoinTokens(ctx context.Context, expiry time.Time) (err error) {
return ds.withWriteTx(ctx, func(tx *gorm.DB) (err error) {
err = pruneJoinTokens(tx, expiry)
return err
})
}
// CreateFederationRelationship creates a new federation relationship. If the bundle endpoint
// profile is 'https_spiffe' and the given federation relationship contains a bundle, the current
// stored bundle is overridden.
// If no bundle is provided and there is not a previously stored bundle in the datastore, the
// federation relationship is not created.
func (ds *Plugin) CreateFederationRelationship(ctx context.Context, fr *datastore.FederationRelationship) (newFr *datastore.FederationRelationship, err error) {
if err := validateFederationRelationship(fr, protoutil.AllTrueFederationRelationshipMask); err != nil {
return nil, err
}
return newFr, ds.withWriteTx(ctx, func(tx *gorm.DB) error {
newFr, err = createFederationRelationship(tx, fr)
return err
})
}
// DeleteFederationRelationship deletes the federation relationship to the
// given trust domain. The associated trust bundle is not deleted.
func (ds *Plugin) DeleteFederationRelationship(ctx context.Context, trustDomain spiffeid.TrustDomain) error {
if trustDomain.IsZero() {
return status.Error(codes.InvalidArgument, "trust domain is required")
}
return ds.withWriteTx(ctx, func(tx *gorm.DB) (err error) {
err = deleteFederationRelationship(tx, trustDomain)
return err
})
}
// FetchFederationRelationship fetches the federation relationship that matches
// the given trust domain. If the federation relationship is not found, nil is returned.
func (ds *Plugin) FetchFederationRelationship(ctx context.Context, trustDomain spiffeid.TrustDomain) (fr *datastore.FederationRelationship, err error) {
if trustDomain.IsZero() {
return nil, status.Error(codes.InvalidArgument, "trust domain is required")
}
if err = ds.withReadTx(ctx, func(tx *gorm.DB) (err error) {
fr, err = fetchFederationRelationship(tx, trustDomain)
return err
}); err != nil {
return nil, err
}
return fr, nil
}
// ListFederationRelationships can be used to list all existing federation relationships
func (ds *Plugin) ListFederationRelationships(ctx context.Context, req *datastore.ListFederationRelationshipsRequest) (resp *datastore.ListFederationRelationshipsResponse, err error) {
if err = ds.withReadTx(ctx, func(tx *gorm.DB) (err error) {
resp, err = listFederationRelationships(tx, req)
return err
}); err != nil {
return nil, err
}
return resp, nil
}
// UpdateFederationRelationship updates the given federation relationship.
// Attributes are only updated if the correspondent mask value is set to true.
func (ds *Plugin) UpdateFederationRelationship(ctx context.Context, fr *datastore.FederationRelationship, mask *types.FederationRelationshipMask) (newFr *datastore.FederationRelationship, err error) {
if err := validateFederationRelationship(fr, mask); err != nil {
return nil, err
}
return newFr, ds.withReadModifyWriteTx(ctx, func(tx *gorm.DB) error {
newFr, err = updateFederationRelationship(tx, fr, mask)
return err
})
}
// SetUseServerTimestamps controls whether server-generated timestamps should be used in the database.
// This is only intended to be used by tests in order to produce deterministic timestamp data,
// since some databases round off timestamp data with lower precision.
func (ds *Plugin) SetUseServerTimestamps(useServerTimestamps bool) {
ds.useServerTimestamps = useServerTimestamps
}
// FetchCAJournal fetches the CA journal that has the given active X509
// authority domain. If the CA journal is not found, nil is returned.
func (ds *Plugin) FetchCAJournal(ctx context.Context, activeX509AuthorityID string) (caJournal *datastore.CAJournal, err error) {
if activeX509AuthorityID == "" {
return nil, status.Error(codes.InvalidArgument, "active X509 authority ID is required")
}
if err = ds.withReadTx(ctx, func(tx *gorm.DB) (err error) {
caJournal, err = fetchCAJournal(tx, activeX509AuthorityID)
return err
}); err != nil {
return nil, err
}
return caJournal, nil
}
// ListCAJournalsForTesting returns all the CA journal records, and is meant to
// be used in tests.
func (ds *Plugin) ListCAJournalsForTesting(ctx context.Context) (caJournals []*datastore.CAJournal, err error) {
if err = ds.withReadTx(ctx, func(tx *gorm.DB) (err error) {
caJournals, err = listCAJournalsForTesting(tx)
return err
}); err != nil {
return nil, err
}
return caJournals, nil
}
// SetCAJournal sets the content for the specified CA journal. If the CA journal
// does not exist, it is created.
func (ds *Plugin) SetCAJournal(ctx context.Context, caJournal *datastore.CAJournal) (caj *datastore.CAJournal, err error) {
if err := validateCAJournal(caJournal); err != nil {
return nil, err
}
if err = ds.withReadModifyWriteTx(ctx, func(tx *gorm.DB) (err error) {
if caJournal.ID == 0 {
caj, err = createCAJournal(tx, caJournal)
return err
}
// The CA journal already exists, update it.
caj, err = updateCAJournal(tx, caJournal)
return err
}); err != nil {
return nil, err
}
return caj, nil
}
// PruneCAJournals prunes the CA journals that have all of their authorities
// expired.
func (ds *Plugin) PruneCAJournals(ctx context.Context, allAuthoritiesExpireBefore int64) error {
return ds.withWriteTx(ctx, func(tx *gorm.DB) (err error) {
err = ds.pruneCAJournals(tx, allAuthoritiesExpireBefore)
return err
})
}
func (ds *Plugin) pruneCAJournals(tx *gorm.DB, allAuthoritiesExpireBefore int64) error {
var caJournals []CAJournal
if err := tx.Find(&caJournals).Error; err != nil {
return sqlError.Wrap(err)
}
checkAuthorities:
for _, model := range caJournals {
entries := new(journal.Entries)
if err := proto.Unmarshal(model.Data, entries); err != nil {
return status.Errorf(codes.Internal, "unable to unmarshal entries from CA journal record: %v", err)
}
for _, x509CA := range entries.X509CAs {
if x509CA.NotAfter > allAuthoritiesExpireBefore {
continue checkAuthorities
}
}
for _, jwtKey := range entries.JwtKeys {
if jwtKey.NotAfter > allAuthoritiesExpireBefore {
continue checkAuthorities
}
}
if err := deleteCAJournal(tx, model.ID); err != nil {
return status.Errorf(codes.Internal, "failed to delete CA journal: %v", err)
}
ds.log.WithFields(logrus.Fields{
telemetry.CAJournalID: model.ID,
}).Info("Pruned stale CA journal record")
}
return nil
}
// Configure parses HCL config payload into config struct, opens new DB based on the result, and
// prunes all orphaned records
func (ds *Plugin) Configure(_ context.Context, hclConfiguration string) error {
config := &configuration{}
if err := hcl.Decode(config, hclConfiguration); err != nil {
return err
}
dbTypeConfig, err := parseDatabaseTypeASTNode(config.DatabaseTypeNode)
if err != nil {
return err
}
config.databaseTypeConfig = dbTypeConfig
if err := config.Validate(); err != nil {
return err
}
return ds.openConnections(config)
}
func (ds *Plugin) openConnections(config *configuration) error {
ds.mu.Lock()
defer ds.mu.Unlock()
if err := ds.openConnection(config, false); err != nil {
return err
}
if config.RoConnectionString == "" {
return nil
}
return ds.openConnection(config, true)
}
func (ds *Plugin) openConnection(config *configuration, isReadOnly bool) error {
connectionString := getConnectionString(config, isReadOnly)
sqlDb := ds.db
if isReadOnly {
sqlDb = ds.roDb
}
if sqlDb == nil || connectionString != sqlDb.connectionString || config.databaseTypeConfig.databaseType != ds.db.databaseType {
db, version, supportsCTE, dialect, err := ds.openDB(config, isReadOnly)
if err != nil {
return err
}
raw := db.DB()
if raw == nil {
return sqlError.New("unable to get raw database object")
}
if sqlDb != nil {
sqlDb.Close()
}
ds.log.WithFields(logrus.Fields{
telemetry.Type: config.databaseTypeConfig.databaseType,
telemetry.Version: version,
telemetry.ReadOnly: isReadOnly,
}).Info("Connected to SQL database")
sqlDb = &sqlDB{
DB: db,
raw: raw,
databaseType: config.databaseTypeConfig.databaseType,
dialect: dialect,
connectionString: connectionString,
stmtCache: newStmtCache(raw),
supportsCTE: supportsCTE,
}
}
if isReadOnly {
ds.roDb = sqlDb
} else {
ds.db = sqlDb
}
sqlDb.LogMode(config.LogSQL)
return nil
}
func (ds *Plugin) Close() error {
var errs errs.Group
if ds.db != nil {
errs.Add(ds.db.Close())
}
if ds.roDb != nil {
errs.Add(ds.roDb.Close())
}
return errs.Err()
}
// withReadModifyWriteTx wraps the operation in a transaction appropriate for
// operations that will read one or more rows, change one or more columns in
// those rows, and then set them back. This requires a stronger level of
// consistency that prevents two transactions from doing read-modify-write
// concurrently.
func (ds *Plugin) withReadModifyWriteTx(ctx context.Context, op func(tx *gorm.DB) error) error {
return ds.withTx(ctx, func(tx *gorm.DB) error {
switch {
case isMySQLDbType(ds.db.databaseType):
// MySQL REPEATABLE READ is weaker than that of PostgreSQL. Namely,
// PostgreSQL, beyond providing the minimum consistency guarantees
// mandated for REPEATABLE READ in the standard, automatically fails
// concurrent transactions that try to update the same target row.
//
// To get the same consistency guarantees, have the queries do a
// `SELECT .. FOR UPDATE` which will implicitly lock queried rows
// from update by other transactions. This is preferred to a stronger
// isolation level, like SERIALIZABLE, which is not supported by
// some MySQL-compatible databases (i.e. Percona XtraDB cluster)
tx = tx.Set("gorm:query_option", "FOR UPDATE")
case isPostgresDbType(ds.db.databaseType):
// `SELECT .. FOR UPDATE`is also required when PostgreSQL is in
// hot standby mode for this operation to work properly (see issue #3039).
tx = tx.Set("gorm:query_option", "FOR UPDATE")
}
return op(tx)
}, false)
}
// withWriteTx wraps the operation in a transaction appropriate for operations
// that unconditionally create/update rows, without reading them first. If two
// transactions try and update at the same time, last writer wins.
func (ds *Plugin) withWriteTx(ctx context.Context, op func(tx *gorm.DB) error) error {
return ds.withTx(ctx, op, false)
}
// withReadTx wraps the operation in a transaction appropriate for operations
// that only read rows.
func (ds *Plugin) withReadTx(ctx context.Context, op func(tx *gorm.DB) error) error {
return ds.withTx(ctx, op, true)
}
func (ds *Plugin) withTx(ctx context.Context, op func(tx *gorm.DB) error, readOnly bool) error {
ds.mu.Lock()
db := ds.db
ds.mu.Unlock()
if db.databaseType == SQLite && !readOnly {
// sqlite3 can only have one writer at a time. since we're in WAL mode,
// there can be concurrent reads and writes, so no lock is necessary
// over the read operations.
db.opMu.Lock()
defer db.opMu.Unlock()
}
tx := db.BeginTx(ctx, nil)
if err := tx.Error; err != nil {
return sqlError.Wrap(err)
}
if err := op(tx); err != nil {
tx.Rollback()
return ds.gormToGRPCStatus(err)
}
if readOnly {
// rolling back makes sure that functions that are invoked with
// withReadTx, and then do writes, will not pass unit tests, since the
// writes won't be committed.
return sqlError.Wrap(tx.Rollback().Error)
}
return sqlError.Wrap(tx.Commit().Error)
}
// gormToGRPCStatus takes an error, and converts it to a GRPC error. If the
// error is already a gRPC status , it will be returned unmodified. Otherwise
// if the error is a gorm error type with a known mapping to a GRPC status,
// that code will be set, otherwise the code will be set to Unknown.
func (ds *Plugin) gormToGRPCStatus(err error) error {
unwrapped := errs.Unwrap(err)
if _, ok := status.FromError(unwrapped); ok {
return unwrapped
}
code := codes.Unknown
switch {
case gorm.IsRecordNotFoundError(unwrapped):
code = codes.NotFound
case ds.db.dialect.isConstraintViolation(unwrapped):
code = codes.AlreadyExists
default:
}
return status.Error(code, err.Error())
}
func (ds *Plugin) openDB(cfg *configuration, isReadOnly bool) (*gorm.DB, string, bool, dialect, error) {
var dialect dialect
ds.log.WithField(telemetry.DatabaseType, cfg.databaseTypeConfig.databaseType).Info("Opening SQL database")
switch {
case isSQLiteDbType(cfg.databaseTypeConfig.databaseType):
dialect = sqliteDB{log: ds.log}
case isPostgresDbType(cfg.databaseTypeConfig.databaseType):
dialect = postgresDB{}
case isMySQLDbType(cfg.databaseTypeConfig.databaseType):
dialect = mysqlDB{}
default:
return nil, "", false, nil, sqlError.New("unsupported database_type: %v", cfg.databaseTypeConfig.databaseType)
}
db, version, supportsCTE, err := dialect.connect(cfg, isReadOnly)
if err != nil {
return nil, "", false, nil, sqlError.Wrap(err)
}