-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathdeployment.go
More file actions
4698 lines (4469 loc) · 198 KB
/
deployment.go
File metadata and controls
4698 lines (4469 loc) · 198 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 codersdk
import (
"context"
"encoding/json"
"flag"
"fmt"
"net/http"
"os"
"path/filepath"
"reflect"
"slices"
"strconv"
"strings"
"time"
"github.com/coreos/go-oidc/v3/oidc"
"github.com/google/uuid"
"golang.org/x/mod/semver"
"golang.org/x/text/cases"
"golang.org/x/text/language"
"golang.org/x/xerrors"
"github.com/coder/coder/v2/buildinfo"
"github.com/coder/coder/v2/coderd/agentmetrics"
"github.com/coder/coder/v2/coderd/workspaceapps/appurl"
"github.com/coder/serpent"
)
// Entitlement represents whether a feature is licensed.
type Entitlement string
const (
EntitlementEntitled Entitlement = "entitled"
EntitlementGracePeriod Entitlement = "grace_period"
EntitlementNotEntitled Entitlement = "not_entitled"
)
// Entitled returns if the entitlement can be used. So this is true if it
// is entitled or still in it's grace period.
func (e Entitlement) Entitled() bool {
return e == EntitlementEntitled || e == EntitlementGracePeriod
}
// Weight converts the enum types to a numerical value for easier
// comparisons. Easier than sets of if statements.
func (e Entitlement) Weight() int {
switch e {
case EntitlementEntitled:
return 2
case EntitlementGracePeriod:
return 1
case EntitlementNotEntitled:
return -1
default:
return -2
}
}
// Addon represents a grouping of features used for additional license SKUs.
// It is complementary to FeatureSet and similar in implementation, allowing
// features to be grouped together dynamically. Unlike FeatureSet, licenses
// can have multiple addons. This also means that entitlements don't require
// reissuing when new features are added to an addon.
type Addon string
const (
AddonAIGovernance Addon = "ai_governance"
)
var (
// AddonsNames must be kept in-sync with the Addon enum above.
AddonsNames = []Addon{
AddonAIGovernance,
}
// AddonsMap is a map of all addon names for quick lookups.
AddonsMap = func() map[Addon]struct{} {
addonsMap := make(map[Addon]struct{}, len(AddonsNames))
for _, addon := range AddonsNames {
addonsMap[addon] = struct{}{}
}
return addonsMap
}()
)
// Features returns all the features that are part of the addon.
func (a Addon) Features() []FeatureName {
switch a {
case AddonAIGovernance:
// Return all AI Governance features.
var features []FeatureName
for _, featureName := range FeatureNames {
if featureName.IsAIGovernanceAddon() {
features = append(features, featureName)
}
}
return features
default:
return nil
}
}
// ValidateDependencies validates the dependencies of the addon
// and returns a list of errors for the missing dependencies.
func (a Addon) ValidateDependencies(features map[FeatureName]Feature) []string {
errors := []string{}
// Candidate for a switch statement once we have more addons.
if a == AddonAIGovernance {
requiredFeatures := []FeatureName{
FeatureAIGovernanceUserLimit,
}
for _, featureName := range requiredFeatures {
feature, ok := features[featureName]
if !ok {
errors = append(errors,
fmt.Sprintf(
"Feature %s must be set when using the %s addon.",
featureName.Humanize(),
a.Humanize(),
),
)
continue
}
// For limit features, check if the Limit is set (not nil).
// For usage period features, check if the Limit is set.
if featureName.UsesLimit() || featureName.UsesUsagePeriod() {
if feature.Limit == nil {
errors = append(errors,
fmt.Sprintf(
"Feature %s must be set when using the %s addon.",
featureName.Humanize(),
a.Humanize(),
),
)
}
} else if feature.Entitlement == EntitlementNotEntitled {
// For non-limit features, check if the feature is entitled.
errors = append(errors,
fmt.Sprintf(
"Feature %s must be set when using the %s addon.",
featureName.Humanize(),
a.Humanize(),
),
)
}
}
}
return errors
}
// Humanize returns the addon name in a human-readable format.
func (a Addon) Humanize() string {
switch a {
case AddonAIGovernance:
return "AI Governance"
default:
return strings.Title(strings.ReplaceAll(string(a), "_", " "))
}
}
// FeatureName represents the internal name of a feature.
// To add a new feature, add it to this set of enums as well as the FeatureNames
// array below.
type FeatureName string
const (
FeatureUserLimit FeatureName = "user_limit"
FeatureAuditLog FeatureName = "audit_log"
FeatureConnectionLog FeatureName = "connection_log"
FeatureBrowserOnly FeatureName = "browser_only"
FeatureSCIM FeatureName = "scim"
FeatureTemplateRBAC FeatureName = "template_rbac"
FeatureUserRoleManagement FeatureName = "user_role_management"
FeatureHighAvailability FeatureName = "high_availability"
FeatureMultipleExternalAuth FeatureName = "multiple_external_auth"
FeatureExternalProvisionerDaemons FeatureName = "external_provisioner_daemons"
FeatureAppearance FeatureName = "appearance"
FeatureAdvancedTemplateScheduling FeatureName = "advanced_template_scheduling"
FeatureWorkspaceProxy FeatureName = "workspace_proxy"
FeatureExternalTokenEncryption FeatureName = "external_token_encryption"
FeatureWorkspaceBatchActions FeatureName = "workspace_batch_actions"
FeatureTaskBatchActions FeatureName = "task_batch_actions"
FeatureAccessControl FeatureName = "access_control"
FeatureControlSharedPorts FeatureName = "control_shared_ports"
FeatureCustomRoles FeatureName = "custom_roles"
FeatureMultipleOrganizations FeatureName = "multiple_organizations"
FeatureWorkspacePrebuilds FeatureName = "workspace_prebuilds"
// ManagedAgentLimit is a usage period feature, so the value in the license
// contains both a soft and hard limit. Refer to
// enterprise/coderd/license/license.go for the license format.
FeatureManagedAgentLimit FeatureName = "managed_agent_limit"
FeatureWorkspaceExternalAgent FeatureName = "workspace_external_agent"
FeatureAIBridge FeatureName = "aibridge"
FeatureBoundary FeatureName = "boundary"
FeatureServiceAccounts FeatureName = "service_accounts"
FeatureAIGovernanceUserLimit FeatureName = "ai_governance_user_limit"
)
var (
// FeatureNames must be kept in-sync with the Feature enum above.
FeatureNames = []FeatureName{
FeatureUserLimit,
FeatureAuditLog,
FeatureConnectionLog,
FeatureBrowserOnly,
FeatureSCIM,
FeatureTemplateRBAC,
FeatureHighAvailability,
FeatureMultipleExternalAuth,
FeatureExternalProvisionerDaemons,
FeatureAppearance,
FeatureAdvancedTemplateScheduling,
FeatureWorkspaceProxy,
FeatureUserRoleManagement,
FeatureExternalTokenEncryption,
FeatureWorkspaceBatchActions,
FeatureTaskBatchActions,
FeatureAccessControl,
FeatureControlSharedPorts,
FeatureCustomRoles,
FeatureMultipleOrganizations,
FeatureWorkspacePrebuilds,
FeatureManagedAgentLimit,
FeatureWorkspaceExternalAgent,
FeatureAIBridge,
FeatureBoundary,
FeatureServiceAccounts,
FeatureAIGovernanceUserLimit,
}
// FeatureNamesMap is a map of all feature names for quick lookups.
FeatureNamesMap = func() map[FeatureName]struct{} {
featureNamesMap := make(map[FeatureName]struct{}, len(FeatureNames))
for _, featureName := range FeatureNames {
featureNamesMap[featureName] = struct{}{}
}
return featureNamesMap
}()
)
// Humanize returns the feature name in a human-readable format.
func (n FeatureName) Humanize() string {
switch n {
case FeatureTemplateRBAC:
return "Template RBAC"
case FeatureSCIM:
return "SCIM"
case FeatureAIBridge:
return "AI Bridge"
case FeatureAIGovernanceUserLimit:
return "AI Governance User Limit"
default:
return strings.Title(strings.ReplaceAll(string(n), "_", " "))
}
}
// AlwaysEnable returns if the feature is always enabled if entitled.
// This is required because some features are only enabled if they are entitled
// and not required.
// E.g: "multiple-organizations" is disabled by default in AGPL and enterprise
// deployments. This feature should only be enabled for premium deployments
// when it is entitled.
func (n FeatureName) AlwaysEnable() bool {
return map[FeatureName]bool{
FeatureMultipleExternalAuth: true,
FeatureExternalProvisionerDaemons: true,
FeatureAppearance: true,
FeatureWorkspaceBatchActions: true,
FeatureTaskBatchActions: true,
FeatureHighAvailability: true,
FeatureCustomRoles: true,
FeatureMultipleOrganizations: true,
FeatureWorkspacePrebuilds: true,
FeatureWorkspaceExternalAgent: true,
FeatureBoundary: true,
FeatureServiceAccounts: true,
}[n]
}
// Enterprise returns true if the feature is an enterprise feature.
func (n FeatureName) Enterprise() bool {
switch n {
// Add all features that should be excluded in the Enterprise feature set.
case FeatureMultipleOrganizations, FeatureCustomRoles, FeatureServiceAccounts:
return false
default:
return true
}
}
// UsesLimit returns true if the feature uses a limit, and therefore should not
// be included in any feature sets (as they are not boolean features).
func (n FeatureName) UsesLimit() bool {
return map[FeatureName]bool{
FeatureUserLimit: true,
FeatureManagedAgentLimit: true,
FeatureAIGovernanceUserLimit: true,
}[n]
}
// UsesUsagePeriod returns true if the feature uses period-based usage limits.
func (n FeatureName) UsesUsagePeriod() bool {
return map[FeatureName]bool{
FeatureManagedAgentLimit: true,
}[n]
}
// IsAIGovernanceAddon returns true if the feature is an AI Governance addon feature.
func (n FeatureName) IsAIGovernanceAddon() bool {
return n == FeatureAIBridge || n == FeatureBoundary
}
// IsAddon returns true if the feature is an addon feature.
func (n FeatureName) IsAddonFeature() bool {
features := []FeatureName{}
for addon := range AddonsMap {
features = append(features, addon.Features()...)
}
return slices.Contains(features, n)
}
// FeatureSet represents a grouping of features. Rather than manually
// assigning features al-la-carte when making a license, a set can be specified.
// Sets are dynamic in the sense a feature can be added to a set, granting the
// feature to existing licenses out in the wild.
// If features were granted al-la-carte, we would need to reissue the existing
// old licenses to include the new feature.
type FeatureSet string
const (
FeatureSetNone FeatureSet = ""
FeatureSetEnterprise FeatureSet = "enterprise"
FeatureSetPremium FeatureSet = "premium"
)
func (set FeatureSet) Features() []FeatureName {
switch FeatureSet(strings.ToLower(string(set))) {
case FeatureSetEnterprise:
// Enterprise is the set 'AllFeatures' minus some select features.
// Copy the list of all features
enterpriseFeatures := make([]FeatureName, len(FeatureNames))
copy(enterpriseFeatures, FeatureNames)
// Remove the selection
enterpriseFeatures = slices.DeleteFunc(enterpriseFeatures, func(f FeatureName) bool {
// TODO: In future release, restore the f.IsAddonFeature() check.
return !f.Enterprise() || f.UsesLimit()
})
return enterpriseFeatures
case FeatureSetPremium:
premiumFeatures := make([]FeatureName, len(FeatureNames))
copy(premiumFeatures, FeatureNames)
// Remove the selection
premiumFeatures = slices.DeleteFunc(premiumFeatures, func(f FeatureName) bool {
// TODO: In future release, restore the f.IsAddonFeature() check.
return f.UsesLimit()
})
// FeatureSetPremium is just all features.
return premiumFeatures
}
// By default, return an empty set.
return []FeatureName{}
}
type Feature struct {
Entitlement Entitlement `json:"entitlement"`
Enabled bool `json:"enabled"`
Limit *int64 `json:"limit,omitempty"`
Actual *int64 `json:"actual,omitempty"`
// Below is only for features that use usage periods.
// UsagePeriod denotes that the usage is a counter that accumulates over
// this period (and most likely resets with the issuance of the next
// license).
//
// These dates are determined from the license that this entitlement comes
// from, see enterprise/coderd/license/license.go.
//
// Only certain features set these fields:
// - FeatureManagedAgentLimit
UsagePeriod *UsagePeriod `json:"usage_period,omitempty"`
}
type UsagePeriod struct {
IssuedAt time.Time `json:"issued_at" format:"date-time"`
Start time.Time `json:"start" format:"date-time"`
End time.Time `json:"end" format:"date-time"`
}
// Compare compares two features and returns an integer representing
// if the first feature (f) is greater than, equal to, or less than the second
// feature (b). "Greater than" means the first feature has more functionality
// than the second feature. It is assumed the features are for the same FeatureName.
//
// A feature is considered greater than another feature if:
// 1. The usage period has a greater issued at date (note: only certain features use usage periods)
// 2. The usage period has a greater end date (note: only certain features use usage periods)
// 3. Graceful & capable > Entitled & not capable (only if both have "Actual" values)
// 4. The entitlement is greater
// 5. The limit is greater
// 6. Enabled is greater than disabled
// 7. The actual is greater
func (f Feature) Compare(b Feature) int {
// For features with usage period constraints only, check the issued at and
// end dates.
bothHaveUsagePeriod := f.UsagePeriod != nil && b.UsagePeriod != nil
if bothHaveUsagePeriod {
issuedAtCmp := f.UsagePeriod.IssuedAt.Compare(b.UsagePeriod.IssuedAt)
if issuedAtCmp != 0 {
return issuedAtCmp
}
endCmp := f.UsagePeriod.End.Compare(b.UsagePeriod.End)
if endCmp != 0 {
return endCmp
}
}
// Only perform capability comparisons if both features have actual values.
if f.Actual != nil && b.Actual != nil && (!f.Capable() || !b.Capable()) {
// If either is incapable, then it is possible a grace period
// feature can be "greater" than an entitled.
// If either is "NotEntitled" then we can defer to a strict entitlement
// check.
if f.Entitlement.Weight() >= 0 && b.Entitlement.Weight() >= 0 {
if f.Capable() && !b.Capable() {
return 1
}
if b.Capable() && !f.Capable() {
return -1
}
}
}
// Strict entitlement check. Higher is better. We don't apply this check for
// usage period features as we always want the issued at date to be the main
// decision maker.
entitlementDifference := f.Entitlement.Weight() - b.Entitlement.Weight()
if entitlementDifference != 0 {
return entitlementDifference
}
// If the entitlement is the same, then we can compare the limits.
if f.Limit == nil && b.Limit != nil {
return -1
}
if f.Limit != nil && b.Limit == nil {
return 1
}
if f.Limit != nil && b.Limit != nil {
difference := *f.Limit - *b.Limit
if difference != 0 {
return int(difference)
}
}
// Enabled is better than disabled.
if f.Enabled && !b.Enabled {
return 1
}
if !f.Enabled && b.Enabled {
return -1
}
// Higher actual is better
if f.Actual == nil && b.Actual != nil {
return -1
}
if f.Actual != nil && b.Actual == nil {
return 1
}
if f.Actual != nil && b.Actual != nil {
difference := *f.Actual - *b.Actual
if difference != 0 {
return int(difference)
}
}
return 0
}
// Capable is a helper function that returns if a given feature has a limit
// that is greater than or equal to the actual.
// If this condition is not true, then the feature is not capable of being used
// since the limit is not high enough.
func (f Feature) Capable() bool {
if f.Limit != nil && f.Actual != nil {
return *f.Limit >= *f.Actual
}
return true
}
type Entitlements struct {
Features map[FeatureName]Feature `json:"features"`
Warnings []string `json:"warnings"`
Errors []string `json:"errors"`
HasLicense bool `json:"has_license"`
Trial bool `json:"trial"`
RequireTelemetry bool `json:"require_telemetry"`
RefreshedAt time.Time `json:"refreshed_at" format:"date-time"`
}
// AddFeature will add the feature to the entitlements iff it expands
// the set of features granted by the entitlements. If it does not, it will
// be ignored and the existing feature with the same name will remain.
//
// Features that abide by usage period constraints should have the following
// fields set or they will be ignored. Other features will have these fields
// cleared.
// - UsagePeriodIssuedAt
// - UsagePeriodStart
// - UsagePeriodEnd
//
// All features should be added as atomic items, and not merged in any way.
// Merging entitlements could lead to unexpected behavior, like a larger user
// limit in grace period merging with a smaller one in an "entitled" state. This
// could lead to the larger limit being extended as "entitled", which is not correct.
func (e *Entitlements) AddFeature(name FeatureName, add Feature) {
existing, ok := e.Features[name]
if !ok {
e.Features[name] = add
return
}
// If we're trying to add a feature that uses a usage period and it's not
// set, then we should not add it.
if name.UsesUsagePeriod() {
if add.UsagePeriod == nil || add.UsagePeriod.IssuedAt.IsZero() || add.UsagePeriod.Start.IsZero() || add.UsagePeriod.End.IsZero() {
return
}
} else {
add.UsagePeriod = nil
}
// Compare the features, keep the one that is "better"
comparison := add.Compare(existing)
if comparison > 0 {
e.Features[name] = add
return
}
}
func (c *Client) Entitlements(ctx context.Context) (Entitlements, error) {
res, err := c.Request(ctx, http.MethodGet, "/api/v2/entitlements", nil)
if err != nil {
return Entitlements{}, err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return Entitlements{}, ReadBodyAsError(res)
}
var ent Entitlements
return ent, json.NewDecoder(res.Body).Decode(&ent)
}
type PostgresAuth string
const (
PostgresAuthPassword PostgresAuth = "password"
PostgresAuthAWSIAMRDS PostgresAuth = "awsiamrds"
)
var PostgresAuthDrivers = []string{
string(PostgresAuthPassword),
string(PostgresAuthAWSIAMRDS),
}
// PostgresConnMaxIdleAuto is the value for auto-computing max idle connections
// based on max open connections.
const PostgresConnMaxIdleAuto = "auto"
// DeploymentValues is the central configuration values the coder server.
type DeploymentValues struct {
Verbose serpent.Bool `json:"verbose,omitempty"`
AccessURL serpent.URL `json:"access_url,omitempty"`
WildcardAccessURL serpent.String `json:"wildcard_access_url,omitempty"`
DocsURL serpent.URL `json:"docs_url,omitempty"`
RedirectToAccessURL serpent.Bool `json:"redirect_to_access_url,omitempty"`
// HTTPAddress is a string because it may be set to zero to disable.
HTTPAddress serpent.String `json:"http_address,omitempty" typescript:",notnull"`
AutobuildPollInterval serpent.Duration `json:"autobuild_poll_interval,omitempty"`
JobReaperDetectorInterval serpent.Duration `json:"job_hang_detector_interval,omitempty"`
DERP DERP `json:"derp,omitempty" typescript:",notnull"`
Prometheus PrometheusConfig `json:"prometheus,omitempty" typescript:",notnull"`
Pprof PprofConfig `json:"pprof,omitempty" typescript:",notnull"`
ProxyTrustedHeaders serpent.StringArray `json:"proxy_trusted_headers,omitempty" typescript:",notnull"`
ProxyTrustedOrigins serpent.StringArray `json:"proxy_trusted_origins,omitempty" typescript:",notnull"`
CacheDir serpent.String `json:"cache_directory,omitempty" typescript:",notnull"`
EphemeralDeployment serpent.Bool `json:"ephemeral_deployment,omitempty" typescript:",notnull"`
PostgresURL serpent.String `json:"pg_connection_url,omitempty" typescript:",notnull"`
PostgresAuth string `json:"pg_auth,omitempty" typescript:",notnull"`
PostgresConnMaxOpen serpent.Int64 `json:"pg_conn_max_open,omitempty" typescript:",notnull"`
PostgresConnMaxIdle serpent.String `json:"pg_conn_max_idle,omitempty" typescript:",notnull"`
OAuth2 OAuth2Config `json:"oauth2,omitempty" typescript:",notnull"`
OIDC OIDCConfig `json:"oidc,omitempty" typescript:",notnull"`
Telemetry TelemetryConfig `json:"telemetry,omitempty" typescript:",notnull"`
TLS TLSConfig `json:"tls,omitempty" typescript:",notnull"`
Trace TraceConfig `json:"trace,omitempty" typescript:",notnull"`
HTTPCookies HTTPCookieConfig `json:"http_cookies,omitempty" typescript:",notnull"`
StrictTransportSecurity serpent.Int64 `json:"strict_transport_security,omitempty" typescript:",notnull"`
StrictTransportSecurityOptions serpent.StringArray `json:"strict_transport_security_options,omitempty" typescript:",notnull"`
SSHKeygenAlgorithm serpent.String `json:"ssh_keygen_algorithm,omitempty" typescript:",notnull"`
MetricsCacheRefreshInterval serpent.Duration `json:"metrics_cache_refresh_interval,omitempty" typescript:",notnull"`
AgentStatRefreshInterval serpent.Duration `json:"agent_stat_refresh_interval,omitempty" typescript:",notnull"`
AgentFallbackTroubleshootingURL serpent.URL `json:"agent_fallback_troubleshooting_url,omitempty" typescript:",notnull"`
BrowserOnly serpent.Bool `json:"browser_only,omitempty" typescript:",notnull"`
SCIMAPIKey serpent.String `json:"scim_api_key,omitempty" typescript:",notnull"`
ExternalTokenEncryptionKeys serpent.StringArray `json:"external_token_encryption_keys,omitempty" typescript:",notnull"`
Provisioner ProvisionerConfig `json:"provisioner,omitempty" typescript:",notnull"`
RateLimit RateLimitConfig `json:"rate_limit,omitempty" typescript:",notnull"`
Experiments serpent.StringArray `json:"experiments,omitempty" typescript:",notnull"`
UpdateCheck serpent.Bool `json:"update_check,omitempty" typescript:",notnull"`
Swagger SwaggerConfig `json:"swagger,omitempty" typescript:",notnull"`
Logging LoggingConfig `json:"logging,omitempty" typescript:",notnull"`
Dangerous DangerousConfig `json:"dangerous,omitempty" typescript:",notnull"`
DisablePathApps serpent.Bool `json:"disable_path_apps,omitempty" typescript:",notnull"`
Sessions SessionLifetime `json:"session_lifetime,omitempty" typescript:",notnull"`
DisablePasswordAuth serpent.Bool `json:"disable_password_auth,omitempty" typescript:",notnull"`
Support SupportConfig `json:"support,omitempty" typescript:",notnull"`
EnableAuthzRecording serpent.Bool `json:"enable_authz_recording,omitempty" typescript:",notnull"`
ExternalAuthConfigs serpent.Struct[[]ExternalAuthConfig] `json:"external_auth,omitempty" typescript:",notnull"`
ExternalAuthGithubDefaultProviderEnable serpent.Bool `json:"external_auth_github_default_provider_enable,omitempty" typescript:",notnull"`
SSHConfig SSHConfig `json:"config_ssh,omitempty" typescript:",notnull"`
WgtunnelHost serpent.String `json:"wgtunnel_host,omitempty" typescript:",notnull"`
DisableOwnerWorkspaceExec serpent.Bool `json:"disable_owner_workspace_exec,omitempty" typescript:",notnull"`
DisableWorkspaceSharing serpent.Bool `json:"disable_workspace_sharing,omitempty" typescript:",notnull"`
ProxyHealthStatusInterval serpent.Duration `json:"proxy_health_status_interval,omitempty" typescript:",notnull"`
EnableTerraformDebugMode serpent.Bool `json:"enable_terraform_debug_mode,omitempty" typescript:",notnull"`
UserQuietHoursSchedule UserQuietHoursScheduleConfig `json:"user_quiet_hours_schedule,omitempty" typescript:",notnull"`
WebTerminalRenderer serpent.String `json:"web_terminal_renderer,omitempty" typescript:",notnull"`
AllowWorkspaceRenames serpent.Bool `json:"allow_workspace_renames,omitempty" typescript:",notnull"`
Healthcheck HealthcheckConfig `json:"healthcheck,omitempty" typescript:",notnull"`
Retention RetentionConfig `json:"retention,omitempty" typescript:",notnull"`
CLIUpgradeMessage serpent.String `json:"cli_upgrade_message,omitempty" typescript:",notnull"`
TermsOfServiceURL serpent.String `json:"terms_of_service_url,omitempty" typescript:",notnull"`
Notifications NotificationsConfig `json:"notifications,omitempty" typescript:",notnull"`
AdditionalCSPPolicy serpent.StringArray `json:"additional_csp_policy,omitempty" typescript:",notnull"`
WorkspaceHostnameSuffix serpent.String `json:"workspace_hostname_suffix,omitempty" typescript:",notnull"`
Prebuilds PrebuildsConfig `json:"workspace_prebuilds,omitempty" typescript:",notnull"`
HideAITasks serpent.Bool `json:"hide_ai_tasks,omitempty" typescript:",notnull"`
AI AIConfig `json:"ai,omitempty"`
StatsCollection StatsCollectionConfig `json:"stats_collection,omitempty" typescript:",notnull"`
Config serpent.YAMLConfigPath `json:"config,omitempty" typescript:",notnull"`
WriteConfig serpent.Bool `json:"write_config,omitempty" typescript:",notnull"`
// Deprecated: Use HTTPAddress or TLS.Address instead.
Address serpent.HostPort `json:"address,omitempty" typescript:",notnull"`
}
// SSHConfig is configuration the cli & vscode extension use for configuring
// ssh connections.
type SSHConfig struct {
// DeploymentName is the config-ssh Hostname prefix
DeploymentName serpent.String
// SSHConfigOptions are additional options to add to the ssh config file.
// This will override defaults.
SSHConfigOptions serpent.StringArray
}
func (c SSHConfig) ParseOptions() (map[string]string, error) {
m := make(map[string]string)
for _, opt := range c.SSHConfigOptions {
key, value, err := ParseSSHConfigOption(opt)
if err != nil {
return nil, err
}
m[key] = value
}
return m, nil
}
// ParseSSHConfigOption parses a single ssh config option into it's key/value pair.
func ParseSSHConfigOption(opt string) (key string, value string, err error) {
// An equal sign or whitespace is the separator between the key and value.
idx := strings.IndexFunc(opt, func(r rune) bool {
return r == ' ' || r == '='
})
if idx == -1 {
return "", "", xerrors.Errorf("invalid config-ssh option %q", opt)
}
return opt[:idx], opt[idx+1:], nil
}
// SessionLifetime refers to "sessions" authenticating into Coderd. Coder has
// multiple different session types: api keys, tokens, workspace app tokens,
// agent tokens, etc. This configuration struct should be used to group all
// settings referring to any of these session lifetime controls.
// TODO: These config options were created back when coder only had api keys.
// Today, the config is ambigously used for all of them. For example:
// - cli based api keys ignore all settings
// - login uses the default lifetime, not the MaximumTokenDuration
// - Tokens use the Default & MaximumTokenDuration
// - ... etc ...
// The rational behind each decision is undocumented. The naming behind these
// config options is also confusing without any clear documentation.
// 'CreateAPIKey' is used to make all sessions, and it's parameters are just
// 'LifetimeSeconds' and 'DefaultLifetime'. Which does not directly correlate to
// the config options here.
type SessionLifetime struct {
// DisableExpiryRefresh will disable automatically refreshing api
// keys when they are used from the api. This means the api key lifetime at
// creation is the lifetime of the api key.
DisableExpiryRefresh serpent.Bool `json:"disable_expiry_refresh,omitempty" typescript:",notnull"`
// DefaultDuration is only for browser, workspace app and oauth sessions.
DefaultDuration serpent.Duration `json:"default_duration" typescript:",notnull"`
// RefreshDefaultDuration is the default lifetime for OAuth2 refresh tokens.
// This should generally be longer than access token lifetimes to allow
// refreshing after access token expiry.
RefreshDefaultDuration serpent.Duration `json:"refresh_default_duration,omitempty" typescript:",notnull"`
DefaultTokenDuration serpent.Duration `json:"default_token_lifetime,omitempty" typescript:",notnull"`
MaximumTokenDuration serpent.Duration `json:"max_token_lifetime,omitempty" typescript:",notnull"`
MaximumAdminTokenDuration serpent.Duration `json:"max_admin_token_lifetime,omitempty" typescript:",notnull"`
}
type DERP struct {
Server DERPServerConfig `json:"server" typescript:",notnull"`
Config DERPConfig `json:"config" typescript:",notnull"`
}
type DERPServerConfig struct {
Enable serpent.Bool `json:"enable" typescript:",notnull"`
RegionID serpent.Int64 `json:"region_id" typescript:",notnull"`
RegionCode serpent.String `json:"region_code" typescript:",notnull"`
RegionName serpent.String `json:"region_name" typescript:",notnull"`
STUNAddresses serpent.StringArray `json:"stun_addresses" typescript:",notnull"`
RelayURL serpent.URL `json:"relay_url" typescript:",notnull"`
}
type DERPConfig struct {
BlockDirect serpent.Bool `json:"block_direct" typescript:",notnull"`
ForceWebSockets serpent.Bool `json:"force_websockets" typescript:",notnull"`
URL serpent.String `json:"url" typescript:",notnull"`
Path serpent.String `json:"path" typescript:",notnull"`
}
type UsageStatsConfig struct {
Enable serpent.Bool `json:"enable" typescript:",notnull"`
}
type StatsCollectionConfig struct {
UsageStats UsageStatsConfig `json:"usage_stats" tyescript:",notnull"`
}
type PrometheusConfig struct {
Enable serpent.Bool `json:"enable" typescript:",notnull"`
Address serpent.HostPort `json:"address" typescript:",notnull"`
CollectAgentStats serpent.Bool `json:"collect_agent_stats" typescript:",notnull"`
CollectDBMetrics serpent.Bool `json:"collect_db_metrics" typescript:",notnull"`
AggregateAgentStatsBy serpent.StringArray `json:"aggregate_agent_stats_by" typescript:",notnull"`
}
type PprofConfig struct {
Enable serpent.Bool `json:"enable" typescript:",notnull"`
Address serpent.HostPort `json:"address" typescript:",notnull"`
}
type OAuth2Config struct {
Github OAuth2GithubConfig `json:"github" typescript:",notnull"`
}
type OAuth2GithubConfig struct {
ClientID serpent.String `json:"client_id" typescript:",notnull"`
ClientSecret serpent.String `json:"client_secret" typescript:",notnull"`
DeviceFlow serpent.Bool `json:"device_flow" typescript:",notnull"`
DefaultProviderEnable serpent.Bool `json:"default_provider_enable" typescript:",notnull"`
AllowedOrgs serpent.StringArray `json:"allowed_orgs" typescript:",notnull"`
AllowedTeams serpent.StringArray `json:"allowed_teams" typescript:",notnull"`
AllowSignups serpent.Bool `json:"allow_signups" typescript:",notnull"`
AllowEveryone serpent.Bool `json:"allow_everyone" typescript:",notnull"`
EnterpriseBaseURL serpent.String `json:"enterprise_base_url" typescript:",notnull"`
}
type OIDCConfig struct {
AllowSignups serpent.Bool `json:"allow_signups" typescript:",notnull"`
ClientID serpent.String `json:"client_id" typescript:",notnull"`
ClientSecret serpent.String `json:"client_secret" typescript:",notnull"`
// ClientKeyFile & ClientCertFile are used in place of ClientSecret for PKI auth.
ClientKeyFile serpent.String `json:"client_key_file" typescript:",notnull"`
ClientCertFile serpent.String `json:"client_cert_file" typescript:",notnull"`
EmailDomain serpent.StringArray `json:"email_domain" typescript:",notnull"`
IssuerURL serpent.String `json:"issuer_url" typescript:",notnull"`
Scopes serpent.StringArray `json:"scopes" typescript:",notnull"`
IgnoreEmailVerified serpent.Bool `json:"ignore_email_verified" typescript:",notnull"`
UsernameField serpent.String `json:"username_field" typescript:",notnull"`
NameField serpent.String `json:"name_field" typescript:",notnull"`
EmailField serpent.String `json:"email_field" typescript:",notnull"`
AuthURLParams serpent.Struct[map[string]string] `json:"auth_url_params" typescript:",notnull"`
// IgnoreUserInfo & UserInfoFromAccessToken are mutually exclusive. Only 1
// can be set to true. Ideally this would be an enum with 3 states, ['none',
// 'userinfo', 'access_token']. However, for backward compatibility,
// `ignore_user_info` must remain. And `access_token` is a niche, non-spec
// compliant edge case. So it's use is rare, and should not be advised.
IgnoreUserInfo serpent.Bool `json:"ignore_user_info" typescript:",notnull"`
// UserInfoFromAccessToken as mentioned above is an edge case. This allows
// sourcing the user_info from the access token itself instead of a user_info
// endpoint. This assumes the access token is a valid JWT with a set of claims to
// be merged with the id_token.
UserInfoFromAccessToken serpent.Bool `json:"source_user_info_from_access_token" typescript:",notnull"`
OrganizationField serpent.String `json:"organization_field" typescript:",notnull"`
OrganizationMapping serpent.Struct[map[string][]uuid.UUID] `json:"organization_mapping" typescript:",notnull"`
OrganizationAssignDefault serpent.Bool `json:"organization_assign_default" typescript:",notnull"`
GroupAutoCreate serpent.Bool `json:"group_auto_create" typescript:",notnull"`
GroupRegexFilter serpent.Regexp `json:"group_regex_filter" typescript:",notnull"`
GroupAllowList serpent.StringArray `json:"group_allow_list" typescript:",notnull"`
GroupField serpent.String `json:"groups_field" typescript:",notnull"`
GroupMapping serpent.Struct[map[string]string] `json:"group_mapping" typescript:",notnull"`
UserRoleField serpent.String `json:"user_role_field" typescript:",notnull"`
UserRoleMapping serpent.Struct[map[string][]string] `json:"user_role_mapping" typescript:",notnull"`
UserRolesDefault serpent.StringArray `json:"user_roles_default" typescript:",notnull"`
SignInText serpent.String `json:"sign_in_text" typescript:",notnull"`
IconURL serpent.URL `json:"icon_url" typescript:",notnull"`
SignupsDisabledText serpent.String `json:"signups_disabled_text" typescript:",notnull"`
SkipIssuerChecks serpent.Bool `json:"skip_issuer_checks" typescript:",notnull"`
// RedirectURL is optional, defaulting to 'ACCESS_URL'. Only useful in niche
// situations where the OIDC callback domain is different from the ACCESS_URL
// domain.
RedirectURL serpent.URL `json:"redirect_url" typescript:",notnull"`
}
type TelemetryConfig struct {
Enable serpent.Bool `json:"enable" typescript:",notnull"`
Trace serpent.Bool `json:"trace" typescript:",notnull"`
URL serpent.URL `json:"url" typescript:",notnull"`
}
type TLSConfig struct {
Enable serpent.Bool `json:"enable" typescript:",notnull"`
Address serpent.HostPort `json:"address" typescript:",notnull"`
RedirectHTTP serpent.Bool `json:"redirect_http" typescript:",notnull"`
CertFiles serpent.StringArray `json:"cert_file" typescript:",notnull"`
ClientAuth serpent.String `json:"client_auth" typescript:",notnull"`
ClientCAFile serpent.String `json:"client_ca_file" typescript:",notnull"`
KeyFiles serpent.StringArray `json:"key_file" typescript:",notnull"`
MinVersion serpent.String `json:"min_version" typescript:",notnull"`
ClientCertFile serpent.String `json:"client_cert_file" typescript:",notnull"`
ClientKeyFile serpent.String `json:"client_key_file" typescript:",notnull"`
SupportedCiphers serpent.StringArray `json:"supported_ciphers" typescript:",notnull"`
AllowInsecureCiphers serpent.Bool `json:"allow_insecure_ciphers" typescript:",notnull"`
}
type TraceConfig struct {
Enable serpent.Bool `json:"enable" typescript:",notnull"`
HoneycombAPIKey serpent.String `json:"honeycomb_api_key" typescript:",notnull"`
CaptureLogs serpent.Bool `json:"capture_logs" typescript:",notnull"`
DataDog serpent.Bool `json:"data_dog" typescript:",notnull"`
}
const cookieHostPrefix = "__Host-"
type HTTPCookieConfig struct {
Secure serpent.Bool `json:"secure_auth_cookie,omitempty" typescript:",notnull"`
SameSite string `json:"same_site,omitempty" typescript:",notnull"`
EnableHostPrefix bool `json:"host_prefix,omitempty" typescript:",notnull"`
}
// cookiesToPrefix is the set of cookies that should be prefixed with the host prefix if EnableHostPrefix is true.
// This is a constant, do not ever mutate it.
var cookiesToPrefix = map[string]struct{}{
SessionTokenCookie: {},
}
// Middleware handles some cookie mutation the requests.
//
// For performance of this, see 'BenchmarkHTTPCookieConfigMiddleware'
// This code is executed on every request, so efficiency is important.
// If making changes, please consider the performance implications and run benchmarks.
func (cfg *HTTPCookieConfig) Middleware(next http.Handler) http.Handler {
prefixed := make(map[string]struct{})
for name := range cookiesToPrefix {
prefixed[cookieHostPrefix+name] = struct{}{}
}
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
if !cfg.EnableHostPrefix {
// If a deployment has this config on, then turned it off. Then some old __Host-
// cookies could exist on the browsers of the clients. These cookies have no
// impact, so we are going to ignore them if they exist (niche scenario)
next.ServeHTTP(rw, r)
return
}
// When 'EnableHostPrefix', some cookies are set with a `__Host-` prefix. This
// middleware will strip any prefixes, so the backend is unaware of this security
// feature.
//
// This code also handles any unprefixed cookies that are now invalid.
cookies := r.Cookies()
for i, c := range cookies {
// If any cookies that should be prefixed are found without the prefix, remove
// them from the client and the request. This is usually from a migration where
// the prefix was just turned on. In any case, these cookies MUST be dropped
if _, ok := cookiesToPrefix[c.Name]; ok {
// Remove the cookie from the client to prevent any future requests from sending it.
http.SetCookie(rw, &http.Cookie{
MaxAge: -1, // Delete
Name: c.Name,
Path: "/",
})
// And remove it from the request so the rest of the code doesn't see it.
cookies[i] = nil
}
// Only strip prefix's from the cookies we care about. Let other `__Host-` cookies be
if _, ok := prefixed[c.Name]; ok {
c.Name = strings.TrimPrefix(c.Name, cookieHostPrefix)
}
}
// r.Cookies() returns copies, so we need to rebuild the header.
r.Header.Del("Cookie")
for _, c := range cookies {
if c != nil {
r.AddCookie(c)
}
}
next.ServeHTTP(rw, r)
})
}
func (cfg *HTTPCookieConfig) Apply(c *http.Cookie) *http.Cookie {
c.Secure = cfg.Secure.Value()
c.SameSite = cfg.HTTPSameSite()
if cfg.EnableHostPrefix {
// Only prefix the cookies we want to be prefixed.
if _, ok := cookiesToPrefix[c.Name]; ok {
c.Name = cookieHostPrefix + c.Name
}
}
return c
}
func (cfg HTTPCookieConfig) HTTPSameSite() http.SameSite {
switch strings.ToLower(cfg.SameSite) {
case "lax":
return http.SameSiteLaxMode
case "strict":
return http.SameSiteStrictMode
case "none":
return http.SameSiteNoneMode
default:
return http.SameSiteDefaultMode
}
}
type ExternalAuthConfig struct {
// Type is the type of external auth config.
Type string `json:"type" yaml:"type"`
ClientID string `json:"client_id" yaml:"client_id"`
ClientSecret string `json:"-" yaml:"client_secret"`
// ID is a unique identifier for the auth config.
// It defaults to `type` when not provided.
ID string `json:"id" yaml:"id"`
AuthURL string `json:"auth_url" yaml:"auth_url"`
TokenURL string `json:"token_url" yaml:"token_url"`
ValidateURL string `json:"validate_url" yaml:"validate_url"`
RevokeURL string `json:"revoke_url" yaml:"revoke_url"`
AppInstallURL string `json:"app_install_url" yaml:"app_install_url"`
AppInstallationsURL string `json:"app_installations_url" yaml:"app_installations_url"`
NoRefresh bool `json:"no_refresh" yaml:"no_refresh"`
Scopes []string `json:"scopes" yaml:"scopes"`
ExtraTokenKeys []string `json:"-" yaml:"extra_token_keys"`
DeviceFlow bool `json:"device_flow" yaml:"device_flow"`
DeviceCodeURL string `json:"device_code_url" yaml:"device_code_url"`
// Deprecated: Injected MCP in AI Bridge is deprecated and will be removed in a future release.
MCPURL string `json:"mcp_url" yaml:"mcp_url"`
// Deprecated: Injected MCP in AI Bridge is deprecated and will be removed in a future release.
MCPToolAllowRegex string `json:"mcp_tool_allow_regex" yaml:"mcp_tool_allow_regex"`
// Deprecated: Injected MCP in AI Bridge is deprecated and will be removed in a future release.
MCPToolDenyRegex string `json:"mcp_tool_deny_regex" yaml:"mcp_tool_deny_regex"`
// Regex allows API requesters to match an auth config by
// a string (e.g. coder.com) instead of by it's type.
//
// Git clone makes use of this by parsing the URL from:
// 'Username for "https://github.com":'
// And sending it to the Coder server to match against the Regex.
Regex string `json:"regex" yaml:"regex"`
// APIBaseURL is the base URL for provider REST API calls
// (e.g., "https://api.github.com" for GitHub). Derived from
// defaults when not explicitly configured.
APIBaseURL string `json:"api_base_url" yaml:"api_base_url"`
// DisplayName is shown in the UI to identify the auth config.
DisplayName string `json:"display_name" yaml:"display_name"`
// DisplayIcon is a URL to an icon to display in the UI.
DisplayIcon string `json:"display_icon" yaml:"display_icon"`
// CodeChallengeMethodsSupported lists the PKCE code challenge methods
// The only one supported by Coder is "S256".
CodeChallengeMethodsSupported []string `json:"code_challenge_methods_supported" yaml:"code_challenge_methods_supported"`
}