-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathpath_tidy.go
2088 lines (1814 loc) · 73 KB
/
path_tidy.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
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: BUSL-1.1
package pki
import (
"context"
"crypto/x509"
"errors"
"fmt"
"math/rand/v2"
"net/http"
"sync/atomic"
"time"
"github.com/armon/go-metrics"
"github.com/hashicorp/go-hclog"
"github.com/hashicorp/go-secure-stdlib/parseutil"
"github.com/hashicorp/vault/builtin/logical/pki/issuing"
"github.com/hashicorp/vault/builtin/logical/pki/revocation"
"github.com/hashicorp/vault/helper/constants"
"github.com/hashicorp/vault/sdk/framework"
"github.com/hashicorp/vault/sdk/helper/consts"
"github.com/hashicorp/vault/sdk/logical"
)
var tidyCancelledError = errors.New("tidy operation cancelled")
//go:generate enumer -type=tidyStatusState -trimprefix=tidyStatus
type tidyStatusState int
const (
tidyStatusInactive tidyStatusState = iota
tidyStatusStarted
tidyStatusFinished
tidyStatusError
tidyStatusCancelling
tidyStatusCancelled
)
type tidyStatus struct {
// Parameters used to initiate the operation
safetyBuffer int
issuerSafetyBuffer int
revQueueSafetyBuffer int
acmeAccountSafetyBuffer int
tidyCertStore bool
tidyRevokedCerts bool
tidyRevokedAssocs bool
tidyExpiredIssuers bool
tidyBackupBundle bool
tidyRevocationQueue bool
tidyCrossRevokedCerts bool
tidyAcme bool
tidyCertMetadata bool
tidyCMPV2NonceStore bool
pauseDuration string
// Status
state tidyStatusState
err error
timeStarted time.Time
timeFinished time.Time
message string
// These counts use a custom incrementer that grab and release
// a lock prior to reading.
certStoreDeletedCount uint
revokedCertDeletedCount uint
missingIssuerCertCount uint
revQueueDeletedCount uint
crossRevokedDeletedCount uint
certMetadataDeletedCount uint
cmpv2NonceDeletedCount uint
acmeAccountsCount uint
acmeAccountsRevokedCount uint
acmeAccountsDeletedCount uint
acmeOrdersDeletedCount uint
}
type tidyConfig struct {
// AutoTidy config
Enabled bool `json:"enabled"`
Interval time.Duration `json:"interval_duration"`
MinStartupBackoff time.Duration `json:"min_startup_backoff_duration"`
MaxStartupBackoff time.Duration `json:"max_startup_backoff_duration"`
// Tidy Operations
CertStore bool `json:"tidy_cert_store"`
RevokedCerts bool `json:"tidy_revoked_certs"`
IssuerAssocs bool `json:"tidy_revoked_cert_issuer_associations"`
ExpiredIssuers bool `json:"tidy_expired_issuers"`
BackupBundle bool `json:"tidy_move_legacy_ca_bundle"`
RevocationQueue bool `json:"tidy_revocation_queue"`
CrossRevokedCerts bool `json:"tidy_cross_cluster_revoked_certs"`
TidyAcme bool `json:"tidy_acme"`
CertMetadata bool `json:"tidy_cert_metadata"`
CMPV2NonceStore bool `json:"tidy_cmpv2_nonce_store"`
// Safety Buffers
SafetyBuffer time.Duration `json:"safety_buffer"`
IssuerSafetyBuffer time.Duration `json:"issuer_safety_buffer"`
QueueSafetyBuffer time.Duration `json:"revocation_queue_safety_buffer"`
AcmeAccountSafetyBuffer time.Duration `json:"acme_account_safety_buffer"`
PauseDuration time.Duration `json:"pause_duration"`
// Metrics.
MaintainCount bool `json:"maintain_stored_certificate_counts"`
PublishMetrics bool `json:"publish_stored_certificate_count_metrics"`
}
func (tc *tidyConfig) IsAnyTidyEnabled() bool {
return tc.CertStore || tc.RevokedCerts || tc.IssuerAssocs || tc.ExpiredIssuers || tc.BackupBundle || tc.TidyAcme || tc.CrossRevokedCerts || tc.RevocationQueue || tc.CertMetadata || tc.CMPV2NonceStore
}
func (tc *tidyConfig) AnyTidyConfig() string {
return "tidy_cert_store / tidy_revoked_certs / tidy_revoked_cert_issuer_associations / tidy_expired_issuers / tidy_move_legacy_ca_bundle / tidy_revocation_queue / tidy_cross_cluster_revoked_certs / tidy_acme"
}
func (tc *tidyConfig) CalculateStartupBackoff(mountStartup time.Time) time.Time {
minBackoff := int64(tc.MinStartupBackoff.Seconds())
maxBackoff := int64(tc.MaxStartupBackoff.Seconds())
maxNumber := maxBackoff - minBackoff
if maxNumber <= 0 {
return mountStartup.Add(tc.MinStartupBackoff)
}
backoffSecs := rand.Int64N(maxNumber) + minBackoff
return mountStartup.Add(time.Duration(backoffSecs) * time.Second)
}
var defaultTidyConfig = tidyConfig{
Enabled: false,
Interval: 12 * time.Hour,
MinStartupBackoff: 5 * time.Minute,
MaxStartupBackoff: 15 * time.Minute,
CertStore: false,
RevokedCerts: false,
IssuerAssocs: false,
ExpiredIssuers: false,
BackupBundle: false,
TidyAcme: false,
SafetyBuffer: 72 * time.Hour,
IssuerSafetyBuffer: 365 * 24 * time.Hour,
AcmeAccountSafetyBuffer: 30 * 24 * time.Hour,
PauseDuration: 0 * time.Second,
MaintainCount: false,
PublishMetrics: false,
RevocationQueue: false,
QueueSafetyBuffer: 48 * time.Hour,
CrossRevokedCerts: false,
CertMetadata: false,
CMPV2NonceStore: false,
}
var tidyStatusResponseFields = map[string]*framework.FieldSchema{
"safety_buffer": {
Type: framework.TypeInt,
Description: `Safety buffer time duration`,
Required: true,
},
"issuer_safety_buffer": {
Type: framework.TypeInt,
Description: `Issuer safety buffer`,
Required: true,
},
"revocation_queue_safety_buffer": {
Type: framework.TypeInt,
Description: `Revocation queue safety buffer`,
Required: true,
},
"acme_account_safety_buffer": {
Type: framework.TypeInt,
Description: `Safety buffer after creation after which accounts lacking orders are revoked`,
Required: false,
},
"tidy_cert_store": {
Type: framework.TypeBool,
Description: `Tidy certificate store`,
Required: true,
},
"tidy_revoked_certs": {
Type: framework.TypeBool,
Description: `Tidy revoked certificates`,
Required: true,
},
"tidy_revoked_cert_issuer_associations": {
Type: framework.TypeBool,
Description: `Tidy revoked certificate issuer associations`,
Required: true,
},
"tidy_expired_issuers": {
Type: framework.TypeBool,
Description: `Tidy expired issuers`,
Required: true,
},
"tidy_cross_cluster_revoked_certs": {
Type: framework.TypeBool,
Description: `Tidy the cross-cluster revoked certificate store`,
Required: false,
},
"tidy_acme": {
Type: framework.TypeBool,
Description: `Tidy Unused Acme Accounts, and Orders`,
Required: true,
},
"tidy_cert_metadata": {
Type: framework.TypeBool,
Description: `Tidy cert metadata`,
Required: true,
},
"tidy_cmpv2_nonce_store": {
Type: framework.TypeBool,
Description: `Tidy CMPv2 nonce store`,
Required: true,
},
"pause_duration": {
Type: framework.TypeString,
Description: `Duration to pause between tidying certificates`,
Required: true,
},
"state": {
Type: framework.TypeString,
Description: `One of Inactive, Running, Finished, or Error`,
Required: true,
},
"error": {
Type: framework.TypeString,
Description: `The error message`,
Required: true,
},
"time_started": {
Type: framework.TypeString,
Description: `Time the operation started`,
Required: true,
},
"time_finished": {
Type: framework.TypeString,
Description: `Time the operation finished`,
Required: false,
},
"last_auto_tidy_finished": {
Type: framework.TypeString,
Description: `Time the last auto-tidy operation finished`,
Required: true,
},
"message": {
Type: framework.TypeString,
Description: `Message of the operation`,
Required: true,
},
"cert_store_deleted_count": {
Type: framework.TypeInt,
Description: `The number of certificate storage entries deleted`,
Required: true,
},
"revoked_cert_deleted_count": {
Type: framework.TypeInt,
Description: `The number of revoked certificate entries deleted`,
Required: true,
},
"current_cert_store_count": {
Type: framework.TypeInt,
Description: `The number of revoked certificate entries deleted`,
Required: true,
},
"cross_revoked_cert_deleted_count": {
Type: framework.TypeInt,
Description: ``,
Required: true,
},
"current_revoked_cert_count": {
Type: framework.TypeInt,
Description: `The number of revoked certificate entries deleted`,
Required: true,
},
"revocation_queue_deleted_count": {
Type: framework.TypeInt,
Required: true,
},
"tidy_move_legacy_ca_bundle": {
Type: framework.TypeBool,
Required: true,
},
"tidy_revocation_queue": {
Type: framework.TypeBool,
Required: true,
},
"missing_issuer_cert_count": {
Type: framework.TypeInt,
Required: true,
},
"internal_backend_uuid": {
Type: framework.TypeString,
Required: true,
},
"total_acme_account_count": {
Type: framework.TypeInt,
Description: `Total number of acme accounts iterated over`,
Required: false,
},
"acme_account_deleted_count": {
Type: framework.TypeInt,
Description: `The number of revoked acme accounts removed`,
Required: false,
},
"acme_account_revoked_count": {
Type: framework.TypeInt,
Description: `The number of unused acme accounts revoked`,
Required: false,
},
"acme_orders_deleted_count": {
Type: framework.TypeInt,
Description: `The number of expired, unused acme orders removed`,
Required: false,
},
"cert_metadata_deleted_count": {
Type: framework.TypeInt,
Description: `The number of metadata entries removed`,
Required: false,
},
"cmpv2_nonce_deleted_count": {
Type: framework.TypeInt,
Description: `The number of CMPv2 nonces removed`,
Required: false,
},
}
func pathTidy(b *backend) *framework.Path {
return &framework.Path{
Pattern: "tidy$",
DisplayAttrs: &framework.DisplayAttributes{
OperationPrefix: operationPrefixPKI,
OperationVerb: "tidy",
},
Fields: addTidyFields(map[string]*framework.FieldSchema{}),
Operations: map[logical.Operation]framework.OperationHandler{
logical.UpdateOperation: &framework.PathOperation{
Callback: b.pathTidyWrite,
Responses: map[int][]framework.Response{
http.StatusAccepted: {{
Description: "Accepted",
Fields: map[string]*framework.FieldSchema{},
}},
},
ForwardPerformanceStandby: true,
},
},
HelpSynopsis: pathTidyHelpSyn,
HelpDescription: pathTidyHelpDesc,
}
}
func pathTidyCancel(b *backend) *framework.Path {
return &framework.Path{
Pattern: "tidy-cancel$",
DisplayAttrs: &framework.DisplayAttributes{
OperationPrefix: operationPrefixPKI,
OperationVerb: "tidy",
OperationSuffix: "cancel",
},
Operations: map[logical.Operation]framework.OperationHandler{
logical.UpdateOperation: &framework.PathOperation{
Callback: b.pathTidyCancelWrite,
Responses: map[int][]framework.Response{
http.StatusOK: {{
Description: "OK",
Fields: tidyStatusResponseFields,
}},
},
ForwardPerformanceStandby: true,
},
},
HelpSynopsis: pathTidyCancelHelpSyn,
HelpDescription: pathTidyCancelHelpDesc,
}
}
func pathTidyStatus(b *backend) *framework.Path {
return &framework.Path{
Pattern: "tidy-status$",
DisplayAttrs: &framework.DisplayAttributes{
OperationPrefix: operationPrefixPKI,
OperationVerb: "tidy",
OperationSuffix: "status",
},
Operations: map[logical.Operation]framework.OperationHandler{
logical.ReadOperation: &framework.PathOperation{
Callback: b.pathTidyStatusRead,
Responses: map[int][]framework.Response{
http.StatusOK: {{
Description: "OK",
Fields: tidyStatusResponseFields,
}},
},
ForwardPerformanceStandby: true,
},
},
HelpSynopsis: pathTidyStatusHelpSyn,
HelpDescription: pathTidyStatusHelpDesc,
}
}
func pathConfigAutoTidy(b *backend) *framework.Path {
autoTidyResponseFields := map[string]*framework.FieldSchema{
"enabled": {
Type: framework.TypeBool,
Description: `Specifies whether automatic tidy is enabled or not`,
Required: true,
},
"min_startup_backoff_duration": {
Type: framework.TypeInt,
Description: `The minimum amount of time in seconds auto-tidy will be delayed after startup`,
Required: true,
},
"max_startup_backoff_duration": {
Type: framework.TypeInt,
Description: `The maximum amount of time in seconds auto-tidy will be delayed after startup`,
Required: true,
},
"interval_duration": {
Type: framework.TypeInt,
Description: `Specifies the duration between automatic tidy operation`,
Required: true,
},
"tidy_cert_store": {
Type: framework.TypeBool,
Description: `Specifies whether to tidy up the certificate store`,
Required: true,
},
"tidy_revoked_certs": {
Type: framework.TypeBool,
Description: `Specifies whether to remove all invalid and expired certificates from storage`,
Required: true,
},
"tidy_revoked_cert_issuer_associations": {
Type: framework.TypeBool,
Description: `Specifies whether to associate revoked certificates with their corresponding issuers`,
Required: true,
},
"tidy_expired_issuers": {
Type: framework.TypeBool,
Description: `Specifies whether tidy expired issuers`,
Required: true,
},
"tidy_acme": {
Type: framework.TypeBool,
Description: `Tidy Unused Acme Accounts, and Orders`,
Required: true,
},
"tidy_cert_metadata": {
Type: framework.TypeBool,
Description: `Tidy cert metadata`,
Required: true,
},
"tidy_cmpv2_nonce_store": {
Type: framework.TypeBool,
Description: `Tidy CMPv2 nonce store`,
Required: true,
},
"safety_buffer": {
Type: framework.TypeInt,
Description: `Safety buffer time duration`,
Required: true,
},
"issuer_safety_buffer": {
Type: framework.TypeInt,
Description: `Issuer safety buffer`,
Required: true,
},
"acme_account_safety_buffer": {
Type: framework.TypeInt,
Description: `Safety buffer after creation after which accounts lacking orders are revoked`,
Required: true,
},
"pause_duration": {
Type: framework.TypeString,
Description: `Duration to pause between tidying certificates`,
Required: true,
},
"tidy_cross_cluster_revoked_certs": {
Type: framework.TypeBool,
Description: `Tidy the cross-cluster revoked certificate store`,
Required: true,
},
"tidy_revocation_queue": {
Type: framework.TypeBool,
Required: true,
},
"tidy_move_legacy_ca_bundle": {
Type: framework.TypeBool,
Required: true,
},
"revocation_queue_safety_buffer": {
Type: framework.TypeInt,
Required: true,
},
"publish_stored_certificate_count_metrics": {
Type: framework.TypeBool,
Required: true,
},
"maintain_stored_certificate_counts": {
Type: framework.TypeBool,
Required: true,
},
}
return &framework.Path{
Pattern: "config/auto-tidy",
DisplayAttrs: &framework.DisplayAttributes{
OperationPrefix: operationPrefixPKI,
},
Fields: addTidyFields(map[string]*framework.FieldSchema{
"enabled": {
Type: framework.TypeBool,
Description: `Set to true to enable automatic tidy operations.`,
},
"min_startup_backoff_duration": {
Type: framework.TypeDurationSecond,
Description: `The minimum amount of time in seconds auto-tidy will be delayed after startup.`,
Default: int(defaultTidyConfig.MinStartupBackoff.Seconds()),
},
"max_startup_backoff_duration": {
Type: framework.TypeDurationSecond,
Description: `The maximum amount of time in seconds auto-tidy will be delayed after startup.`,
Default: int(defaultTidyConfig.MaxStartupBackoff.Seconds()),
},
"interval_duration": {
Type: framework.TypeDurationSecond,
Description: `Interval at which to run an auto-tidy operation. This is the time between tidy invocations (after one finishes to the start of the next). Running a manual tidy will reset this duration.`,
Default: int(defaultTidyConfig.Interval / time.Second), // TypeDurationSecond currently requires the default to be an int.
},
"maintain_stored_certificate_counts": {
Type: framework.TypeBool,
Description: `This configures whether stored certificates
are counted upon initialization of the backend, and whether during
normal operation, a running count of certificates stored is maintained.`,
Default: false,
},
"publish_stored_certificate_count_metrics": {
Type: framework.TypeBool,
Description: `This configures whether the stored certificate
count is published to the metrics consumer. It does not affect if the
stored certificate count is maintained, and if maintained, it will be
available on the tidy-status endpoint.`,
Default: false,
},
}),
Operations: map[logical.Operation]framework.OperationHandler{
logical.ReadOperation: &framework.PathOperation{
Callback: b.pathConfigAutoTidyRead,
DisplayAttrs: &framework.DisplayAttributes{
OperationSuffix: "auto-tidy-configuration",
},
Responses: map[int][]framework.Response{
http.StatusOK: {{
Description: "OK",
Fields: autoTidyResponseFields,
}},
},
},
logical.UpdateOperation: &framework.PathOperation{
Callback: b.pathConfigAutoTidyWrite,
DisplayAttrs: &framework.DisplayAttributes{
OperationVerb: "configure",
OperationSuffix: "auto-tidy",
},
Responses: map[int][]framework.Response{
http.StatusOK: {{
Description: "OK",
Fields: autoTidyResponseFields,
}},
},
// Read more about why these flags are set in backend.go.
ForwardPerformanceStandby: true,
ForwardPerformanceSecondary: true,
},
},
HelpSynopsis: pathConfigAutoTidySyn,
HelpDescription: pathConfigAutoTidyDesc,
}
}
func (b *backend) pathTidyWrite(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
safetyBuffer := d.Get("safety_buffer").(int)
tidyCertStore := d.Get("tidy_cert_store").(bool)
tidyRevokedCerts := d.Get("tidy_revoked_certs").(bool) || d.Get("tidy_revocation_list").(bool)
tidyRevokedAssocs := d.Get("tidy_revoked_cert_issuer_associations").(bool)
tidyExpiredIssuers := d.Get("tidy_expired_issuers").(bool)
tidyBackupBundle := d.Get("tidy_move_legacy_ca_bundle").(bool)
issuerSafetyBuffer := d.Get("issuer_safety_buffer").(int)
pauseDurationStr := d.Get("pause_duration").(string)
pauseDuration := 0 * time.Second
tidyRevocationQueue := d.Get("tidy_revocation_queue").(bool)
queueSafetyBuffer := d.Get("revocation_queue_safety_buffer").(int)
tidyCrossRevokedCerts := d.Get("tidy_cross_cluster_revoked_certs").(bool)
tidyAcme := d.Get("tidy_acme").(bool)
acmeAccountSafetyBuffer := d.Get("acme_account_safety_buffer").(int)
tidyCertMetadata := d.Get("tidy_cert_metadata").(bool)
tidyCMPV2NonceStore := d.Get("tidy_cmpv2_nonce_store").(bool)
if safetyBuffer < 1 {
return logical.ErrorResponse("safety_buffer must be greater than zero"), nil
}
if issuerSafetyBuffer < 1 {
return logical.ErrorResponse("issuer_safety_buffer must be greater than zero"), nil
}
if queueSafetyBuffer < 1 {
return logical.ErrorResponse("revocation_queue_safety_buffer must be greater than zero"), nil
}
if acmeAccountSafetyBuffer < 1 {
return logical.ErrorResponse("acme_account_safety_buffer must be greater than zero"), nil
}
if pauseDurationStr != "" {
var err error
pauseDuration, err = parseutil.ParseDurationSecond(pauseDurationStr)
if err != nil {
return logical.ErrorResponse(fmt.Sprintf("Error parsing pause_duration: %v", err)), nil
}
if pauseDuration < (0 * time.Second) {
return logical.ErrorResponse("received invalid, negative pause_duration"), nil
}
}
if tidyCertMetadata && !constants.IsEnterprise {
return logical.ErrorResponse("certificate metadata is only supported on Vault Enterprise"), nil
}
bufferDuration := time.Duration(safetyBuffer) * time.Second
issuerBufferDuration := time.Duration(issuerSafetyBuffer) * time.Second
queueSafetyBufferDuration := time.Duration(queueSafetyBuffer) * time.Second
acmeAccountSafetyBufferDuration := time.Duration(acmeAccountSafetyBuffer) * time.Second
// Manual run with constructed configuration.
config := &tidyConfig{
Enabled: true,
Interval: 0 * time.Second,
CertStore: tidyCertStore,
RevokedCerts: tidyRevokedCerts,
IssuerAssocs: tidyRevokedAssocs,
ExpiredIssuers: tidyExpiredIssuers,
BackupBundle: tidyBackupBundle,
SafetyBuffer: bufferDuration,
IssuerSafetyBuffer: issuerBufferDuration,
PauseDuration: pauseDuration,
RevocationQueue: tidyRevocationQueue,
QueueSafetyBuffer: queueSafetyBufferDuration,
CrossRevokedCerts: tidyCrossRevokedCerts,
TidyAcme: tidyAcme,
AcmeAccountSafetyBuffer: acmeAccountSafetyBufferDuration,
CertMetadata: tidyCertMetadata,
CMPV2NonceStore: tidyCMPV2NonceStore,
}
if !atomic.CompareAndSwapUint32(b.tidyCASGuard, 0, 1) {
resp := &logical.Response{}
resp.AddWarning("Tidy operation already in progress.")
return resp, nil
}
// Tests using framework will screw up the storage so make a locally
// scoped req to hold a reference
req = &logical.Request{
Storage: req.Storage,
}
resp := &logical.Response{}
// Mark the last tidy operation as relatively recent, to ensure we don't
// try to trigger the periodic function.
// NOTE: not sure this is correct as we are updating the auto tidy time with this manual run. Ideally we
// could track when we ran each type of tidy was last run which would allow manual runs and auto
// runs to properly impact each other.
sc := b.makeStorageContext(ctx, req.Storage)
if err := b.updateLastAutoTidyTime(sc, time.Now()); err != nil {
resp.AddWarning(fmt.Sprintf("failed persisting tidy last run time: %v", err))
}
// Kick off the actual tidy.
b.startTidyOperation(req, config)
if !config.IsAnyTidyEnabled() {
resp.AddWarning("Manual tidy requested but no tidy operations were set. Enable at least one tidy operation to be run (" + config.AnyTidyConfig() + ").")
} else {
resp.AddWarning("Tidy operation successfully started. Any information from the operation will be printed to Vault's server logs.")
}
if tidyRevocationQueue || tidyCrossRevokedCerts {
isNotPerfPrimary := b.System().ReplicationState().HasState(consts.ReplicationDRSecondary|consts.ReplicationPerformanceStandby) ||
(!b.System().LocalMount() && b.System().ReplicationState().HasState(consts.ReplicationPerformanceSecondary))
if isNotPerfPrimary {
resp.AddWarning("tidy_revocation_queue=true and tidy_cross_cluster_revoked_certs=true can only be set on the active node of the primary cluster unless a local mount is used; this option has been ignored.")
}
}
return logical.RespondWithStatusCode(resp, req, http.StatusAccepted)
}
func (b *backend) startTidyOperation(req *logical.Request, config *tidyConfig) {
go func() {
atomic.StoreUint32(b.tidyCancelCAS, 0)
defer atomic.StoreUint32(b.tidyCASGuard, 0)
b.tidyStatusStart(config)
// Don't cancel when the original client request goes away.
ctx := context.Background()
logger := b.Logger().Named("tidy")
doTidy := func() error {
if config.CertStore {
if err := b.doTidyCertStore(ctx, req, logger, config); err != nil {
return err
}
}
// Check for cancel before continuing.
if atomic.CompareAndSwapUint32(b.tidyCancelCAS, 1, 0) {
return tidyCancelledError
}
if config.RevokedCerts || config.IssuerAssocs {
if err := b.doTidyRevocationStore(ctx, req, logger, config); err != nil {
return err
}
}
// Check for cancel before continuing.
if atomic.CompareAndSwapUint32(b.tidyCancelCAS, 1, 0) {
return tidyCancelledError
}
if config.ExpiredIssuers {
if err := b.doTidyExpiredIssuers(ctx, req, logger, config); err != nil {
return err
}
}
// Check for cancel before continuing.
if atomic.CompareAndSwapUint32(b.tidyCancelCAS, 1, 0) {
return tidyCancelledError
}
if config.BackupBundle {
if err := b.doTidyMoveCABundle(ctx, req, logger, config); err != nil {
return err
}
}
// Check for cancel before continuing.
if atomic.CompareAndSwapUint32(b.tidyCancelCAS, 1, 0) {
return tidyCancelledError
}
if config.RevocationQueue {
if err := b.doTidyRevocationQueue(ctx, req, logger, config); err != nil {
return err
}
}
// Check for cancel before continuing.
if atomic.CompareAndSwapUint32(b.tidyCancelCAS, 1, 0) {
return tidyCancelledError
}
if config.CrossRevokedCerts {
if err := b.doTidyCrossRevocationStore(ctx, req, logger, config); err != nil {
return err
}
}
// Check for cancel before continuing.
if atomic.CompareAndSwapUint32(b.tidyCancelCAS, 1, 0) {
return tidyCancelledError
}
if config.TidyAcme {
if err := b.doTidyAcme(ctx, req, logger, config); err != nil {
return err
}
}
// Check for cancel before continuing.
if atomic.CompareAndSwapUint32(b.tidyCancelCAS, 1, 0) {
return tidyCancelledError
}
if config.CertMetadata {
if err := b.doTidyCertMetadata(ctx, req, logger, config); err != nil {
return err
}
}
// Check for cancel before continuing.
if atomic.CompareAndSwapUint32(b.tidyCancelCAS, 1, 0) {
return tidyCancelledError
}
if config.CMPV2NonceStore {
if err := b.doTidyCMPV2NonceStore(ctx, req.Storage); err != nil {
return err
}
}
return nil
}
if err := doTidy(); err != nil {
logger.Error("error running tidy", "error", err)
b.tidyStatusStop(err)
} else {
b.tidyStatusStop(nil)
// Since the tidy operation finished without an error, we don't
// really want to start another tidy right away (if the interval
// is too short). So mark the last tidy as now.
sc := b.makeStorageContext(ctx, req.Storage)
if err := b.updateLastAutoTidyTime(sc, time.Now()); err != nil {
logger.Error("error persisting last tidy run time", "error", err)
}
}
}()
}
func (b *backend) doTidyCertStore(ctx context.Context, req *logical.Request, logger hclog.Logger, config *tidyConfig) error {
serials, err := req.Storage.List(ctx, issuing.PathCerts)
if err != nil {
return fmt.Errorf("error fetching list of certs: %w", err)
}
serialCount := len(serials)
metrics.SetGauge([]string{"secrets", "pki", "tidy", "cert_store_total_entries"}, float32(serialCount))
for i, serial := range serials {
b.tidyStatusMessage(fmt.Sprintf("Tidying certificate store: checking entry %d of %d", i, serialCount))
metrics.SetGauge([]string{"secrets", "pki", "tidy", "cert_store_current_entry"}, float32(i))
// Check for cancel before continuing.
if atomic.CompareAndSwapUint32(b.tidyCancelCAS, 1, 0) {
return tidyCancelledError
}
// Check for pause duration to reduce resource consumption.
if config.PauseDuration > (0 * time.Second) {
time.Sleep(config.PauseDuration)
}
certEntry, err := req.Storage.Get(ctx, issuing.PathCerts+serial)
if err != nil {
return fmt.Errorf("error fetching certificate %q: %w", serial, err)
}
if certEntry == nil {
logger.Warn("certificate entry is nil; tidying up since it is no longer useful for any server operations", "serial", serial)
if err := req.Storage.Delete(ctx, issuing.PathCerts+serial); err != nil {
return fmt.Errorf("error deleting nil entry with serial %s: %w", serial, err)
}
b.tidyStatusIncCertStoreCount()
continue
}
if certEntry.Value == nil || len(certEntry.Value) == 0 {
logger.Warn("certificate entry has no value; tidying up since it is no longer useful for any server operations", "serial", serial)
if err := req.Storage.Delete(ctx, issuing.PathCerts+serial); err != nil {
return fmt.Errorf("error deleting entry with nil value with serial %s: %w", serial, err)
}
b.tidyStatusIncCertStoreCount()
continue
}
cert, err := x509.ParseCertificate(certEntry.Value)
if err != nil {
return fmt.Errorf("unable to parse stored certificate with serial %q: %w", serial, err)
}
if time.Since(cert.NotAfter) > config.SafetyBuffer {
if err := req.Storage.Delete(ctx, issuing.PathCerts+serial); err != nil {
return fmt.Errorf("error deleting serial %q from storage: %w", serial, err)
}
b.tidyStatusIncCertStoreCount()
}
}
b.tidyStatusLock.RLock()
metrics.SetGauge([]string{"secrets", "pki", "tidy", "cert_store_total_entries_remaining"}, float32(uint(serialCount)-b.tidyStatus.certStoreDeletedCount))
b.tidyStatusLock.RUnlock()
return nil
}
func (b *backend) doTidyRevocationStore(ctx context.Context, req *logical.Request, logger hclog.Logger, config *tidyConfig) error {
b.GetRevokeStorageLock().Lock()
defer b.GetRevokeStorageLock().Unlock()
// Fetch and parse our issuers so we can associate them if necessary.
sc := b.makeStorageContext(ctx, req.Storage)
issuerIDCertMap, err := revocation.FetchIssuerMapForRevocationChecking(sc)
if err != nil {
return err
}
rebuildCRL := false
revokedSerials, err := req.Storage.List(ctx, "revoked/")
if err != nil {
return fmt.Errorf("error fetching list of revoked certs: %w", err)
}
revokedSerialsCount := len(revokedSerials)
metrics.SetGauge([]string{"secrets", "pki", "tidy", "revoked_cert_total_entries"}, float32(revokedSerialsCount))
fixedIssuers := 0
var revInfo revocation.RevocationInfo
for i, serial := range revokedSerials {
b.tidyStatusMessage(fmt.Sprintf("Tidying revoked certificates: checking certificate %d of %d", i, len(revokedSerials)))
metrics.SetGauge([]string{"secrets", "pki", "tidy", "revoked_cert_current_entry"}, float32(i))
// Check for cancel before continuing.
if atomic.CompareAndSwapUint32(b.tidyCancelCAS, 1, 0) {
return tidyCancelledError
}
// Check for pause duration to reduce resource consumption.
if config.PauseDuration > (0 * time.Second) {
b.GetRevokeStorageLock().Unlock()
time.Sleep(config.PauseDuration)
b.GetRevokeStorageLock().Lock()
}
revokedEntry, err := req.Storage.Get(ctx, "revoked/"+serial)
if err != nil {
return fmt.Errorf("unable to fetch revoked cert with serial %q: %w", serial, err)
}
if revokedEntry == nil {
logger.Warn("revoked entry is nil; tidying up since it is no longer useful for any server operations", "serial", serial)
if err := req.Storage.Delete(ctx, "revoked/"+serial); err != nil {
return fmt.Errorf("error deleting nil revoked entry with serial %s: %w", serial, err)
}
b.tidyStatusIncRevokedCertCount()
continue
}
if revokedEntry.Value == nil || len(revokedEntry.Value) == 0 {
logger.Warn("revoked entry has nil value; tidying up since it is no longer useful for any server operations", "serial", serial)
if err := req.Storage.Delete(ctx, "revoked/"+serial); err != nil {
return fmt.Errorf("error deleting revoked entry with nil value with serial %s: %w", serial, err)
}
b.tidyStatusIncRevokedCertCount()
continue
}
err = revokedEntry.DecodeJSON(&revInfo)
if err != nil {
return fmt.Errorf("error decoding revocation entry for serial %q: %w", serial, err)
}
revokedCert, err := x509.ParseCertificate(revInfo.CertificateBytes)
if err != nil {
return fmt.Errorf("unable to parse stored revoked certificate with serial %q: %w", serial, err)
}
// Tidy operations over revoked certs should execute prior to
// tidyRevokedCerts as that may remove the entry. If that happens,
// we won't persist the revInfo changes (as it was deleted instead).
var storeCert bool
if config.IssuerAssocs {
if !isRevInfoIssuerValid(&revInfo, issuerIDCertMap) {
b.tidyStatusIncMissingIssuerCertCount()
revInfo.CertificateIssuer = issuing.IssuerID("")
storeCert = true
if revInfo.AssociateRevokedCertWithIsssuer(revokedCert, issuerIDCertMap) {
fixedIssuers += 1
}
}
}
if config.RevokedCerts {
// Only remove the entries from revoked/ and certs/ if we're
// past its NotAfter value. This is because we use the
// information on revoked/ to build the CRL and the
// information on certs/ for lookup.
if time.Since(revokedCert.NotAfter) > config.SafetyBuffer {
if err := req.Storage.Delete(ctx, "revoked/"+serial); err != nil {
return fmt.Errorf("error deleting serial %q from revoked list: %w", serial, err)
}
if err := req.Storage.Delete(ctx, issuing.PathCerts+serial); err != nil {