This repository has been archived by the owner on Jul 12, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 83
/
migrations.go
2611 lines (2468 loc) · 80.1 KB
/
migrations.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 2020 the Exposure Notifications Verification Server authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package database
import (
"context"
"fmt"
"strings"
"time"
"github.com/google/exposure-notifications-server/pkg/logging"
"github.com/google/exposure-notifications-verification-server/pkg/rbac"
"github.com/jinzhu/gorm"
"gopkg.in/gormigrate.v1"
)
const (
initState = "00000-Init"
VerCodesCodeUniqueIndex = "uix_verification_codes_realm_code"
VerCodesLongCodeUniqueIndex = "uix_verification_codes_realm_long_code"
)
func (db *Database) Migrations(ctx context.Context) []*gormigrate.Migration {
logger := logging.FromContext(ctx)
return []*gormigrate.Migration{
{
ID: initState,
Migrate: func(tx *gorm.DB) error {
// Create required extensions on new DB so AutoMigrate doesn't fail.
return tx.Exec("CREATE EXTENSION IF NOT EXISTS hstore").Error
},
Rollback: func(tx *gorm.DB) error {
return nil
},
},
{
ID: "00001-CreateUsers",
Migrate: func(tx *gorm.DB) error {
// This is "out of order" as it were, but is needed to bootstrap fresh systems.
// Also in migration 8
if err := tx.AutoMigrate(&Realm{}).Error; err != nil {
return err
}
return tx.AutoMigrate(&User{}).Error
},
Rollback: func(tx *gorm.DB) error {
if err := tx.DropTable("users").Error; err != nil {
return err
}
return tx.DropTable("realms").Error
},
},
{
ID: "00002-CreateVerificationCodes",
Migrate: func(tx *gorm.DB) error {
return tx.AutoMigrate(&VerificationCode{}).Error
},
Rollback: func(tx *gorm.DB) error {
return tx.DropTable("verification_codes").Error
},
},
{
ID: "00003-CreateAuthorizedApps",
Migrate: func(tx *gorm.DB) error {
return tx.AutoMigrate(&AuthorizedApp{}).Error
},
Rollback: func(tx *gorm.DB) error {
return tx.DropTable("authorized_apps").Error
},
},
{
ID: "00004-CreateTokens",
Migrate: func(tx *gorm.DB) error {
return tx.AutoMigrate(&Token{}).Error
},
Rollback: func(tx *gorm.DB) error {
return tx.DropTable("tokens").Error
},
},
{
ID: "00005-CreateCleanups",
Migrate: func(tx *gorm.DB) error {
// CleanupStatus is the model that existed at the time of this
// migration.
type CleanupStatus struct {
gorm.Model
Type string `gorm:"type:varchar(50);unique_index"`
Generation uint
NotBefore time.Time
}
if err := tx.AutoMigrate(&CleanupStatus{}).Error; err != nil {
return err
}
// Seed database w/ cleanup record.
if err := tx.Create(&CleanupStatus{Type: "cleanup", Generation: 1, NotBefore: time.Now()}).Error; err != nil {
return err
}
return nil
},
Rollback: func(tx *gorm.DB) error {
return tx.DropTable("cleanup_statuses").Error
},
},
{
ID: "00006-AddIndexes",
Migrate: func(tx *gorm.DB) error {
if err := tx.Model(&User{}).AddIndex("users_purge_index", "updated_at").Error; err != nil {
return err
}
if err := tx.Model(&VerificationCode{}).AddIndex("ver_code_purge_index", "expires_at").Error; err != nil {
return err
}
if err := tx.Model(&VerificationCode{}).AddIndex("token_purge_index", "expires_at").Error; err != nil {
return err
}
return nil
},
Rollback: func(tx *gorm.DB) error {
if err := tx.Model(&User{}).RemoveIndex("users_purge_index").Error; err != nil {
return err
}
if err := tx.Model(&VerificationCode{}).RemoveIndex("ver_code_purge_index").Error; err != nil {
return err
}
if err := tx.Model(&VerificationCode{}).RemoveIndex("token_purge_index").Error; err != nil {
return err
}
return nil
},
},
{
ID: "00007-AddSymptomOnset",
Migrate: func(tx *gorm.DB) error {
// AutoMigrate will add missing fields.
if err := tx.AutoMigrate(&VerificationCode{}).Error; err != nil {
return err
}
// If not upgrading from an old version, this column will have never been created.
if tx.NewScope(&VerificationCode{}).HasColumn("test_date") {
if err := tx.Model(&VerificationCode{}).DropColumn("test_date").Error; err != nil {
return err
}
}
if err := tx.AutoMigrate(&Token{}).Error; err != nil {
return err
}
// If not upgrading from an old version, this column will have never been created.
if tx.NewScope(&Token{}).HasColumn("test_date") {
if err := tx.Model(&Token{}).DropColumn("test_date").Error; err != nil {
return err
}
}
return nil
},
Rollback: func(tx *gorm.DB) error {
if err := tx.Model(&VerificationCode{}).DropColumn("symptom_date").Error; err != nil {
return err
}
if err := tx.Model(&Token{}).DropColumn("symptom_date").Error; err != nil {
return err
}
return nil
},
},
{
ID: "00008-AddKeyTypes",
Migrate: func(tx *gorm.DB) error {
return tx.AutoMigrate(&AuthorizedApp{}).Error
},
Rollback: func(tx *gorm.DB) error {
if err := tx.Model(&AuthorizedApp{}).DropColumn("admin_key").Error; err != nil {
return err
}
return nil
},
},
{
ID: "00009-AddIssuerColumns",
Migrate: func(tx *gorm.DB) error {
return tx.AutoMigrate(&VerificationCode{}).Error
},
Rollback: func(tx *gorm.DB) error {
if err := tx.Model(&VerificationCode{}).DropColumn("issuing_user").Error; err != nil {
return err
}
if err := tx.Model(&VerificationCode{}).DropColumn("issuing_app").Error; err != nil {
return err
}
return nil
},
},
{
ID: "00010-AddSMSConfig",
Migrate: func(tx *gorm.DB) error {
return tx.AutoMigrate(&SMSConfig{}).Error
},
Rollback: func(tx *gorm.DB) error {
return tx.DropTable("sms_configs").Error
},
},
{
ID: "00011-AddRealms",
Migrate: func(tx *gorm.DB) error {
// Add the realms table.
if err := tx.AutoMigrate(&Realm{}).Error; err != nil {
return err
}
// Create the default realm with all of the default settings.
defaultRealm := NewRealmWithDefaults("Default")
defaultRealm.RequireDate = false
if err := tx.FirstOrCreate(defaultRealm).Error; err != nil {
return err
}
// Add realm relations to the rest of the tables.
if err := tx.AutoMigrate(&User{}).Error; err != nil {
return err
}
var users []*User
if err := tx.Find(&users).Error; err != nil {
return err
}
for _, u := range users {
permission := rbac.LegacyRealmUser
if u.SystemAdmin {
permission = rbac.LegacyRealmAdmin
}
if err := u.AddToRealm(db, defaultRealm, permission, System); err != nil {
return err
}
}
if err := tx.AutoMigrate(&AuthorizedApp{}).Error; err != nil {
return err
}
var authApps []*AuthorizedApp
if err := tx.Unscoped().Find(&authApps).Error; err != nil {
return err
}
for _, a := range authApps {
a.RealmID = defaultRealm.ID
if err := tx.Save(a).Error; err != nil {
return err
}
}
if err := tx.AutoMigrate(&VerificationCode{}).Error; err != nil {
return err
}
if err := tx.Exec("UPDATE verification_codes SET realm_id=?", defaultRealm.ID).Error; err != nil {
return err
}
if err := tx.AutoMigrate(&Token{}).Error; err != nil {
return err
}
if err := tx.Exec("UPDATE tokens SET realm_id=?", defaultRealm.ID).Error; err != nil {
return err
}
if err := tx.AutoMigrate(&SMSConfig{}).Error; err != nil {
return err
}
if err := tx.Exec("UPDATE sms_configs SET realm_id=?", defaultRealm.ID).Error; err != nil {
return err
}
return nil
},
Rollback: func(tx *gorm.DB) error {
ddl := []string{
"ALTER TABLE sms_configs DROP COLUMN IF EXISTS realm_id",
"ALTER TABLE tokens DROP COLUMN IF EXISTS realm_id",
"ALTER TABLE verification_codes DROP COLUMN IF EXISTS realm_id",
"ALTER TABLE authorized_apps DROP COLUMN IF EXISTS realm_id",
"DROP TABLE admin_realms",
"DROP TABLE user_realms",
"DROP TABLE realms",
}
for _, stmt := range ddl {
if err := tx.Exec(stmt).Error; err != nil {
return fmt.Errorf("unable to execute '%v': %w", stmt, err)
}
}
return nil
},
},
{
ID: "00012-DropAuthorizedAppUniqueNameIndex",
Migrate: func(tx *gorm.DB) error {
sql := "DROP INDEX IF EXISTS uix_authorized_apps_name"
if err := tx.Exec(sql).Error; err != nil {
return err
}
return nil
},
Rollback: func(tx *gorm.DB) error {
return nil
},
},
{
ID: "00013-AddCompositeIndexOnAuthorizedApp",
Migrate: func(tx *gorm.DB) error {
if err := tx.AutoMigrate(&AuthorizedApp{}).Error; err != nil {
return err
}
return nil
},
Rollback: func(tx *gorm.DB) error {
return nil
},
},
{
ID: "00014-DropUserPurgeIndex",
Migrate: func(tx *gorm.DB) error {
sql := "DROP INDEX IF EXISTS users_purge_index"
return tx.Exec(sql).Error
},
Rollback: func(tx *gorm.DB) error {
return tx.Model(&User{}).AddIndex("users_purge_index", "updated_at").Error
},
},
{
ID: "00015-DropUserDisabled",
Migrate: func(tx *gorm.DB) error {
sql := "ALTER TABLE users DROP COLUMN IF EXISTS disabled"
return tx.Exec(sql).Error
},
Rollback: func(tx *gorm.DB) error {
sql := "ALTER TABLE users ADD COLUMN disabled bool NOT NULL DEFAULT true"
return tx.Exec(sql).Error
},
},
{
ID: "00016-MigrateSMSConfigs",
Migrate: func(tx *gorm.DB) error {
var sms SMSConfig
rows, err := tx.Model(&SMSConfig{}).Rows()
if err != nil {
return err
}
defer rows.Close()
for rows.Next() {
if err := tx.ScanRows(rows, &sms); err != nil {
return err
}
// Convert from secret manager -> kms.
if strings.HasPrefix(sms.TwilioAuthToken, "projects/") {
// Get the secret
val, err := db.secretManager.GetSecretValue(ctx, sms.TwilioAuthToken)
if err != nil {
return err
}
// Save the plaintext back on the model. The model's hook will
// encrypt this with the KMS configuration.
sms.TwilioAuthToken = val
if err := db.SaveSMSConfig(&sms); err != nil {
return err
}
}
}
return nil
},
Rollback: func(tx *gorm.DB) error {
return nil
},
},
{
ID: "00017-AddIssuerIDColumns",
Migrate: func(tx *gorm.DB) error {
err := tx.AutoMigrate(&VerificationCode{}, &UserStat{}, &AuthorizedAppStat{}).Error
return err
},
Rollback: func(tx *gorm.DB) error {
if tx.NewScope(&VerificationCode{}).HasColumn("issuing_user_id") {
if err := tx.Model(&VerificationCode{}).DropColumn("issuing_user_id").Error; err != nil {
return err
}
}
if tx.NewScope(&VerificationCode{}).HasColumn("issuing_app_id") {
if err := tx.Model(&VerificationCode{}).DropColumn("issuing_app_id").Error; err != nil {
return err
}
}
if err := tx.DropTableIfExists(&UserStat{}).Error; err != nil {
return err
}
return nil
},
},
{
ID: "00018-IncreaseAPIKeySize",
Migrate: func(tx *gorm.DB) error {
sql := "ALTER TABLE authorized_apps ALTER COLUMN api_key TYPE varchar(512)"
return tx.Exec(sql).Error
},
Rollback: func(tx *gorm.DB) error {
sql := "ALTER TABLE authorized_apps ALTER COLUMN api_key TYPE varchar(100)"
return tx.Exec(sql).Error
},
},
{
ID: "00019-AddAPIKeyPreviewAuthApp",
Migrate: func(tx *gorm.DB) error {
return tx.AutoMigrate(AuthorizedApp{}).Error
},
Rollback: func(tx *gorm.DB) error {
return nil
},
},
{
ID: "00020-HMACAPIKeys",
Migrate: func(tx *gorm.DB) error {
var apps []AuthorizedApp
if err := tx.Model(AuthorizedApp{}).Find(&apps).Error; err != nil {
return err
}
for _, app := range apps {
app := app
// If the key has a preview, it's v2
if app.APIKeyPreview != "" {
continue
}
apiKeyPreview := app.APIKey[:6]
newAPIKey, err := db.GenerateAPIKeyHMAC(app.APIKey)
if err != nil {
return fmt.Errorf("failed to hmac %v: %w", app.Name, err)
}
app.APIKey = newAPIKey
app.APIKeyPreview = apiKeyPreview
if err := db.db.Save(&app).Error; err != nil {
return fmt.Errorf("failed to save %v: %w", app.Name, err)
}
}
return nil
},
Rollback: func(tx *gorm.DB) error {
return nil
},
},
{
ID: "00021-AddUUIDExtension",
Migrate: func(tx *gorm.DB) error {
return tx.Exec("CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\"").Error
},
Rollback: func(tx *gorm.DB) error {
return nil
},
},
{
ID: "00022-AddUUIDToVerificationCodes",
Migrate: func(tx *gorm.DB) error {
if err := tx.AutoMigrate(VerificationCode{}).Error; err != nil {
return fmt.Errorf("failed to auto migrate: %w", err)
}
if err := tx.Exec("ALTER TABLE verification_codes ALTER COLUMN uuid SET DEFAULT uuid_generate_v4()").Error; err != nil {
return fmt.Errorf("failed to set default: %w", err)
}
if err := tx.Exec("UPDATE verification_codes SET uuid = uuid_generate_v4() WHERE uuid IS NULL").Error; err != nil {
return fmt.Errorf("failed to add defaults: %w", err)
}
return nil
},
Rollback: func(tx *gorm.DB) error {
if err := tx.Exec("ALTER TABLE verification_codes ALTER COLUMN uuid DROP DEFAULT").Error; err != nil {
return fmt.Errorf("failed to set default: %w", err)
}
return nil
},
},
{
ID: "00023-MakeUUIDVerificationCodesNotNull",
Migrate: func(tx *gorm.DB) error {
if err := tx.Exec("ALTER TABLE verification_codes ALTER COLUMN uuid SET NOT NULL").Error; err != nil {
return fmt.Errorf("failed to set null: %w", err)
}
return nil
},
Rollback: func(tx *gorm.DB) error {
if err := tx.Exec("ALTER TABLE verification_codes ALTER COLUMN uuid DROP NOT NULL").Error; err != nil {
return fmt.Errorf("failed to set null: %w", err)
}
return nil
},
},
{
ID: "00024-AddTestTypesToRealms",
Migrate: func(tx *gorm.DB) error {
sql := fmt.Sprintf("ALTER TABLE realms ADD COLUMN IF NOT EXISTS allowed_test_types INTEGER DEFAULT %d",
TestTypeConfirmed|TestTypeLikely|TestTypeNegative)
if err := tx.Exec(sql).Error; err != nil {
return err
}
return nil
},
Rollback: func(tx *gorm.DB) error {
if err := tx.Exec("ALTER TABLE realms DROP COLUMN IF EXISTS allowed_test_types").Error; err != nil {
return err
}
return nil
},
},
{
ID: "00025-SetTestTypesNotNull",
Migrate: func(tx *gorm.DB) error {
if err := tx.Exec("ALTER TABLE realms ALTER COLUMN allowed_test_types SET NOT NULL").Error; err != nil {
return err
}
return nil
},
Rollback: func(tx *gorm.DB) error {
if err := tx.Exec("ALTER TABLE realms ALTER COLUMN allowed_test_types DROP NOT NULL").Error; err != nil {
return err
}
return nil
},
},
{
ID: "00026-EnableExtension_citext",
Migrate: func(tx *gorm.DB) error {
return tx.Exec("CREATE EXTENSION citext").Error
},
Rollback: func(tx *gorm.DB) error {
return tx.Exec("DROP EXTENSION citext").Error
},
},
{
ID: "00027-AlterColumns_citext",
Migrate: func(tx *gorm.DB) error {
sqls := []string{
"ALTER TABLE authorized_apps ALTER COLUMN name TYPE CITEXT",
"ALTER TABLE realms ALTER COLUMN name TYPE CITEXT",
"ALTER TABLE users ALTER COLUMN email TYPE CITEXT",
}
for _, sql := range sqls {
if err := tx.Exec(sql).Error; err != nil {
return err
}
}
return nil
},
Rollback: func(tx *gorm.DB) error {
sqls := []string{
"ALTER TABLE authorized_apps ALTER COLUMN name TYPE TEXT",
"ALTER TABLE realms ALTER COLUMN name TYPE TEXT",
"ALTER TABLE users ALTER COLUMN email TYPE TEXT",
}
for _, sql := range sqls {
if err := tx.Exec(sql).Error; err != nil {
return err
}
}
return nil
},
},
{
ID: "00028-AddSMSDeeplinkFields",
Migrate: func(tx *gorm.DB) error {
// long_code cannot be auto migrated because of unique index.
// manually create long_code and long_expires_at and backfill with existing data.
sqls := []string{
"ALTER TABLE verification_codes ADD COLUMN IF NOT EXISTS long_code VARCHAR(20)",
"UPDATE verification_codes SET long_code = code",
"CREATE UNIQUE INDEX IF NOT EXISTS uix_verification_codes_long_code ON verification_codes(long_code)",
"ALTER TABLE verification_codes ALTER COLUMN long_code SET NOT NULL",
"ALTER TABLE verification_codes ADD COLUMN IF NOT EXISTS long_expires_at TIMESTAMPTZ",
"UPDATE verification_codes SET long_expires_at = expires_at",
}
for _, stmt := range sqls {
if err := tx.Exec(stmt).Error; err != nil {
return fmt.Errorf("unable to execute '%v': %w", stmt, err)
}
}
if err := tx.AutoMigrate(&Realm{}).Error; err != nil {
return err
}
if err := tx.AutoMigrate(&VerificationCode{}).Error; err != nil {
return err
}
if err := tx.Model(&VerificationCode{}).AddIndex("ver_code_long_purge_index", "long_expires_at").Error; err != nil {
return err
}
return nil
},
Rollback: func(tx *gorm.DB) error {
dropColumns := []string{
"long_code_length",
"long_code_duration",
"region_code",
"code_length",
"code_duration",
"sms_text_template",
}
for _, col := range dropColumns {
stmt := fmt.Sprintf("ALTER TABLE realms DROP COLUMN IF EXISTS %s", col)
if err := tx.Exec(stmt).Error; err != nil {
return fmt.Errorf("unable to execute '%v': %w", stmt, err)
}
}
return nil
},
},
{
ID: "00029-IncreaseVerificationCodeSizes",
Migrate: func(tx *gorm.DB) error {
sqls := []string{
"ALTER TABLE verification_codes ALTER COLUMN code TYPE varchar(512)",
"ALTER TABLE verification_codes ALTER COLUMN long_code TYPE varchar(512)",
}
for _, sql := range sqls {
if err := tx.Exec(sql).Error; err != nil {
return err
}
}
return nil
},
Rollback: func(tx *gorm.DB) error {
// No rollback for this, which would destroy data.
return nil
},
},
{
ID: "00030-HMACCodes",
Migrate: func(tx *gorm.DB) error {
if err := tx.AutoMigrate(&Realm{}).Error; err != nil {
return err
}
var codes []VerificationCode
if err := tx.Model(VerificationCode{}).Find(&codes).Error; err != nil {
return err
}
for _, code := range codes {
code := code
changed := false
// Sanity
if len(code.Code) < 20 {
h, err := db.GenerateVerificationCodeHMAC(code.Code)
if err != nil {
return err
}
code.Code = h
changed = true
}
// Sanity
if len(code.LongCode) < 20 {
h, err := db.GenerateVerificationCodeHMAC(code.LongCode)
if err != nil {
return err
}
code.LongCode = h
changed = true
}
if changed {
if err := tx.Save(&code).Error; err != nil {
return fmt.Errorf("failed to save code %v: %w", code.ID, err)
}
}
}
return nil
},
Rollback: func(tx *gorm.DB) error {
return nil
},
},
{
ID: "00031-AlterStatsColumns",
Migrate: func(tx *gorm.DB) error {
sqls := []string{
// AuthorizedApps
"CREATE UNIQUE INDEX IF NOT EXISTS idx_authorized_app_stats_date_authorized_app_id ON authorized_app_stats (date, authorized_app_id)",
"DROP INDEX IF EXISTS idx_date_app_realm",
"DROP INDEX IF EXISTS idx_authorized_app_stats_deleted_at",
"CREATE INDEX IF NOT EXISTS idx_authorized_app_stats_date ON authorized_app_stats (date)",
"ALTER TABLE authorized_app_stats DROP COLUMN IF EXISTS id",
"ALTER TABLE authorized_app_stats DROP COLUMN IF EXISTS created_at",
"ALTER TABLE authorized_app_stats DROP COLUMN IF EXISTS updated_at",
"ALTER TABLE authorized_app_stats DROP COLUMN IF EXISTS deleted_at",
"ALTER TABLE authorized_app_stats DROP COLUMN IF EXISTS realm_id",
"ALTER TABLE authorized_app_stats ALTER COLUMN date TYPE date",
"ALTER TABLE authorized_app_stats ALTER COLUMN date SET NOT NULL",
"ALTER TABLE authorized_app_stats ALTER COLUMN authorized_app_id SET NOT NULL",
"ALTER TABLE authorized_app_stats ALTER COLUMN codes_issued TYPE INTEGER",
"ALTER TABLE authorized_app_stats ALTER COLUMN codes_issued SET DEFAULT 0",
"ALTER TABLE authorized_app_stats ALTER COLUMN codes_issued SET NOT NULL",
// Users
"CREATE UNIQUE INDEX IF NOT EXISTS idx_user_stats_date_realm_id_user_id ON user_stats (date, realm_id, user_id)",
"DROP INDEX IF EXISTS idx_date_user_realm",
"DROP INDEX IF EXISTS idx_user_stats_deleted_at",
"CREATE INDEX IF NOT EXISTS idx_user_stats_date ON user_stats (date)",
"ALTER TABLE user_stats DROP COLUMN IF EXISTS id",
"ALTER TABLE user_stats DROP COLUMN IF EXISTS created_at",
"ALTER TABLE user_stats DROP COLUMN IF EXISTS updated_at",
"ALTER TABLE user_stats DROP COLUMN IF EXISTS deleted_at",
"ALTER TABLE user_stats ALTER COLUMN date TYPE date",
"ALTER TABLE user_stats ALTER COLUMN date SET NOT NULL",
"ALTER TABLE user_stats ALTER COLUMN realm_id SET NOT NULL",
"ALTER TABLE user_stats ALTER COLUMN user_id SET NOT NULL",
"ALTER TABLE user_stats ALTER COLUMN codes_issued TYPE INTEGER",
"ALTER TABLE user_stats ALTER COLUMN codes_issued SET DEFAULT 0",
"ALTER TABLE user_stats ALTER COLUMN codes_issued SET NOT NULL",
}
for _, sql := range sqls {
if err := tx.Exec(sql).Error; err != nil {
return fmt.Errorf("%s: %w", sql, err)
}
}
return nil
},
Rollback: func(tx *gorm.DB) error {
return nil
},
},
{
ID: "00032-RegionCodeSize",
Migrate: func(tx *gorm.DB) error {
sqls := []string{
"ALTER TABLE realms ALTER COLUMN region_code TYPE varchar(10)",
}
for _, sql := range sqls {
if err := tx.Exec(sql).Error; err != nil {
return err
}
}
return nil
},
Rollback: func(tx *gorm.DB) error {
return nil
},
},
{
ID: "00033-PerlRealmSigningKeys",
Migrate: func(tx *gorm.DB) error {
if err := tx.AutoMigrate(&Realm{}).Error; err != nil {
return err
}
if err := tx.AutoMigrate(&SigningKey{}).Error; err != nil {
return err
}
return nil
},
Rollback: func(tx *gorm.DB) error {
// SigningKeys table left in place so references to crypto keys aren't lost.
return nil
},
},
{
ID: "00034-AddENExpressSettings",
Migrate: func(tx *gorm.DB) error {
if err := tx.AutoMigrate(&Realm{}).Error; err != nil {
return err
}
return nil
},
Rollback: func(tx *gorm.DB) error {
return nil
},
},
{
ID: "00035-AddMFARequiredToRealms",
Migrate: func(tx *gorm.DB) error {
return tx.Exec("ALTER TABLE realms ADD COLUMN IF NOT EXISTS mfa_mode INTEGER DEFAULT 0").Error
},
Rollback: func(tx *gorm.DB) error {
return tx.Exec("ALTER TABLE realms DROP COLUMN IF EXISTS mfa_mode").Error
},
},
{
ID: "00036-AddRealmStats",
Migrate: func(tx *gorm.DB) error {
if err := tx.AutoMigrate(&RealmStat{}).Error; err != nil {
return err
}
statements := []string{
"CREATE UNIQUE INDEX IF NOT EXISTS idx_realm_stats_stats_date_realm_id ON realm_stats (date, realm_id)",
"CREATE INDEX IF NOT EXISTS idx_realm_stats_date ON realm_stats (date)",
}
for _, sql := range statements {
if err := tx.Exec(sql).Error; err != nil {
return err
}
}
return nil
},
Rollback: func(tx *gorm.DB) error {
if err := tx.DropTable(&RealmStat{}).Error; err != nil {
return err
}
return nil
},
},
{
ID: "00037-AddRealmRequireDate",
Migrate: func(tx *gorm.DB) error {
return tx.Exec("ALTER TABLE realms ADD COLUMN IF NOT EXISTS require_date bool DEFAULT false").Error
},
Rollback: func(tx *gorm.DB) error {
return tx.Exec("ALTER TABLE realms DROP COLUMN IF EXISTS require_date").Error
},
},
{
ID: "00038-AddRealmRequireDateNotNull",
Migrate: func(tx *gorm.DB) error {
return tx.Exec("ALTER TABLE realms ALTER COLUMN require_date SET NOT NULL").Error
},
Rollback: func(tx *gorm.DB) error {
return tx.Exec("ALTER TABLE realms ALTER COLUMN require_date SET NULL").Error
},
},
{
ID: "00039-RealmStatsToDate",
Migrate: func(tx *gorm.DB) error {
return tx.Exec("ALTER TABLE realm_stats ALTER COLUMN date TYPE date").Error
},
Rollback: func(tx *gorm.DB) error {
return tx.Exec("ALTER TABLE realm_stats ALTER COLUMN date TYPE timestamp with time zone").Error
},
},
{
ID: "00040-BackfillRealmStats",
Migrate: func(tx *gorm.DB) error {
sqls := []string{
`
INSERT INTO realm_stats (
SELECT date, realm_id, SUM(codes_issued) AS codes_issued
FROM user_stats
WHERE user_stats.date < date('2020-09-15')
GROUP BY 1, 2
ORDER BY 1 DESC
) ON CONFLICT(date, realm_id) DO UPDATE
SET codes_issued = realm_stats.codes_issued + excluded.codes_issued
`,
`
INSERT INTO realm_stats (
SELECT date, authorized_apps.realm_id AS realm_id, SUM(codes_issued) AS codes_issued
FROM authorized_app_stats
JOIN authorized_apps
ON authorized_app_stats.authorized_app_id = authorized_apps.id
WHERE authorized_app_stats.date < date('2020-09-15')
GROUP BY 1, 2
ORDER BY 1 DESC
) ON CONFLICT(date, realm_id) DO UPDATE
SET codes_issued = realm_stats.codes_issued + excluded.codes_issued
`,
}
for _, sql := range sqls {
if err := tx.Exec(sql).Error; err != nil {
return err
}
}
return nil
},
Rollback: func(tx *gorm.DB) error {
return nil
},
},
{
ID: "00041-AddRealmAbusePrevention",
Migrate: func(tx *gorm.DB) error {
sqls := []string{
`ALTER TABLE realms ADD COLUMN IF NOT EXISTS abuse_prevention_enabled bool NOT NULL DEFAULT false`,
`ALTER TABLE realms ADD COLUMN IF NOT EXISTS abuse_prevention_limit integer NOT NULL DEFAULT 100`,
`ALTER TABLE realms ADD COLUMN IF NOT EXISTS abuse_prevention_limit_factor numeric(8, 5) NOT NULL DEFAULT 1.0`,
}
for _, sql := range sqls {
if err := tx.Exec(sql).Error; err != nil {
return err
}
}
return nil
},
Rollback: func(tx *gorm.DB) error {
sqls := []string{
`ALTER TABLE realms DROP COLUMN IF EXISTS abuse_prevention_enabled`,
`ALTER TABLE realms DROP COLUMN IF EXISTS abuse_prevention_limit`,
`ALTER TABLE realms DROP COLUMN IF EXISTS abuse_prevention_limit_factor`,
}
for _, sql := range sqls {
if err := tx.Exec(sql).Error; err != nil {
return err
}
}
return nil
},
},
{
ID: "00042-ChangeRealmAbusePreventionLimitDefault",
Migrate: func(tx *gorm.DB) error {
sqls := []string{
`ALTER TABLE realms ALTER COLUMN abuse_prevention_limit SET DEFAULT 10`,
}
for _, sql := range sqls {
if err := tx.Exec(sql).Error; err != nil {
return err
}
}
return nil
},
Rollback: func(tx *gorm.DB) error {
sqls := []string{
`ALTER TABLE realms ALTER COLUMN abuse_prevention_limit SET DEFAULT 100`,
}
for _, sql := range sqls {
if err := tx.Exec(sql).Error; err != nil {
return err
}
}
return nil
},
},
{
ID: "00043-CreateModelerStatus",
Migrate: func(tx *gorm.DB) error {
// ModelerStatus is the legacy definition that existed when this
// migration first existed.
type ModelerStatus struct {
ID uint `gorm:"primary_key"`
NotBefore time.Time
}
if err := tx.AutoMigrate(&ModelerStatus{}).Error; err != nil {
return err
}
if err := tx.Create(&ModelerStatus{}).Error; err != nil {
return err
}
return nil
},
Rollback: func(tx *gorm.DB) error {
return tx.DropTable("modeler_statuses").Error
},
},
{
ID: "00044-AddEmailVerifiedRequiredToRealms",
Migrate: func(tx *gorm.DB) error {
return tx.Exec("ALTER TABLE realms ADD COLUMN IF NOT EXISTS email_verified_mode INTEGER DEFAULT 0").Error
},
Rollback: func(tx *gorm.DB) error {
return tx.Exec("ALTER TABLE realms DROP COLUMN IF EXISTS email_verified_mode").Error
},