forked from sourcegraph/sourcegraph-public-snapshot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexternal_services.go
More file actions
1556 lines (1358 loc) · 46.8 KB
/
external_services.go
File metadata and controls
1556 lines (1358 loc) · 46.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 database
import (
"bytes"
"context"
"database/sql"
"fmt"
"net/url"
"strings"
"time"
jsoniter "github.com/json-iterator/go"
"github.com/keegancsmith/sqlf"
"github.com/lib/pq"
"github.com/tidwall/gjson"
"github.com/xeipuuv/gojsonschema"
"github.com/sourcegraph/log"
"github.com/sourcegraph/sourcegraph/cmd/frontend/envvar"
"github.com/sourcegraph/sourcegraph/internal/conf"
"github.com/sourcegraph/sourcegraph/internal/database/basestore"
"github.com/sourcegraph/sourcegraph/internal/database/dbutil"
"github.com/sourcegraph/sourcegraph/internal/database/locker"
"github.com/sourcegraph/sourcegraph/internal/encryption"
"github.com/sourcegraph/sourcegraph/internal/encryption/keyring"
"github.com/sourcegraph/sourcegraph/internal/extsvc"
"github.com/sourcegraph/sourcegraph/internal/jsonc"
"github.com/sourcegraph/sourcegraph/internal/timeutil"
"github.com/sourcegraph/sourcegraph/internal/trace/ot"
"github.com/sourcegraph/sourcegraph/internal/types"
"github.com/sourcegraph/sourcegraph/lib/errors"
"github.com/sourcegraph/sourcegraph/schema"
)
// BeforeCreateExternalService (if set) is invoked as a hook prior to creating a
// new external service in the database.
var BeforeCreateExternalService func(context.Context, ExternalServiceStore, *types.ExternalService) error
type ExternalServiceStore interface {
// Count counts all external services that satisfy the options (ignoring limit and offset).
//
// 🚨 SECURITY: The caller must ensure that the actor is a site admin or owner of the external service.
Count(ctx context.Context, opt ExternalServicesListOptions) (int, error)
// Create creates an external service.
//
// Since this method is used before the configuration server has started (search
// for "EXTSVC_CONFIG_FILE") you must pass the conf.Get function in so that an
// alternative can be used when the configuration server has not started,
// otherwise a panic would occur once pkg/conf's deadlock detector determines a
// deadlock occurred.
//
// 🚨 SECURITY: The caller must ensure that the actor is a site admin or owner
// of the external service. Otherwise, `es.NamespaceUserID` must be specified
// (i.e. non-nil) for a user-added external service.
//
// 🚨 SECURITY: The value of `es.Unrestricted` is disregarded and will always be
// recalculated based on whether "authorization" field is presented in
// `es.Config`. For Sourcegraph Cloud, the `es.Unrestricted` will always be
// false (i.e. enforce permissions).
Create(ctx context.Context, confGet func() *conf.Unified, es *types.ExternalService) error
// Delete deletes an external service.
//
// 🚨 SECURITY: The caller must ensure that the actor is a site admin or owner of the external service.
Delete(ctx context.Context, id int64) (err error)
// DistinctKinds returns the distinct list of external services kinds that are stored in the database.
DistinctKinds(ctx context.Context) ([]string, error)
// GetLatestSyncErrors returns the most recent sync failure message for
// each external service. If the latest sync did not have an error, the
// string will be empty. We exclude cloud_default external services as they
// are never synced.
GetLatestSyncErrors(ctx context.Context) (map[int64]string, error)
// GetByID returns the external service for id.
//
// 🚨 SECURITY: The caller must ensure that the actor is a site admin or owner of the external service.
GetByID(ctx context.Context, id int64) (*types.ExternalService, error)
// GetLastSyncError returns the error associated with the latest sync of the
// supplied external service.
//
// 🚨 SECURITY: The caller must ensure that the actor is a site admin or owner of the external service
GetLastSyncError(ctx context.Context, id int64) (string, error)
// GetSyncJobByID gets a sync job by its ID.
GetSyncJobByID(ctx context.Context, id int64) (job *types.ExternalServiceSyncJob, err error)
// GetSyncJobs gets all sync jobs.
GetSyncJobs(ctx context.Context, opt ExternalServicesGetSyncJobsOptions) ([]*types.ExternalServiceSyncJob, error)
// CountSyncJobs counts all sync jobs.
CountSyncJobs(ctx context.Context, opt ExternalServicesGetSyncJobsOptions) (int64, error)
// CancelSyncJob cancels a given sync job. It returns an error when the job was not
// found or not in processing or queued state.
CancelSyncJob(ctx context.Context, id int64) error
// List returns external services under given namespace.
// If no namespace is given, it returns all external services.
//
// 🚨 SECURITY: The caller must ensure one of the following:
// - The actor is a site admin
// - The opt.NamespaceUserID is same as authenticated user ID (i.e. actor.UID)
List(ctx context.Context, opt ExternalServicesListOptions) ([]*types.ExternalService, error)
// ListRepos returns external service repos for given externalServiceID.
//
// 🚨 SECURITY: The caller must ensure that the actor is a site admin or owner of the external service.
ListRepos(ctx context.Context, opt ExternalServiceReposListOptions) ([]*types.ExternalServiceRepo, error)
// RepoCount returns the number of repos synced by the external service with the
// given id.
//
// 🚨 SECURITY: The caller must ensure that the actor is a site admin or owner of the external service.
RepoCount(ctx context.Context, id int64) (int32, error)
// SyncDue returns true if any of the supplied external services are due to sync
// now or within given duration from now.
SyncDue(ctx context.Context, intIDs []int64, d time.Duration) (bool, error)
// Update updates an external service.
//
// 🚨 SECURITY: The caller must ensure that the actor is a site admin,
// or has the legitimate access to the external service (i.e. the owner).
Update(ctx context.Context, ps []schema.AuthProviders, id int64, update *ExternalServiceUpdate) (err error)
// Upsert updates or inserts the given ExternalServices.
//
// NOTE: Deletion of an external service via Upsert is not allowed. Use Delete()
// instead.
//
// 🚨 SECURITY: The value of `es.Unrestricted` is disregarded and will always be
// recalculated based on whether "authorization" field is presented in
// `es.Config`. For Sourcegraph Cloud, the `es.Unrestricted` will always be
// false (i.e. enforce permissions).
Upsert(ctx context.Context, svcs ...*types.ExternalService) (err error)
WithEncryptionKey(key encryption.Key) ExternalServiceStore
Transact(ctx context.Context) (ExternalServiceStore, error)
With(other basestore.ShareableStore) ExternalServiceStore
Done(err error) error
basestore.ShareableStore
}
// An externalServiceStore stores external services and their configuration.
// Before updating or creating a new external service, validation is performed.
// The enterprise code registers additional validators at run-time and sets the
// global instance in stores.go
type externalServiceStore struct {
logger log.Logger
*basestore.Store
key encryption.Key
}
func (e *externalServiceStore) copy() *externalServiceStore {
return &externalServiceStore{
Store: e.Store,
key: e.key,
}
}
// ExternalServicesWith instantiates and returns a new ExternalServicesStore with prepared statements.
func ExternalServicesWith(logger log.Logger, other basestore.ShareableStore) ExternalServiceStore {
return &externalServiceStore{
logger: logger,
Store: basestore.NewWithHandle(other.Handle()),
}
}
func (e *externalServiceStore) With(other basestore.ShareableStore) ExternalServiceStore {
s := e.copy()
s.Store = e.Store.With(other)
return s
}
func (e *externalServiceStore) WithEncryptionKey(key encryption.Key) ExternalServiceStore {
s := e.copy()
s.key = key
return s
}
func (e *externalServiceStore) Transact(ctx context.Context) (ExternalServiceStore, error) {
return e.transact(ctx)
}
func (e *externalServiceStore) transact(ctx context.Context) (*externalServiceStore, error) {
txBase, err := e.Store.Transact(ctx)
s := e.copy()
s.Store = txBase
return s, err
}
func (e *externalServiceStore) Done(err error) error {
return e.Store.Done(err)
}
// ExternalServiceKinds contains a map of all supported kinds of
// external services.
var ExternalServiceKinds = map[string]ExternalServiceKind{
extsvc.KindAWSCodeCommit: {CodeHost: true, JSONSchema: schema.AWSCodeCommitSchemaJSON},
extsvc.KindBitbucketCloud: {CodeHost: true, JSONSchema: schema.BitbucketCloudSchemaJSON},
extsvc.KindBitbucketServer: {CodeHost: true, JSONSchema: schema.BitbucketServerSchemaJSON},
extsvc.KindGerrit: {CodeHost: true, JSONSchema: schema.GerritSchemaJSON},
extsvc.KindGitHub: {CodeHost: true, JSONSchema: schema.GitHubSchemaJSON},
extsvc.KindGitLab: {CodeHost: true, JSONSchema: schema.GitLabSchemaJSON},
extsvc.KindGitolite: {CodeHost: true, JSONSchema: schema.GitoliteSchemaJSON},
extsvc.KindGoPackages: {CodeHost: true, JSONSchema: schema.GoModulesSchemaJSON},
extsvc.KindJVMPackages: {CodeHost: true, JSONSchema: schema.JVMPackagesSchemaJSON},
extsvc.KindNpmPackages: {CodeHost: true, JSONSchema: schema.NpmPackagesSchemaJSON},
extsvc.KindOther: {CodeHost: true, JSONSchema: schema.OtherExternalServiceSchemaJSON},
extsvc.KindPagure: {CodeHost: true, JSONSchema: schema.PagureSchemaJSON},
extsvc.KindPerforce: {CodeHost: true, JSONSchema: schema.PerforceSchemaJSON},
extsvc.KindPhabricator: {CodeHost: true, JSONSchema: schema.PhabricatorSchemaJSON},
extsvc.KindPythonPackages: {CodeHost: true, JSONSchema: schema.PythonPackagesSchemaJSON},
extsvc.KindRustPackages: {CodeHost: true, JSONSchema: schema.RustPackagesSchemaJSON},
}
// ExternalServiceKind describes a kind of external service.
type ExternalServiceKind struct {
// True if the external service can host repositories.
CodeHost bool
JSONSchema string // JSON Schema for the external service's configuration
}
type ExternalServiceReposListOptions ExternalServicesGetSyncJobsOptions
type ExternalServicesGetSyncJobsOptions struct {
ExternalServiceID int64
*LimitOffset
}
// ExternalServicesListOptions contains options for listing external services.
type ExternalServicesListOptions struct {
// When specified, only include external services with the given IDs.
IDs []int64
// When true, only include external services not under any namespace (i.e. owned
// by all site admins), and values of ExcludeNamespaceUser, NamespaceUserID and
// NamespaceOrgID are ignored.
NoNamespace bool
// When true, will exclude external services under any user namespace, and the
// value of NamespaceUserID is ignored.
ExcludeNamespaceUser bool
// When specified, only include external services under given user namespace.
NamespaceUserID int32
// When specified, only include external services under given organization namespace.
NamespaceOrgID int32
// When specified, only include external services with given list of kinds.
Kinds []string
// When specified, only include external services with ID below this number
// (because we're sorting results by ID in descending order).
AfterID int64
// When specified, only include external services with that were updated after
// the specified time.
UpdatedAfter time.Time
// Possible values are ASC or DESC. Defaults to DESC.
OrderByDirection string
// When true, will only return services that have the cloud_default flag set to
// true.
OnlyCloudDefault bool
*LimitOffset
// When true, soft-deleted external services will also be included in the results.
IncludeDeleted bool
}
func (o ExternalServicesListOptions) sqlConditions() []*sqlf.Query {
conds := []*sqlf.Query{}
if !o.IncludeDeleted {
conds = append(conds, sqlf.Sprintf("deleted_at IS NULL"))
}
if len(o.IDs) > 0 {
conds = append(conds, sqlf.Sprintf("id = ANY(%s)", pq.Array(o.IDs)))
}
if o.NoNamespace {
conds = append(conds, sqlf.Sprintf(`namespace_user_id IS NULL AND namespace_org_id IS NULL`))
} else {
if o.ExcludeNamespaceUser {
conds = append(conds, sqlf.Sprintf(`namespace_user_id IS NULL`))
} else if o.NamespaceUserID > 0 {
conds = append(conds, sqlf.Sprintf(`namespace_user_id = %d`, o.NamespaceUserID))
}
if o.NamespaceOrgID > 0 {
conds = append(conds, sqlf.Sprintf(`namespace_org_id = %d`, o.NamespaceOrgID))
}
}
if len(o.Kinds) > 0 {
conds = append(conds, sqlf.Sprintf("kind = ANY(%s)", pq.Array(o.Kinds)))
}
if o.AfterID > 0 {
conds = append(conds, sqlf.Sprintf(`id < %d`, o.AfterID))
}
if !o.UpdatedAfter.IsZero() {
conds = append(conds, sqlf.Sprintf(`updated_at > %s`, o.UpdatedAfter))
}
if o.OnlyCloudDefault {
conds = append(conds, sqlf.Sprintf("cloud_default = true"))
}
if len(conds) == 0 {
conds = append(conds, sqlf.Sprintf("TRUE"))
}
return conds
}
type ValidateExternalServiceConfigOptions struct {
// The ID of the external service, 0 is a valid value for not-yet-created external service.
ExternalServiceID int64
// The kind of external service.
Kind string
// The actual config of the external service.
Config string
// The list of authN providers configured on the instance.
AuthProviders []schema.AuthProviders
// If non zero, indicates the user that owns the external service.
NamespaceUserID int32
// If non zero, indicates the organization that owns the codehost connection.
NamespaceOrgID int32
}
// IsSiteOwned returns true if the external service is owned by the site.
func (e *ValidateExternalServiceConfigOptions) IsSiteOwned() bool {
return e.NamespaceUserID == 0 && e.NamespaceOrgID == 0
}
type ValidateExternalServiceConfigFunc = func(ctx context.Context, e ExternalServiceStore, opt ValidateExternalServiceConfigOptions) (normalized []byte, err error)
// ValidateExternalServiceConfig is the default non-enterprise version of our validation function
var ValidateExternalServiceConfig = MakeValidateExternalServiceConfigFunc(nil, nil, nil, nil)
func MakeValidateExternalServiceConfigFunc(gitHubValidators []func(*types.GitHubConnection) error, gitLabValidators []func(*schema.GitLabConnection, []schema.AuthProviders) error, bitbucketServerValidators []func(*schema.BitbucketServerConnection) error, perforceValidators []func(*schema.PerforceConnection) error) ValidateExternalServiceConfigFunc {
return func(ctx context.Context, e ExternalServiceStore, opt ValidateExternalServiceConfigOptions) (normalized []byte, err error) {
ext, ok := ExternalServiceKinds[opt.Kind]
if !ok {
return nil, errors.Errorf("invalid external service kind: %s", opt.Kind)
}
// All configs must be valid JSON.
// If this requirement is ever changed, you will need to update
// serveExternalServiceConfigs to handle this case.
sl := gojsonschema.NewSchemaLoader()
sc, err := sl.Compile(gojsonschema.NewStringLoader(ext.JSONSchema))
if err != nil {
return nil, errors.Wrapf(err, "unable to compile schema for external service of kind %q", opt.Kind)
}
normalized, err = jsonc.Parse(opt.Config)
if err != nil {
return nil, errors.Wrapf(err, "unable to normalize JSON")
}
// Check for any redacted secrets, in
// graphqlbackend/external_service.go:externalServiceByID() we call
// svc.RedactConfigSecrets() replacing any secret fields in the JSON with
// types.RedactedSecret, this is to prevent us leaking tokens that users add.
// Here we check that the config we've been passed doesn't contain any redacted
// secrets in order to avoid breaking configs by writing the redacted version to
// the database. we should have called svc.UnredactConfig(oldSvc) before this
// point, e.g. in the Update method of the ExternalServiceStore.
if bytes.Contains(normalized, []byte(types.RedactedSecret)) {
return nil, errors.Errorf(
"unable to write external service config as it contains redacted fields, this is likely a bug rather than a problem with your config",
)
}
// For user-added and org-added external services, we need to prevent them from using disallowed fields.
if !opt.IsSiteOwned() {
// We do not allow users to add external service other than GitHub.com and GitLab.com
result := gjson.GetBytes(normalized, "url")
baseURL, err := url.Parse(result.String())
if err != nil {
return nil, errors.Wrap(err, "parse base URL")
}
normalizedURL := extsvc.NormalizeBaseURL(baseURL).String()
if normalizedURL != "https://github.com/" &&
normalizedURL != "https://gitlab.com/" {
return nil, errors.New("external service only allowed for https://github.com/ and https://gitlab.com/")
}
disallowedFields := []string{"repositoryPathPattern", "nameTransformations", "rateLimit"}
results := gjson.GetManyBytes(normalized, disallowedFields...)
for i, r := range results {
if r.Exists() {
return nil, errors.Errorf("field %q is not allowed in a user-added external service", disallowedFields[i])
}
}
}
res, err := sc.Validate(gojsonschema.NewBytesLoader(normalized))
if err != nil {
return nil, errors.Wrap(err, "unable to validate config against schema")
}
var errs error
for _, err := range res.Errors() {
errString := err.String()
// Remove `(root): ` from error formatting since these errors are
// presented to users.
errString = strings.TrimPrefix(errString, "(root): ")
errs = errors.Append(errs, errors.New(errString))
}
// Extra validation not based on JSON Schema.
switch opt.Kind {
case extsvc.KindGitHub:
var c schema.GitHubConnection
if err = jsoniter.Unmarshal(normalized, &c); err != nil {
return nil, err
}
err = validateGitHubConnection(gitHubValidators, opt.ExternalServiceID, &c)
case extsvc.KindGitLab:
var c schema.GitLabConnection
if err = jsoniter.Unmarshal(normalized, &c); err != nil {
return nil, err
}
err = validateGitLabConnection(gitLabValidators, opt.ExternalServiceID, &c, opt.AuthProviders)
case extsvc.KindBitbucketServer:
var c schema.BitbucketServerConnection
if err = jsoniter.Unmarshal(normalized, &c); err != nil {
return nil, err
}
err = validateBitbucketServerConnection(bitbucketServerValidators, opt.ExternalServiceID, &c)
case extsvc.KindBitbucketCloud:
var c schema.BitbucketCloudConnection
if err = jsoniter.Unmarshal(normalized, &c); err != nil {
return nil, err
}
case extsvc.KindPerforce:
var c schema.PerforceConnection
if err = jsoniter.Unmarshal(normalized, &c); err != nil {
return nil, err
}
err = validatePerforceConnection(perforceValidators, opt.ExternalServiceID, &c)
case extsvc.KindOther:
var c schema.OtherExternalServiceConnection
if err = jsoniter.Unmarshal(normalized, &c); err != nil {
return nil, err
}
err = validateOtherExternalServiceConnection(&c)
}
return normalized, errors.Append(errs, err)
}
}
// Neither our JSON schema library nor the Monaco editor we use supports
// object dependencies well, so we must validate here that repo items
// match the uri-reference format when url is set, instead of uri when
// it isn't.
func validateOtherExternalServiceConnection(c *schema.OtherExternalServiceConnection) error {
parseRepo := url.Parse
if c.Url != "" {
// We ignore the error because this already validated by JSON Schema.
baseURL, _ := url.Parse(c.Url)
parseRepo = baseURL.Parse
}
for i, repo := range c.Repos {
cloneURL, err := parseRepo(repo)
if err != nil {
return errors.Errorf(`repos.%d: %s`, i, err)
}
switch cloneURL.Scheme {
case "git", "http", "https", "ssh":
continue
default:
return errors.Errorf("repos.%d: scheme %q not one of git, http, https or ssh", i, cloneURL.Scheme)
}
}
return nil
}
func validateGitHubConnection(githubValidators []func(*types.GitHubConnection) error, id int64, c *schema.GitHubConnection) error {
var err error
for _, validate := range githubValidators {
err = errors.Append(err,
validate(&types.GitHubConnection{
URN: extsvc.URN(extsvc.KindGitHub, id),
GitHubConnection: c,
}),
)
}
if c.Token == "" && c.GithubAppInstallationID == "" {
err = errors.Append(err, errors.New("at least one of token or githubAppInstallationID must be set"))
}
if c.Repos == nil && c.RepositoryQuery == nil && c.Orgs == nil {
err = errors.Append(err, errors.New("at least one of repositoryQuery, repos or orgs must be set"))
}
return err
}
func validateGitLabConnection(gitLabValidators []func(*schema.GitLabConnection, []schema.AuthProviders) error, _ int64, c *schema.GitLabConnection, ps []schema.AuthProviders) error {
var err error
for _, validate := range gitLabValidators {
err = errors.Append(err, validate(c, ps))
}
return err
}
func validateBitbucketServerConnection(bitbucketServerValidators []func(connection *schema.BitbucketServerConnection) error, _ int64, c *schema.BitbucketServerConnection) error {
var err error
for _, validate := range bitbucketServerValidators {
err = errors.Append(err, validate(c))
}
if c.Repos == nil && c.RepositoryQuery == nil && c.ProjectKeys == nil {
err = errors.Append(err, errors.New("at least one of: repositoryQuery, projectKeys, or repos must be set"))
}
return err
}
func validatePerforceConnection(perforceValidators []func(*schema.PerforceConnection) error, _ int64, c *schema.PerforceConnection) error {
var err error
for _, validate := range perforceValidators {
err = errors.Append(err, validate(c))
}
if c.Depots == nil {
err = errors.Append(err, errors.New("depots must be set"))
}
return err
}
// upsertAuthorizationToExternalService adds "authorization" field to the
// external service config when not yet present for GitHub and GitLab.
func upsertAuthorizationToExternalService(kind, config string) (string, error) {
switch kind {
case extsvc.KindGitHub:
return jsonc.Edit(config, &schema.GitHubAuthorization{}, "authorization")
case extsvc.KindGitLab:
return jsonc.Edit(config,
&schema.GitLabAuthorization{
IdentityProvider: schema.IdentityProvider{
Oauth: &schema.OAuthIdentity{
Type: "oauth",
},
},
},
"authorization")
}
return config, nil
}
func (e *externalServiceStore) Create(ctx context.Context, confGet func() *conf.Unified, es *types.ExternalService) error {
rawConfig, err := es.Config.Decrypt(ctx)
if err != nil {
return err
}
normalized, err := ValidateExternalServiceConfig(ctx, e, ValidateExternalServiceConfigOptions{
Kind: es.Kind,
Config: rawConfig,
AuthProviders: confGet().AuthProviders,
NamespaceUserID: es.NamespaceUserID,
NamespaceOrgID: es.NamespaceOrgID,
})
if err != nil {
return err
}
// 🚨 SECURITY: For all GitHub and GitLab code host connections on Sourcegraph
// Cloud, we always want to enforce repository permissions using OAuth to
// prevent unexpected resource leaking.
if envvar.SourcegraphDotComMode() {
rawConfig, err = upsertAuthorizationToExternalService(es.Kind, rawConfig)
if err != nil {
return err
}
es.Config.Set(rawConfig)
}
es.CreatedAt = timeutil.Now()
es.UpdatedAt = es.CreatedAt
// Prior to saving the record, run a validation hook.
if BeforeCreateExternalService != nil {
if err = BeforeCreateExternalService(ctx, NewDBWith(e.logger, e.Store).ExternalServices(), es); err != nil {
return err
}
}
// Ensure the calculated fields in the external service are up to date.
if err := e.recalculateFields(es, string(normalized)); err != nil {
return err
}
encryptedConfig, keyID, err := es.Config.Encrypt(ctx, e.getEncryptionKey())
if err != nil {
return err
}
return e.QueryRow(
ctx,
sqlf.Sprintf(
createExternalServiceQueryFmtstr,
es.Kind,
es.DisplayName,
encryptedConfig,
keyID,
es.CreatedAt,
es.UpdatedAt,
nullInt32Column(es.NamespaceUserID),
nullInt32Column(es.NamespaceOrgID),
es.Unrestricted,
es.CloudDefault,
es.HasWebhooks,
),
).Scan(&es.ID)
}
const createExternalServiceQueryFmtstr = `
INSERT INTO external_services
(kind, display_name, config, encryption_key_id, created_at, updated_at, namespace_user_id, namespace_org_id, unrestricted, cloud_default, has_webhooks)
VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
RETURNING id
`
func (e *externalServiceStore) getEncryptionKey() encryption.Key {
if e.key != nil {
return e.key
}
return keyring.Default().ExternalServiceKey
}
func (e *externalServiceStore) Upsert(ctx context.Context, svcs ...*types.ExternalService) (err error) {
if len(svcs) == 0 {
return nil
}
authProviders := conf.Get().AuthProviders
for _, s := range svcs {
rawConfig, err := s.Config.Decrypt(ctx)
if err != nil {
return err
}
normalized, err := ValidateExternalServiceConfig(ctx, e, ValidateExternalServiceConfigOptions{
Kind: s.Kind,
Config: rawConfig,
AuthProviders: authProviders,
NamespaceUserID: s.NamespaceUserID,
NamespaceOrgID: s.NamespaceOrgID,
})
if err != nil {
return errors.Wrapf(err, "validating service of kind %q", s.Kind)
}
// 🚨 SECURITY: For all GitHub and GitLab code host connections on Sourcegraph
// Cloud, we always want to enforce repository permissions using OAuth to
// prevent unexpected resource leaking.
if envvar.SourcegraphDotComMode() {
rawConfig, err = upsertAuthorizationToExternalService(s.Kind, rawConfig)
if err != nil {
return err
}
s.Config.Set(rawConfig)
}
if err := e.recalculateFields(s, string(normalized)); err != nil {
return err
}
}
tx, err := e.transact(ctx)
if err != nil {
return err
}
defer func() { err = tx.Done(err) }()
// Get the list services that are marked as deleted. We don't know at this point
// whether they are marked as deleted in the DB too.
var deleted []int64
for _, es := range svcs {
if es.ID != 0 && es.IsDeleted() {
deleted = append(deleted, es.ID)
}
}
// Fetch any services marked for deletion. list() only fetches non deleted
// services so if we find anything here it indicates that we are marking a
// service as deleted that is NOT deleted in the DB
if len(deleted) > 0 {
existing, err := tx.List(ctx, ExternalServicesListOptions{IDs: deleted})
if err != nil {
return errors.Wrap(err, "fetching services marked for deletion")
}
if len(existing) > 0 {
// We found services marked for deletion that are currently not deleted in the
// DB.
return errors.New("deletion via Upsert() not allowed, use Delete()")
}
}
q, err := tx.upsertExternalServicesQuery(ctx, svcs)
if err != nil {
return err
}
rows, err := tx.Query(ctx, q)
if err != nil {
return err
}
defer func() { err = basestore.CloseRows(rows, err) }()
i := 0
for rows.Next() {
var encryptedConfig, keyID string
err = rows.Scan(
&svcs[i].ID,
&svcs[i].Kind,
&svcs[i].DisplayName,
&encryptedConfig,
&svcs[i].CreatedAt,
&dbutil.NullTime{Time: &svcs[i].UpdatedAt},
&dbutil.NullTime{Time: &svcs[i].DeletedAt},
&dbutil.NullTime{Time: &svcs[i].LastSyncAt},
&dbutil.NullTime{Time: &svcs[i].NextSyncAt},
&dbutil.NullInt32{N: &svcs[i].NamespaceUserID},
&dbutil.NullInt32{N: &svcs[i].NamespaceOrgID},
&svcs[i].Unrestricted,
&svcs[i].CloudDefault,
&keyID,
&dbutil.NullBool{B: svcs[i].HasWebhooks},
)
if err != nil {
return err
}
svcs[i].Config = extsvc.NewEncryptedConfig(encryptedConfig, keyID, e.getEncryptionKey())
i++
}
return nil
}
func (e *externalServiceStore) upsertExternalServicesQuery(ctx context.Context, svcs []*types.ExternalService) (*sqlf.Query, error) {
vals := make([]*sqlf.Query, 0, len(svcs))
for _, s := range svcs {
encryptedConfig, keyID, err := s.Config.Encrypt(ctx, e.getEncryptionKey())
if err != nil {
return nil, err
}
vals = append(vals, sqlf.Sprintf(
upsertExternalServicesQueryValueFmtstr,
s.ID,
s.Kind,
s.DisplayName,
encryptedConfig,
keyID,
s.CreatedAt.UTC(),
s.UpdatedAt.UTC(),
nullTimeColumn(s.DeletedAt),
nullTimeColumn(s.LastSyncAt),
nullTimeColumn(s.NextSyncAt),
nullInt32Column(s.NamespaceUserID),
nullInt32Column(s.NamespaceOrgID),
s.Unrestricted,
s.CloudDefault,
s.HasWebhooks,
))
}
return sqlf.Sprintf(
upsertExternalServicesQueryFmtstr,
sqlf.Join(vals, ",\n"),
), nil
}
const upsertExternalServicesQueryValueFmtstr = `
(COALESCE(NULLIF(%s, 0), (SELECT nextval('external_services_id_seq'))), UPPER(%s), %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
`
const upsertExternalServicesQueryFmtstr = `
-- source: internal/database/external_services.go:ExternalServiceStore.Upsert
INSERT INTO external_services (
id,
kind,
display_name,
config,
encryption_key_id,
created_at,
updated_at,
deleted_at,
last_sync_at,
next_sync_at,
namespace_user_id,
namespace_org_id,
unrestricted,
cloud_default,
has_webhooks
)
VALUES %s
ON CONFLICT(id) DO UPDATE
SET
kind = UPPER(excluded.kind),
display_name = excluded.display_name,
config = excluded.config,
encryption_key_id = excluded.encryption_key_id,
created_at = excluded.created_at,
updated_at = excluded.updated_at,
deleted_at = excluded.deleted_at,
last_sync_at = excluded.last_sync_at,
next_sync_at = excluded.next_sync_at,
namespace_user_id = excluded.namespace_user_id,
namespace_org_id = excluded.namespace_org_id,
unrestricted = excluded.unrestricted,
cloud_default = excluded.cloud_default,
has_webhooks = excluded.has_webhooks
RETURNING
id,
kind,
display_name,
config,
created_at,
updated_at,
deleted_at,
last_sync_at,
next_sync_at,
namespace_user_id,
namespace_org_id,
unrestricted,
cloud_default,
encryption_key_id,
has_webhooks
`
// ExternalServiceUpdate contains optional fields to update.
type ExternalServiceUpdate struct {
DisplayName *string
Config *string
CloudDefault *bool
TokenExpiresAt *time.Time
}
func (e *externalServiceStore) Update(ctx context.Context, ps []schema.AuthProviders, id int64, update *ExternalServiceUpdate) (err error) {
var (
normalized []byte
encryptedConfig string
keyID string
hasWebhooks bool
)
if update.Config != nil {
rawConfig := *update.Config
// Query to get the kind (which is immutable) so we can validate the new config.
externalService, err := e.GetByID(ctx, id)
if err != nil {
return err
}
newSvc := types.ExternalService{
Kind: externalService.Kind,
Config: extsvc.NewUnencryptedConfig(rawConfig),
}
if err := newSvc.UnredactConfig(ctx, externalService); err != nil {
return errors.Wrapf(err, "error unredacting config")
}
unredactedConfig, err := newSvc.Config.Decrypt(ctx)
if err != nil {
return err
}
cfg, err := newSvc.Configuration(ctx)
if err == nil {
hasWebhooks = configurationHasWebhooks(cfg)
} else {
// Legacy configurations might not be valid JSON; in that case, they
// also can't have webhooks, so we'll just log the issue and move
// on.
e.logger.Warn("cannot parse external service configuration as JSON", log.Error(err), log.Int64("id", id))
hasWebhooks = false
}
normalized, err = ValidateExternalServiceConfig(ctx, e, ValidateExternalServiceConfigOptions{
ExternalServiceID: id,
Kind: externalService.Kind,
Config: unredactedConfig,
AuthProviders: ps,
NamespaceUserID: externalService.NamespaceUserID,
NamespaceOrgID: externalService.NamespaceOrgID,
})
if err != nil {
return err
}
// 🚨 SECURITY: For all GitHub and GitLab code host connections on Sourcegraph
// Cloud, we always want to enforce repository permissions using OAuth to
// prevent unexpected resource leaking.
if envvar.SourcegraphDotComMode() {
unredactedConfig, err = upsertAuthorizationToExternalService(externalService.Kind, unredactedConfig)
if err != nil {
return err
}
newSvc.Config.Set(unredactedConfig)
}
encryptedConfig, keyID, err = newSvc.Config.Encrypt(ctx, e.getEncryptionKey())
if err != nil {
return err
}
}
// 4 is the number of fields of the ExternalServiceUpdate
updates := make([]*sqlf.Query, 0, 4)
if update.DisplayName != nil {
updates = append(updates, sqlf.Sprintf("display_name = %s", update.DisplayName))
}
if update.Config != nil {
unrestricted := !envvar.SourcegraphDotComMode() && !gjson.GetBytes(normalized, "authorization").Exists()
updates = append(updates,
sqlf.Sprintf(
"config = %s, encryption_key_id = %s, next_sync_at = NOW(), unrestricted = %s, has_webhooks = %s",
encryptedConfig, keyID, unrestricted, hasWebhooks,
))
}
if update.CloudDefault != nil {
updates = append(updates, sqlf.Sprintf("cloud_default = %s", update.CloudDefault))
}
if update.TokenExpiresAt != nil {
updates = append(updates, sqlf.Sprintf("token_expires_at = %s", update.TokenExpiresAt))
}
if len(updates) == 0 {
return nil
}
q := sqlf.Sprintf("UPDATE external_services SET %s, updated_at = NOW() WHERE id = %d AND deleted_at IS NULL", sqlf.Join(updates, ","), id)
res, err := e.Store.Handle().ExecContext(ctx, q.Query(sqlf.PostgresBindVar), q.Args()...)
if err != nil {
return err
}
affected, err := res.RowsAffected()
if err != nil {
return err
}
if affected == 0 {
return externalServiceNotFoundError{id: id}
}
return nil
}
type externalServiceNotFoundError struct {
id int64
}
func (e externalServiceNotFoundError) Error() string {
return fmt.Sprintf("external service not found: %v", e.id)
}
func (e externalServiceNotFoundError) NotFound() bool {
return true
}
func (e *externalServiceStore) Delete(ctx context.Context, id int64) (err error) {
tx, err := e.transact(ctx)
if err != nil {
return err
}
defer func() { err = tx.Done(err) }()
// We take an advisory lock here and also when syncing an external service to
// ensure that they can't happen at the same time.
lock := locker.NewWith(tx, "external_service")
locked, err := lock.LockInTransaction(ctx, locker.StringKey(fmt.Sprintf("%d", id)), false)
if err != nil {
return errors.Wrap(err, "getting advisory lock")
}
if !locked {
return errors.Errorf("could not get advisory lock for service %d", id)
}
// Create a temporary table where we'll store repos affected by the deletion of
// the external service
if err := tx.Exec(ctx, sqlf.Sprintf(`