-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathssh.go
More file actions
1843 lines (1731 loc) · 55.8 KB
/
ssh.go
File metadata and controls
1843 lines (1731 loc) · 55.8 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
package main
import (
"bufio"
"bytes"
"context"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"sort"
"strings"
"time"
"golang.org/x/crypto/ssh"
)
const defaultSSHHost = "git.bucketgit.com"
var brokerIdentityPreference string
func setBrokerIdentityPreference(value string) {
brokerIdentityPreference = strings.TrimSpace(value)
}
type sshSetupOptions struct {
broker string
region string
firestoreDatabase string
firestoreLocation string
keys []string
noAgent bool
}
type provisionedBroker struct {
URL string
BootstrapToken string
}
func sshCommand(base config, args []string, stdout, stderr io.Writer) error {
if len(args) == 0 {
return errors.New("usage: bgit ssh git-upload-pack|git-receive-pack [args]")
}
switch args[0] {
case "git-upload-pack", "git-receive-pack", "git-upload-archive":
return sshGitServiceCommand(args, stdout)
default:
if looksLikeSSHInvocation(args) {
return sshGitServiceCommand(args, stdout)
}
return fmt.Errorf("unknown ssh command %q", args[0])
}
}
func sshGitServiceCommand(args []string, stdout io.Writer) error {
inv, err := parseGitCommandInvocation(args)
if err != nil {
return err
}
switch inv.service {
case gitUploadPackService, gitReceivePackService:
return sshServeGitService(inv.service, inv.repo, inv.host, os.Stdin, stdout)
default:
return fmt.Errorf("unsupported git service %q", inv.service)
}
}
func sshServeGitService(service, repo, host string, stdin io.Reader, stdout io.Writer) error {
ctx := context.Background()
cfg, err := configForSSHRepoForService(ctx, repo, host, service == gitUploadPackService)
if err != nil {
return err
}
if err := authorizeSSHGitService(cfg, service); err != nil {
return err
}
store, closeStore, err := newRemoteStore(ctx, cfg, service == gitUploadPackService)
if err != nil {
return fmt.Errorf("create remote store: %w", err)
}
defer closeStore()
refs, err := openNativeGitRepo(store, cfg).refs(ctx)
if err != nil {
return err
}
if head, ok := refs[branchRef(cfg.branch)]; ok {
refs["HEAD"] = head
}
caps := uploadPackCapabilities()
if service == gitReceivePackService {
caps = receivePackCapabilities()
}
if err := writeAdvertisedRefs(stdout, service, refs, caps); err != nil {
return err
}
if service == gitUploadPackService {
return serveUploadPack(ctx, openNativeGitRepo(store, cfg), stdin, stdout)
}
return serveReceivePack(ctx, openNativeGitRepo(store, cfg), stdin, stdout)
}
func configForSSHRepo(repo string) (config, error) {
repo = cleanGitServiceRepo(repo)
if repo == "" {
return config{}, errors.New("missing repository path")
}
if localCfg, err := readLocalConfig("."); err == nil && localCfg.logicalRepo != "" {
if strings.Trim(localCfg.logicalRepo, "/") == strings.Trim(repo, "/") {
return mergeSSHRepoAuth(localCfg), nil
}
}
if strings.Contains(repo, "://") {
cfg, _, err := parseRepoURI(repo)
if err != nil {
return config{}, err
}
return mergeSSHRepoAuth(cfg), nil
}
if provider, rest, ok := strings.Cut(repo, "/"); ok && (provider == "s3" || provider == "gs" || provider == "gcs") {
scheme := provider
if scheme == "gcs" {
scheme = "gs"
}
cfg, _, err := parseRepoURI(scheme + "://" + rest)
if err != nil {
return config{}, err
}
return mergeSSHRepoAuth(cfg), nil
}
_, bucket, prefix := normalizeAdminTarget(repo)
if bucket == "" || prefix == "" {
return config{}, fmt.Errorf("repository path must be bucket/prefix.git, got %q", repo)
}
cfg := config{provider: "gcs", bucket: bucket, prefix: prefix, branch: defaultBranch, auth: defaultAuthMode}
if localCfg, err := readLocalConfig("."); err == nil {
if localCfg.bucket == bucket && strings.Trim(localCfg.prefix, "/") == strings.Trim(prefix, "/") {
localCfg.authExplicit = false
localCfg.gcloudConfigurationExplicit = false
cfg = mergeConfig(localCfg, cfg)
}
}
if cfg.origin == "" {
cfg.origin = originForConfig(cfg)
}
return mergeSSHRepoAuth(cfg), nil
}
func configForSSHRepoForService(ctx context.Context, repo, host string, publicFallback bool) (config, error) {
_ = host
cfg, err := configForSSHRepo(repo)
if err != nil {
return config{}, err
}
if cfg.provider == "local" {
if _, err := ensureLocalBrokerForCommand(ctx, &cfg); err != nil {
return config{}, err
}
return cfg, nil
}
if cfg.provider != "gcs" || strings.Contains(cleanGitServiceRepo(repo), "://") {
persistDiscoveredSSHRepoConfig(cfg)
return cfg, nil
}
if localCfg, err := readLocalConfig("."); err == nil {
if localCfg.bucket == cfg.bucket && strings.Trim(localCfg.prefix, "/") == strings.Trim(cfg.prefix, "/") && strings.TrimSpace(localCfg.provider) != "" {
return cfg, nil
}
}
provider, err := autodiscoverSSHRepoProvider(ctx, cfg, publicFallback)
if err != nil {
return config{}, err
}
cfg.provider = provider
cfg.origin = ""
cfg.origin = originForConfig(cfg)
persistDiscoveredSSHRepoConfig(cfg)
return cfg, nil
}
func autodiscoverSSHRepoProvider(ctx context.Context, cfg config, publicFallback bool) (string, error) {
var misses []string
for _, provider := range []string{"s3", "gcs"} {
probe := cfg
probe.provider = provider
probe.origin = originForConfig(probe)
store, closeStore, err := newRemoteStore(ctx, probe, publicFallback)
if err != nil {
misses = append(misses, provider+": "+err.Error())
continue
}
refs, err := openNativeGitRepo(store, probe).refs(ctx)
closeStore()
if err != nil {
misses = append(misses, provider+": "+err.Error())
continue
}
if len(refs) > 0 {
return provider, nil
}
misses = append(misses, provider+": no refs found")
}
return "", fmt.Errorf("could not autodiscover provider for %s/%s (%s)", cfg.bucket, strings.Trim(cfg.prefix, "/"), strings.Join(misses, "; "))
}
func persistDiscoveredSSHRepoConfig(cfg config) {
worktree, err := requireWorktree(".")
if err != nil {
return
}
_ = writeBucketGitConfig(worktree, cfg)
}
func mergeSSHRepoAuth(cfg config) config {
cfg.branch = firstNonEmpty(cfg.branch, defaultBranch)
cfg.auth = firstNonEmpty(cfg.auth, defaultAuthMode)
if localCfg, err := readLocalConfig("."); err == nil {
cfg = mergeConfig(cfg, localCfg)
}
if cfg.origin == "" {
cfg.origin = originForConfig(cfg)
}
return cfg
}
func parseSSHSetupArgs(args []string) (sshSetupOptions, string, error) {
var opts sshSetupOptions
var repoArg string
for i := 0; i < len(args); i++ {
arg := args[i]
name, value, hasValue := strings.Cut(arg, "=")
switch name {
case "--broker":
if !hasValue {
i++
if i >= len(args) {
return opts, "", errors.New("--broker requires a value")
}
value = args[i]
}
opts.broker = value
case "--key":
if !hasValue {
i++
if i >= len(args) {
return opts, "", errors.New("--key requires a value")
}
value = args[i]
}
opts.keys = append(opts.keys, value)
case "--region":
if !hasValue {
i++
if i >= len(args) {
return opts, "", errors.New("--region requires a value")
}
value = args[i]
}
opts.region = value
case "--firestore-database":
if !hasValue {
i++
if i >= len(args) {
return opts, "", errors.New("--firestore-database requires a value")
}
value = args[i]
}
opts.firestoreDatabase = value
case "--firestore-location":
if !hasValue {
i++
if i >= len(args) {
return opts, "", errors.New("--firestore-location requires a value")
}
value = args[i]
}
opts.firestoreLocation = value
case "--no-agent":
opts.noAgent = true
default:
if strings.HasPrefix(arg, "-") {
return opts, "", fmt.Errorf("unsupported ssh option %s", arg)
}
if repoArg != "" {
return opts, "", errors.New("ssh commands accept at most one repository URI")
}
repoArg = arg
}
}
return opts, repoArg, nil
}
func sshSetupConfig(base config, repoArg string) (config, error) {
if strings.TrimSpace(repoArg) != "" {
cfg, _, err := parseRepoURI(repoArg)
if err != nil {
return config{}, err
}
cfg.auth = base.auth
cfg.authExplicit = base.authExplicit
cfg.gcloudConfiguration = base.gcloudConfiguration
cfg.gcloudConfigurationExplicit = base.gcloudConfigurationExplicit
return cfg, nil
}
cfg := base
if cfg.bucket == "" && cfg.logicalRepo == "" {
localCfg, err := readLocalConfig(".")
if err != nil {
return config{}, errors.New("ssh command requires a repository URI or an existing bgit origin")
}
cfg = mergeConfig(cfg, localCfg)
}
if cfg.brokerURL != "" && cfg.logicalRepo != "" {
if cfg.branch == "" {
cfg.branch = defaultBranch
}
if cfg.origin == "" {
cfg.origin = fmt.Sprintf("git@%s:%s", defaultSSHHost, strings.Trim(cfg.logicalRepo, "/"))
}
return cfg, nil
}
if cfg.bucket == "" || cfg.prefix == "" {
return config{}, errors.New("ssh command requires a repository URI or an existing bgit origin")
}
if cfg.branch == "" {
cfg.branch = defaultBranch
}
if cfg.origin == "" {
cfg.origin = originForConfig(cfg)
}
return cfg, nil
}
func sshKeysCommand(base config, args []string, stdout io.Writer) error {
if len(args) == 0 {
return errors.New("usage: bgit admin keys list|add|remove|suspend [args]")
}
action := args[0]
opts, repoArg, err := parseSSHKeyArgs(args[1:])
if err != nil {
return err
}
cfg, err := sshSetupConfig(base, repoArg)
if err != nil {
return err
}
brokerURL, err := brokerURLForCommand(opts.setup)
if err != nil {
return err
}
switch action {
case "list":
keys, err := brokerListKeys(brokerURL, cfg)
if err != nil {
return err
}
for _, key := range keys {
state := "active"
if key.Suspended {
state = "suspended"
}
fmt.Fprintf(stdout, "%s\t%s\t%s\t%s\n", key.User, key.Role, state, key.PublicKey)
}
return nil
case "add":
keys, err := collectSSHPublicKeys(opts.setup)
if err != nil {
return err
}
if len(keys) == 0 {
return errors.New("admin keys add requires --key or a key loaded in ssh-agent")
}
if err := brokerAddKeys(brokerURL, cfg, opts.user, opts.role, keys); err != nil {
return err
}
fmt.Fprintf(stdout, "added %d key(s) for user %s with role %s\n", len(keys), opts.user, opts.role)
return nil
case "remove":
identity, err := keyIdentityForMutation(opts)
if err != nil {
return err
}
if err := brokerMutateKey(brokerURL, "/keys/remove", cfg, identity); err != nil {
return err
}
fmt.Fprintf(stdout, "removed key %s\n", identity)
return nil
case "suspend":
identity, err := keyIdentityForMutation(opts)
if err != nil {
return err
}
if err := brokerMutateKey(brokerURL, "/keys/suspend", cfg, identity); err != nil {
return err
}
fmt.Fprintf(stdout, "suspended key %s\n", identity)
return nil
default:
return fmt.Errorf("unknown admin keys command %q", action)
}
}
type sshKeyOptions struct {
setup sshSetupOptions
user string
role string
keyID string
fingerprint string
}
func parseSSHKeyArgs(args []string) (sshKeyOptions, string, error) {
opts := sshKeyOptions{user: "admin", role: "read"}
var repoArg string
for i := 0; i < len(args); i++ {
arg := args[i]
name, value, hasValue := strings.Cut(arg, "=")
switch name {
case "--broker":
value, next, err := optionValue(args, i, hasValue, value, name)
if err != nil {
return opts, "", err
}
i = next
opts.setup.broker = value
case "--key":
value, next, err := optionValue(args, i, hasValue, value, name)
if err != nil {
return opts, "", err
}
i = next
opts.setup.keys = append(opts.setup.keys, value)
case "--region":
value, next, err := optionValue(args, i, hasValue, value, name)
if err != nil {
return opts, "", err
}
i = next
opts.setup.region = value
case "--no-agent":
opts.setup.noAgent = true
case "--user":
var err error
value, i, err = optionValue(args, i, hasValue, value, name)
if err != nil {
return opts, "", err
}
opts.user = value
case "--role":
var err error
value, i, err = optionValue(args, i, hasValue, value, name)
if err != nil {
return opts, "", err
}
opts.role = value
case "--fingerprint":
var err error
value, i, err = optionValue(args, i, hasValue, value, name)
if err != nil {
return opts, "", err
}
opts.fingerprint = value
default:
if strings.HasPrefix(arg, "-") {
return opts, "", fmt.Errorf("unsupported admin keys option %s", arg)
}
if repoArg == "" && strings.Contains(arg, "://") {
repoArg = arg
continue
}
if opts.keyID == "" {
opts.keyID = arg
continue
}
if repoArg == "" {
repoArg = arg
continue
}
return opts, "", errors.New("too many admin keys arguments")
}
}
return opts, repoArg, nil
}
func optionValue(args []string, i int, hasValue bool, value, name string) (string, int, error) {
if hasValue {
return value, i, nil
}
i++
if i >= len(args) {
return "", i, fmt.Errorf("%s requires a value", name)
}
return args[i], i, nil
}
func keyIdentityForMutation(opts sshKeyOptions) (string, error) {
if strings.TrimSpace(opts.fingerprint) != "" {
return strings.TrimSpace(opts.fingerprint), nil
}
if strings.TrimSpace(opts.keyID) != "" {
return strings.TrimSpace(opts.keyID), nil
}
keys, err := collectSSHPublicKeys(opts.setup)
if err != nil {
return "", err
}
if len(keys) != 1 {
return "", errors.New("key mutation requires exactly one --key, --fingerprint, or key argument")
}
return keys[0], nil
}
func brokerURLForCommand(opts sshSetupOptions) (string, error) {
if strings.TrimSpace(opts.broker) != "" {
return strings.TrimSpace(opts.broker), nil
}
if out, err := runGit(".", "config", "--get", "bucketgit.broker"); err == nil {
if value := strings.TrimSpace(string(out)); value != "" {
return value, nil
}
}
return "", errors.New("broker URL is required; run bgit setup/init or pass --broker URL")
}
func sshRemoteURL(cfg config) string {
repo := fmt.Sprintf("%s/%s", cfg.bucket, strings.Trim(cfg.prefix, "/"))
return fmt.Sprintf("git@%s:%s", defaultSSHHost, repo)
}
func writeBrokerConfig(worktree, brokerURL string, stdout io.Writer) error {
if strings.TrimSpace(brokerURL) == "" {
return nil
}
if _, err := runGit(worktree, "config", "--local", "bucketgit.broker", strings.TrimSpace(brokerURL)); err != nil {
return err
}
fmt.Fprintf(stdout, "configured broker %s\n", strings.TrimSpace(brokerURL))
return nil
}
type brokerRepo struct {
Provider string `json:"provider"`
Bucket string `json:"bucket"`
Prefix string `json:"prefix"`
Origin string `json:"origin"`
Logical string `json:"logical,omitempty"`
Host string `json:"host,omitempty"`
Profile string `json:"profile,omitempty"`
Region string `json:"region,omitempty"`
TeamID string `json:"team_id,omitempty"`
TeamName string `json:"team_name,omitempty"`
}
const coreTeamID = "t_core"
const coreTeamName = "core"
type brokerKey struct {
User string `json:"user"`
Role string `json:"role"`
PublicKey string `json:"public_key"`
Source string `json:"source,omitempty"`
Suspended bool `json:"suspended,omitempty"`
}
type brokerRepoRequest struct {
Repo brokerRepo `json:"repo"`
AdminUser string `json:"admin_user,omitempty"`
PublicKeys []string `json:"public_keys,omitempty"`
Role string `json:"role,omitempty"`
}
type brokerKeyRequest struct {
Repo brokerRepo `json:"repo"`
User string `json:"user,omitempty"`
Role string `json:"role,omitempty"`
PublicKeys []string `json:"public_keys,omitempty"`
Key string `json:"key,omitempty"`
Source string `json:"source,omitempty"`
}
type brokerAuthRequest struct {
Repo brokerRepo `json:"repo"`
Operation string `json:"operation"`
}
type brokerAuthResponse struct {
Allowed bool `json:"allowed"`
User string `json:"user,omitempty"`
Role string `json:"role,omitempty"`
}
type brokerRefUpdateRequest struct {
Repo brokerRepo `json:"repo"`
Ref string `json:"ref"`
Old string `json:"old"`
New string `json:"new"`
Override bool `json:"override,omitempty"`
}
type brokerKeysResponse struct {
Keys []brokerKey `json:"keys"`
}
func brokerUpsertLogicalRepo(brokerURL, provider, logicalRepo string, teamID ...string) error {
logical, err := normalizeLogicalRepoName(logicalRepo)
if err != nil {
return err
}
team := ""
if len(teamID) > 0 {
team = strings.TrimSpace(teamID[0])
}
cfg := config{
provider: provider,
prefix: logical,
logicalRepo: logical,
origin: fmt.Sprintf("git@%s:%s", defaultSSHHost, logical),
}
repo := repoForBroker(cfg)
if team != "" {
repo.TeamID = team
}
req := brokerRepoRequest{Repo: repo}
return brokerPost(brokerURL, "/repos/upsert", req, nil)
}
func brokerListKeys(brokerURL string, cfg config) ([]brokerKey, error) {
var resp brokerKeysResponse
if err := brokerPost(brokerURL, "/keys/list", brokerKeyRequest{Repo: repoForBroker(cfg)}, &resp); err != nil {
return nil, err
}
return resp.Keys, nil
}
func brokerAddKeys(brokerURL string, cfg config, user, role string, publicKeys []string) error {
return brokerAddKeysWithSource(brokerURL, cfg, user, role, "", publicKeys)
}
func brokerAddKeysWithSource(brokerURL string, cfg config, user, role, source string, publicKeys []string) error {
role = normalizeBrokerRole(role)
if !validBrokerRole(role) {
return fmt.Errorf("invalid broker role %q", role)
}
req := brokerKeyRequest{
Repo: repoForBroker(cfg),
User: user,
Role: role,
PublicKeys: publicKeys,
Source: source,
}
return brokerPost(brokerURL, "/keys/add", req, nil)
}
func brokerMutateKey(brokerURL, path string, cfg config, key string) error {
return brokerPost(brokerURL, path, brokerKeyRequest{Repo: repoForBroker(cfg), Key: key}, nil)
}
func validBrokerRole(role string) bool {
switch strings.TrimSpace(role) {
case "owner", "admin", "maintainer", "developer", "triage", "read":
return true
default:
return false
}
}
func normalizeBrokerRole(role string) string {
switch strings.TrimSpace(role) {
case "write":
return "developer"
default:
return strings.TrimSpace(role)
}
}
func brokerUpdateRef(brokerURL string, cfg config, ref, oldHash, newHash string) error {
return brokerUpdateRefWithOverride(brokerURL, cfg, ref, oldHash, newHash, false)
}
func brokerUpdateRefWithOverride(brokerURL string, cfg config, ref, oldHash, newHash string, override bool) error {
req := brokerRefUpdateRequest{
Repo: repoForBroker(cfg),
Ref: ref,
Old: firstNonEmpty(strings.TrimSpace(oldHash), zeroObjectID()),
New: firstNonEmpty(strings.TrimSpace(newHash), zeroObjectID()),
Override: override,
}
return brokerPost(brokerURL, "/refs/update", req, nil)
}
func optionalBrokerURLForPush() string {
out, err := runGit(".", "config", "--get", "bucketgit.broker")
if err != nil {
return ""
}
return strings.TrimSpace(string(out))
}
func brokerPushError(err error) error {
return fmt.Errorf("%w\n\nBroker ref coordination failed. Retry after fetching, or use --skip-broker for a direct bucket push if this is an operator recovery action.", err)
}
func authorizeSSHGitService(cfg config, service string) error {
operation, err := brokerOperationForGitService(service)
if err != nil {
return err
}
brokerURL, err := brokerURLForSSHService(cfg)
if err != nil {
return err
}
var resp brokerAuthResponse
req := brokerAuthRequest{Repo: repoForBroker(cfg), Operation: operation}
if err := brokerPost(brokerURL, "/auth/check", req, &resp); err != nil {
return err
}
if !resp.Allowed {
return fmt.Errorf("broker denied %s access", operation)
}
return nil
}
func brokerOperationForGitService(service string) (string, error) {
switch service {
case gitUploadPackService:
return "read", nil
case gitReceivePackService:
return "write", nil
default:
return "", fmt.Errorf("unsupported git service %q", service)
}
}
func brokerURLForSSHService(cfg config) (string, error) {
if cfg.provider == "local" {
if cfg.brokerURL != "" {
return cfg.brokerURL, nil
}
profileName, regionName := localProfileSelection(cfg.gcloudConfiguration)
return localBrokerURL(profileName, regionName), nil
}
if out, err := runGit(".", "config", "--get", "bucketgit.broker"); err == nil {
if value := strings.TrimSpace(string(out)); value != "" {
return value, nil
}
}
url, err := discoverBrokerURL(cfg, sshSetupOptions{})
if err != nil {
return "", fmt.Errorf("broker URL is required for SSH Git access; run bgit init: %w", err)
}
return url, nil
}
func repoForBroker(cfg config) brokerRepo {
if cfg.origin == "" {
cfg.origin = originForConfig(cfg)
}
logical := strings.Trim(firstNonEmpty(cfg.logicalRepo, cfg.prefix), "/")
if normalized, err := normalizeLogicalRepoName(logical); err == nil {
logical = normalized
}
return brokerRepo{
Provider: firstNonEmpty(cfg.storageProvider, cfg.provider, "gcs"),
Bucket: cfg.bucket,
Prefix: strings.Trim(cfg.prefix, "/"),
Origin: cfg.origin,
Logical: logical,
Profile: cfg.storageProfile,
Region: cfg.storageRegion,
TeamID: brokerTeamIDForConfig(cfg),
}
}
func brokerTeamIDForConfig(cfg config) string {
teamID := strings.TrimSpace(cfg.teamID)
if teamID == "" && strings.TrimSpace(cfg.logicalRepo) != "" {
teamID = coreTeamID
}
return teamID
}
func brokerPost(brokerURL, path string, req any, resp any) error {
return brokerPostContext(context.Background(), brokerURL, path, req, resp)
}
func brokerPostContext(ctx context.Context, brokerURL, path string, req any, resp any) error {
if isLocalBrokerURL(brokerURL) {
return localBrokerPostContext(ctx, brokerURL, path, req, resp)
}
return brokerPostJSONContextWithHeaders(ctx, brokerURL, path, req, resp, nil)
}
func brokerPostJSONContextWithHeaders(ctx context.Context, brokerURL, path string, req any, resp any, extraHeaders map[string]string) error {
if isLocalBrokerURL(brokerURL) {
return localBrokerPostContext(ctx, brokerURL, path, req, resp)
}
endpoint := strings.TrimRight(brokerURL, "/") + path
data, err := json.Marshal(req)
if err != nil {
return err
}
headerSets := brokerSignatureHeaderSetsForBroker(brokerURL, path, data)
if len(headerSets) == 0 {
headerSets = []map[string]string{{}}
} else {
headerSets = append(headerSets, map[string]string{})
}
var lastErr error
for i, headers := range headerSets {
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(data))
if err != nil {
return err
}
httpReq.Header.Set("content-type", "application/json")
for key, value := range headers {
httpReq.Header.Set(key, value)
}
for key, value := range extraHeaders {
httpReq.Header.Set(key, value)
}
httpResp, err := http.DefaultClient.Do(httpReq)
if err != nil {
return err
}
body, readErr := io.ReadAll(httpResp.Body)
_ = httpResp.Body.Close()
if readErr != nil {
return readErr
}
if httpResp.StatusCode >= 200 && httpResp.StatusCode < 300 {
if fingerprint := headers["X-Bgit-Key-Fingerprint"]; fingerprint != "" {
_ = writeRepoAuthCache(brokerURL, data, fingerprint)
}
if resp != nil && len(body) > 0 {
if err := json.Unmarshal(body, resp); err != nil {
return err
}
}
return nil
}
msg := strings.TrimSpace(string(body))
if msg == "" {
msg = httpResp.Status
}
lastErr = brokerHTTPError(path, msg)
if httpResp.StatusCode != http.StatusForbidden || i == len(headerSets)-1 || !brokerForbiddenAllowsSignatureRetry(msg) {
return lastErr
}
}
return lastErr
}
func brokerHTTPError(path, msg string) error {
if brokerLooksIncompatibleWithV2Signatures(msg) {
return fmt.Errorf("broker %s: %s\nbroker is incompatible with this bgit version and must be upgraded for v2 request signatures; run `bgit admin broker upgrade` with a bgit version that can administer this broker", path, msg)
}
return fmt.Errorf("broker %s: %s", path, msg)
}
func brokerLooksIncompatibleWithV2Signatures(msg string) bool {
msg = strings.ToLower(strings.TrimSpace(msg))
if !strings.Contains(msg, "ssh signature required") {
return false
}
for _, scoped := range []string{"read ssh signature required", "write ssh signature required", "admin ssh signature required", "owner ssh signature required", "merge ssh signature required", "broker admin ssh signature required"} {
if strings.Contains(msg, scoped) {
return false
}
}
return true
}
func brokerForbiddenAllowsSignatureRetry(msg string) bool {
msg = strings.ToLower(strings.TrimSpace(msg))
if msg == "" {
return false
}
return strings.Contains(msg, "ssh signature required")
}
func brokerSignatureHeaders(payload []byte) map[string]string {
sets := brokerSignatureHeaderSetsForBroker("", "/", payload)
if len(sets) == 0 {
return map[string]string{}
}
return sets[0]
}
func brokerSignatureHeaderSets(payload []byte) []map[string]string {
return brokerSignatureHeaderSetsForBroker("", "/", payload)
}
func brokerSignatureHeaderSetsForBroker(brokerURL, requestPath string, payload []byte) []map[string]string {
signers := explicitBrokerSigners()
agentSigners, cleanup, err := sshAgentSigners()
if err == nil && len(agentSigners) > 0 {
signers = append(signers, agentSigners...)
}
if len(signers) == 0 {
return nil
}
if cleanup != nil {
defer cleanup()
}
host := brokerSignatureHost(brokerURL)
preferred := preferredBrokerKeyFingerprints(brokerURL, payload)
type signedHeaders struct {
fingerprint string
headers map[string]string
}
var signed []signedHeaders
for _, signer := range signers {
timestamp := fmt.Sprintf("%d", time.Now().Unix())
nonce, err := randomBrokerSignatureNonce()
if err != nil {
continue
}
message := brokerSignatureMessage(http.MethodPost, requestPath, host, timestamp, nonce, payload)
sig, err := signBrokerMessage(signer, message)
if err != nil {
continue
}
fingerprint := ssh.FingerprintSHA256(signer.PublicKey())
signed = append(signed, signedHeaders{fingerprint: fingerprint, headers: map[string]string{
"X-Bgit-Signature-Version": "2",
"X-Bgit-Key": strings.TrimSpace(string(ssh.MarshalAuthorizedKey(signer.PublicKey()))),
"X-Bgit-Key-Fingerprint": fingerprint,
"X-Bgit-Timestamp": timestamp,
"X-Bgit-Nonce": nonce,
"X-Bgit-Signed-Host": host,
"X-Bgit-Signature": base64.StdEncoding.EncodeToString(ssh.Marshal(sig)),
"X-Bgit-Signature-Message": base64.StdEncoding.EncodeToString(message),
}})
}
sort.SliceStable(signed, func(i, j int) bool {
return preferredBrokerKeyRank(signed[i].fingerprint, preferred) < preferredBrokerKeyRank(signed[j].fingerprint, preferred)
})
var sets []map[string]string
for _, item := range signed {
sets = append(sets, item.headers)
}
return sets
}
func brokerSignatureHost(brokerURL string) string {
u, err := url.Parse(strings.TrimSpace(brokerURL))
if err != nil || u.Host == "" {
return ""
}
return strings.ToLower(u.Host)
}
func randomBrokerSignatureNonce() (string, error) {
var nonce [16]byte
if _, err := rand.Read(nonce[:]); err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(nonce[:]), nil
}
func signBrokerMessage(signer ssh.Signer, message []byte) (*ssh.Signature, error) {
if signer.PublicKey().Type() == ssh.KeyAlgoRSA {
if algorithmSigner, ok := signer.(ssh.AlgorithmSigner); ok {
if sig, err := algorithmSigner.SignWithAlgorithm(rand.Reader, message, ssh.KeyAlgoRSASHA256); err == nil {
return sig, nil
}
}
}
return signer.Sign(rand.Reader, message)
}
func explicitBrokerSigners() []ssh.Signer {
var paths []string
for _, envName := range []string{"BGIT_SSH_KEY", "BGIT_SSH_KEYS"} {
for _, value := range filepath.SplitList(os.Getenv(envName)) {
if value = strings.TrimSpace(value); value != "" {
paths = append(paths, value)
}
}
}
if value := strings.TrimSpace(brokerIdentityPreference); value != "" && !strings.HasPrefix(value, "SHA256:") {
paths = append(paths, value)
}
seen := map[string]struct{}{}
var signers []ssh.Signer
for _, path := range paths {
path = expandHome(path)
if _, ok := seen[path]; ok {
continue
}
seen[path] = struct{}{}
data, err := os.ReadFile(path)
if err != nil {
continue