-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcoverage.html
More file actions
3843 lines (3221 loc) · 171 KB
/
Copy pathcoverage.html
File metadata and controls
3843 lines (3221 loc) · 171 KB
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
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>omg: Go Coverage Report</title>
<style>
body {
background: black;
color: rgb(80, 80, 80);
}
body, pre, #legend span {
font-family: Menlo, monospace;
font-weight: bold;
}
#topbar {
background: black;
position: fixed;
top: 0; left: 0; right: 0;
height: 42px;
border-bottom: 1px solid rgb(80, 80, 80);
}
#content {
margin-top: 50px;
}
#nav, #legend {
float: left;
margin-left: 10px;
}
#legend {
margin-top: 12px;
}
#nav {
margin-top: 10px;
}
#legend span {
margin: 0 5px;
}
.cov0 { color: rgb(192, 0, 0) }
.cov1 { color: rgb(128, 128, 128) }
.cov2 { color: rgb(116, 140, 131) }
.cov3 { color: rgb(104, 152, 134) }
.cov4 { color: rgb(92, 164, 137) }
.cov5 { color: rgb(80, 176, 140) }
.cov6 { color: rgb(68, 188, 143) }
.cov7 { color: rgb(56, 200, 146) }
.cov8 { color: rgb(44, 212, 149) }
.cov9 { color: rgb(32, 224, 152) }
.cov10 { color: rgb(20, 236, 155) }
</style>
</head>
<body>
<div id="topbar">
<div id="nav">
<select id="files">
<option value="file0">github.com/demetere/omg/cmd/omg/main.go (0.0%)</option>
<option value="file1">github.com/demetere/omg/internal/testhelpers/testhelpers.go (0.0%)</option>
<option value="file2">github.com/demetere/omg/migrations/00000000000000_example.go (0.0%)</option>
<option value="file3">github.com/demetere/omg/pkg/client.go (54.3%)</option>
<option value="file4">github.com/demetere/omg/pkg/helpers.go (34.7%)</option>
<option value="file5">github.com/demetere/omg/pkg/migration.go (100.0%)</option>
<option value="file6">github.com/demetere/omg/pkg/migration_generator.go (95.6%)</option>
<option value="file7">github.com/demetere/omg/pkg/model_parser.go (66.2%)</option>
<option value="file8">github.com/demetere/omg/pkg/model_tracker.go (84.7%)</option>
<option value="file9">github.com/demetere/omg/pkg/tracker.go (92.9%)</option>
</select>
</div>
<div id="legend">
<span>not tracked</span>
<span class="cov0">not covered</span>
<span class="cov8">covered</span>
</div>
</div>
<div id="content">
<pre class="file" id="file0" style="display: none">package main
import (
"context"
"flag"
"fmt"
"net/url"
"os"
"strings"
"time"
"github.com/demetere/omg/pkg"
_ "github.com/demetere/omg/migrations" // Import migrations
"github.com/joho/godotenv"
)
var (
migrationsDir string
dbURL string
)
func main() <span class="cov0" title="0">{
// Load .env file
_ = godotenv.Load()
// Define flags
flag.StringVar(&migrationsDir, "dir", "migrations", "directory with migration files")
flag.StringVar(&dbURL, "dburl", "", "OpenFGA database URL (openfga://store_id@host:port?auth=...)")
if len(os.Args) < 2 </span><span class="cov0" title="0">{
printUsage()
os.Exit(1)
}</span>
<span class="cov0" title="0">command := os.Args[1]
// Parse flags from remaining arguments
flagSet := flag.NewFlagSet(command, flag.ExitOnError)
flagSet.StringVar(&migrationsDir, "dir", "migrations", "directory with migration files")
flagSet.StringVar(&dbURL, "dburl", os.Getenv("OPENFGA_DATABASE_URL"), "OpenFGA database URL")
flagSet.Parse(os.Args[2:])
ctx := context.Background()
// Commands that don't need OpenFGA client
switch command </span>{
case "create":<span class="cov0" title="0">
args := flagSet.Args()
if len(args) < 1 </span><span class="cov0" title="0">{
fmt.Println("Usage: omg create <migration_name>")
os.Exit(1)
}</span>
<span class="cov0" title="0">if err := createMigration(args[0]); err != nil </span><span class="cov0" title="0">{
fmt.Printf("Error: Failed to create migration: %v\n", err)
os.Exit(1)
}</span>
<span class="cov0" title="0">return</span>
case "generate":<span class="cov0" title="0">
args := flagSet.Args()
name := "auto_migration"
if len(args) >= 1 </span><span class="cov0" title="0">{
name = args[0]
}</span>
<span class="cov0" title="0">if err := generateMigration(name); err != nil </span><span class="cov0" title="0">{
fmt.Printf("Error: Failed to generate migration: %v\n", err)
os.Exit(1)
}</span>
<span class="cov0" title="0">return</span>
case "diff":<span class="cov0" title="0">
if err := showDiff(); err != nil </span><span class="cov0" title="0">{
fmt.Printf("Error: Failed to show diff: %v\n", err)
os.Exit(1)
}</span>
<span class="cov0" title="0">return</span>
case "init":<span class="cov0" title="0">
args := flagSet.Args()
if len(args) < 1 </span><span class="cov0" title="0">{
fmt.Println("Usage: omg init <store_name>")
os.Exit(1)
}</span>
<span class="cov0" title="0">if err := initStore(args[0]); err != nil </span><span class="cov0" title="0">{
fmt.Printf("Error: Failed to initialize store: %v\n", err)
os.Exit(1)
}</span>
<span class="cov0" title="0">return</span>
case "list-stores":<span class="cov0" title="0">
if err := listStores(); err != nil </span><span class="cov0" title="0">{
fmt.Printf("Error: Failed to list stores: %v\n", err)
os.Exit(1)
}</span>
<span class="cov0" title="0">return</span>
}
// Initialize OpenFGA client for other commands
<span class="cov0" title="0">client, err := initOpenFGAClient()
if err != nil </span><span class="cov0" title="0">{
fmt.Printf("Error: Failed to initialize OpenFGA client: %v\n", err)
os.Exit(1)
}</span>
<span class="cov0" title="0">switch command </span>{
case "up":<span class="cov0" title="0">
if err := runUp(ctx, client); err != nil </span><span class="cov0" title="0">{
fmt.Printf("Error: Migration up failed: %v\n", err)
os.Exit(1)
}</span>
case "down":<span class="cov0" title="0">
if err := runDown(ctx, client); err != nil </span><span class="cov0" title="0">{
fmt.Printf("Error: Migration down failed: %v\n", err)
os.Exit(1)
}</span>
case "status":<span class="cov0" title="0">
if err := showStatus(ctx, client); err != nil </span><span class="cov0" title="0">{
fmt.Printf("Error: Failed to show status: %v\n", err)
os.Exit(1)
}</span>
case "list-tuples":<span class="cov0" title="0">
filter := ""
args := flagSet.Args()
if len(args) >= 1 </span><span class="cov0" title="0">{
filter = args[0]
}</span>
<span class="cov0" title="0">if err := listTuples(ctx, client, filter); err != nil </span><span class="cov0" title="0">{
fmt.Printf("Error: Failed to list tuples: %v\n", err)
os.Exit(1)
}</span>
case "show-model":<span class="cov0" title="0">
if err := showModel(ctx, client); err != nil </span><span class="cov0" title="0">{
fmt.Printf("Error: Failed to show model: %v\n", err)
os.Exit(1)
}</span>
default:<span class="cov0" title="0">
fmt.Printf("Error: Unknown command: %s\n", command)
printUsage()
os.Exit(1)</span>
}
}
func printUsage() <span class="cov0" title="0">{
fmt.Println("OpenFGA Migration Tool - Model-First Migrations")
fmt.Println("")
fmt.Println("Usage:")
fmt.Println(" omg [options] <command>")
fmt.Println("")
fmt.Println("Model-First Workflow:")
fmt.Println(" diff Show changes between model.fga and current state")
fmt.Println(" generate [name] Auto-generate migration from model.fga changes")
fmt.Println(" up Apply pending migrations")
fmt.Println(" down Rollback last migration")
fmt.Println(" status Show migration status")
fmt.Println("")
fmt.Println("Manual Migration Commands:")
fmt.Println(" create <name> Create blank migration file")
fmt.Println("")
fmt.Println("Store Management:")
fmt.Println(" init <name> Create a new OpenFGA store")
fmt.Println(" list-stores List all OpenFGA stores")
fmt.Println("")
fmt.Println("Utilities:")
fmt.Println(" show-model Show current authorization model")
fmt.Println(" list-tuples [type] List all tuples (optionally filtered)")
fmt.Println("")
fmt.Println("Options:")
fmt.Println(" -dir string Directory with migration files (default: migrations)")
fmt.Println(" -dburl string OpenFGA database URL")
fmt.Println("")
fmt.Println("Database URL format:")
fmt.Println(" openfga://store_id@host:port")
fmt.Println("")
fmt.Println("Environment variables:")
fmt.Println(" OPENFGA_DATABASE_URL - Database URL (alternative to -dburl)")
fmt.Println(" OPENFGA_API_URL - OpenFGA API URL (alternative)")
fmt.Println(" OPENFGA_STORE_ID - OpenFGA Store ID (alternative)")
fmt.Println(" OPENFGA_AUTH_METHOD - Auth method: none, token, client_credentials")
fmt.Println(" OPENFGA_API_TOKEN - API token (if auth_method=token)")
fmt.Println(" OPENFGA_CLIENT_ID - Client ID (if auth_method=client_credentials)")
fmt.Println(" OPENFGA_CLIENT_SECRET - Client secret (if auth_method=client_credentials)")
fmt.Println(" OPENFGA_TOKEN_ISSUER - Token issuer (optional)")
fmt.Println(" OPENFGA_TOKEN_AUDIENCE - Token audience (optional)")
fmt.Println("")
fmt.Println("Typical Workflow:")
fmt.Println(" 1. Edit model.fga with your changes")
fmt.Println(" 2. Run 'omg diff' to see what changed")
fmt.Println(" 3. Run 'omg generate my_feature' to create migration")
fmt.Println(" 4. Review and edit the generated migration if needed")
fmt.Println(" 5. Run 'omg up' to apply migrations")
fmt.Println("")
fmt.Println("Examples:")
fmt.Println(" omg diff # See model changes")
fmt.Println(" omg generate add_files # Generate migration from model changes")
fmt.Println(" omg up # Apply migrations")
fmt.Println(" omg down # Rollback last migration")
fmt.Println(" omg status # Check migration status")
}</span>
func initOpenFGAClient() (*omg.Client, error) <span class="cov0" title="0">{
var cfg omg.Config
// Try to parse database URL first
if dbURL != "" </span><span class="cov0" title="0">{
parsedCfg, err := parseDBURL(dbURL)
if err != nil </span><span class="cov0" title="0">{
return nil, fmt.Errorf("invalid database URL: %w", err)
}</span>
<span class="cov0" title="0">cfg = parsedCfg</span>
} else<span class="cov0" title="0"> {
// Fall back to environment variables
cfg = omg.Config{
ApiURL: os.Getenv("OPENFGA_API_URL"),
StoreID: os.Getenv("OPENFGA_STORE_ID"),
AuthMethod: os.Getenv("OPENFGA_AUTH_METHOD"),
APIToken: os.Getenv("OPENFGA_API_TOKEN"),
ClientID: os.Getenv("OPENFGA_CLIENT_ID"),
ClientSecret: os.Getenv("OPENFGA_CLIENT_SECRET"),
TokenIssuer: os.Getenv("OPENFGA_TOKEN_ISSUER"),
TokenAudience: os.Getenv("OPENFGA_TOKEN_AUDIENCE"),
}
}</span>
<span class="cov0" title="0">return omg.NewClient(cfg)</span>
}
// parseDBURL parses a database URL in the format:
// openfga://store_id@host:port
func parseDBURL(dburl string) (omg.Config, error) <span class="cov0" title="0">{
u, err := url.Parse(dburl)
if err != nil </span><span class="cov0" title="0">{
return omg.Config{}, err
}</span>
<span class="cov0" title="0">if u.Scheme != "openfga" </span><span class="cov0" title="0">{
return omg.Config{}, fmt.Errorf("invalid scheme: expected 'openfga', got '%s'", u.Scheme)
}</span>
<span class="cov0" title="0">storeID := u.User.Username()
if storeID == "" </span><span class="cov0" title="0">{
return omg.Config{}, fmt.Errorf("store ID is required")
}</span>
<span class="cov0" title="0">host := u.Host
if host == "" </span><span class="cov0" title="0">{
return omg.Config{}, fmt.Errorf("host is required")
}</span>
// Build API URL
<span class="cov0" title="0">scheme := "https"
if u.Query().Get("tls") == "false" </span><span class="cov0" title="0">{
scheme = "http"
}</span>
<span class="cov0" title="0">apiURL := fmt.Sprintf("%s://%s", scheme, host)
cfg := omg.Config{
ApiURL: apiURL,
StoreID: storeID,
}
// Parse query parameters for auth
query := u.Query()
if authMethod := query.Get("auth"); authMethod != "" </span><span class="cov0" title="0">{
cfg.AuthMethod = authMethod
}</span>
<span class="cov0" title="0">if token := query.Get("token"); token != "" </span><span class="cov0" title="0">{
cfg.APIToken = token
}</span>
<span class="cov0" title="0">if clientID := query.Get("client_id"); clientID != "" </span><span class="cov0" title="0">{
cfg.ClientID = clientID
}</span>
<span class="cov0" title="0">if clientSecret := query.Get("client_secret"); clientSecret != "" </span><span class="cov0" title="0">{
cfg.ClientSecret = clientSecret
}</span>
<span class="cov0" title="0">if issuer := query.Get("issuer"); issuer != "" </span><span class="cov0" title="0">{
cfg.TokenIssuer = issuer
}</span>
<span class="cov0" title="0">if audience := query.Get("audience"); audience != "" </span><span class="cov0" title="0">{
cfg.TokenAudience = audience
}</span>
<span class="cov0" title="0">return cfg, nil</span>
}
func runUp(ctx context.Context, client *omg.Client) error <span class="cov0" title="0">{
tracker := omg.NewTracker(client)
migrations := omg.GetAll()
applied, err := tracker.GetApplied(ctx)
if err != nil </span><span class="cov0" title="0">{
return err
}</span>
<span class="cov0" title="0">count := 0
for _, m := range migrations </span><span class="cov0" title="0">{
if _, exists := applied[m.Version]; exists </span><span class="cov0" title="0">{
continue</span>
}
<span class="cov0" title="0">fmt.Printf("OK %s %s\n", m.Version, m.Name)
if err := m.Up(ctx, client); err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("migration %s failed: %w", m.Version, err)
}</span>
<span class="cov0" title="0">if err := tracker.Record(ctx, m.Version, m.Name); err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("failed to record migration %s: %w", m.Version, err)
}</span>
<span class="cov0" title="0">count++</span>
}
<span class="cov0" title="0">if count == 0 </span><span class="cov0" title="0">{
fmt.Println("goose: no migrations to run. current version: up to date")
}</span> else<span class="cov0" title="0"> {
fmt.Println("\n✓ All migrations applied successfully")
}</span>
<span class="cov0" title="0">return nil</span>
}
func runDown(ctx context.Context, client *omg.Client) error <span class="cov0" title="0">{
tracker := omg.NewTracker(client)
migrations := omg.GetAll()
applied, err := tracker.GetApplied(ctx)
if err != nil </span><span class="cov0" title="0">{
return err
}</span>
<span class="cov0" title="0">if len(applied) == 0 </span><span class="cov0" title="0">{
fmt.Println("goose: no migrations to roll back")
return nil
}</span>
// Find last applied migration
<span class="cov0" title="0">var lastMigration *omg.Migration
for i := len(migrations) - 1; i >= 0; i-- </span><span class="cov0" title="0">{
if _, exists := applied[migrations[i].Version]; exists </span><span class="cov0" title="0">{
lastMigration = &migrations[i]
break</span>
}
}
<span class="cov0" title="0">if lastMigration == nil </span><span class="cov0" title="0">{
fmt.Println("goose: no migrations to roll back")
return nil
}</span>
<span class="cov0" title="0">fmt.Printf("OK %s %s\n", lastMigration.Version, lastMigration.Name)
if err := lastMigration.Down(ctx, client); err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("rollback %s failed: %w", lastMigration.Version, err)
}</span>
<span class="cov0" title="0">if err := tracker.Remove(ctx, lastMigration.Version); err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("failed to remove migration record %s: %w", lastMigration.Version, err)
}</span>
<span class="cov0" title="0">return nil</span>
}
func showStatus(ctx context.Context, client *omg.Client) error <span class="cov0" title="0">{
tracker := omg.NewTracker(client)
migrations := omg.GetAll()
applied, err := tracker.GetApplied(ctx)
if err != nil </span><span class="cov0" title="0">{
return err
}</span>
<span class="cov0" title="0">if len(migrations) == 0 </span><span class="cov0" title="0">{
fmt.Println("goose: no migrations found")
return nil
}</span>
<span class="cov0" title="0">fmt.Printf("goose: status for environment '%s'\n", strings.TrimPrefix(dbURL, "openfga://"))
for _, m := range migrations </span><span class="cov0" title="0">{
status := "Pending"
if info, exists := applied[m.Version]; exists </span><span class="cov0" title="0">{
status = fmt.Sprintf("Applied At: %s", info.AppliedAt.Format("Mon Jan 2 15:04:05 2006"))
}</span>
<span class="cov0" title="0">fmt.Printf(" %-15s %-40s %s\n", m.Version, m.Name, status)</span>
}
<span class="cov0" title="0">return nil</span>
}
func createMigration(name string) error <span class="cov0" title="0">{
timestamp := time.Now().Format("20060102150405")
filename := fmt.Sprintf("%s/%s_%s.go", migrationsDir, timestamp, name)
template := fmt.Sprintf(`package migrations
import (
"context"
"github.com/demetere/omg/pkg"
)
func init() {
omg.Register(omg.Migration{
Version: "%s",
Name: "%s",
Up: up_%s,
Down: down_%s,
})
}
func up_%s(ctx context.Context, client *omg.Client) error {
// TODO: Implement migration
//
// Available omg functions:
//
// MODEL OPERATIONS:
// - omg.GetCurrentModel(ctx, client) - Get current model as DSL string
//
// TUPLE OPERATIONS:
// - omg.RenameRelation(ctx, client, objectType, oldRel, newRel) - Rename relation on all tuples
// - omg.RenameType(ctx, client, oldType, newType) - Rename object type on all tuples
// - omg.CopyRelation(ctx, client, objectType, sourceRel, targetRel) - Copy tuples to new relation
// - omg.DeleteRelation(ctx, client, objectType, relation) - Delete all tuples with relation
// - omg.MigrateRelationWithTransform(ctx, client, objectType, oldRel, newRel, transform) - Custom transform
//
// READ OPERATIONS:
// - omg.ReadAllTuples(ctx, client, objectType, relation) - Read tuples by type/relation
// - omg.CountTuples(ctx, client, objectType, relation) - Count matching tuples
//
// BATCH OPERATIONS:
// - omg.WriteTuplesBatch(ctx, client, tuples) - Write tuples in batches
// - omg.DeleteTuplesBatch(ctx, client, tuples) - Delete tuples in batches
//
// UTILITY:
// - omg.BackupTuples(ctx, client) - Backup all tuples before migration
// - omg.RestoreTuples(ctx, client, tuples) - Restore tuples from backup
return nil
}
func down_%s(ctx context.Context, client *omg.Client) error {
// TODO: Implement rollback
// Reverse the operations from Up
return nil
}
`, timestamp, name, timestamp, timestamp, timestamp, timestamp)
if err := os.MkdirAll(migrationsDir, 0755); err != nil </span><span class="cov0" title="0">{
return err
}</span>
<span class="cov0" title="0">if err := os.WriteFile(filename, []byte(template), 0644); err != nil </span><span class="cov0" title="0">{
return err
}</span>
<span class="cov0" title="0">fmt.Printf("goose: created new file: %s\n", filename)
return nil</span>
}
func listTuples(ctx context.Context, client *omg.Client, filter string) error <span class="cov0" title="0">{
req := omg.ReadTuplesRequest{}
if filter != "" </span><span class="cov0" title="0">{
req.Object = filter + ":"
}</span>
<span class="cov0" title="0">tuples, err := client.ReadAllTuples(ctx, req)
if err != nil </span><span class="cov0" title="0">{
return err
}</span>
<span class="cov0" title="0">fmt.Printf("Found %d tuples:\n\n", len(tuples))
for _, tuple := range tuples </span><span class="cov0" title="0">{
fmt.Printf("%s %s %s\n", tuple.User, tuple.Relation, tuple.Object)
}</span>
<span class="cov0" title="0">return nil</span>
}
func showModel(ctx context.Context, client *omg.Client) error <span class="cov0" title="0">{
model, err := client.GetCurrentModel(ctx)
if err != nil </span><span class="cov0" title="0">{
return err
}</span>
<span class="cov0" title="0">fmt.Println(model)
return nil</span>
}
func initStore(storeName string) error <span class="cov0" title="0">{
// Get API URL from environment or dbURL
apiURL := os.Getenv("OPENFGA_API_URL")
if apiURL == "" && dbURL != "" </span><span class="cov0" title="0">{
cfg, err := parseDBURL(dbURL)
if err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("invalid database URL: %w", err)
}</span>
<span class="cov0" title="0">apiURL = cfg.ApiURL</span>
}
<span class="cov0" title="0">if apiURL == "" </span><span class="cov0" title="0">{
return fmt.Errorf("OPENFGA_API_URL or -dburl is required")
}</span>
<span class="cov0" title="0">fmt.Printf("Creating OpenFGA store '%s'...\n", storeName)
storeID, err := omg.CreateStore(apiURL, storeName)
if err != nil </span><span class="cov0" title="0">{
return err
}</span>
<span class="cov0" title="0">fmt.Printf("\nStore created successfully!\n\n")
fmt.Printf("Store ID: %s\n", storeID)
fmt.Printf("Store Name: %s\n\n", storeName)
fmt.Println("Add to your environment:")
fmt.Printf(" export OPENFGA_STORE_ID=%s\n", storeID)
fmt.Printf(" export OPENFGA_DATABASE_URL=openfga://%s@%s\n", storeID, strings.TrimPrefix(apiURL, "http://"))
fmt.Println("")
fmt.Println("Or use with -dburl flag:")
fmt.Printf(" omg -dburl openfga://%s@%s up\n", storeID, strings.TrimPrefix(apiURL, "http://"))
return nil</span>
}
func listStores() error <span class="cov0" title="0">{
// Get API URL from environment or dbURL
apiURL := os.Getenv("OPENFGA_API_URL")
if apiURL == "" && dbURL != "" </span><span class="cov0" title="0">{
cfg, err := parseDBURL(dbURL)
if err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("invalid database URL: %w", err)
}</span>
<span class="cov0" title="0">apiURL = cfg.ApiURL</span>
}
<span class="cov0" title="0">if apiURL == "" </span><span class="cov0" title="0">{
return fmt.Errorf("OPENFGA_API_URL or -dburl is required")
}</span>
<span class="cov0" title="0">stores, err := omg.ListStores(apiURL)
if err != nil </span><span class="cov0" title="0">{
return err
}</span>
<span class="cov0" title="0">if len(stores) == 0 </span><span class="cov0" title="0">{
fmt.Println("No stores found")
return nil
}</span>
<span class="cov0" title="0">fmt.Printf("Found %d store(s):\n\n", len(stores))
for _, store := range stores </span><span class="cov0" title="0">{
fmt.Printf(" ID: %s\n", store.ID)
fmt.Printf(" Name: %s\n\n", store.Name)
}</span>
<span class="cov0" title="0">return nil</span>
}
func generateMigration(name string) error <span class="cov0" title="0">{
fmt.Println("Detecting model changes...")
// Create client to query OpenFGA
client, err := initOpenFGAClient()
if err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("failed to create client: %w", err)
}</span>
<span class="cov0" title="0">ctx := context.Background()
// Load current state from OpenFGA
fmt.Println("Querying OpenFGA for current model...")
oldState, err := omg.LoadModelStateFromOpenFGA(ctx, client)
if err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("failed to load current model from OpenFGA: %w\nMake sure OpenFGA is running and accessible", err)
}</span>
// Load desired model from file
<span class="cov0" title="0">newModelDSL, err := omg.LoadCurrentModel()
if err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("failed to load model.fga: %w", err)
}</span>
// Parse desired model
<span class="cov0" title="0">newModel, err := omg.ParseDSLToModel(newModelDSL)
if err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("failed to parse model.fga: %w", err)
}</span>
// Build desired state
<span class="cov0" title="0">newState := omg.BuildModelState(newModel)
// Detect changes
changes := omg.DetectChanges(oldState, newState)
if len(changes) == 0 </span><span class="cov0" title="0">{
fmt.Println("No changes detected")
return nil
}</span>
// Detect potential renames
<span class="cov0" title="0">changes = omg.DetectPotentialRenames(changes, oldState, newState)
// Print detected changes
fmt.Printf("\nDetected %d change(s):\n", len(changes))
for i, change := range changes </span><span class="cov0" title="0">{
fmt.Printf(" %d. %s\n", i+1, change.Details)
}</span>
// Ask for confirmation on potential renames
<span class="cov0" title="0">confirmedChanges, err := confirmChanges(changes)
if err != nil </span><span class="cov0" title="0">{
return err
}</span>
// Generate migration
<span class="cov0" title="0">fmt.Println("\nGenerating migration...")
filename, err := omg.GenerateMigrationFromChanges(confirmedChanges, name)
if err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("failed to generate migration: %w", err)
}</span>
<span class="cov0" title="0">fmt.Printf("\n✓ Migration created: %s\n", filename)
fmt.Println("\nNext steps:")
fmt.Println(" 1. Review the generated migration file")
fmt.Println(" 2. Edit if needed (especially for renames)")
fmt.Println(" 3. Run 'omg up' to apply the migration")
return nil</span>
}
func showDiff() error <span class="cov0" title="0">{
fmt.Println("Comparing model.fga with OpenFGA...")
// Create client to query OpenFGA
client, err := initOpenFGAClient()
if err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("failed to create client: %w", err)
}</span>
<span class="cov0" title="0">ctx := context.Background()
// Load current state from OpenFGA
oldState, err := omg.LoadModelStateFromOpenFGA(ctx, client)
if err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("failed to load current model from OpenFGA: %w\nMake sure OpenFGA is running and accessible", err)
}</span>
// Load desired model from file
<span class="cov0" title="0">newModelDSL, err := omg.LoadCurrentModel()
if err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("failed to load model.fga: %w", err)
}</span>
// Parse desired model
<span class="cov0" title="0">newModel, err := omg.ParseDSLToModel(newModelDSL)
if err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("failed to parse model.fga: %w", err)
}</span>
// Build desired state
<span class="cov0" title="0">newState := omg.BuildModelState(newModel)
// Detect changes
changes := omg.DetectChanges(oldState, newState)
if len(changes) == 0 </span><span class="cov0" title="0">{
fmt.Println("\n✓ No changes detected - model.fga matches current state")
return nil
}</span>
// Detect potential renames
<span class="cov0" title="0">changes = omg.DetectPotentialRenames(changes, oldState, newState)
// Print changes
fmt.Printf("\nDetected %d change(s):\n\n", len(changes))
for _, change := range changes </span><span class="cov0" title="0">{
symbol := getChangeSymbol(change.Type)
fmt.Printf("%s %s\n", symbol, change.Details)
switch change.Type </span>{
case omg.ChangeTypeRenameType, omg.ChangeTypeRenameRelation:<span class="cov0" title="0">
fmt.Printf(" Old: %s\n", change.OldValue)
fmt.Printf(" New: %s\n", change.NewValue)</span>
}
}
<span class="cov0" title="0">fmt.Println("\nRun 'omg generate <name>' to create a migration for these changes")
return nil</span>
}
func getChangeSymbol(changeType omg.ChangeType) string <span class="cov0" title="0">{
switch changeType </span>{
case omg.ChangeTypeAddType, omg.ChangeTypeAddRelation:<span class="cov0" title="0">
return "+"</span>
case omg.ChangeTypeRemoveType, omg.ChangeTypeRemoveRelation:<span class="cov0" title="0">
return "-"</span>
case omg.ChangeTypeUpdateRelation:<span class="cov0" title="0">
return "~"</span>
case omg.ChangeTypeRenameType, omg.ChangeTypeRenameRelation:<span class="cov0" title="0">
return "→"</span>
default:<span class="cov0" title="0">
return "•"</span>
}
}
func confirmChanges(changes []omg.ModelChange) ([]omg.ModelChange, error) <span class="cov0" title="0">{
// Process changes with confidence-aware handling
var confirmed []omg.ModelChange
for _, change := range changes </span><span class="cov0" title="0">{
if change.Type == omg.ChangeTypeRenameType || change.Type == omg.ChangeTypeRenameRelation </span><span class="cov0" title="0">{
// Handle based on confidence level
switch change.Confidence </span>{
case omg.ConfidenceHigh:<span class="cov0" title="0">
// High confidence: keep as rename, inform user
fmt.Printf("\n✓ Rename detected: %s -> %s (high confidence)\n", change.OldValue, change.NewValue)
fmt.Println(" Will generate rename migration that preserves tuples.")
confirmed = append(confirmed, change)</span>
case omg.ConfidenceMedium:<span class="cov0" title="0">
// Medium confidence: keep as rename but warn user to review
fmt.Printf("\n⚠ Possible rename: %s -> %s (medium confidence - review required)\n", change.OldValue, change.NewValue)
fmt.Println(" Will generate rename migration - review before applying.")
confirmed = append(confirmed, change)</span>
case omg.ConfidenceLow:<span class="cov0" title="0">
// Low confidence: keep as rename, generator will create commented code
fmt.Printf("\n⚠ Potential rename: %s -> %s (low confidence)\n", change.OldValue, change.NewValue)
fmt.Println(" Will generate both options - uncomment the rename if confirmed.")
confirmed = append(confirmed, change)</span>
default:<span class="cov0" title="0">
// No confidence info (legacy): treat conservatively
fmt.Printf("\n⚠ Detected potential rename: %s -> %s\n", change.OldValue, change.NewValue)
fmt.Println(" Will generate rename migration - review carefully.")
confirmed = append(confirmed, change)</span>
}
} else<span class="cov0" title="0"> {
confirmed = append(confirmed, change)
}</span>
}
<span class="cov0" title="0">return confirmed, nil</span>
}
</pre>
<pre class="file" id="file1" style="display: none">package testhelpers
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"testing"
"github.com/demetere/omg/pkg"
openfgaSdk "github.com/openfga/go-sdk"
"github.com/openfga/go-sdk/client"
"github.com/stretchr/testify/require"
openfgacontainer "github.com/testcontainers/testcontainers-go/modules/openfga"
)
// SetupOpenFGAContainer starts an OpenFGA container and returns it with a configured client
func SetupOpenFGAContainer(t *testing.T, ctx context.Context, modelDSL string) (*openfgacontainer.OpenFGAContainer, *omg.Client) <span class="cov0" title="0">{
container, err := openfgacontainer.Run(ctx, "openfga/openfga:v1.8.0")
require.NoError(t, err)
httpEndpoint, err := container.HttpEndpoint(ctx)
require.NoError(t, err)
// Create a store using HTTP API
storeID, err := createStore(ctx, httpEndpoint, "test-store")
require.NoError(t, err)
// Create our client
client, err := omg.NewClient(omg.Config{
ApiURL: httpEndpoint,
StoreID: storeID,
AuthMethod: "none",
})
require.NoError(t, err)
// Write the model if provided
if modelDSL != "" </span><span class="cov0" title="0">{
err = WriteModel(ctx, client, modelDSL)
require.NoError(t, err)
}</span>
<span class="cov0" title="0">return container, client</span>
}
func createStore(ctx context.Context, apiURL, name string) (string, error) <span class="cov0" title="0">{
reqBody := fmt.Sprintf(`{"name":"%s"}`, name)
resp, err := http.Post(apiURL+"/stores", "application/json", strings.NewReader(reqBody))
if err != nil </span><span class="cov0" title="0">{
return "", err
}</span>
<span class="cov0" title="0">defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil </span><span class="cov0" title="0">{
return "", err
}</span>
<span class="cov0" title="0">var result struct {
ID string `json:"id"`
}
if err := json.Unmarshal(body, &result); err != nil </span><span class="cov0" title="0">{
return "", err
}</span>
<span class="cov0" title="0">return result.ID, nil</span>
}
// WriteModel writes an authorization model for testing
// This is a simplified version that parses basic DSL
func WriteModel(ctx context.Context, cl *omg.Client, modelDSL string) error <span class="cov0" title="0">{
sdkClient := cl.GetSDKClient()
// Parse model DSL and create type definitions
// For now, this is hardcoded for common test scenarios
// In production, you'd use the FGA CLI or a proper DSL parser
typeDefinitions := parseModelDSL(modelDSL)
body := client.ClientWriteAuthorizationModelRequest{
TypeDefinitions: typeDefinitions,
SchemaVersion: "1.1",
}
_, err := sdkClient.WriteAuthorizationModel(ctx).Body(body).Execute()
return err
}</span>
// parseModelDSL is a simplified DSL parser for testing
// In production, use the official FGA DSL parser
func parseModelDSL(dsl string) []openfgaSdk.TypeDefinition <span class="cov0" title="0">{
// This is a very basic parser - for testing only
// Returns predefined types based on what's in the DSL
types := []openfgaSdk.TypeDefinition{
{Type: "user"},
}
// Add common test types if they appear in the DSL
if strings.Contains(dsl, "type document") </span><span class="cov0" title="0">{
types = append(types, openfgaSdk.TypeDefinition{
Type: "document",
Relations: &map[string]openfgaSdk.Userset{
"owner": {This: &map[string]interface{}{}},
"editor": {This: &map[string]interface{}{}},
"viewer": {This: &map[string]interface{}{}},
},
Metadata: &openfgaSdk.Metadata{
Relations: &map[string]openfgaSdk.RelationMetadata{
"owner": {DirectlyRelatedUserTypes: &[]openfgaSdk.RelationReference{{Type: "user"}}},
"editor": {DirectlyRelatedUserTypes: &[]openfgaSdk.RelationReference{{Type: "user"}}},
"viewer": {DirectlyRelatedUserTypes: &[]openfgaSdk.RelationReference{{Type: "user"}}},
},
},
})
}</span>
<span class="cov0" title="0">if strings.Contains(dsl, "type folder") </span><span class="cov0" title="0">{
types = append(types, openfgaSdk.TypeDefinition{
Type: "folder",
Relations: &map[string]openfgaSdk.Userset{
"owner": {This: &map[string]interface{}{}},
"editor": {This: &map[string]interface{}{}},
"viewer": {This: &map[string]interface{}{}},
},
Metadata: &openfgaSdk.Metadata{
Relations: &map[string]openfgaSdk.RelationMetadata{
"owner": {DirectlyRelatedUserTypes: &[]openfgaSdk.RelationReference{{Type: "user"}}},
"editor": {DirectlyRelatedUserTypes: &[]openfgaSdk.RelationReference{{Type: "user"}}},
"viewer": {DirectlyRelatedUserTypes: &[]openfgaSdk.RelationReference{{Type: "user"}}},
},
},
})
}</span>
<span class="cov0" title="0">if strings.Contains(dsl, "type team") </span><span class="cov0" title="0">{
types = append(types, createTeamType())
}</span>
<span class="cov0" title="0">if strings.Contains(dsl, "type organization") </span><span class="cov0" title="0">{
types = append(types, createOrganizationType())
}</span>
<span class="cov0" title="0">if strings.Contains(dsl, "type migration") </span><span class="cov0" title="0">{
types = append(types, openfgaSdk.TypeDefinition{
Type: "system",
})
types = append(types, openfgaSdk.TypeDefinition{
Type: "migration",
Relations: &map[string]openfgaSdk.Userset{
"applied": {This: &map[string]interface{}{}},
},
Metadata: &openfgaSdk.Metadata{
Relations: &map[string]openfgaSdk.RelationMetadata{
"applied": {DirectlyRelatedUserTypes: &[]openfgaSdk.RelationReference{{Type: "system"}}},
},
},
})
}</span>
<span class="cov0" title="0">return types</span>
}
func createTeamType() openfgaSdk.TypeDefinition <span class="cov0" title="0">{
relations := &map[string]openfgaSdk.Userset{
"owner": {This: &map[string]interface{}{}},
"admin": {This: &map[string]interface{}{}},
"member": {This: &map[string]interface{}{}},
"manager": {This: &map[string]interface{}{}},
"employee": {This: &map[string]interface{}{}},
"can_manage": {This: &map[string]interface{}{}},
"can_manage_members": {This: &map[string]interface{}{}},
"deprecated": {This: &map[string]interface{}{}},