2022-08-22 15:02:50 -07:00
package coderd
import (
2022-08-29 16:45:40 -07:00
"context"
2022-09-19 23:11:01 -05:00
"crypto/ed25519"
2022-10-17 08:43:30 -05:00
"crypto/tls"
"crypto/x509"
2023-07-26 09:21:04 -07:00
"fmt"
"math"
2022-09-19 23:11:01 -05:00
"net/http"
2023-07-26 09:21:04 -07:00
"net/url"
"strconv"
"strings"
2022-09-19 23:11:01 -05:00
"sync"
"time"
2022-08-29 16:45:40 -07:00
2022-08-22 15:02:50 -07:00
"golang.org/x/xerrors"
2023-07-26 09:21:04 -07:00
"tailscale.com/tailcfg"
2022-08-22 15:02:50 -07:00
2022-09-19 23:11:01 -05:00
"github.com/cenkalti/backoff/v4"
"github.com/go-chi/chi/v5"
2023-01-13 16:07:15 -06:00
"github.com/prometheus/client_golang/prometheus"
2022-09-19 23:11:01 -05:00
"cdr.dev/slog"
2022-08-22 15:02:50 -07:00
"github.com/coder/coder/coderd"
2022-10-06 19:28:22 -05:00
agplaudit "github.com/coder/coder/coderd/audit"
2023-06-30 11:32:35 -04:00
"github.com/coder/coder/coderd/database/dbauthz"
2022-09-19 23:11:01 -05:00
"github.com/coder/coder/coderd/httpapi"
"github.com/coder/coder/coderd/httpmw"
2022-10-10 15:37:06 -05:00
"github.com/coder/coder/coderd/rbac"
2023-07-20 06:35:41 -07:00
agplschedule "github.com/coder/coder/coderd/schedule"
2022-09-19 23:11:01 -05:00
"github.com/coder/coder/codersdk"
2022-10-06 19:28:22 -05:00
"github.com/coder/coder/enterprise/coderd/license"
2023-04-24 10:25:35 -05:00
"github.com/coder/coder/enterprise/coderd/proxyhealth"
2023-07-20 06:35:41 -07:00
"github.com/coder/coder/enterprise/coderd/schedule"
2022-10-17 08:43:30 -05:00
"github.com/coder/coder/enterprise/derpmesh"
"github.com/coder/coder/enterprise/replicasync"
"github.com/coder/coder/enterprise/tailnet"
2022-11-14 11:57:33 -06:00
"github.com/coder/coder/provisionerd/proto"
2022-10-17 08:43:30 -05:00
agpltailnet "github.com/coder/coder/tailnet"
2022-08-22 15:02:50 -07:00
)
2022-09-19 23:11:01 -05:00
// New constructs an Enterprise coderd API instance.
// This handler is designed to wrap the AGPL Coder code and
// layer Enterprise functionality on top as much as possible.
2023-06-13 20:18:31 +03:00
func New ( ctx context . Context , options * Options ) ( _ * API , err error ) {
2022-09-19 23:11:01 -05:00
if options . EntitlementsUpdateInterval == 0 {
options . EntitlementsUpdateInterval = 10 * time . Minute
}
if options . Keys == nil {
options . Keys = Keys
}
2022-10-15 02:46:38 +10:00
if options . Options == nil {
options . Options = & coderd . Options {}
}
2023-01-13 16:07:15 -06:00
if options . PrometheusRegistry == nil {
options . PrometheusRegistry = prometheus . NewRegistry ()
}
2022-10-15 02:46:38 +10:00
if options . Options . Authorizer == nil {
2023-02-15 08:56:07 -06:00
options . Options . Authorizer = rbac . NewCachingAuthorizer ( options . PrometheusRegistry )
2022-10-15 02:46:38 +10:00
}
2023-07-20 06:35:41 -07:00
2022-09-19 23:11:01 -05:00
ctx , cancelFunc := context . WithCancel ( ctx )
api := & API {
2023-04-24 10:25:35 -05:00
ctx : ctx ,
cancel : cancelFunc ,
AGPL : coderd . New ( options . Options ),
Options : options ,
2023-08-04 12:32:28 +04:00
provisionerDaemonAuth : & provisionerDaemonAuth {
psk : options . ProvisionerDaemonPSK ,
authorizer : options . Authorizer ,
},
2022-09-19 23:11:01 -05:00
}
2023-06-13 20:18:31 +03:00
defer func () {
if err != nil {
_ = api . Close ()
}
}()
2022-10-17 08:43:30 -05:00
2023-02-02 13:53:48 -06:00
api . AGPL . Options . SetUserGroups = api . setUserGroups
2023-07-24 08:34:24 -04:00
api . AGPL . Options . SetUserSiteRoles = api . setUserSiteRoles
2023-06-18 13:57:27 -05:00
api . AGPL . SiteHandler . AppearanceFetcher = api . fetchAppearanceConfig
2023-06-30 11:32:35 -04:00
api . AGPL . SiteHandler . RegionsFetcher = func ( ctx context . Context ) ( any , error ) {
// If the user can read the workspace proxy resource, return that.
// If not, always default to the regions.
actor , ok := dbauthz . ActorFromContext ( ctx )
if ok && api . Authorizer . Authorize ( ctx , actor , rbac . ActionRead , rbac . ResourceWorkspaceProxy ) == nil {
return api . fetchWorkspaceProxies ( ctx )
}
return api . fetchRegions ( ctx )
}
2023-02-02 13:53:48 -06:00
2022-09-19 23:11:01 -05:00
oauthConfigs := & httpmw . OAuth2Configs {
Github : options . GithubOAuth2Config ,
OIDC : options . OIDCConfig ,
}
2023-03-08 06:38:11 +11:00
apiKeyMiddleware := httpmw . ExtractAPIKeyMW ( httpmw . ExtractAPIKeyConfig {
2023-07-10 16:51:50 +03:00
DB : options . Database ,
OAuth2Configs : oauthConfigs ,
RedirectToLogin : false ,
DisableSessionExpiryRefresh : options . DeploymentValues . DisableSessionExpiryRefresh . Value (),
Optional : false ,
2023-07-11 14:30:33 +01:00
SessionTokenFunc : nil , // Default behavior
2022-09-23 08:30:32 +10:00
})
2023-06-30 10:41:29 -08:00
apiKeyMiddlewareOptional := httpmw . ExtractAPIKeyMW ( httpmw . ExtractAPIKeyConfig {
2023-07-10 16:51:50 +03:00
DB : options . Database ,
OAuth2Configs : oauthConfigs ,
RedirectToLogin : false ,
DisableSessionExpiryRefresh : options . DeploymentValues . DisableSessionExpiryRefresh . Value (),
Optional : true ,
2023-07-11 14:30:33 +01:00
SessionTokenFunc : nil , // Default behavior
2023-06-30 10:41:29 -08:00
})
2022-09-23 08:30:32 +10:00
2023-06-08 10:30:15 -05:00
deploymentID , err := options . Database . GetDeploymentID ( ctx )
if err != nil {
return nil , xerrors . Errorf ( "failed to get deployment ID: %w" , err )
}
2022-09-19 23:11:01 -05:00
api . AGPL . APIHandler . Group ( func ( r chi . Router ) {
r . Get ( "/entitlements" , api . serveEntitlements )
2023-04-25 07:37:52 -07:00
// /regions overrides the AGPL /regions endpoint
r . Group ( func ( r chi . Router ) {
r . Use ( apiKeyMiddleware )
r . Get ( "/regions" , api . regions )
})
2022-10-17 08:43:30 -05:00
r . Route ( "/replicas" , func ( r chi . Router ) {
r . Use ( apiKeyMiddleware )
r . Get ( "/" , api . replicas )
})
2022-09-19 23:11:01 -05:00
r . Route ( "/licenses" , func ( r chi . Router ) {
r . Use ( apiKeyMiddleware )
r . Post ( "/" , api . postLicense )
r . Get ( "/" , api . licenses )
r . Delete ( "/{id}" , api . deleteLicense )
})
2023-04-20 16:59:45 -07:00
r . Route ( "/applications/reconnecting-pty-signed-token" , func ( r chi . Router ) {
r . Use ( apiKeyMiddleware )
r . Post ( "/" , api . reconnectingPTYSignedToken )
})
2023-07-19 11:11:11 -05:00
r . With (
apiKeyMiddlewareOptional ,
httpmw . ExtractWorkspaceProxy ( httpmw . ExtractWorkspaceProxyConfig {
DB : options . Database ,
Optional : true ,
}),
httpmw . RequireAPIKeyOrWorkspaceProxyAuth (),
). Get ( "/workspaceagents/{workspaceagent}/legacy" , api . agentIsLegacy )
2023-04-04 15:07:29 -05:00
r . Route ( "/workspaceproxies" , func ( r chi . Router ) {
r . Use (
api . moonsEnabledMW ,
)
2023-04-17 14:57:21 -05:00
r . Group ( func ( r chi . Router ) {
r . Use (
apiKeyMiddleware ,
)
r . Post ( "/" , api . postWorkspaceProxy )
r . Get ( "/" , api . workspaceProxies )
})
r . Route ( "/me" , func ( r chi . Router ) {
r . Use (
httpmw . ExtractWorkspaceProxy ( httpmw . ExtractWorkspaceProxyConfig {
DB : options . Database ,
Optional : false ,
}),
)
2023-07-19 11:11:11 -05:00
r . Get ( "/coordinate" , api . workspaceProxyCoordinate )
2023-04-17 14:57:21 -05:00
r . Post ( "/issue-signed-app-token" , api . workspaceProxyIssueSignedAppToken )
2023-04-20 09:48:47 -05:00
r . Post ( "/register" , api . workspaceProxyRegister )
2023-07-26 09:21:04 -07:00
r . Post ( "/deregister" , api . workspaceProxyDeregister )
2023-04-20 09:48:47 -05:00
})
r . Route ( "/{workspaceproxy}" , func ( r chi . Router ) {
r . Use (
apiKeyMiddleware ,
2023-06-08 10:30:15 -05:00
httpmw . ExtractWorkspaceProxyParam ( api . Database , deploymentID , api . AGPL . PrimaryWorkspaceProxy ),
2023-04-20 09:48:47 -05:00
)
2023-05-09 13:46:50 -05:00
r . Get ( "/" , api . workspaceProxy )
r . Patch ( "/" , api . patchWorkspaceProxy )
2023-04-20 09:48:47 -05:00
r . Delete ( "/" , api . deleteWorkspaceProxy )
2023-04-17 14:57:21 -05:00
})
2023-04-04 15:07:29 -05:00
})
2022-10-10 15:37:06 -05:00
r . Route ( "/organizations/{organization}/groups" , func ( r chi . Router ) {
r . Use (
apiKeyMiddleware ,
2022-10-27 16:49:35 -05:00
api . templateRBACEnabledMW ,
2022-10-10 15:37:06 -05:00
httpmw . ExtractOrganizationParam ( api . Database ),
)
r . Post ( "/" , api . postGroupByOrganization )
2023-01-11 16:05:42 +01:00
r . Get ( "/" , api . groupsByOrganization )
2022-10-27 16:49:35 -05:00
r . Route ( "/{groupName}" , func ( r chi . Router ) {
r . Use (
httpmw . ExtractGroupByNameParam ( api . Database ),
)
2023-01-13 12:27:21 +01:00
r . Get ( "/" , api . groupByOrganization )
2022-10-27 16:49:35 -05:00
})
2022-10-10 15:37:06 -05:00
})
2023-08-04 12:32:28 +04:00
// TODO: provisioner daemons are not scoped to organizations in the database, so placing them
// under an organization route doesn't make sense. In order to allow the /serve endpoint to
// work with a pre-shared key (PSK) without an API key, these routes will simply ignore the
// value of {organization}. That is, the route will work with any organization ID, whether or
// not it exits. This doesn't leak any information about the existence of organizations, so is
// fine from a security perspective, but might be a little surprising.
//
// We may in future decide to scope provisioner daemons to organizations, so we'll keep the API
// route as is.
2022-11-16 16:34:06 -06:00
r . Route ( "/organizations/{organization}/provisionerdaemons" , func ( r chi . Router ) {
r . Use (
api . provisionerDaemonsEnabledMW ,
)
2023-08-04 12:32:28 +04:00
r . With ( apiKeyMiddleware ). Get ( "/" , api . provisionerDaemons )
r . With ( apiKeyMiddlewareOptional ). Get ( "/serve" , api . provisionerDaemonServe )
2022-11-16 16:34:06 -06:00
})
2022-10-10 15:37:06 -05:00
r . Route ( "/templates/{template}/acl" , func ( r chi . Router ) {
r . Use (
2022-10-12 04:51:41 +10:00
api . templateRBACEnabledMW ,
2022-10-10 15:37:06 -05:00
apiKeyMiddleware ,
httpmw . ExtractTemplateParam ( api . Database ),
)
2023-07-26 10:33:48 -04:00
r . Get ( "/available" , api . templateAvailablePermissions )
2022-10-10 15:37:06 -05:00
r . Get ( "/" , api . templateACL )
r . Patch ( "/" , api . patchTemplateACL )
})
r . Route ( "/groups/{group}" , func ( r chi . Router ) {
r . Use (
2022-10-12 04:51:41 +10:00
api . templateRBACEnabledMW ,
2022-10-10 15:37:06 -05:00
apiKeyMiddleware ,
httpmw . ExtractGroupParam ( api . Database ),
)
r . Get ( "/" , api . group )
r . Patch ( "/" , api . patchGroup )
r . Delete ( "/" , api . deleteGroup )
})
2022-09-30 14:01:20 -04:00
r . Route ( "/workspace-quota" , func ( r chi . Router ) {
2022-11-14 11:57:33 -06:00
r . Use (
apiKeyMiddleware ,
)
2022-09-30 14:01:20 -04:00
r . Route ( "/{user}" , func ( r chi . Router ) {
2022-10-15 02:46:38 +10:00
r . Use ( httpmw . ExtractUserParam ( options . Database , false ))
2022-09-30 14:01:20 -04:00
r . Get ( "/" , api . workspaceQuota )
})
})
2023-01-04 15:31:45 -06:00
r . Route ( "/appearance" , func ( r chi . Router ) {
2023-06-30 10:41:29 -08:00
r . Group ( func ( r chi . Router ) {
r . Use (
apiKeyMiddlewareOptional ,
httpmw . ExtractWorkspaceAgent ( httpmw . ExtractWorkspaceAgentConfig {
DB : options . Database ,
Optional : true ,
}),
httpmw . RequireAPIKeyOrWorkspaceAgent (),
)
r . Get ( "/" , api . appearance )
})
r . Group ( func ( r chi . Router ) {
r . Use (
apiKeyMiddleware ,
)
r . Put ( "/" , api . putAppearance )
})
2022-12-06 12:38:38 -06:00
})
2023-07-20 06:35:41 -07:00
r . Route ( "/users/{user}/quiet-hours" , func ( r chi . Router ) {
r . Use (
api . restartRequirementEnabledMW ,
apiKeyMiddleware ,
httpmw . ExtractUserParam ( options . Database , false ),
)
r . Get ( "/" , api . userQuietHoursSchedule )
r . Put ( "/" , api . putUserQuietHoursSchedule )
})
2022-09-19 23:11:01 -05:00
})
2022-09-20 15:16:26 -05:00
if len ( options . SCIMAPIKey ) != 0 {
api . AGPL . RootHandler . Route ( "/scim/v2" , func ( r chi . Router ) {
2023-02-14 08:27:06 -06:00
r . Use (
api . scimEnabledMW ,
)
2022-09-20 15:16:26 -05:00
r . Post ( "/Users" , api . scimPostUser )
r . Route ( "/Users" , func ( r chi . Router ) {
r . Get ( "/" , api . scimGetUsers )
r . Post ( "/" , api . scimPostUser )
r . Get ( "/{id}" , api . scimGetUser )
r . Patch ( "/{id}" , api . scimPatchUser )
})
})
}
2022-10-17 08:43:30 -05:00
meshRootCA := x509 . NewCertPool ()
for _ , certificate := range options . TLSCertificates {
for _ , certificatePart := range certificate . Certificate {
certificate , err := x509 . ParseCertificate ( certificatePart )
if err != nil {
return nil , xerrors . Errorf ( "parse certificate %s: %w" , certificate . Subject . CommonName , err )
}
meshRootCA . AddCert ( certificate )
}
}
// This TLS configuration spoofs access from the access URL hostname
// assuming that the certificates provided will cover that hostname.
//
// Replica sync and DERP meshing require accessing replicas via their
// internal IP addresses, and if TLS is configured we use the same
// certificates.
meshTLSConfig := & tls . Config {
MinVersion : tls . VersionTLS12 ,
Certificates : options . TLSCertificates ,
RootCAs : meshRootCA ,
ServerName : options . AccessURL . Hostname (),
}
api . replicaManager , err = replicasync . New ( ctx , options . Logger , options . Database , options . Pubsub , & replicasync . Options {
2023-07-26 09:21:04 -07:00
ID : api . AGPL . ID ,
RelayAddress : options . DERPServerRelayAddress ,
RegionID : int32 ( options . DERPServerRegionID ),
TLSConfig : meshTLSConfig ,
UpdateInterval : options . ReplicaSyncUpdateInterval ,
2022-10-17 08:43:30 -05:00
})
if err != nil {
return nil , xerrors . Errorf ( "initialize replica: %w" , err )
}
api . derpMesh = derpmesh . New ( options . Logger . Named ( "derpmesh" ), api . DERPServer , meshTLSConfig )
2023-04-24 10:25:35 -05:00
if api . AGPL . Experiments . Enabled ( codersdk . ExperimentMoons ) {
// Proxy health is a moon feature.
2023-04-25 07:37:52 -07:00
api . ProxyHealth , err = proxyhealth . New ( & proxyhealth . Options {
2023-05-10 19:23:16 -05:00
Interval : options . ProxyHealthInterval ,
2023-04-24 10:25:35 -05:00
DB : api . Database ,
Logger : options . Logger . Named ( "proxyhealth" ),
Client : api . HTTPClient ,
Prometheus : api . PrometheusRegistry ,
})
if err != nil {
return nil , xerrors . Errorf ( "initialize proxy health: %w" , err )
}
2023-04-25 07:37:52 -07:00
go api . ProxyHealth . Run ( ctx )
2023-04-24 10:25:35 -05:00
// Force the initial loading of the cache. Do this in a go routine in case
// the calls to the workspace proxies hang and this takes some time.
go api . forceWorkspaceProxyHealthUpdate ( ctx )
2023-05-02 08:30:44 -05:00
// Use proxy health to return the healthy workspace proxy hostnames.
f := api . ProxyHealth . ProxyHosts
api . AGPL . WorkspaceProxyHostsFn . Store ( & f )
2023-04-24 10:25:35 -05:00
}
2022-10-17 08:43:30 -05:00
err = api . updateEntitlements ( ctx )
2022-09-19 23:11:01 -05:00
if err != nil {
return nil , xerrors . Errorf ( "update entitlements: %w" , err )
}
go api . runEntitlementsLoop ( ctx )
return api , nil
}
type Options struct {
* coderd . Options
2022-10-17 08:43:30 -05:00
RBAC bool
2022-09-22 10:14:22 -05:00
AuditLogging bool
// Whether to block non-browser connections.
2022-11-14 11:57:33 -06:00
BrowserOnly bool
SCIMAPIKey [] byte
2022-09-30 14:01:20 -04:00
2022-10-17 08:43:30 -05:00
// Used for high availability.
2023-07-26 09:21:04 -07:00
ReplicaSyncUpdateInterval time . Duration
DERPServerRelayAddress string
DERPServerRegionID int
2022-10-17 08:43:30 -05:00
2023-07-20 06:35:41 -07:00
// Used for user quiet hours schedules.
DefaultQuietHoursSchedule string // cron schedule, if empty user quiet hours schedules are disabled
2022-09-19 23:11:01 -05:00
EntitlementsUpdateInterval time . Duration
2023-04-24 10:25:35 -05:00
ProxyHealthInterval time . Duration
2022-09-19 23:11:01 -05:00
Keys map [ string ] ed25519 . PublicKey
2023-08-04 12:32:28 +04:00
// optional pre-shared key for authentication of external provisioner daemons
ProvisionerDaemonPSK string
2022-09-19 23:11:01 -05:00
}
type API struct {
AGPL * coderd . API
* Options
2023-04-24 10:25:35 -05:00
// ctx is canceled immediately on shutdown, it can be used to abort
// interruptible tasks.
ctx context . Context
cancel context . CancelFunc
2022-10-17 08:43:30 -05:00
// Detects multiple Coder replicas running at the same time.
replicaManager * replicasync . Manager
// Meshes DERP connections from multiple replicas.
derpMesh * derpmesh . Mesh
2023-04-25 07:37:52 -07:00
// ProxyHealth checks the reachability of all workspace proxies.
ProxyHealth * proxyhealth . ProxyHealth
2022-10-17 08:43:30 -05:00
2023-06-26 20:22:28 +03:00
entitlementsUpdateMu sync . Mutex
entitlementsMu sync . RWMutex
entitlements codersdk . Entitlements
2023-08-04 12:32:28 +04:00
provisionerDaemonAuth * provisionerDaemonAuth
2022-09-19 23:11:01 -05:00
}
func ( api * API ) Close () error {
2023-04-24 10:25:35 -05:00
api . cancel ()
2023-06-13 20:18:31 +03:00
if api . replicaManager != nil {
_ = api . replicaManager . Close ()
}
if api . derpMesh != nil {
_ = api . derpMesh . Close ()
}
2022-09-19 23:11:01 -05:00
return api . AGPL . Close ()
}
func ( api * API ) updateEntitlements ( ctx context . Context ) error {
2023-06-26 20:22:28 +03:00
api . entitlementsUpdateMu . Lock ()
defer api . entitlementsUpdateMu . Unlock ()
2022-10-06 19:28:22 -05:00
2023-02-14 19:40:08 -06:00
entitlements , err := license . Entitlements (
ctx , api . Database ,
2023-07-26 09:21:04 -07:00
api . Logger , len ( api . replicaManager . AllPrimary ()), len ( api . GitAuthConfigs ), api . Keys , map [ codersdk . FeatureName ] bool {
2023-02-14 19:40:08 -06:00
codersdk . FeatureAuditLog : api . AuditLogging ,
codersdk . FeatureBrowserOnly : api . BrowserOnly ,
codersdk . FeatureSCIM : len ( api . SCIMAPIKey ) != 0 ,
codersdk . FeatureHighAvailability : api . DERPServerRelayAddress != "" ,
codersdk . FeatureMultipleGitAuth : len ( api . GitAuthConfigs ) > 1 ,
codersdk . FeatureTemplateRBAC : api . RBAC ,
codersdk . FeatureExternalProvisionerDaemons : true ,
2023-03-08 01:14:58 +11:00
codersdk . FeatureAdvancedTemplateScheduling : true ,
2023-07-20 06:35:41 -07:00
// FeatureTemplateRestartRequirement depends on
// FeatureAdvancedTemplateScheduling.
codersdk . FeatureTemplateRestartRequirement : api . DefaultQuietHoursSchedule != "" ,
2023-04-04 15:07:29 -05:00
codersdk . FeatureWorkspaceProxy : true ,
2023-07-24 08:34:24 -04:00
codersdk . FeatureUserRoleManagement : true ,
2023-02-14 19:40:08 -06:00
})
2022-09-19 23:11:01 -05:00
if err != nil {
return err
}
2023-02-14 14:26:47 -06:00
2023-03-07 15:10:01 -06:00
if entitlements . RequireTelemetry && ! api . DeploymentValues . Telemetry . Enable . Value () {
2023-02-14 14:26:47 -06:00
// We can't fail because then the user couldn't remove the offending
// license w/o a restart.
2023-02-14 19:40:08 -06:00
//
// We don't simply append to entitlement.Errors since we don't want any
// enterprise features enabled.
2023-02-14 14:26:47 -06:00
api . entitlements . Errors = [] string {
"License requires telemetry but telemetry is disabled" ,
}
api . Logger . Error ( ctx , "license requires telemetry enabled" )
return nil
}
2023-07-20 06:35:41 -07:00
if entitlements . Features [ codersdk . FeatureTemplateRestartRequirement ]. Enabled && ! entitlements . Features [ codersdk . FeatureAdvancedTemplateScheduling ]. Enabled {
api . entitlements . Errors = [] string {
`Your license is entitled to the feature "template restart ` +
`requirement" (and you have it enabled by setting the ` +
"default quiet hours schedule), but you are not entitled to " +
`the dependency feature "advanced template scheduling". ` +
"Please contact support for a new license." ,
}
api . Logger . Error ( ctx , "license is entitled to template restart requirement but not advanced template scheduling" )
return nil
}
2023-07-19 10:32:29 -05:00
featureChanged := func ( featureName codersdk . FeatureName ) ( initial , changed , enabled bool ) {
2022-10-06 19:28:22 -05:00
if api . entitlements . Features == nil {
2023-07-19 10:32:29 -05:00
return true , false , entitlements . Features [ featureName ]. Enabled
2022-10-06 19:28:22 -05:00
}
oldFeature := api . entitlements . Features [ featureName ]
newFeature := entitlements . Features [ featureName ]
if oldFeature . Enabled != newFeature . Enabled {
2023-07-19 10:32:29 -05:00
return false , true , newFeature . Enabled
2022-10-06 19:28:22 -05:00
}
2023-07-19 10:32:29 -05:00
return false , false , newFeature . Enabled
2022-09-19 23:11:01 -05:00
}
2023-07-19 10:32:29 -05:00
shouldUpdate := func ( initial , changed , enabled bool ) bool {
// Avoid an initial tick on startup unless the feature is enabled.
return changed || ( initial && enabled )
}
if initial , changed , enabled := featureChanged ( codersdk . FeatureAuditLog ); shouldUpdate ( initial , changed , enabled ) {
2022-10-06 19:28:22 -05:00
auditor := agplaudit . NewNop ()
if enabled {
2022-10-19 02:00:45 -05:00
auditor = api . AGPL . Options . Auditor
2022-09-19 23:11:01 -05:00
}
2022-10-06 19:28:22 -05:00
api . AGPL . Auditor . Store ( & auditor )
2022-08-29 16:45:40 -07:00
}
2022-09-19 23:11:01 -05:00
2023-07-19 10:32:29 -05:00
if initial , changed , enabled := featureChanged ( codersdk . FeatureBrowserOnly ); shouldUpdate ( initial , changed , enabled ) {
2022-09-22 10:14:22 -05:00
var handler func ( rw http . ResponseWriter ) bool
2022-10-06 19:28:22 -05:00
if enabled {
2022-09-22 10:14:22 -05:00
handler = api . shouldBlockNonBrowserConnections
}
api . AGPL . WorkspaceClientCoordinateOverride . Store ( & handler )
}
2023-07-19 10:32:29 -05:00
if initial , changed , enabled := featureChanged ( codersdk . FeatureTemplateRBAC ); shouldUpdate ( initial , changed , enabled ) {
2022-10-06 19:28:22 -05:00
if enabled {
2022-11-14 11:57:33 -06:00
committer := committer { Database : api . Database }
ptr := proto . QuotaCommitter ( & committer )
api . AGPL . QuotaCommitter . Store ( & ptr )
} else {
api . AGPL . QuotaCommitter . Store ( nil )
2022-09-30 14:01:20 -04:00
}
}
2023-07-19 10:32:29 -05:00
if initial , changed , enabled := featureChanged ( codersdk . FeatureAdvancedTemplateScheduling ); shouldUpdate ( initial , changed , enabled ) {
2023-03-08 01:14:58 +11:00
if enabled {
2023-07-20 06:35:41 -07:00
templateStore := schedule . NewEnterpriseTemplateScheduleStore ()
templateStoreInterface := agplschedule . TemplateScheduleStore ( templateStore )
api . AGPL . TemplateScheduleStore . Store ( & templateStoreInterface )
2023-03-08 01:14:58 +11:00
} else {
2023-07-20 06:35:41 -07:00
templateStore := agplschedule . NewAGPLTemplateScheduleStore ()
api . AGPL . TemplateScheduleStore . Store ( & templateStore )
}
}
if initial , changed , enabled := featureChanged ( codersdk . FeatureTemplateRestartRequirement ); shouldUpdate ( initial , changed , enabled ) {
if enabled {
templateStore := * ( api . AGPL . TemplateScheduleStore . Load ())
enterpriseTemplateStore , ok := templateStore .( * schedule . EnterpriseTemplateScheduleStore )
if ! ok {
api . Logger . Error ( ctx , "unable to set up enterprise template schedule store, template restart requirements will not be applied to workspace builds" )
}
enterpriseTemplateStore . UseRestartRequirement . Store ( true )
quietHoursStore , err := schedule . NewEnterpriseUserQuietHoursScheduleStore ( api . DefaultQuietHoursSchedule )
if err != nil {
api . Logger . Error ( ctx , "unable to set up enterprise user quiet hours schedule store, template restart requirements will not be applied to workspace builds" , slog . Error ( err ))
} else {
api . AGPL . UserQuietHoursScheduleStore . Store ( & quietHoursStore )
}
} else {
if api . DefaultQuietHoursSchedule != "" {
api . Logger . Warn ( ctx , "template restart requirements are not enabled (due to setting default quiet hours schedule) as your license is not entitled to this feature" )
}
templateStore := * ( api . AGPL . TemplateScheduleStore . Load ())
enterpriseTemplateStore , ok := templateStore .( * schedule . EnterpriseTemplateScheduleStore )
if ok {
enterpriseTemplateStore . UseRestartRequirement . Store ( false )
}
quietHoursStore := agplschedule . NewAGPLUserQuietHoursScheduleStore ()
api . AGPL . UserQuietHoursScheduleStore . Store ( & quietHoursStore )
2023-03-08 01:14:58 +11:00
}
}
2023-07-19 10:32:29 -05:00
if initial , changed , enabled := featureChanged ( codersdk . FeatureHighAvailability ); shouldUpdate ( initial , changed , enabled ) {
var coordinator agpltailnet . Coordinator
2022-10-25 09:33:37 -05:00
if enabled {
2023-06-22 13:12:29 +04:00
var haCoordinator agpltailnet . Coordinator
2023-07-28 18:38:32 -05:00
if api . AGPL . Experiments . Enabled ( codersdk . ExperimentTailnetPGCoordinator ) {
2023-07-12 13:35:29 +04:00
haCoordinator , err = tailnet . NewPGCoord ( api . ctx , api . Logger , api . Pubsub , api . Database )
2023-07-28 18:38:32 -05:00
} else {
haCoordinator , err = tailnet . NewCoordinator ( api . Logger , api . Pubsub )
2023-06-22 13:12:29 +04:00
}
2022-10-17 08:43:30 -05:00
if err != nil {
api . Logger . Error ( ctx , "unable to set up high availability coordinator" , slog . Error ( err ))
// If we try to setup the HA coordinator and it fails, nothing
// is actually changing.
} else {
coordinator = haCoordinator
}
api . replicaManager . SetCallback ( func () {
addresses := make ([] string , 0 )
for _ , replica := range api . replicaManager . Regional () {
addresses = append ( addresses , replica . RelayAddress )
}
api . derpMesh . SetAddresses ( addresses , false )
_ = api . updateEntitlements ( ctx )
})
} else {
2023-07-19 10:32:29 -05:00
coordinator = agpltailnet . NewCoordinator ( api . Logger )
2022-10-17 08:43:30 -05:00
api . derpMesh . SetAddresses ([] string {}, false )
api . replicaManager . SetCallback ( func () {
// If the amount of replicas change, so should our entitlements.
// This is to display a warning in the UI if the user is unlicensed.
_ = api . updateEntitlements ( ctx )
})
}
// Recheck changed in case the HA coordinator failed to set up.
2023-07-19 10:32:29 -05:00
if coordinator != nil {
2022-10-17 08:43:30 -05:00
oldCoordinator := * api . AGPL . TailnetCoordinator . Swap ( & coordinator )
err := oldCoordinator . Close ()
if err != nil {
api . Logger . Error ( ctx , "close old tailnet coordinator" , slog . Error ( err ))
}
}
}
2023-07-26 09:21:04 -07:00
if initial , changed , enabled := featureChanged ( codersdk . FeatureWorkspaceProxy ); shouldUpdate ( initial , changed , enabled ) {
if enabled {
2023-08-10 12:04:17 -07:00
fn := derpMapper ( api . Logger , api . ProxyHealth )
2023-07-26 09:21:04 -07:00
api . AGPL . DERPMapper . Store ( & fn )
} else {
api . AGPL . DERPMapper . Store ( nil )
}
}
2023-06-26 20:22:28 +03:00
api . entitlementsMu . Lock ()
defer api . entitlementsMu . Unlock ()
2022-09-19 23:11:01 -05:00
api . entitlements = entitlements
2023-06-18 13:57:27 -05:00
api . AGPL . SiteHandler . Entitlements . Store ( & entitlements )
2022-09-19 23:11:01 -05:00
return nil
}
2023-07-26 09:21:04 -07:00
// getProxyDERPStartingRegionID returns the starting region ID that should be
// used for workspace proxies. A proxy's actual region ID is the return value
// from this function + it's RegionID field.
//
// Two ints are returned, the first is the starting region ID for proxies, and
// the second is the maximum region ID that already exists in the DERP map.
func getProxyDERPStartingRegionID ( derpMap * tailcfg . DERPMap ) ( sID int64 , mID int64 ) {
var maxRegionID int64
for _ , region := range derpMap . Regions {
rid := int64 ( region . RegionID )
if rid > maxRegionID {
maxRegionID = rid
}
}
if maxRegionID < 0 {
maxRegionID = 0
}
// Round to the nearest 10,000 with a sufficient buffer of at least 2,000.
// The buffer allows for future "fixed" regions to be added to the base DERP
// map without conflicting with proxy region IDs (standard DERP maps usually
// use incrementing IDs for new regions).
//
// Example:
// maxRegionID = -2_000 -> startingRegionID = 10_000
// maxRegionID = 8_000 -> startingRegionID = 10_000
// maxRegionID = 8_500 -> startingRegionID = 20_000
// maxRegionID = 12_000 -> startingRegionID = 20_000
// maxRegionID = 20_000 -> startingRegionID = 30_000
const roundStartingRegionID = 10_000
const startingRegionIDBuffer = 2_000
// Add the buffer first.
startingRegionID := maxRegionID + startingRegionIDBuffer
// Round UP to the nearest 10,000. Go's math.Ceil rounds up to the nearest
// integer, so we need to divide by 10,000 first and then multiply by
// 10,000.
startingRegionID = int64 ( math . Ceil ( float64 ( startingRegionID ) / roundStartingRegionID ) * roundStartingRegionID )
// This should never be hit but it's here just in case.
if startingRegionID < roundStartingRegionID {
startingRegionID = roundStartingRegionID
}
return startingRegionID , maxRegionID
}
var (
lastDerpConflictMutex sync . Mutex
lastDerpConflictLog time . Time
)
2023-08-10 12:04:17 -07:00
func derpMapper ( logger slog . Logger , proxyHealth * proxyhealth . ProxyHealth ) func ( * tailcfg . DERPMap ) * tailcfg . DERPMap {
2023-07-26 09:21:04 -07:00
return func ( derpMap * tailcfg . DERPMap ) * tailcfg . DERPMap {
derpMap = derpMap . Clone ()
// Find the starting region ID that we'll use for proxies. This must be
// deterministic based on the derp map.
startingRegionID , largestRegionID := getProxyDERPStartingRegionID ( derpMap )
if largestRegionID >= 1 << 32 {
// Enforce an upper bound on the region ID. This shouldn't be hit in
// practice, but it's a good sanity check.
lastDerpConflictMutex . Lock ()
shouldLog := lastDerpConflictLog . IsZero () || time . Since ( lastDerpConflictLog ) > time . Minute
if shouldLog {
lastDerpConflictLog = time . Now ()
}
lastDerpConflictMutex . Unlock ()
if shouldLog {
logger . Warn (
context . Background (),
"existing DERP region IDs are too large, proxy region IDs will not be populated in the derp map. Please ensure that all DERP region IDs are less than 2^32" ,
slog . F ( "largest_region_id" , largestRegionID ),
2023-07-26 10:30:47 -07:00
slog . F ( "max_region_id" , int64 ( 1 << 32 - 1 )),
2023-07-26 09:21:04 -07:00
)
return derpMap
}
}
// Add all healthy proxies to the DERP map.
statusMap := proxyHealth . HealthStatus ()
statusLoop :
for _ , status := range statusMap {
if status . Status != proxyhealth . Healthy || ! status . Proxy . DerpEnabled {
// Only add healthy proxies with DERP enabled to the DERP map.
continue
}
u , err := url . Parse ( status . Proxy . Url )
if err != nil {
// Not really any need to log, the proxy should be unreachable
// anyways and filtered out by the above condition.
continue
}
port := u . Port ()
if port == "" {
port = "80"
if u . Scheme == "https" {
port = "443"
}
}
portInt , err := strconv . Atoi ( port )
if err != nil {
// Not really any need to log, the proxy should be unreachable
// anyways and filtered out by the above condition.
continue
}
// Sanity check that the region ID and code is unique.
//
// This should be impossible to hit as the IDs are enforced to be
// unique by the database and the computed ID is greater than any
// existing ID in the DERP map.
regionID := int ( startingRegionID ) + int ( status . Proxy . RegionID )
regionCode := fmt . Sprintf ( "coder_%s" , strings . ToLower ( status . Proxy . Name ))
2023-08-01 20:18:46 -07:00
regionName := status . Proxy . DisplayName
if regionName == "" {
regionName = status . Proxy . Name
}
2023-07-26 09:21:04 -07:00
for _ , r := range derpMap . Regions {
if r . RegionID == regionID || r . RegionCode == regionCode {
// Log a warning if we haven't logged one in the last
// minute.
lastDerpConflictMutex . Lock ()
shouldLog := lastDerpConflictLog . IsZero () || time . Since ( lastDerpConflictLog ) > time . Minute
if shouldLog {
lastDerpConflictLog = time . Now ()
}
lastDerpConflictMutex . Unlock ()
if shouldLog {
logger . Warn ( context . Background (),
2023-08-01 08:50:43 -07:00
"proxy region ID or code conflict, ignoring workspace proxy for DERP map" ,
2023-07-26 09:21:04 -07:00
slog . F ( "proxy_id" , status . Proxy . ID ),
slog . F ( "proxy_name" , status . Proxy . Name ),
slog . F ( "proxy_display_name" , status . Proxy . DisplayName ),
slog . F ( "proxy_url" , status . Proxy . Url ),
slog . F ( "proxy_region_id" , status . Proxy . RegionID ),
slog . F ( "proxy_computed_region_id" , regionID ),
slog . F ( "proxy_computed_region_code" , regionCode ),
)
}
continue statusLoop
}
}
derpMap . Regions [ regionID ] = & tailcfg . DERPRegion {
// EmbeddedRelay ONLY applies to the primary.
EmbeddedRelay : false ,
RegionID : regionID ,
RegionCode : regionCode ,
2023-08-01 20:18:46 -07:00
RegionName : regionName ,
2023-08-10 12:04:17 -07:00
Nodes : [] * tailcfg . DERPNode {
{
Name : fmt . Sprintf ( "%da" , regionID ),
RegionID : regionID ,
HostName : u . Hostname (),
DERPPort : portInt ,
STUNPort : - 1 ,
ForceHTTP : u . Scheme == "http" ,
},
},
2023-07-26 09:21:04 -07:00
}
}
return derpMap
}
}
2023-01-11 16:05:42 +01:00
// @Summary Get entitlements
// @ID get-entitlements
// @Security CoderSessionToken
// @Produce json
// @Tags Enterprise
// @Success 200 {object} codersdk.Entitlements
// @Router /entitlements [get]
2022-09-19 23:11:01 -05:00
func ( api * API ) serveEntitlements ( rw http . ResponseWriter , r * http . Request ) {
2022-09-21 17:07:00 -05:00
ctx := r . Context ()
2022-09-19 23:11:01 -05:00
api . entitlementsMu . RLock ()
entitlements := api . entitlements
api . entitlementsMu . RUnlock ()
2022-10-06 19:28:22 -05:00
httpapi . Write ( ctx , rw , http . StatusOK , entitlements )
2022-09-19 23:11:01 -05:00
}
func ( api * API ) runEntitlementsLoop ( ctx context . Context ) {
eb := backoff . NewExponentialBackOff ()
eb . MaxElapsedTime = 0 // retry indefinitely
b := backoff . WithContext ( eb , ctx )
updates := make ( chan struct {}, 1 )
subscribed := false
for {
select {
case <- ctx . Done ():
return
default :
// pass
}
if ! subscribed {
cancel , err := api . Pubsub . Subscribe ( PubsubEventLicenses , func ( _ context . Context , _ [] byte ) {
// don't block. If the channel is full, drop the event, as there is a resync
// scheduled already.
select {
case updates <- struct {}{}:
// pass
default :
// pass
}
})
if err != nil {
api . Logger . Warn ( ctx , "failed to subscribe to license updates" , slog . Error ( err ))
select {
case <- ctx . Done ():
return
case <- time . After ( b . NextBackOff ()):
}
continue
}
// nolint: revive
defer cancel ()
subscribed = true
api . Logger . Debug ( ctx , "successfully subscribed to pubsub" )
}
2022-09-24 14:55:17 -05:00
api . Logger . Debug ( ctx , "syncing licensed entitlements" )
2022-09-19 23:11:01 -05:00
err := api . updateEntitlements ( ctx )
if err != nil {
api . Logger . Warn ( ctx , "failed to get feature entitlements" , slog . Error ( err ))
time . Sleep ( b . NextBackOff ())
continue
}
b . Reset ()
api . Logger . Debug ( ctx , "synced licensed entitlements" )
select {
case <- ctx . Done ():
return
case <- time . After ( api . EntitlementsUpdateInterval ):
continue
case <- updates :
api . Logger . Debug ( ctx , "got pubsub update" )
continue
}
}
}
2022-10-10 15:37:06 -05:00
func ( api * API ) Authorize ( r * http . Request , action rbac . Action , object rbac . Objecter ) bool {
return api . AGPL . HTTPAuth . Authorize ( r , action , object )
}