2022-01-13 16:55:28 -06:00
package coderd
import (
2022-11-16 16:34:06 -06:00
"context"
2022-10-17 08:43:30 -05:00
"crypto/tls"
2022-04-19 08:48:13 -05:00
"crypto/x509"
2023-12-18 16:44:52 +00:00
"database/sql"
2024-11-21 11:53:53 -06:00
"errors"
2024-02-14 15:11:45 +04:00
"expvar"
2023-05-11 14:30:51 -05:00
"flag"
2022-10-24 19:46:24 -05:00
"fmt"
2022-06-13 13:14:22 -05:00
"io"
2026-03-19 00:54:32 +11:00
"math"
2022-01-13 16:55:28 -06:00
"net/http"
2025-10-21 14:13:11 +11:00
httppprof "net/http/pprof"
2022-02-28 12:26:01 -06:00
"net/url"
2022-06-21 19:53:36 +03:00
"path/filepath"
2022-10-15 04:25:11 +10:00
"regexp"
2025-08-07 13:58:39 -05:00
"runtime/pprof"
2023-01-18 19:12:53 +00:00
"strings"
2022-02-20 16:29:16 -06:00
"sync"
2022-09-19 23:11:01 -05:00
"sync/atomic"
2022-03-22 13:17:50 -06:00
"time"
2022-01-13 16:55:28 -06:00
2022-01-30 19:13:14 -08:00
"github.com/go-chi/chi/v5"
2022-05-03 07:48:02 -05:00
"github.com/go-chi/chi/v5/middleware"
2022-11-06 13:27:09 -08:00
"github.com/google/uuid"
2022-08-08 10:09:46 -05:00
"github.com/prometheus/client_golang/prometheus"
2026-01-20 10:28:52 +11:00
"github.com/prometheus/client_golang/prometheus/collectors"
2025-10-21 14:13:11 +11:00
"github.com/prometheus/client_golang/prometheus/promhttp"
2023-03-30 11:46:58 -05:00
httpSwagger "github.com/swaggo/http-swagger/v2"
2022-09-16 11:43:22 -05:00
"go.opentelemetry.io/otel/trace"
2022-05-03 16:10:19 -05:00
"golang.org/x/xerrors"
2022-02-21 14:36:29 -06:00
"google.golang.org/api/idtoken"
2022-11-16 16:34:06 -06:00
"storj.io/drpc/drpcmux"
"storj.io/drpc/drpcserver"
2022-08-31 20:09:44 -05:00
"tailscale.com/derp"
"tailscale.com/derp/derphttp"
"tailscale.com/tailcfg"
"tailscale.com/types/key"
2023-04-03 01:28:42 -05:00
"tailscale.com/util/singleflight"
2022-01-20 07:46:51 -06:00
2026-01-08 10:29:41 +04:00
"cdr.dev/slog/v3"
2024-01-29 12:17:31 +04:00
agentproto "github.com/coder/coder/v2/agent/proto"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/buildinfo"
2026-02-06 16:26:02 -06:00
"github.com/coder/coder/v2/coderd/agentapi"
2026-01-22 22:47:49 -08:00
"github.com/coder/coder/v2/coderd/agentapi/metadatabatcher"
2026-03-16 12:36:26 -05:00
"github.com/coder/coder/v2/coderd/aiseats"
2024-01-29 12:17:31 +04:00
_ "github.com/coder/coder/v2/coderd/apidoc" // Used for swagger docs.
"github.com/coder/coder/v2/coderd/appearance"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/coderd/audit"
"github.com/coder/coder/v2/coderd/awsidentity"
2026-01-27 19:11:40 -07:00
"github.com/coder/coder/v2/coderd/boundaryusage"
2026-02-27 11:50:56 -05:00
"github.com/coder/coder/v2/coderd/chatd"
2025-07-15 14:36:06 +10:00
"github.com/coder/coder/v2/coderd/connectionlog"
2026-01-08 15:24:11 +04:00
"github.com/coder/coder/v2/coderd/cryptokeys"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/database/dbauthz"
2024-03-22 18:42:43 +02:00
"github.com/coder/coder/v2/coderd/database/dbrollup"
2023-12-18 16:44:52 +00:00
"github.com/coder/coder/v2/coderd/database/dbtime"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/coderd/database/pubsub"
2026-01-08 15:24:11 +04:00
"github.com/coder/coder/v2/coderd/entitlements"
2023-12-18 04:53:28 -08:00
"github.com/coder/coder/v2/coderd/externalauth"
2026-01-08 15:24:11 +04:00
"github.com/coder/coder/v2/coderd/files"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/coderd/gitsshkey"
2026-03-10 18:46:01 +00:00
"github.com/coder/coder/v2/coderd/gitsync"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/coderd/healthcheck"
2023-12-18 04:53:28 -08:00
"github.com/coder/coder/v2/coderd/healthcheck/derphealth"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/coderd/httpapi"
"github.com/coder/coder/v2/coderd/httpmw"
2025-04-15 13:27:23 +02:00
"github.com/coder/coder/v2/coderd/httpmw/loggermw"
2026-01-08 15:24:11 +04:00
"github.com/coder/coder/v2/coderd/idpsync"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/coderd/metricscache"
2024-07-08 15:38:50 +02:00
"github.com/coder/coder/v2/coderd/notifications"
2026-01-08 15:24:11 +04:00
"github.com/coder/coder/v2/coderd/oauth2provider"
2024-02-13 09:31:20 -05:00
"github.com/coder/coder/v2/coderd/portsharing"
2026-01-08 15:24:11 +04:00
"github.com/coder/coder/v2/coderd/pproflabel"
"github.com/coder/coder/v2/coderd/prebuilds"
2024-01-29 12:17:31 +04:00
"github.com/coder/coder/v2/coderd/prometheusmetrics"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/coderd/provisionerdserver"
2025-06-17 09:00:32 -08:00
"github.com/coder/coder/v2/coderd/proxyhealth"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/coderd/rbac"
2024-05-15 09:46:35 -05:00
"github.com/coder/coder/v2/coderd/rbac/policy"
2024-05-16 13:47:47 -05:00
"github.com/coder/coder/v2/coderd/rbac/rolestore"
2026-01-08 15:24:11 +04:00
"github.com/coder/coder/v2/coderd/runtimeconfig"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/coderd/schedule"
"github.com/coder/coder/v2/coderd/telemetry"
"github.com/coder/coder/v2/coderd/tracing"
"github.com/coder/coder/v2/coderd/updatecheck"
2026-01-08 15:24:11 +04:00
"github.com/coder/coder/v2/coderd/usage"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/coderd/util/slice"
2026-01-08 15:24:11 +04:00
"github.com/coder/coder/v2/coderd/webpush"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/coderd/workspaceapps"
2025-06-17 09:00:32 -08:00
"github.com/coder/coder/v2/coderd/workspaceapps/appurl"
2024-05-29 11:49:08 -04:00
"github.com/coder/coder/v2/coderd/workspacestats"
2026-01-08 15:24:11 +04:00
"github.com/coder/coder/v2/coderd/wsbuilder"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/codersdk"
2026-01-08 15:24:11 +04:00
"github.com/coder/coder/v2/codersdk/drpcsdk"
2024-03-26 12:44:31 -05:00
"github.com/coder/coder/v2/codersdk/healthsdk"
2025-11-25 14:59:20 -09:00
sharedhttpmw "github.com/coder/coder/v2/httpmw"
2026-01-08 15:24:11 +04:00
"github.com/coder/coder/v2/provisionerd/proto"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/provisionersdk"
"github.com/coder/coder/v2/site"
"github.com/coder/coder/v2/tailnet"
2026-03-06 01:57:58 -06:00
"github.com/coder/coder/v2/tailnet/derpmetrics"
2026-01-08 15:24:11 +04:00
"github.com/coder/quartz"
"github.com/coder/serpent"
2022-01-13 16:55:28 -06:00
)
2023-01-11 12:42:49 +02:00
// We must only ever instantiate one httpSwagger.Handler because of a data race
// inside the handler. This issue is triggered by tests that create multiple
// coderd instances.
//
// See https://github.com/swaggo/http-swagger/issues/78
var globalHTTPSwaggerHandler http . HandlerFunc
func init () {
2024-07-01 08:44:35 -10:00
globalHTTPSwaggerHandler = httpSwagger . Handler (
httpSwagger . URL ( "/swagger/doc.json" ),
// The swagger UI has an "Authorize" button that will input the
// credentials into the Coder-Session-Token header. This bypasses
// CSRF checks **if** there is no cookie auth also present.
// (If the cookie matches, then it's ok too)
//
// Because swagger is hosted on the same domain, we have the cookie
// auth and the header auth competing. This can cause CSRF errors,
// and can be confusing what authentication is being used.
//
// So remove authenticating via a cookie, and rely on the authorization
// header passed in.
httpSwagger . UIConfig ( map [ string ] string {
// Pulled from https://swagger.io/docs/open-source-tools/swagger-ui/usage/configuration/
// 'withCredentials' should disable fetch sending browser credentials, but
// for whatever reason it does not.
// So this `requestInterceptor` ensures browser credentials are
// omitted from all requests.
"requestInterceptor" : `(a => {
a.credentials = "omit";
return a;
})` ,
"withCredentials" : "false" ,
}))
2023-01-11 12:42:49 +02:00
}
2024-02-14 15:11:45 +04:00
var expDERPOnce = sync . Once {}
2022-01-13 16:55:28 -06:00
// Options are requires parameters for Coder to start.
type Options struct {
2022-04-18 17:40:25 -05:00
AccessURL * url . URL
2022-09-23 08:30:32 +10:00
// AppHostname should be the wildcard hostname to use for workspace
2022-10-15 04:25:11 +10:00
// applications INCLUDING the asterisk, (optional) suffix and leading dot.
2022-12-16 04:43:00 +10:00
// It will use the same scheme and port number as the access URL.
2024-01-18 09:44:05 -06:00
// E.g. "*.apps.coder.com" or "*-apps.coder.com" or "*.apps.coder.com:8080".
2022-09-23 08:30:32 +10:00
AppHostname string
2022-10-15 04:25:11 +10:00
// AppHostnameRegex contains the regex version of options.AppHostname as
2024-01-17 10:41:42 -06:00
// generated by appurl.CompileHostnamePattern(). It MUST be set if
2022-10-15 04:25:11 +10:00
// options.AppHostname is set.
AppHostnameRegex * regexp . Regexp
Logger slog . Logger
Database database . Store
2023-06-14 10:34:54 -05:00
Pubsub pubsub . Pubsub
2024-09-09 14:14:52 -05:00
RuntimeConfig * runtimeconfig . Manager
2022-04-18 17:40:25 -05:00
2022-06-21 19:53:36 +03:00
// CacheDir is used for caching files served by the API.
CacheDir string
2022-09-19 23:11:01 -05:00
Auditor audit . Auditor
2025-07-15 14:36:06 +10:00
ConnectionLogger connectionlog . ConnectionLogger
2022-03-22 13:17:50 -06:00
AgentConnectionUpdateFrequency time . Duration
2022-06-27 10:06:51 -05:00
AgentInactiveDisconnectTimeout time . Duration
2023-01-05 12:05:20 -06:00
AWSCertificates awsidentity . Certificates
Authorizer rbac . Authorizer
AzureCertificates x509 . VerifyOptions
GoogleTokenValidator * idtoken . Validator
GithubOAuth2Config * GithubOAuth2Config
OIDCConfig * OIDCConfig
PrometheusRegistry * prometheus . Registry
2023-02-10 10:52:49 -06:00
StrictTransportSecurityCfg httpmw . HSTSConfig
2023-01-05 12:05:20 -06:00
SSHKeygenAlgorithm gitsshkey . Algorithm
Telemetry telemetry . Reporter
TracerProvider trace . TracerProvider
2023-09-30 14:30:01 -05:00
ExternalAuthConfigs [] * externalauth . Config
2023-01-05 12:05:20 -06:00
RealIPConfig * httpmw . RealIPConfig
2024-01-16 18:19:16 -06:00
TrialGenerator func ( ctx context . Context , body codersdk . LicensorTrialRequest ) error
2024-02-23 17:48:24 +01:00
// RefreshEntitlements is used to set correct entitlements after creating first user and generating trial license.
RefreshEntitlements func ( ctx context . Context ) error
2024-08-23 16:21:58 -05:00
// Entitlements can come from the enterprise caller if enterprise code is
// included.
Entitlements * entitlements . Set
2024-03-25 20:01:42 +01:00
// PostAuthAdditionalHeadersFunc is used to add additional headers to the response
// after a successful authentication.
// This is somewhat janky, but seemingly the only reasonable way to add a header
// for all authenticated users under a condition, only in Enterprise.
2024-03-29 10:14:27 -05:00
PostAuthAdditionalHeadersFunc func ( auth rbac . Subject , header http . Header )
2024-03-25 20:01:42 +01:00
2022-10-17 08:43:30 -05:00
// TLSCertificates is used to mesh DERP servers securely.
2023-07-26 09:21:04 -07:00
TLSCertificates [] tls . Certificate
TailnetCoordinator tailnet . Coordinator
DERPServer * derp . Server
// BaseDERPMap is used as the base DERP map for all clients and agents.
// Proxies are added to this list.
2024-07-02 01:50:52 +10:00
BaseDERPMap * tailcfg . DERPMap
DERPMapUpdateFrequency time . Duration
NetworkTelemetryBatchFrequency time . Duration
NetworkTelemetryBatchMaxSize int
SwaggerEndpoint bool
TemplateScheduleStore * atomic . Pointer [ schedule . TemplateScheduleStore ]
UserQuietHoursScheduleStore * atomic . Pointer [ schedule . UserQuietHoursScheduleStore ]
AccessControlStore * atomic . Pointer [ dbauthz . AccessControlStore ]
2025-08-20 23:38:09 +10:00
UsageInserter * atomic . Pointer [ usage . Inserter ]
2024-08-20 17:16:49 +10:00
// CoordinatorResumeTokenProvider is used to provide and validate resume
// tokens issued by and passed to the coordinator DRPC API.
CoordinatorResumeTokenProvider tailnet . ResumeTokenProvider
2023-11-24 15:06:51 +00:00
2026-01-15 16:37:05 +00:00
HealthcheckFunc func ( ctx context . Context , apiKey string , progress * healthcheck . Progress ) * healthsdk . HealthcheckReport
2023-11-24 15:06:51 +00:00
HealthcheckTimeout time . Duration
HealthcheckRefresh time . Duration
WorkspaceProxiesFetchUpdater * atomic . Pointer [ healthcheck . WorkspaceProxiesFetchUpdater ]
2022-09-01 14:58:23 -05:00
2023-06-30 08:38:48 -04:00
// OAuthSigningKey is the crypto key used to sign and encrypt state strings
// related to OAuth. This is a symmetric secret key using hmac to sign payloads.
// So this secret should **never** be exposed to the client.
OAuthSigningKey [ 32 ] byte
2023-01-05 12:05:20 -06:00
// APIRateLimit is the minutely throughput rate limit per user or ip.
// Setting a rate limit <0 will disable the rate limiter across the entire
// app. Some specific routes have their own configurable rate limits.
APIRateLimit int
LoginRateLimit int
FilesRateLimit int
2022-09-01 14:58:23 -05:00
MetricsCacheRefreshInterval time . Duration
AgentStatsRefreshInterval time . Duration
2023-03-07 15:10:01 -06:00
DeploymentValues * codersdk . DeploymentValues
2023-09-29 12:04:28 -05:00
// DeploymentOptions do contain the copy of DeploymentValues, and contain
// contextual information about how the values were set.
// Do not use DeploymentOptions to retrieve values, use DeploymentValues instead.
// All secrets values are stripped.
2024-03-15 11:24:38 -05:00
DeploymentOptions serpent . OptionSet
2023-09-29 12:04:28 -05:00
UpdateCheckOptions * updatecheck . Options // Set non-nil to enable update checking.
2022-12-19 18:43:46 +01:00
2023-03-16 13:03:37 -05:00
// SSHConfig is the response clients use to configure config-ssh locally.
SSHConfig codersdk . SSHConfigResponse
2022-12-19 18:43:46 +01:00
HTTPClient * http . Client
2026-03-04 18:42:28 -05:00
// ChatSubscribeFn provides cross-replica subscription merging.
2026-02-27 11:50:56 -05:00
// Set by enterprise for HA deployments. Nil in AGPL single-replica.
2026-03-04 18:42:28 -05:00
ChatSubscribeFn chatd . SubscribeFn
2023-04-27 12:34:00 +02:00
2023-12-18 04:53:28 -08:00
UpdateAgentMetrics func ( ctx context . Context , labels prometheusmetrics . AgentMetricLabels , metrics [] * agentproto . Stats_Metric )
2024-06-25 10:58:45 -04:00
StatsBatcher workspacestats . Batcher
2023-08-16 15:22:00 +03:00
2026-01-22 22:47:49 -08:00
MetadataBatcherOptions [] metadatabatcher . Option
2025-08-28 15:00:26 +01:00
ProvisionerdServerMetrics * provisionerdserver . Metrics
2026-02-12 13:40:47 -08:00
WorkspaceBuilderMetrics * wsbuilder . Metrics
2025-08-28 15:00:26 +01:00
2025-03-18 13:50:52 +02:00
// WorkspaceAppAuditSessionTimeout allows changing the timeout for audit
// sessions. Raising or lowering this value will directly affect the write
// load of the audit log table. This is used for testing. Default 1 hour.
WorkspaceAppAuditSessionTimeout time . Duration
2023-08-16 15:22:00 +03:00
WorkspaceAppsStatsCollectorOptions workspaceapps . StatsCollectorOptions
2023-12-14 15:52:52 -06:00
// This janky function is used in telemetry to parse fields out of the raw
// JWT. It needs to be passed through like this because license parsing is
// under the enterprise license, and can't be imported into AGPL.
2023-12-15 13:38:47 -05:00
ParseLicenseClaims func ( rawJWT string ) ( email string , trial bool , err error )
AllowWorkspaceRenames bool
2024-01-12 14:27:22 -06:00
// NewTicker is used for unit tests to replace "time.NewTicker".
NewTicker func ( duration time . Duration ) ( tick <- chan time . Time , done func ())
2024-03-20 16:44:12 +00:00
2024-03-22 18:42:43 +02:00
// DatabaseRolluper rolls up template usage stats from raw agent and app
// stats. This is used to provide insights in the WebUI.
DatabaseRolluper * dbrollup . Rolluper
2024-03-20 16:44:12 +00:00
// WorkspaceUsageTracker tracks workspace usage by the CLI.
2024-06-10 15:35:23 -04:00
WorkspaceUsageTracker * workspacestats . UsageTracker
2026-01-27 19:11:40 -07:00
// BoundaryUsageTracker tracks boundary usage for telemetry.
BoundaryUsageTracker * boundaryusage . Tracker
2024-07-08 15:38:50 +02:00
// NotificationsEnqueuer handles enqueueing notifications for delivery by SMTP, webhook, etc.
NotificationsEnqueuer notifications . Enqueuer
2024-08-30 11:19:36 -05:00
// IDPSync holds all configured values for syncing external IDP users into Coder.
IDPSync idpsync . IDPSync
2024-10-04 11:53:25 +01:00
// OneTimePasscodeValidityPeriod specifies how long a one time passcode should be valid for.
OneTimePasscodeValidityPeriod time . Duration
2024-10-25 17:14:35 +01:00
// Keycaches
AppSigningKeyCache cryptokeys . SigningKeycache
AppEncryptionKeyCache cryptokeys . EncryptionKeycache
OIDCConvertKeyCache cryptokeys . SigningKeycache
Clock quartz . Clock
2025-03-27 10:03:53 +00:00
// WebPushDispatcher is a way to send notifications over Web Push.
WebPushDispatcher webpush . Dispatcher
2022-01-13 16:55:28 -06:00
}
2022-12-19 18:43:46 +01:00
// @title Coder API
// @version 2.0
// @description Coderd is the service created by running coder server. It is a thin API that connects workspaces, provisioners and users. coderd stores its state in Postgres and is the only service that communicates with Postgres.
// @termsOfService https://coder.com/legal/terms-of-service
// @contact.name API Support
// @contact.url https://coder.com
// @contact.email support@coder.com
// @license.name AGPL-3.0
// @license.url https://github.com/coder/coder/blob/main/LICENSE
// @BasePath /api/v2
2024-10-25 12:40:13 -05:00
// @securitydefinitions.apiKey Authorization
// @in header
// @name Authorizaiton
2022-12-19 18:43:46 +01:00
// @securitydefinitions.apiKey CoderSessionToken
// @in header
// @name Coder-Session-Token
2022-05-25 22:14:08 -05:00
// New constructs a Coder API handler.
func New ( options * Options ) * API {
2022-09-19 23:11:01 -05:00
if options == nil {
options = & Options {}
}
2024-08-23 16:21:58 -05:00
if options . Entitlements == nil {
options . Entitlements = entitlements . New ()
}
2024-01-12 14:27:22 -06:00
if options . NewTicker == nil {
options . NewTicker = func ( duration time . Duration ) ( tick <- chan time . Time , done func ()) {
ticker := time . NewTicker ( duration )
return ticker . C , ticker . Stop
}
}
2023-03-21 09:10:22 -05:00
2023-05-31 06:55:57 -07:00
// Safety check: if we're not running a unit test, we *must* have a Prometheus registry.
if options . PrometheusRegistry == nil && flag . Lookup ( "test.v" ) == nil {
panic ( "developer error: options.PrometheusRegistry is nil and not running a unit test" )
}
2026-03-02 19:04:55 -07:00
if options . DeploymentValues . DisableOwnerWorkspaceExec || options . DeploymentValues . DisableWorkspaceSharing {
2023-04-11 08:57:23 -05:00
rbac . ReloadBuiltinRoles ( & rbac . RoleOptions {
2026-03-02 19:04:55 -07:00
NoOwnerWorkspaceExec : bool ( options . DeploymentValues . DisableOwnerWorkspaceExec ),
NoWorkspaceSharing : bool ( options . DeploymentValues . DisableWorkspaceSharing ),
2023-04-11 08:57:23 -05:00
})
}
2025-12-09 08:13:09 -08:00
if options . DeploymentValues . DisableWorkspaceSharing {
rbac . SetWorkspaceACLDisabled ( true )
}
2025-08-20 10:00:44 +01:00
if options . PrometheusRegistry == nil {
options . PrometheusRegistry = prometheus . NewRegistry ()
2026-01-20 10:28:52 +11:00
options . PrometheusRegistry . MustRegister ( collectors . NewGoCollector ())
2025-08-20 10:00:44 +01:00
}
2023-03-21 09:10:22 -05:00
if options . Authorizer == nil {
options . Authorizer = rbac . NewCachingAuthorizer ( options . PrometheusRegistry )
2025-04-10 10:36:27 -07:00
if buildinfo . IsDev () {
options . Authorizer = rbac . Recorder ( options . Authorizer )
}
2023-03-21 09:10:22 -05:00
}
2023-10-18 17:07:21 -05:00
if options . AccessControlStore == nil {
options . AccessControlStore = & atomic . Pointer [ dbauthz . AccessControlStore ]{}
var tacs dbauthz . AccessControlStore = dbauthz . AGPLTemplateAccessControlStore {}
options . AccessControlStore . Store ( & tacs )
}
2023-03-21 09:10:22 -05:00
options . Database = dbauthz . New (
options . Database ,
options . Authorizer ,
options . Logger . Named ( "authz_querier" ),
2023-10-18 17:07:21 -05:00
options . AccessControlStore ,
2023-03-21 09:10:22 -05:00
)
2023-10-18 17:07:21 -05:00
2024-09-11 13:43:50 -05:00
if options . IDPSync == nil {
options . IDPSync = idpsync . NewAGPLSync ( options . Logger , options . RuntimeConfig , idpsync . FromDeploymentValues ( options . DeploymentValues ))
}
2023-07-19 11:11:11 -05:00
experiments := ReadExperiments (
2023-03-07 15:10:01 -06:00
options . Logger , options . DeploymentValues . Experiments . Value (),
)
2022-10-15 04:25:11 +10:00
if options . AppHostname != "" && options . AppHostnameRegex == nil || options . AppHostname == "" && options . AppHostnameRegex != nil {
panic ( "coderd: both AppHostname and AppHostnameRegex must be set or unset" )
}
2022-03-22 13:17:50 -06:00
if options . AgentConnectionUpdateFrequency == 0 {
2023-04-05 20:58:54 -05:00
options . AgentConnectionUpdateFrequency = 15 * time . Second
2022-03-22 13:17:50 -06:00
}
2022-06-27 10:06:51 -05:00
if options . AgentInactiveDisconnectTimeout == 0 {
// Multiply the update by two to allow for some lag-time.
options . AgentInactiveDisconnectTimeout = options . AgentConnectionUpdateFrequency * 2
2023-03-14 15:14:47 +02:00
// Set a minimum timeout to avoid disconnecting too soon.
if options . AgentInactiveDisconnectTimeout < 2 * time . Second {
options . AgentInactiveDisconnectTimeout = 2 * time . Second
}
2022-06-27 10:06:51 -05:00
}
2022-09-19 19:46:29 -05:00
if options . AgentStatsRefreshInterval == 0 {
2022-12-01 19:43:28 +02:00
options . AgentStatsRefreshInterval = 5 * time . Minute
2022-09-19 19:46:29 -05:00
}
if options . MetricsCacheRefreshInterval == 0 {
options . MetricsCacheRefreshInterval = time . Hour
}
2022-04-22 15:27:55 -05:00
if options . APIRateLimit == 0 {
options . APIRateLimit = 512
}
2023-01-05 12:05:20 -06:00
if options . LoginRateLimit == 0 {
options . LoginRateLimit = 60
}
if options . FilesRateLimit == 0 {
options . FilesRateLimit = 12
}
2024-10-25 17:14:35 +01:00
if options . Clock == nil {
options . Clock = quartz . NewReal ()
}
2024-03-21 16:53:41 -05:00
if options . DERPServer == nil && options . DeploymentValues . DERP . Server . Enable {
2022-10-17 08:43:30 -05:00
options . DERPServer = derp . NewServer ( key . NewNode (), tailnet . Logger ( options . Logger . Named ( "derp" )))
}
2023-07-26 09:21:04 -07:00
if options . DERPMapUpdateFrequency == 0 {
options . DERPMapUpdateFrequency = 5 * time . Second
}
2024-07-02 01:50:52 +10:00
if options . NetworkTelemetryBatchFrequency == 0 {
options . NetworkTelemetryBatchFrequency = 1 * time . Minute
}
if options . NetworkTelemetryBatchMaxSize == 0 {
options . NetworkTelemetryBatchMaxSize = 1_000
}
2023-07-26 09:21:04 -07:00
if options . TailnetCoordinator == nil {
options . TailnetCoordinator = tailnet . NewCoordinator ( options . Logger )
}
2022-09-19 23:11:01 -05:00
if options . Auditor == nil {
options . Auditor = audit . NewNop ()
2022-08-29 16:45:40 -07:00
}
2025-07-15 14:36:06 +10:00
if options . ConnectionLogger == nil {
options . ConnectionLogger = connectionlog . NewNop ()
}
2023-03-16 13:03:37 -05:00
if options . SSHConfig . HostnamePrefix == "" {
options . SSHConfig . HostnamePrefix = "coder."
}
2023-05-03 18:02:35 -05:00
if options . TracerProvider == nil {
options . TracerProvider = trace . NewNoopTracerProvider ()
}
2023-03-08 01:14:58 +11:00
if options . TemplateScheduleStore == nil {
2023-04-04 22:48:35 +10:00
options . TemplateScheduleStore = & atomic . Pointer [ schedule . TemplateScheduleStore ]{}
}
if options . TemplateScheduleStore . Load () == nil {
v := schedule . NewAGPLTemplateScheduleStore ()
options . TemplateScheduleStore . Store ( & v )
2023-03-08 01:14:58 +11:00
}
2023-07-20 06:35:41 -07:00
if options . UserQuietHoursScheduleStore == nil {
options . UserQuietHoursScheduleStore = & atomic . Pointer [ schedule . UserQuietHoursScheduleStore ]{}
}
if options . UserQuietHoursScheduleStore . Load () == nil {
v := schedule . NewAGPLUserQuietHoursScheduleStore ()
options . UserQuietHoursScheduleStore . Store ( & v )
}
2025-08-20 23:38:09 +10:00
if options . UsageInserter == nil {
options . UsageInserter = & atomic . Pointer [ usage . Inserter ]{}
}
if options . UsageInserter . Load () == nil {
inserter := usage . NewAGPLInserter ()
options . UsageInserter . Store ( & inserter )
}
2024-10-04 11:53:25 +01:00
if options . OneTimePasscodeValidityPeriod == 0 {
options . OneTimePasscodeValidityPeriod = 20 * time . Minute
}
2022-05-25 22:14:08 -05:00
2023-08-04 17:00:42 +01:00
if options . StatsBatcher == nil {
panic ( "developer error: options.StatsBatcher is nil" )
}
2022-06-21 19:53:36 +03:00
siteCacheDir := options . CacheDir
if siteCacheDir != "" {
siteCacheDir = filepath . Join ( siteCacheDir , "site" )
}
2022-09-01 14:58:23 -05:00
metricsCache := metricscache . New (
options . Database ,
options . Logger . Named ( "metrics_cache" ),
2025-09-08 12:07:38 +10:00
quartz . NewReal (),
2023-03-08 21:05:45 -06:00
metricscache . Intervals {
2024-03-27 18:10:14 +02:00
TemplateBuildTimes : options . MetricsCacheRefreshInterval ,
DeploymentStats : options . AgentStatsRefreshInterval ,
2023-03-08 21:05:45 -06:00
},
2024-09-19 11:52:14 -04:00
experiments . Enabled ( codersdk . ExperimentWorkspaceUsage ),
2022-09-01 14:58:23 -05:00
)
2023-03-08 06:38:11 +11:00
oauthConfigs := & httpmw . OAuth2Configs {
Github : options . GithubOAuth2Config ,
OIDC : options . OIDCConfig ,
}
2024-03-22 18:42:43 +02:00
if options . DatabaseRolluper == nil {
options . DatabaseRolluper = dbrollup . New ( options . Logger . Named ( "dbrollup" ), options . Database )
}
2024-03-20 16:44:12 +00:00
if options . WorkspaceUsageTracker == nil {
2024-06-10 15:35:23 -04:00
options . WorkspaceUsageTracker = workspacestats . NewTracker ( options . Database ,
workspacestats . TrackerWithLogger ( options . Logger . Named ( "workspace_usage_tracker" )),
2024-03-20 16:44:12 +00:00
)
}
2024-07-08 15:38:50 +02:00
if options . NotificationsEnqueuer == nil {
options . NotificationsEnqueuer = notifications . NewNoopEnqueuer ()
}
2023-04-17 14:57:21 -05:00
r := chi . NewRouter ()
2025-04-10 10:36:27 -07:00
// We add this middleware early, to make sure that authorization checks made
// by other middleware get recorded.
if buildinfo . IsDev () {
2025-10-21 09:15:37 -05:00
r . Use ( httpmw . RecordAuthzChecks ( options . DeploymentValues . EnableAuthzRecording . Value ()))
2025-04-10 10:36:27 -07:00
}
ctx , cancel := context . WithCancel ( context . Background ())
2023-06-30 08:38:48 -04:00
// nolint:gocritic // Load deployment ID. This never changes
depID , err := options . Database . GetDeploymentID ( dbauthz . AsSystemRestricted ( ctx ))
if err != nil {
panic ( xerrors . Errorf ( "get deployment ID: %w" , err ))
}
2024-10-25 17:14:35 +01:00
fetcher := & cryptokeys . DBFetcher {
DB : options . Database ,
}
if options . OIDCConvertKeyCache == nil {
options . OIDCConvertKeyCache , err = cryptokeys . NewSigningCache ( ctx ,
options . Logger . Named ( "oidc_convert_keycache" ),
fetcher ,
codersdk . CryptoKeyFeatureOIDCConvert ,
)
if err != nil {
2024-11-18 14:09:04 -06:00
options . Logger . Fatal ( ctx , "failed to properly instantiate oidc convert signing cache" , slog . Error ( err ))
2024-10-25 17:14:35 +01:00
}
}
if options . AppSigningKeyCache == nil {
options . AppSigningKeyCache , err = cryptokeys . NewSigningCache ( ctx ,
options . Logger . Named ( "app_signing_keycache" ),
fetcher ,
codersdk . CryptoKeyFeatureWorkspaceAppsToken ,
)
if err != nil {
2024-11-18 14:09:04 -06:00
options . Logger . Fatal ( ctx , "failed to properly instantiate app signing key cache" , slog . Error ( err ))
2024-10-25 17:14:35 +01:00
}
}
if options . AppEncryptionKeyCache == nil {
options . AppEncryptionKeyCache , err = cryptokeys . NewEncryptionCache ( ctx ,
options . Logger ,
fetcher ,
codersdk . CryptoKeyFeatureWorkspaceAppsAPIKey ,
)
if err != nil {
2024-11-18 14:09:04 -06:00
options . Logger . Fatal ( ctx , "failed to properly instantiate app encryption key cache" , slog . Error ( err ))
2024-10-25 17:14:35 +01:00
}
}
2024-11-18 14:09:04 -06:00
if options . CoordinatorResumeTokenProvider == nil {
fetcher := & cryptokeys . DBFetcher {
DB : options . Database ,
}
resumeKeycache , err := cryptokeys . NewSigningCache ( ctx ,
options . Logger ,
fetcher ,
codersdk . CryptoKeyFeatureTailnetResume ,
)
if err != nil {
options . Logger . Fatal ( ctx , "failed to properly instantiate tailnet resume signing cache" , slog . Error ( err ))
}
options . CoordinatorResumeTokenProvider = tailnet . NewResumeTokenKeyProvider (
resumeKeycache ,
options . Clock ,
tailnet . DefaultResumeTokenExpiry ,
)
}
2024-11-01 14:53:53 +11:00
updatesProvider := NewUpdatesProvider ( options . Logger . Named ( "workspace_updates" ), options . Pubsub , options . Database , options . Authorizer )
2024-10-25 17:14:35 +01:00
// Start a background process that rotates keys. We intentionally start this after the caches
// are created to force initial requests for a key to populate the caches. This helps catch
// bugs that may only occur when a key isn't precached in tests and the latency cost is minimal.
cryptokeys . StartRotator ( ctx , options . Logger , options . Database )
2026-01-12 18:19:19 -08:00
// Ensure all system role permissions are current.
//nolint:gocritic // Startup reconciliation reads/writes system roles. There is
// no user request context here, so use a system-restricted context.
err = rolestore . ReconcileSystemRoles ( dbauthz . AsSystemRestricted ( ctx ), options . Logger , options . Database )
if err != nil {
// Not ideal, but not using Fatal here and just continuing
// after logging the error would be a potential security hole.
options . Logger . Fatal ( ctx , "failed to reconcile system role permissions" , slog . Error ( err ))
}
2025-07-22 13:39:26 +10:00
// AGPL uses a no-op build usage checker as there are no license
// entitlements to enforce. This is swapped out in
// enterprise/coderd/coderd.go.
var buildUsageChecker atomic . Pointer [ wsbuilder . UsageChecker ]
var noopUsageChecker wsbuilder . UsageChecker = wsbuilder . NoopUsageChecker {}
buildUsageChecker . Store ( & noopUsageChecker )
2022-05-25 22:14:08 -05:00
api := & API {
2023-06-30 08:38:48 -04:00
ctx : ctx ,
cancel : cancel ,
DeploymentID : depID ,
2023-02-10 20:23:02 +02:00
2022-11-06 13:27:09 -08:00
ID : uuid . New (),
2022-06-04 15:13:37 -05:00
Options : options ,
2022-09-19 23:11:01 -05:00
RootHandler : r ,
HTTPAuth : & HTTPAuthorizer {
2022-08-22 15:02:50 -07:00
Authorizer : options . Authorizer ,
Logger : options . Logger ,
},
2023-07-20 06:35:41 -07:00
metricsCache : metricsCache ,
Auditor : atomic . Pointer [ audit . Auditor ]{},
2025-07-15 14:36:06 +10:00
ConnectionLogger : atomic . Pointer [ connectionlog . ConnectionLogger ]{},
2023-12-18 04:53:28 -08:00
TailnetCoordinator : atomic . Pointer [ tailnet . Coordinator ]{},
2024-11-01 14:53:53 +11:00
UpdatesProvider : updatesProvider ,
2023-07-20 06:35:41 -07:00
TemplateScheduleStore : options . TemplateScheduleStore ,
UserQuietHoursScheduleStore : options . UserQuietHoursScheduleStore ,
2023-10-18 17:07:21 -05:00
AccessControlStore : options . AccessControlStore ,
2025-07-22 13:39:26 +10:00
BuildUsageChecker : & buildUsageChecker ,
2025-08-20 23:38:09 +10:00
UsageInserter : options . UsageInserter ,
2025-06-23 11:58:52 -05:00
FileCache : files . New ( options . PrometheusRegistry , options . Authorizer ),
2023-07-20 06:35:41 -07:00
Experiments : experiments ,
2025-03-27 10:03:53 +00:00
WebpushDispatcher : options . WebPushDispatcher ,
2024-03-26 12:44:31 -05:00
healthCheckGroup : & singleflight . Group [ string , * healthsdk . HealthcheckReport ]{},
2023-09-19 10:25:57 +04:00
Acquirer : provisionerdserver . NewAcquirer (
ctx ,
options . Logger . Named ( "acquirer" ),
options . Database ,
2024-03-22 18:42:43 +02:00
options . Pubsub ,
),
2026-03-13 15:09:39 +01:00
dbRolluper : options . DatabaseRolluper ,
ProfileCollector : defaultProfileCollector {},
2026-03-16 15:30:25 -05:00
AISeatTracker : aiseats . Noop {},
2022-05-25 22:14:08 -05:00
}
2026-03-16 12:36:26 -05:00
2025-03-18 13:50:52 +02:00
api . WorkspaceAppsProvider = workspaceapps . NewDBTokenProvider (
2025-11-20 13:01:50 +04:00
ctx ,
2025-03-18 13:50:52 +02:00
options . Logger . Named ( "workspaceapps" ),
options . AccessURL ,
options . Authorizer ,
2025-07-15 14:36:06 +10:00
& api . ConnectionLogger ,
2025-03-18 13:50:52 +02:00
options . Database ,
options . DeploymentValues ,
oauthConfigs ,
options . AgentInactiveDisconnectTimeout ,
options . WorkspaceAppAuditSessionTimeout ,
options . AppSigningKeyCache ,
)
2024-01-29 12:17:31 +04:00
2024-08-12 16:01:22 -05:00
f := appearance . NewDefaultFetcher ( api . DeploymentValues . DocsURL . String ())
api . AppearanceFetcher . Store ( & f )
2024-02-13 09:31:20 -05:00
api . PortSharer . Store ( & portsharing . DefaultPortSharer )
2025-04-24 09:39:38 -04:00
api . PrebuildsClaimer . Store ( & prebuilds . DefaultClaimer )
2025-04-25 11:07:15 +02:00
api . PrebuildsReconciler . Store ( & prebuilds . DefaultReconciler )
2024-04-29 20:50:49 -04:00
buildInfo := codersdk . BuildInfoResponse {
2024-08-27 13:40:51 -06:00
ExternalURL : buildinfo . ExternalURL (),
Version : buildinfo . Version (),
AgentAPIVersion : AgentAPIVersionREST ,
ProvisionerAPIVersion : proto . CurrentVersion . String (),
DashboardURL : api . AccessURL . String (),
WorkspaceProxy : false ,
UpgradeMessage : api . DeploymentValues . CLIUpgradeMessage . String (),
DeploymentID : api . DeploymentID ,
2025-03-27 10:03:53 +00:00
WebPushPublicKey : api . WebpushDispatcher . PublicKey (),
2024-08-27 13:40:51 -06:00
Telemetry : api . Telemetry . Enabled (),
2024-04-29 20:50:49 -04:00
}
2026-02-06 10:56:48 +04:00
api . SiteHandler , err = site . New ( & site . Options {
CacheDir : siteCacheDir ,
2024-01-29 12:17:31 +04:00
Database : options . Database ,
2026-03-09 09:12:04 -07:00
Authorizer : options . Authorizer ,
2024-01-29 12:17:31 +04:00
SiteFS : site . FS (),
OAuth2Configs : oauthConfigs ,
DocsURL : options . DeploymentValues . DocsURL . String (),
AppearanceFetcher : & api . AppearanceFetcher ,
2024-04-29 20:50:49 -04:00
BuildInfo : buildInfo ,
2024-08-23 16:21:58 -05:00
Entitlements : options . Entitlements ,
2025-01-31 13:55:46 +01:00
Telemetry : options . Telemetry ,
Logger : options . Logger . Named ( "site" ),
2025-06-18 18:32:34 +02:00
HideAITasks : options . DeploymentValues . HideAITasks . Value (),
2024-01-29 12:17:31 +04:00
})
2026-02-06 10:56:48 +04:00
if err != nil {
options . Logger . Fatal ( ctx , "failed to initialize site handler" , slog . Error ( err ))
}
2024-01-29 12:17:31 +04:00
api . SiteHandler . Experiments . Store ( & experiments )
2022-12-01 19:43:28 +02:00
if options . UpdateCheckOptions != nil {
api . updateChecker = updatecheck . New (
options . Database ,
options . Logger . Named ( "update_checker" ),
* options . UpdateCheckOptions ,
)
}
2023-11-24 15:06:51 +00:00
if options . WorkspaceProxiesFetchUpdater == nil {
options . WorkspaceProxiesFetchUpdater = & atomic . Pointer [ healthcheck . WorkspaceProxiesFetchUpdater ]{}
var wpfu healthcheck . WorkspaceProxiesFetchUpdater = & healthcheck . AGPLWorkspaceProxiesFetchUpdater {}
options . WorkspaceProxiesFetchUpdater . Store ( & wpfu )
}
2023-07-26 09:21:04 -07:00
if options . HealthcheckFunc == nil {
2026-01-15 16:37:05 +00:00
options . HealthcheckFunc = func ( ctx context . Context , apiKey string , progress * healthcheck . Progress ) * healthsdk . HealthcheckReport {
2023-12-06 08:38:03 +00:00
// NOTE: dismissed healthchecks are marked in formatHealthcheck.
// Not here, as this result gets cached.
2023-07-26 09:21:04 -07:00
return healthcheck . Run ( ctx , & healthcheck . ReportOptions {
2023-11-13 14:14:43 +00:00
Database : healthcheck . DatabaseReportOptions {
DB : options . Database ,
Threshold : options . DeploymentValues . Healthcheck . ThresholdDatabase . Value (),
},
Websocket : healthcheck . WebsocketReportOptions {
AccessURL : options . AccessURL ,
APIKey : apiKey ,
},
AccessURL : healthcheck . AccessURLReportOptions {
AccessURL : options . AccessURL ,
},
DerpHealth : derphealth . ReportOptions {
2023-12-06 08:38:03 +00:00
DERPMap : api . DERPMap (),
2023-11-13 14:14:43 +00:00
},
2023-11-24 15:06:51 +00:00
WorkspaceProxy : healthcheck . WorkspaceProxyReportOptions {
WorkspaceProxiesFetchUpdater : * ( options . WorkspaceProxiesFetchUpdater ). Load (),
},
2024-01-08 09:29:04 +00:00
ProvisionerDaemons : healthcheck . ProvisionerDaemonsReportDeps {
CurrentVersion : buildinfo . Version (),
2024-02-20 12:44:19 +00:00
CurrentAPIMajorVersion : proto . CurrentMajor ,
2024-01-08 09:29:04 +00:00
Store : options . Database ,
2024-11-28 12:57:43 +00:00
StaleInterval : provisionerdserver . StaleInterval ,
// TimeNow set to default, see healthcheck/provisioner.go
2024-01-08 09:29:04 +00:00
},
2026-01-15 16:37:05 +00:00
Progress : progress ,
2023-07-26 09:21:04 -07:00
})
}
}
2023-11-24 15:06:51 +00:00
2023-07-26 09:21:04 -07:00
if options . HealthcheckTimeout == 0 {
options . HealthcheckTimeout = 30 * time . Second
}
if options . HealthcheckRefresh == 0 {
2023-11-13 14:14:43 +00:00
options . HealthcheckRefresh = options . DeploymentValues . Healthcheck . Refresh . Value ()
2023-07-26 09:21:04 -07:00
}
2023-03-30 09:36:57 +01:00
var oidcAuthURLParams map [ string ] string
if options . OIDCConfig != nil {
oidcAuthURLParams = options . OIDCConfig . AuthURLParams
}
2022-09-19 23:11:01 -05:00
api . Auditor . Store ( & options . Auditor )
2025-07-15 14:36:06 +10:00
api . ConnectionLogger . Store ( & options . ConnectionLogger )
2022-10-17 08:43:30 -05:00
api . TailnetCoordinator . Store ( & options . TailnetCoordinator )
2024-11-08 13:18:56 +04:00
dialer := & InmemTailnetDialer {
2025-04-15 10:55:30 +02:00
CoordPtr : & api . TailnetCoordinator ,
DERPFn : api . DERPMap ,
Logger : options . Logger ,
ClientID : uuid . New (),
DatabaseHealthCheck : api . Database ,
2024-11-08 13:18:56 +04:00
}
2024-02-05 23:57:18 -06:00
stn , err := NewServerTailnet ( api . ctx ,
2024-01-04 09:27:36 +04:00
options . Logger ,
options . DERPServer ,
2024-11-08 13:18:56 +04:00
dialer ,
2024-01-04 09:27:36 +04:00
options . DeploymentValues . DERP . Config . ForceWebSockets . Value (),
2024-03-07 23:29:54 -06:00
options . DeploymentValues . DERP . Config . BlockDirect . Value (),
2024-01-04 09:27:36 +04:00
api . TracerProvider ,
)
if err != nil {
panic ( "failed to setup server tailnet: " + err . Error ())
2023-07-12 17:37:31 -05:00
}
2024-02-05 23:57:18 -06:00
api . agentProvider = stn
2026-02-27 11:50:56 -05:00
2026-03-19 00:54:32 +11:00
maxChatsPerAcquire := options . DeploymentValues . AI . Chat . AcquireBatchSize . Value ()
if maxChatsPerAcquire > math . MaxInt32 {
maxChatsPerAcquire = math . MaxInt32
}
if maxChatsPerAcquire < math . MinInt32 {
maxChatsPerAcquire = math . MinInt32
}
2026-02-27 11:50:56 -05:00
api . chatDaemon = chatd . New ( chatd . Config {
2026-03-18 17:48:47 +00:00
Logger : options . Logger . Named ( "chatd" ),
2026-03-19 00:54:32 +11:00
Database : options . Database ,
ReplicaID : api . ID ,
SubscribeFn : options . ChatSubscribeFn ,
MaxChatsPerAcquire : int32 ( maxChatsPerAcquire ), //nolint:gosec // maxChatsPerAcquire is clamped to int32 range above.
ProviderAPIKeys : chatProviderAPIKeysFromDeploymentValues ( options . DeploymentValues ),
AgentConn : api . agentProvider . AgentConn ,
CreateWorkspace : api . chatCreateWorkspace ,
StartWorkspace : api . chatStartWorkspace ,
Pubsub : options . Pubsub ,
WebpushDispatcher : options . WebPushDispatcher ,
2026-03-18 19:07:21 +00:00
UsageTracker : options . WorkspaceUsageTracker ,
2026-02-27 11:50:56 -05:00
})
2026-03-10 18:46:01 +00:00
gitSyncLogger := options . Logger . Named ( "gitsync" )
refresher := gitsync . NewRefresher (
api . resolveGitProvider ,
api . resolveChatGitAccessToken ,
gitSyncLogger . Named ( "refresher" ),
quartz . NewReal (),
)
api . gitSyncWorker = gitsync . NewWorker ( options . Database ,
refresher ,
api . chatDaemon . PublishDiffStatusChange ,
quartz . NewReal (),
gitSyncLogger ,
)
// nolint:gocritic // chat diff worker needs to be able to CRUD chats.
go api . gitSyncWorker . Start ( dbauthz . AsChatd ( api . ctx ))
2024-02-05 23:57:18 -06:00
if options . DeploymentValues . Prometheus . Enable {
options . PrometheusRegistry . MustRegister ( stn )
2026-02-06 16:26:02 -06:00
api . lifecycleMetrics = agentapi . NewLifecycleMetrics ( options . PrometheusRegistry )
2024-02-05 23:57:18 -06:00
}
2024-07-02 01:50:52 +10:00
api . NetworkTelemetryBatcher = tailnet . NewNetworkTelemetryBatcher (
2024-07-03 15:02:54 +04:00
quartz . NewReal (),
2024-07-02 01:50:52 +10:00
api . Options . NetworkTelemetryBatchFrequency ,
api . Options . NetworkTelemetryBatchMaxSize ,
api . handleNetworkTelemetry ,
2024-01-02 08:07:57 +04:00
)
2024-08-20 17:16:49 +10:00
if options . CoordinatorResumeTokenProvider == nil {
panic ( "CoordinatorResumeTokenProvider is nil" )
}
2024-07-02 01:50:52 +10:00
api . TailnetClientService , err = tailnet . NewClientService ( tailnet . ClientServiceOptions {
2024-11-01 14:53:53 +11:00
Logger : api . Logger . Named ( "tailnetclient" ),
CoordPtr : & api . TailnetCoordinator ,
DERPMapUpdateFrequency : api . Options . DERPMapUpdateFrequency ,
DERPMapFn : api . DERPMap ,
NetworkTelemetryHandler : api . NetworkTelemetryBatcher . Handler ,
ResumeTokenProvider : api . Options . CoordinatorResumeTokenProvider ,
WorkspaceUpdatesProvider : api . UpdatesProvider ,
2024-07-02 01:50:52 +10:00
})
2023-12-15 14:10:24 +04:00
if err != nil {
2024-10-25 17:14:35 +01:00
api . Logger . Fatal ( context . Background (), "failed to initialize tailnet client service" , slog . Error ( err ))
2023-12-15 14:10:24 +04:00
}
2022-09-23 08:30:32 +10:00
2024-05-29 11:49:08 -04:00
api . statsReporter = workspacestats . NewReporter ( workspacestats . ReporterOptions {
2025-12-13 18:00:03 -09:00
Database : options . Database ,
Logger : options . Logger . Named ( "workspacestats" ),
Pubsub : options . Pubsub ,
TemplateScheduleStore : options . TemplateScheduleStore ,
StatsBatcher : options . StatsBatcher ,
UsageTracker : options . WorkspaceUsageTracker ,
UpdateAgentMetricsFn : options . UpdateAgentMetrics ,
AppStatBatchSize : workspaceapps . DefaultStatsDBReporterBatchSize ,
2026-01-05 11:44:06 -09:00
DisableDatabaseInserts : ! options . DeploymentValues . StatsCollection . UsageStats . Enable . Value (),
2024-05-29 11:49:08 -04:00
})
2026-01-22 22:47:49 -08:00
// Initialize the metadata batcher for batching agent metadata updates.
batcherOpts := [] metadatabatcher . Option {
metadatabatcher . WithLogger ( options . Logger . Named ( "metadata_batcher" )),
}
batcherOpts = append ( batcherOpts , options . MetadataBatcherOptions ... )
api . metadataBatcher , err = metadatabatcher . NewBatcher (
api . ctx ,
options . PrometheusRegistry ,
options . Database ,
options . Pubsub ,
batcherOpts ... ,
)
if err != nil {
api . Logger . Fatal ( context . Background (), "failed to initialize metadata batcher" , slog . Error ( err ))
}
2023-08-16 15:22:00 +03:00
workspaceAppsLogger := options . Logger . Named ( "workspaceapps" )
if options . WorkspaceAppsStatsCollectorOptions . Logger == nil {
named := workspaceAppsLogger . Named ( "stats_collector" )
options . WorkspaceAppsStatsCollectorOptions . Logger = & named
}
if options . WorkspaceAppsStatsCollectorOptions . Reporter == nil {
2024-05-29 11:49:08 -04:00
options . WorkspaceAppsStatsCollectorOptions . Reporter = api . statsReporter
2023-08-16 15:22:00 +03:00
}
2025-09-25 00:30:02 +10:00
api . workspaceAppServer = workspaceapps . NewServer ( workspaceapps . ServerOptions {
2023-08-16 15:22:00 +03:00
Logger : workspaceAppsLogger ,
2023-04-06 04:41:55 +10:00
2023-04-17 14:57:21 -05:00
DashboardURL : api . AccessURL ,
AccessURL : api . AccessURL ,
Hostname : api . AppHostname ,
HostnameRegex : api . AppHostnameRegex ,
RealIPConfig : options . RealIPConfig ,
2023-04-06 04:41:55 +10:00
SignedTokenProvider : api . WorkspaceAppsProvider ,
2023-07-12 17:37:31 -05:00
AgentProvider : api . agentProvider ,
2023-08-16 15:22:00 +03:00
StatsCollector : workspaceapps . NewStatsCollector ( options . WorkspaceAppsStatsCollectorOptions ),
2023-04-17 14:57:21 -05:00
2024-10-25 17:14:35 +01:00
DisablePathApps : options . DeploymentValues . DisablePathApps . Value (),
2025-09-25 00:30:02 +10:00
CookiesConfig : options . DeploymentValues . HTTPCookies ,
2024-10-25 17:14:35 +01:00
APIKeyEncryptionKeycache : options . AppEncryptionKeyCache ,
2025-09-25 00:30:02 +10:00
})
2023-04-06 04:41:55 +10:00
2023-03-08 06:38:11 +11:00
apiKeyMiddleware := httpmw . ExtractAPIKeyMW ( httpmw . ExtractAPIKeyConfig {
2024-03-25 20:01:42 +01:00
DB : options . Database ,
2024-10-31 17:55:42 -05:00
ActivateDormantUser : ActivateDormantUser ( options . Logger , & api . Auditor , options . Database ),
2024-03-25 20:01:42 +01:00
OAuth2Configs : oauthConfigs ,
RedirectToLogin : false ,
2024-04-10 10:34:49 -05:00
DisableSessionExpiryRefresh : options . DeploymentValues . Sessions . DisableExpiryRefresh . Value (),
2024-03-25 20:01:42 +01:00
Optional : false ,
SessionTokenFunc : nil , // Default behavior
PostAuthAdditionalHeadersFunc : options . PostAuthAdditionalHeadersFunc ,
2025-07-02 17:49:00 +02:00
Logger : options . Logger ,
2025-07-19 22:05:15 +02:00
AccessURL : options . AccessURL ,
2022-09-23 08:30:32 +10:00
})
// Same as above but it redirects to the login page.
2023-03-08 06:38:11 +11:00
apiKeyMiddlewareRedirect := httpmw . ExtractAPIKeyMW ( httpmw . ExtractAPIKeyConfig {
2024-03-25 20:01:42 +01:00
DB : options . Database ,
OAuth2Configs : oauthConfigs ,
RedirectToLogin : true ,
2024-04-10 10:34:49 -05:00
DisableSessionExpiryRefresh : options . DeploymentValues . Sessions . DisableExpiryRefresh . Value (),
2024-03-25 20:01:42 +01:00
Optional : false ,
SessionTokenFunc : nil , // Default behavior
PostAuthAdditionalHeadersFunc : options . PostAuthAdditionalHeadersFunc ,
2025-07-02 17:49:00 +02:00
Logger : options . Logger ,
2025-07-19 22:05:15 +02:00
AccessURL : options . AccessURL ,
2022-09-23 08:30:32 +10:00
})
2023-04-17 14:57:21 -05:00
// Same as the first but it's optional.
apiKeyMiddlewareOptional := httpmw . ExtractAPIKeyMW ( httpmw . ExtractAPIKeyConfig {
2024-03-25 20:01:42 +01:00
DB : options . Database ,
OAuth2Configs : oauthConfigs ,
RedirectToLogin : false ,
2024-04-10 10:34:49 -05:00
DisableSessionExpiryRefresh : options . DeploymentValues . Sessions . DisableExpiryRefresh . Value (),
2024-03-25 20:01:42 +01:00
Optional : true ,
SessionTokenFunc : nil , // Default behavior
PostAuthAdditionalHeadersFunc : options . PostAuthAdditionalHeadersFunc ,
2025-07-02 17:49:00 +02:00
Logger : options . Logger ,
2025-07-19 22:05:15 +02:00
AccessURL : options . AccessURL ,
2023-04-17 14:57:21 -05:00
})
2022-05-03 16:10:19 -05:00
2025-05-15 15:32:52 +01:00
workspaceAgentInfo := httpmw . ExtractWorkspaceAgentAndLatestBuild ( httpmw . ExtractWorkspaceAgentAndLatestBuildConfig {
DB : options . Database ,
Optional : false ,
})
2023-01-05 12:05:20 -06:00
// API rate limit middleware. The counter is local and not shared between
// replicas or instances of this middleware.
apiRateLimiter := httpmw . RateLimit ( options . APIRateLimit , time . Minute )
2024-02-14 15:11:45 +04:00
// Register DERP on expvar HTTP handler, which we serve below in the router, c.f. expvar.Handler()
expDERPOnce . Do ( func () {
// We need to do this via a global Once because expvar registry is global and panics if we
// register multiple times. In production there is only one Coderd and one DERP server per
// process, but in testing, we create multiple of both, so the Once protects us from
// panicking.
2026-03-06 01:57:58 -06:00
if options . DERPServer != nil && expvar . Get ( "derp" ) == nil {
2024-03-21 16:53:41 -05:00
expvar . Publish ( "derp" , api . DERPServer . ExpVar ())
}
2024-02-14 15:11:45 +04:00
})
2026-03-06 01:57:58 -06:00
if options . PrometheusRegistry != nil && options . DERPServer != nil {
options . PrometheusRegistry . MustRegister ( derpmetrics . NewDERPExpvarCollector ( options . DERPServer ))
}
2023-05-22 20:02:39 +02:00
cors := httpmw . Cors ( options . DeploymentValues . Dangerous . AllowAllCors . Value ())
2023-06-06 10:26:13 -05:00
prometheusMW := httpmw . Prometheus ( options . PrometheusRegistry )
2023-03-01 16:18:14 -06:00
2022-05-03 07:48:02 -05:00
r . Use (
2025-11-25 14:59:20 -09:00
sharedhttpmw . Recover ( api . Logger ),
2025-08-07 11:21:17 -05:00
httpmw . WithProfilingLabels ,
2022-11-28 13:22:10 -08:00
tracing . StatusWriterMiddleware ,
2026-02-20 09:01:00 -06:00
options . DeploymentValues . HTTPCookies . Middleware ,
2022-11-28 13:22:10 -08:00
tracing . Middleware ( api . TracerProvider ),
httpmw . AttachRequestID ,
2022-10-23 13:21:49 -05:00
httpmw . ExtractRealIP ( api . RealIPConfig ),
2025-04-15 13:27:23 +02:00
loggermw . Logger ( api . Logger ),
2025-02-12 09:23:28 +01:00
singleSlashMW ,
2024-05-16 13:47:47 -05:00
rolestore . CustomRoleMW ,
2026-03-09 13:54:31 +01:00
// Validate API key on every request (if present) and store
// the result in context. The rate limiter reads this to key
// by user ID, and downstream ExtractAPIKeyMW reuses it to
// avoid redundant DB lookups. Never rejects requests.
httpmw . PrecheckAPIKey ( httpmw . ValidateAPIKeyConfig {
DB : options . Database ,
OAuth2Configs : oauthConfigs ,
DisableSessionExpiryRefresh : options . DeploymentValues . Sessions . DisableExpiryRefresh . Value (),
Logger : options . Logger ,
}),
2026-01-15 10:26:50 +00:00
httpmw . HTTPRoute , // NB: prometheusMW depends on this middleware.
2023-06-06 10:26:13 -05:00
prometheusMW ,
2022-09-01 14:58:23 -05:00
// Build-Version is helpful for debugging.
func ( next http . Handler ) http . Handler {
return http . HandlerFunc ( func ( w http . ResponseWriter , r * http . Request ) {
2024-01-03 09:01:57 +00:00
w . Header (). Add ( codersdk . BuildVersionHeader , buildinfo . Version ())
2022-09-01 14:58:23 -05:00
next . ServeHTTP ( w , r )
})
},
2023-12-13 11:45:27 -06:00
// SubdomainAppMW checks if the first subdomain is a valid app URL. If
// it is, it will serve that application.
//
// Workspace apps do their own auth and CORS and must be BEFORE the auth
// and CORS middleware.
api . workspaceAppServer . HandleSubdomain ( apiRateLimiter ),
cors ,
2023-02-25 11:18:45 -06:00
// This header stops a browser from trying to MIME-sniff the content type and
// forces it to stick with the declared content-type. This is the only valid
// value for this header.
// See: https://github.com/coder/security/issues/12
func ( next http . Handler ) http . Handler {
return http . HandlerFunc ( func ( w http . ResponseWriter , r * http . Request ) {
w . Header (). Add ( "X-Content-Type-Options" , "nosniff" )
next . ServeHTTP ( w , r )
})
},
2025-05-30 09:30:49 -05:00
httpmw . CSRF ( options . DeploymentValues . HTTPCookies ),
2022-05-03 07:48:02 -05:00
)
2024-03-28 15:49:43 -05:00
// This incurs a performance hit from the middleware, but is required to make sure
// we do not override subdomain app routes.
r . Get ( "/latency-check" , tracing . StatusWriterMiddleware ( prometheusMW ( LatencyCheck ())). ServeHTTP )
2025-03-26 01:56:39 -05:00
r . Get ( "/healthz" , func ( w http . ResponseWriter , _ * http . Request ) { _ , _ = w . Write ([] byte ( "OK" )) })
2022-11-07 13:35:52 -06:00
2023-04-06 04:41:55 +10:00
// Attach workspace apps routes.
r . Group ( func ( r chi . Router ) {
2023-03-08 06:38:11 +11:00
r . Use ( apiRateLimiter )
2023-04-06 04:41:55 +10:00
api . workspaceAppServer . Attach ( r )
})
2024-03-21 16:53:41 -05:00
if options . DERPServer != nil {
derpHandler := derphttp . Handler ( api . DERPServer )
derpHandler , api . derpCloseFunc = tailnet . WithWebsocketSupport ( api . DERPServer , derpHandler )
r . Route ( "/derp" , func ( r chi . Router ) {
r . Get ( "/" , derpHandler . ServeHTTP )
// This is used when UDP is blocked, and latency must be checked via HTTP(s).
2025-03-26 01:56:39 -05:00
r . Get ( "/latency-check" , func ( w http . ResponseWriter , _ * http . Request ) {
2024-03-21 16:53:41 -05:00
w . WriteHeader ( http . StatusOK )
})
2022-09-01 11:41:47 -05:00
})
2024-03-21 16:53:41 -05:00
}
2022-06-04 15:13:37 -05:00
2023-06-29 13:58:01 -05:00
// Register callback handlers for each OAuth2 provider.
2023-09-30 14:30:01 -05:00
// We must support gitauth and externalauth for backwards compatibility.
2023-10-03 09:04:39 -05:00
for _ , route := range [] string { "gitauth" , "external-auth" } {
2023-09-30 14:30:01 -05:00
r . Route ( "/" + route , func ( r chi . Router ) {
for _ , externalAuthConfig := range options . ExternalAuthConfigs {
// We don't need to register a callback handler for device auth.
if externalAuthConfig . DeviceAuth != nil {
continue
}
r . Route ( fmt . Sprintf ( "/%s/callback" , externalAuthConfig . ID ), func ( r chi . Router ) {
r . Use (
apiKeyMiddlewareRedirect ,
2025-12-15 11:41:47 -06:00
httpmw . ExtractOAuth2 ( externalAuthConfig , options . HTTPClient , options . DeploymentValues . HTTPCookies , nil , externalAuthConfig . CodeChallengeMethodsSupported ),
2023-09-30 14:30:01 -05:00
)
r . Get ( "/" , api . externalAuthCallback ( externalAuthConfig ))
})
2023-06-29 13:58:01 -05:00
}
2023-09-30 14:30:01 -05:00
})
}
2023-06-29 13:58:01 -05:00
2025-07-01 15:39:29 +02:00
// OAuth2 metadata endpoint for RFC 8414 discovery
2025-09-08 14:21:57 +02:00
r . Route ( "/.well-known/oauth-authorization-server" , func ( r chi . Router ) {
2026-03-19 11:42:04 +00:00
r . Use ( httpmw . RequireExperimentWithDevBypass ( api . Experiments , codersdk . ExperimentOAuth2 ))
2025-09-08 14:21:57 +02:00
r . Get ( "/*" , api . oauth2AuthorizationServerMetadata ())
})
2025-07-02 18:58:41 +02:00
// OAuth2 protected resource metadata endpoint for RFC 9728 discovery
2025-09-08 14:21:57 +02:00
r . Route ( "/.well-known/oauth-protected-resource" , func ( r chi . Router ) {
2026-03-19 11:42:04 +00:00
r . Use ( httpmw . RequireExperimentWithDevBypass ( api . Experiments , codersdk . ExperimentOAuth2 ))
2025-09-08 14:21:57 +02:00
r . Get ( "/*" , api . oauth2ProtectedResourceMetadata ())
})
2025-07-01 15:39:29 +02:00
2024-03-25 11:52:22 -08:00
// OAuth2 linking routes do not make sense under the /api/v2 path. These are
// for an external application to use Coder as an OAuth2 provider, not for
// logging into Coder with an external OAuth2 provider.
r . Route ( "/oauth2" , func ( r chi . Router ) {
r . Use (
2025-07-03 20:09:18 +02:00
httpmw . RequireExperimentWithDevBypass ( api . Experiments , codersdk . ExperimentOAuth2 ),
2024-03-25 11:52:22 -08:00
)
r . Route ( "/authorize" , func ( r chi . Router ) {
2025-07-01 15:39:29 +02:00
r . Use (
// Fetch the app as system for the authorize endpoint
httpmw . AsAuthzSystem ( httpmw . ExtractOAuth2ProviderAppWithOAuth2Errors ( options . Database )),
apiKeyMiddlewareRedirect ,
)
// GET shows the consent page, POST processes the consent
2024-03-25 11:52:22 -08:00
r . Get ( "/" , api . getOAuth2ProviderAppAuthorize ())
2025-07-01 15:39:29 +02:00
r . Post ( "/" , api . postOAuth2ProviderAppAuthorize ())
2024-03-25 11:52:22 -08:00
})
r . Route ( "/tokens" , func ( r chi . Router ) {
2025-07-01 15:39:29 +02:00
r . Use (
// Use OAuth2-compliant error responses for the tokens endpoint
httpmw . AsAuthzSystem ( httpmw . ExtractOAuth2ProviderAppWithOAuth2Errors ( options . Database )),
)
2024-03-25 11:52:22 -08:00
r . Group ( func ( r chi . Router ) {
r . Use ( apiKeyMiddleware )
// DELETE on /tokens is not part of the OAuth2 spec. It is our own
// route used to revoke permissions from an application. It is here for
// parity with POST on /tokens.
r . Delete ( "/" , api . deleteOAuth2ProviderAppTokens ())
})
// The POST /tokens endpoint will be called from an unauthorized client so
// we cannot require an API key.
r . Post ( "/" , api . postOAuth2ProviderAppToken ())
})
2025-07-03 18:33:47 +02:00
2025-10-22 15:18:42 -05:00
// RFC 7009 Token Revocation Endpoint
r . Route ( "/revoke" , func ( r chi . Router ) {
r . Use (
// RFC 7009 endpoint uses OAuth2 client authentication, not API key
httpmw . AsAuthzSystem ( httpmw . ExtractOAuth2ProviderAppWithOAuth2Errors ( options . Database )),
)
// POST /revoke is the standard OAuth2 token revocation endpoint per RFC 7009
r . Post ( "/" , api . revokeOAuth2Token ())
})
2025-07-03 18:33:47 +02:00
// RFC 7591 Dynamic Client Registration - Public endpoint
2025-07-03 20:24:45 +02:00
r . Post ( "/register" , api . postOAuth2ClientRegistration ())
2025-07-03 18:33:47 +02:00
// RFC 7592 Client Configuration Management - Protected by registration access token
r . Route ( "/clients/{client_id}" , func ( r chi . Router ) {
r . Use (
// Middleware to validate registration access token
2025-07-03 20:24:45 +02:00
oauth2provider . RequireRegistrationAccessToken ( api . Database ),
2025-07-03 18:33:47 +02:00
)
2025-07-03 20:24:45 +02:00
r . Get ( "/" , api . oauth2ClientConfiguration ()) // Read client configuration
r . Put ( "/" , api . putOAuth2ClientConfiguration ()) // Update client configuration
r . Delete ( "/" , api . deleteOAuth2ClientConfiguration ()) // Delete client
2025-07-03 18:33:47 +02:00
})
2024-03-25 11:52:22 -08:00
})
2025-06-24 13:06:02 +02:00
// Experimental routes are not guaranteed to be stable and may change at any time.
r . Route ( "/api/experimental" , func ( r chi . Router ) {
2025-09-26 16:20:33 +02:00
api . ExperimentalHandler = r
2025-09-25 16:37:28 +02:00
r . NotFound ( func ( rw http . ResponseWriter , _ * http . Request ) { httpapi . RouteNotFound ( rw ) })
2025-09-26 16:20:33 +02:00
r . Use (
apiRateLimiter ,
httpmw . ReportCLITelemetry ( api . Logger , options . Telemetry ),
)
2025-10-29 20:59:12 +02:00
2025-11-25 15:24:25 +00:00
// NOTE(DanielleMaywood):
// Tasks have been promoted to stable, but we have guaranteed a single release transition period
// where these routes must remain. These should be removed no earlier than Coder v2.30.0
2025-09-26 16:20:33 +02:00
r . Route ( "/tasks" , func ( r chi . Router ) {
2025-09-25 15:40:25 +02:00
r . Use ( apiKeyMiddleware )
2025-08-12 11:23:55 +01:00
2025-09-26 16:20:33 +02:00
r . Get ( "/" , api . tasksList )
2025-08-25 16:03:32 +03:00
2025-09-26 16:20:33 +02:00
r . Route ( "/{user}" , func ( r chi . Router ) {
r . Use ( httpmw . ExtractOrganizationMembersParam ( options . Database , api . HTTPAuth . Authorize ))
r . Post ( "/" , api . tasksCreate )
2025-10-23 19:45:18 +03:00
r . Route ( "/{task}" , func ( r chi . Router ) {
r . Use ( httpmw . ExtractTaskParam ( options . Database ))
r . Get ( "/" , api . taskGet )
r . Delete ( "/" , api . taskDelete )
2025-11-25 11:13:32 +00:00
r . Patch ( "/input" , api . taskUpdateInput )
2025-10-23 19:45:18 +03:00
r . Post ( "/send" , api . taskSend )
r . Get ( "/logs" , api . taskLogs )
2026-02-09 08:56:41 +02:00
r . Post ( "/pause" , api . pauseTask )
2026-02-12 09:59:53 +02:00
r . Post ( "/resume" , api . resumeTask )
2025-10-23 19:45:18 +03:00
})
2025-08-12 11:23:55 +01:00
})
2025-07-03 19:27:41 +02:00
})
2026-02-27 11:50:56 -05:00
r . Route ( "/chats" , func ( r chi . Router ) {
r . Use (
apiKeyMiddleware ,
httpmw . RequireExperimentWithDevBypass ( api . Experiments , codersdk . ExperimentAgents ),
)
r . Get ( "/" , api . listChats )
r . Post ( "/" , api . postChats )
r . Get ( "/models" , api . listChatModels )
r . Get ( "/watch" , api . watchChats )
2026-03-13 18:30:49 +01:00
r . Route ( "/cost" , func ( r chi . Router ) {
r . Get ( "/users" , api . chatCostUsers )
r . Route ( "/{user}" , func ( r chi . Router ) {
r . Use ( httpmw . ExtractUserParam ( options . Database ))
r . Get ( "/summary" , api . chatCostSummary )
})
})
2026-03-18 11:29:29 -04:00
r . Route ( "/insights" , func ( r chi . Router ) {
r . Get ( "/pull-requests" , api . prInsights )
})
2026-03-06 21:05:26 +02:00
r . Route ( "/files" , func ( r chi . Router ) {
r . Use ( httpmw . RateLimit ( options . FilesRateLimit , time . Minute ))
r . Post ( "/" , api . postChatFile )
r . Get ( "/{file}" , api . chatFileByID )
})
2026-03-10 11:46:53 +00:00
r . Route ( "/config" , func ( r chi . Router ) {
r . Get ( "/system-prompt" , api . getChatSystemPrompt )
r . Put ( "/system-prompt" , api . putChatSystemPrompt )
2026-03-18 09:35:13 +01:00
r . Get ( "/desktop-enabled" , api . getChatDesktopEnabled )
r . Put ( "/desktop-enabled" , api . putChatDesktopEnabled )
2026-03-10 08:17:52 -07:00
r . Get ( "/user-prompt" , api . getUserChatCustomPrompt )
r . Put ( "/user-prompt" , api . putUserChatCustomPrompt )
2026-03-20 17:38:39 +00:00
r . Get ( "/workspace-ttl" , api . getChatWorkspaceTTL )
r . Put ( "/workspace-ttl" , api . putChatWorkspaceTTL )
2026-03-10 11:46:53 +00:00
})
// TODO(cian): place under /api/experimental/chats/config
2026-02-27 11:50:56 -05:00
r . Route ( "/providers" , func ( r chi . Router ) {
r . Get ( "/" , api . listChatProviders )
r . Post ( "/" , api . createChatProvider )
r . Route ( "/{providerConfig}" , func ( r chi . Router ) {
r . Patch ( "/" , api . updateChatProvider )
r . Delete ( "/" , api . deleteChatProvider )
})
})
2026-03-10 11:46:53 +00:00
// TODO(cian): place under /api/experimental/chats/config
2026-02-27 11:50:56 -05:00
r . Route ( "/model-configs" , func ( r chi . Router ) {
r . Get ( "/" , api . listChatModelConfigs )
r . Post ( "/" , api . createChatModelConfig )
r . Route ( "/{modelConfig}" , func ( r chi . Router ) {
r . Patch ( "/" , api . updateChatModelConfig )
r . Delete ( "/" , api . deleteChatModelConfig )
})
})
2026-03-17 01:24:03 +01:00
r . Route ( "/usage-limits" , func ( r chi . Router ) {
r . Get ( "/" , api . getChatUsageLimitConfig )
r . Put ( "/" , api . updateChatUsageLimitConfig )
r . Get ( "/status" , api . getMyChatUsageLimitStatus )
r . Route ( "/overrides/{user}" , func ( r chi . Router ) {
r . Put ( "/" , api . upsertChatUsageLimitOverride )
r . Delete ( "/" , api . deleteChatUsageLimitOverride )
})
r . Route ( "/group-overrides/{group}" , func ( r chi . Router ) {
r . Put ( "/" , api . upsertChatUsageLimitGroupOverride )
r . Delete ( "/" , api . deleteChatUsageLimitGroupOverride )
})
})
2026-02-27 11:50:56 -05:00
r . Route ( "/{chat}" , func ( r chi . Router ) {
r . Use ( httpmw . ExtractChatParam ( options . Database ))
r . Get ( "/" , api . getChat )
2026-03-17 10:31:11 -04:00
r . Patch ( "/" , api . patchChat )
2026-03-13 05:35:46 -07:00
r . Get ( "/messages" , api . getChatMessages )
2026-02-27 11:50:56 -05:00
r . Post ( "/messages" , api . postChatMessages )
r . Patch ( "/messages/{message}" , api . patchChatMessage )
2026-03-18 14:04:42 -04:00
r . Route ( "/stream" , func ( r chi . Router ) {
r . Get ( "/" , api . streamChat )
r . Get ( "/desktop" , api . watchChatDesktop )
r . Get ( "/git" , api . watchChatGit )
})
2026-02-27 11:50:56 -05:00
r . Post ( "/interrupt" , api . interruptChat )
r . Get ( "/diff" , api . getChatDiffContents )
r . Route ( "/queue/{queuedMessage}" , func ( r chi . Router ) {
r . Delete ( "/" , api . deleteChatQueuedMessage )
r . Post ( "/promote" , api . promoteChatQueuedMessage )
})
})
})
2025-09-26 16:20:33 +02:00
r . Route ( "/mcp" , func ( r chi . Router ) {
r . Use (
apiKeyMiddleware ,
)
2026-03-19 10:07:36 -04:00
// MCP server configuration endpoints.
r . Route ( "/servers" , func ( r chi . Router ) {
r . Use ( httpmw . RequireExperimentWithDevBypass ( api . Experiments , codersdk . ExperimentAgents ))
r . Get ( "/" , api . listMCPServerConfigs )
r . Post ( "/" , api . createMCPServerConfig )
r . Route ( "/{mcpServer}" , func ( r chi . Router ) {
r . Get ( "/" , api . getMCPServerConfig )
r . Patch ( "/" , api . updateMCPServerConfig )
r . Delete ( "/" , api . deleteMCPServerConfig )
// OAuth2 user flow
r . Get ( "/oauth2/connect" , api . mcpServerOAuth2Connect )
r . Get ( "/oauth2/callback" , api . mcpServerOAuth2Callback )
r . Delete ( "/oauth2/disconnect" , api . mcpServerOAuth2Disconnect )
})
})
2025-09-26 16:20:33 +02:00
// MCP HTTP transport endpoint with mandatory authentication
2026-03-19 10:07:36 -04:00
r . Route ( "/http" , func ( r chi . Router ) {
r . Use ( httpmw . RequireExperimentWithDevBypass ( api . Experiments , codersdk . ExperimentOAuth2 , codersdk . ExperimentMCPServerHTTP ))
r . Mount ( "/" , api . mcpHTTPHandler ())
})
2025-09-26 16:20:33 +02:00
})
2026-03-13 20:37:41 -07:00
r . Route ( "/watch-all-workspacebuilds" , func ( r chi . Router ) {
r . Use (
apiKeyMiddleware ,
httpmw . RequireExperiment ( api . Experiments , codersdk . ExperimentWorkspaceBuildUpdates ),
)
r . Get ( "/" , api . watchAllWorkspaceBuilds )
})
2025-06-24 13:06:02 +02:00
})
2022-01-13 16:55:28 -06:00
r . Route ( "/api/v2" , func ( r chi . Router ) {
2022-09-19 23:11:01 -05:00
api . APIHandler = r
2025-03-26 01:56:39 -05:00
r . NotFound ( func ( rw http . ResponseWriter , _ * http . Request ) { httpapi . RouteNotFound ( rw ) })
2022-04-04 17:32:05 -05:00
r . Use (
2023-01-05 12:05:20 -06:00
apiRateLimiter ,
2023-05-24 11:08:03 -05:00
httpmw . ReportCLITelemetry ( api . Logger , options . Telemetry ),
2022-04-04 17:32:05 -05:00
)
2022-12-22 15:53:14 +01:00
r . Get ( "/" , apiRoot )
2022-05-27 09:59:13 -05:00
// All CSP errors will be logged
r . Post ( "/csp/reports" , api . logReportCSPViolations )
2025-09-26 11:43:32 +02:00
r . Get ( "/auth/scopes" , api . listExternalScopes )
2024-04-29 20:50:49 -04:00
r . Get ( "/buildinfo" , buildInfoHandler ( buildInfo ))
2023-04-25 07:37:52 -07:00
// /regions is overridden in the enterprise version
r . Group ( func ( r chi . Router ) {
r . Use ( apiKeyMiddleware )
r . Get ( "/regions" , api . regions )
})
2023-07-26 09:21:04 -07:00
r . Route ( "/derp-map" , func ( r chi . Router ) {
// r.Use(apiKeyMiddleware)
r . Get ( "/" , api . derpMapUpdates )
})
2023-03-08 21:05:45 -06:00
r . Route ( "/deployment" , func ( r chi . Router ) {
r . Use ( apiKeyMiddleware )
r . Get ( "/config" , api . deploymentValues )
r . Get ( "/stats" , api . deploymentStats )
2023-03-16 13:03:37 -05:00
r . Get ( "/ssh" , api . sshConfig )
2023-03-08 21:05:45 -06:00
})
2023-01-18 19:12:53 +00:00
r . Route ( "/experiments" , func ( r chi . Router ) {
r . Use ( apiKeyMiddleware )
2025-06-24 09:14:41 +01:00
r . Get ( "/available" , handleExperimentsAvailable )
2023-01-18 19:12:53 +00:00
r . Get ( "/" , api . handleExperimentsGet )
})
2022-12-22 15:53:14 +01:00
r . Get ( "/updatecheck" , api . updateCheck )
2022-09-07 11:38:19 -05:00
r . Route ( "/audit" , func ( r chi . Router ) {
r . Use (
apiKeyMiddleware ,
2025-02-20 09:56:57 -05:00
// This middleware only checks the site and orgs for the audit_log read
// permission.
// In the future if it makes sense to have this permission on the user as
// well we will need to update this middleware to include that check.
func ( next http . Handler ) http . Handler {
return http . HandlerFunc ( func ( rw http . ResponseWriter , r * http . Request ) {
if api . Authorize ( r , policy . ActionRead , rbac . ResourceAuditLog ) {
next . ServeHTTP ( rw , r )
return
}
if api . Authorize ( r , policy . ActionRead , rbac . ResourceAuditLog . AnyOrganization ()) {
next . ServeHTTP ( rw , r )
return
}
httpapi . Forbidden ( rw )
})
},
2022-09-07 11:38:19 -05:00
)
r . Get ( "/" , api . auditLogs )
r . Post ( "/testgenerate" , api . generateFakeAuditLog )
})
2022-03-07 11:40:54 -06:00
r . Route ( "/files" , func ( r chi . Router ) {
2022-04-04 17:32:05 -05:00
r . Use (
2022-04-23 17:58:57 -05:00
apiKeyMiddleware ,
2023-01-05 12:05:20 -06:00
httpmw . RateLimit ( options . FilesRateLimit , time . Minute ),
2022-04-04 17:32:05 -05:00
)
2022-10-13 18:02:52 -05:00
r . Get ( "/{fileID}" , api . fileByID )
2022-05-25 22:14:08 -05:00
r . Post ( "/" , api . postFile )
2022-01-20 07:46:51 -06:00
})
2023-12-05 14:03:44 -06:00
r . Route ( "/external-auth" , func ( r chi . Router ) {
2023-06-29 13:58:01 -05:00
r . Use (
apiKeyMiddleware ,
)
2023-12-05 14:03:44 -06:00
// Get without a specific external auth ID will return all external auths.
r . Get ( "/" , api . listUserExternalAuths )
r . Route ( "/{externalauth}" , func ( r chi . Router ) {
r . Use (
httpmw . ExtractExternalAuthParam ( options . ExternalAuthConfigs ),
)
r . Delete ( "/" , api . deleteExternalAuthByID )
r . Get ( "/" , api . externalAuthByID )
r . Post ( "/device" , api . postExternalAuthDeviceByID )
r . Get ( "/device" , api . externalAuthDeviceByID )
})
2023-06-29 13:58:01 -05:00
})
2022-05-27 11:19:13 -05:00
r . Route ( "/organizations" , func ( r chi . Router ) {
2022-01-24 11:07:42 -06:00
r . Use (
2022-04-23 17:58:57 -05:00
apiKeyMiddleware ,
2022-01-24 11:07:42 -06:00
)
2024-07-18 12:28:36 -10:00
r . Get ( "/" , api . organizations )
2022-05-27 11:19:13 -05:00
r . Route ( "/{organization}" , func ( r chi . Router ) {
r . Use (
httpmw . ExtractOrganizationParam ( options . Database ),
)
r . Get ( "/" , api . organization )
2023-02-02 15:47:53 -06:00
r . Post ( "/templateversions" , api . postTemplateVersionsByOrganization )
2022-05-27 11:19:13 -05:00
r . Route ( "/templates" , func ( r chi . Router ) {
r . Post ( "/" , api . postTemplateByOrganization )
2024-06-26 07:50:32 -10:00
r . Get ( "/" , api . templatesByOrganization ())
2024-08-06 11:26:26 -06:00
r . Get ( "/examples" , api . templateExamplesByOrganization )
2023-02-02 15:47:53 -06:00
r . Route ( "/{templatename}" , func ( r chi . Router ) {
r . Get ( "/" , api . templateByOrganizationAndName )
r . Route ( "/versions/{templateversionname}" , func ( r chi . Router ) {
r . Get ( "/" , api . templateVersionByOrganizationTemplateAndName )
r . Get ( "/previous" , api . previousTemplateVersionByOrganizationTemplateAndName )
})
})
2022-04-25 16:11:03 -05:00
})
2025-03-10 14:42:07 -04:00
r . Get ( "/paginated-members" , api . paginatedMembers )
2022-05-27 11:19:13 -05:00
r . Route ( "/members" , func ( r chi . Router ) {
2024-06-12 09:52:18 -10:00
r . Get ( "/" , api . listMembers )
2024-05-29 09:49:43 -05:00
r . Route ( "/roles" , func ( r chi . Router ) {
r . Get ( "/" , api . assignableOrgRoles )
})
2022-05-27 11:19:13 -05:00
r . Route ( "/{user}" , func ( r chi . Router ) {
2024-06-20 04:19:24 -10:00
r . Group ( func ( r chi . Router ) {
r . Use (
// Adding a member requires "read" permission
// on the site user. So limited to owners and user-admins.
// TODO: Allow org-admins to add users via some new permission? Or give them
// read on site users.
httpmw . ExtractUserParam ( options . Database ),
)
r . Post ( "/" , api . postOrganizationMember )
})
r . Group ( func ( r chi . Router ) {
r . Use (
httpmw . ExtractOrganizationMemberParam ( options . Database ),
)
2026-02-03 12:48:25 -06:00
r . Get ( "/" , api . organizationMember )
2024-06-20 05:06:37 -10:00
r . Delete ( "/" , api . deleteOrganizationMember )
2024-06-20 04:19:24 -10:00
r . Put ( "/roles" , api . putMemberRoles )
2026-02-19 10:04:53 -08:00
r . Route ( "/workspaces" , func ( r chi . Router ) {
r . Post ( "/" , api . postWorkspacesByOrganization )
r . Get ( "/available-users" , api . workspaceAvailableUsers )
})
2024-06-20 04:19:24 -10:00
})
2022-05-27 11:19:13 -05:00
})
2022-04-29 09:04:19 -05:00
})
2025-01-14 18:40:26 +02:00
r . Route ( "/provisionerdaemons" , func ( r chi . Router ) {
r . Get ( "/" , api . provisionerDaemons )
})
2025-01-20 11:18:53 +02:00
r . Route ( "/provisionerjobs" , func ( r chi . Router ) {
2025-01-27 18:26:56 +02:00
r . Get ( "/{job}" , api . provisionerJob )
2025-01-20 11:18:53 +02:00
r . Get ( "/" , api . provisionerJobs )
})
2022-04-29 09:04:19 -05:00
})
2022-03-07 11:40:54 -06:00
})
2024-06-26 07:50:32 -10:00
r . Route ( "/templates" , func ( r chi . Router ) {
2022-03-07 11:40:54 -06:00
r . Use (
2022-04-23 17:58:57 -05:00
apiKeyMiddleware ,
2022-03-07 11:40:54 -06:00
)
2024-06-26 07:50:32 -10:00
r . Get ( "/" , api . fetchTemplates ( nil ))
2024-08-06 11:26:26 -06:00
r . Get ( "/examples" , api . templateExamples )
2024-06-26 07:50:32 -10:00
r . Route ( "/{template}" , func ( r chi . Router ) {
r . Use (
httpmw . ExtractTemplateParam ( options . Database ),
)
r . Get ( "/daus" , api . templateDAUs )
r . Get ( "/" , api . template )
r . Delete ( "/" , api . deleteTemplate )
r . Patch ( "/" , api . patchTemplateMeta )
r . Route ( "/versions" , func ( r chi . Router ) {
r . Post ( "/archive" , api . postArchiveTemplateVersions )
r . Get ( "/" , api . templateVersionsByTemplate )
r . Patch ( "/" , api . patchActiveTemplateVersion )
r . Get ( "/{templateversionname}" , api . templateVersionByName )
})
2022-03-07 11:40:54 -06:00
})
})
2025-05-27 15:43:00 -05:00
2022-04-06 12:42:40 -05:00
r . Route ( "/templateversions/{templateversion}" , func ( r chi . Router ) {
2022-03-07 11:40:54 -06:00
r . Use (
2022-04-23 17:58:57 -05:00
apiKeyMiddleware ,
2022-04-06 12:42:40 -05:00
httpmw . ExtractTemplateVersionParam ( options . Database ),
2022-03-07 11:40:54 -06:00
)
2022-05-25 22:14:08 -05:00
r . Get ( "/" , api . templateVersion )
2023-03-23 13:26:50 -03:00
r . Patch ( "/" , api . patchTemplateVersion )
2022-05-25 22:14:08 -05:00
r . Patch ( "/cancel" , api . patchCancelTemplateVersion )
2023-10-11 09:26:22 -05:00
r . Post ( "/archive" , api . postArchiveTemplateVersion ())
r . Post ( "/unarchive" , api . postUnarchiveTemplateVersion ())
2023-06-02 11:16:46 +02:00
// Old agents may expect a non-error response from /schema and /parameters endpoints.
// The idea is to return an empty [], so that the coder CLI won't get blocked accidentally.
r . Get ( "/schema" , templateVersionSchemaDeprecated )
r . Get ( "/parameters" , templateVersionParametersDeprecated )
2023-01-17 11:22:11 +01:00
r . Get ( "/rich-parameters" , api . templateVersionRichParameters )
2023-10-03 09:04:39 -05:00
r . Get ( "/external-auth" , api . templateVersionExternalAuth )
2023-02-15 18:24:15 +01:00
r . Get ( "/variables" , api . templateVersionVariables )
2025-02-12 14:41:14 +02:00
r . Get ( "/presets" , api . templateVersionPresets )
2022-05-25 22:14:08 -05:00
r . Get ( "/resources" , api . templateVersionResources )
r . Get ( "/logs" , api . templateVersionLogs )
2022-06-02 00:44:53 +10:00
r . Route ( "/dry-run" , func ( r chi . Router ) {
r . Post ( "/" , api . postTemplateVersionDryRun )
r . Get ( "/{jobID}" , api . templateVersionDryRun )
r . Get ( "/{jobID}/resources" , api . templateVersionDryRunResources )
r . Get ( "/{jobID}/logs" , api . templateVersionDryRunLogs )
2024-12-02 20:54:32 +00:00
r . Get ( "/{jobID}/matched-provisioners" , api . templateVersionDryRunMatchedProvisioners )
2022-06-02 00:44:53 +10:00
r . Patch ( "/{jobID}/cancel" , api . patchTemplateVersionDryRunCancel )
})
2025-05-27 15:43:00 -05:00
r . Group ( func ( r chi . Router ) {
2025-06-02 13:50:07 -05:00
r . Route ( "/dynamic-parameters" , func ( r chi . Router ) {
r . Post ( "/evaluate" , api . templateVersionDynamicParametersEvaluate )
r . Get ( "/" , api . templateVersionDynamicParametersWebsocket )
})
2025-05-27 15:43:00 -05:00
})
2022-03-07 11:40:54 -06:00
})
r . Route ( "/users" , func ( r chi . Router ) {
2022-05-25 22:14:08 -05:00
r . Get ( "/first" , api . firstUser )
r . Post ( "/first" , api . postFirstUser )
r . Get ( "/authmethods" , api . userAuthMethods )
2023-06-30 08:38:48 -04:00
2023-01-05 12:05:20 -06:00
r . Group ( func ( r chi . Router ) {
// We use a tight limit for password login to protect against
// audit-log write DoS, pbkdf2 DoS, and simple brute-force
// attacks.
//
// This value is intentionally increased during tests.
r . Use ( httpmw . RateLimit ( options . LoginRateLimit , time . Minute ))
r . Post ( "/login" , api . postLogin )
2024-10-04 11:53:25 +01:00
r . Post ( "/otp/request" , api . postRequestOneTimePasscode )
2024-11-05 17:22:32 +01:00
r . Post ( "/validate-password" , api . validateUserPassword )
2024-10-04 11:53:25 +01:00
r . Post ( "/otp/change-password" , api . postChangePasswordWithOneTimePasscode )
2023-01-05 12:05:20 -06:00
r . Route ( "/oauth2" , func ( r chi . Router ) {
2025-02-21 18:42:16 +01:00
r . Get ( "/github/device" , api . userOAuth2GithubDevice )
2023-01-05 12:05:20 -06:00
r . Route ( "/github" , func ( r chi . Router ) {
2023-07-10 10:25:41 -04:00
r . Use (
2025-12-15 11:41:47 -06:00
// Github supports PKCE S256
httpmw . ExtractOAuth2 ( options . GithubOAuth2Config , options . HTTPClient , options . DeploymentValues . HTTPCookies , nil , options . GithubOAuth2Config . PKCESupported ()),
2023-07-10 10:25:41 -04:00
)
2023-01-05 12:05:20 -06:00
r . Get ( "/callback" , api . userOAuth2Github )
})
})
r . Route ( "/oidc/callback" , func ( r chi . Router ) {
2023-07-10 10:25:41 -04:00
r . Use (
2025-12-15 11:41:47 -06:00
httpmw . ExtractOAuth2 ( options . OIDCConfig , options . HTTPClient , options . DeploymentValues . HTTPCookies , oidcAuthURLParams , options . OIDCConfig . PKCESupported ()),
2023-07-10 10:25:41 -04:00
)
2023-01-05 12:05:20 -06:00
r . Get ( "/" , api . userOIDC )
2022-04-23 17:58:57 -05:00
})
2022-07-31 23:05:35 -05:00
})
2022-03-07 11:40:54 -06:00
r . Group ( func ( r chi . Router ) {
2022-05-03 16:10:19 -05:00
r . Use (
apiKeyMiddleware ,
)
2022-05-25 22:14:08 -05:00
r . Post ( "/" , api . postUser )
r . Get ( "/" , api . users )
2022-05-27 16:47:03 -04:00
r . Post ( "/logout" , api . postLogout )
2026-03-19 16:12:31 +01:00
r . Post ( "/me/session/token-to-cookie" , api . postSessionTokenCookie )
2026-03-18 22:10:04 +00:00
r . Get ( "/oidc-claims" , api . userOIDCClaims )
2022-05-03 16:10:19 -05:00
// These routes query information about site wide roles.
r . Route ( "/roles" , func ( r chi . Router ) {
2024-05-16 13:47:47 -05:00
r . Get ( "/" , api . AssignableSiteRoles )
2022-05-03 16:10:19 -05:00
})
2022-03-07 11:40:54 -06:00
r . Route ( "/{user}" , func ( r chi . Router ) {
2025-04-09 14:35:43 -05:00
r . Group ( func ( r chi . Router ) {
2025-05-08 14:41:17 -05:00
r . Use ( httpmw . ExtractOrganizationMembersParam ( options . Database , api . HTTPAuth . Authorize ))
2025-04-09 14:35:43 -05:00
// Creating workspaces does not require permissions on the user, only the
// organization member. This endpoint should match the authz story of
// postWorkspacesByOrganization
r . Post ( "/workspaces" , api . postUserWorkspaces )
2025-05-08 14:41:17 -05:00
r . Route ( "/workspace/{workspacename}" , func ( r chi . Router ) {
r . Get ( "/" , api . workspaceByOwnerAndName )
r . Get ( "/builds/{buildnumber}" , api . workspaceBuildByBuildNumber )
})
})
r . Group ( func ( r chi . Router ) {
r . Use ( httpmw . ExtractUserParam ( options . Database ))
2025-04-17 13:51:50 -07:00
2025-04-09 14:35:43 -05:00
r . Post ( "/convert-login" , api . postConvertLoginType )
r . Delete ( "/" , api . deleteUser )
r . Get ( "/" , api . userByName )
r . Get ( "/autofill-parameters" , api . userAutofillParameters )
r . Get ( "/login-type" , api . userLoginType )
r . Put ( "/profile" , api . putUserProfile )
r . Route ( "/status" , func ( r chi . Router ) {
r . Put ( "/suspend" , api . putSuspendUserAccount ())
r . Put ( "/activate" , api . putActivateUserAccount ())
})
r . Get ( "/appearance" , api . userAppearanceSettings )
r . Put ( "/appearance" , api . putUserAppearanceSettings )
2025-11-28 16:50:59 +00:00
r . Get ( "/preferences" , api . userPreferenceSettings )
r . Put ( "/preferences" , api . putUserPreferenceSettings )
2026-03-10 08:17:52 -07:00
2025-04-09 14:35:43 -05:00
r . Route ( "/password" , func ( r chi . Router ) {
r . Use ( httpmw . RateLimit ( options . LoginRateLimit , time . Minute ))
r . Put ( "/" , api . putUserPassword )
})
// These roles apply to the site wide permissions.
r . Put ( "/roles" , api . putUserRoles )
r . Get ( "/roles" , api . userRoles )
r . Route ( "/keys" , func ( r chi . Router ) {
r . Post ( "/" , api . postAPIKey )
r . Route ( "/tokens" , func ( r chi . Router ) {
r . Post ( "/" , api . postToken )
r . Get ( "/" , api . tokens )
r . Get ( "/tokenconfig" , api . tokenConfig )
r . Route ( "/{keyname}" , func ( r chi . Router ) {
r . Get ( "/" , api . apiKeyByName )
})
})
r . Route ( "/{keyid}" , func ( r chi . Router ) {
r . Get ( "/" , api . apiKeyByID )
r . Delete ( "/" , api . deleteAPIKey )
2026-02-17 13:16:46 +00:00
r . Put ( "/expire" , api . expireAPIKey )
2023-03-02 09:39:38 -08:00
})
2022-10-06 15:02:27 -04:00
})
2022-06-27 13:50:52 -05:00
2025-04-09 14:35:43 -05:00
r . Route ( "/organizations" , func ( r chi . Router ) {
r . Get ( "/" , api . organizationsByUser )
r . Get ( "/{organizationname}" , api . organizationByUserAndName )
})
2025-05-08 14:41:17 -05:00
2025-04-09 14:35:43 -05:00
r . Get ( "/gitsshkey" , api . gitSSHKey )
r . Put ( "/gitsshkey" , api . regenerateGitSSHKey )
r . Route ( "/notifications" , func ( r chi . Router ) {
r . Route ( "/preferences" , func ( r chi . Router ) {
r . Get ( "/" , api . userNotificationPreferences )
r . Put ( "/" , api . putUserNotificationPreferences )
})
})
r . Route ( "/webpush" , func ( r chi . Router ) {
2026-03-03 09:49:04 +00:00
r . Use ( httpmw . RequireExperimentWithDevBypass ( api . Experiments , codersdk . ExperimentWebPush ))
2025-04-09 14:35:43 -05:00
r . Post ( "/subscription" , api . postUserWebpushSubscription )
r . Delete ( "/subscription" , api . deleteUserWebpushSubscription )
r . Post ( "/test" , api . postUserPushNotificationTest )
2024-08-05 16:18:45 +02:00
})
2025-03-27 10:03:53 +00:00
})
2022-01-25 13:52:58 -06:00
})
})
})
2022-04-11 16:06:15 -05:00
r . Route ( "/workspaceagents" , func ( r chi . Router ) {
2022-05-25 22:14:08 -05:00
r . Post ( "/azure-instance-identity" , api . postWorkspaceAuthAzureInstanceIdentity )
r . Post ( "/aws-instance-identity" , api . postWorkspaceAuthAWSInstanceIdentity )
r . Post ( "/google-instance-identity" , api . postWorkspaceAuthGoogleInstanceIdentity )
2023-07-17 14:40:12 -05:00
r . With (
apiKeyMiddlewareOptional ,
httpmw . ExtractWorkspaceProxy ( httpmw . ExtractWorkspaceProxyConfig {
DB : options . Database ,
Optional : true ,
}),
httpmw . RequireAPIKeyOrWorkspaceProxyAuth (),
). Get ( "/connection" , api . workspaceAgentConnectionGeneric )
2022-04-11 16:06:15 -05:00
r . Route ( "/me" , func ( r chi . Router ) {
2025-05-15 15:32:52 +01:00
r . Use ( workspaceAgentInfo )
2025-08-07 13:58:39 -05:00
r . Group ( func ( r chi . Router ) {
r . Use (
// Override the request_type for agent rpc traffic.
httpmw . WithStaticProfilingLabels ( pprof . Labels ( pproflabel . RequestTypeTag , "agent-rpc" )),
)
r . Get ( "/rpc" , api . workspaceAgentRPC )
})
2023-07-28 09:57:23 -06:00
r . Patch ( "/logs" , api . patchWorkspaceAgentLogs )
2025-03-31 10:55:44 -04:00
r . Patch ( "/app-status" , api . patchWorkspaceAgentAppStatus )
2023-10-09 18:04:35 -05:00
// Deprecated: Required to support legacy agents
2022-10-24 19:46:24 -05:00
r . Get ( "/gitauth" , api . workspaceAgentsGitAuth )
2023-10-09 18:04:35 -05:00
r . Get ( "/external-auth" , api . workspaceAgentsExternalAuth )
2022-05-25 22:14:08 -05:00
r . Get ( "/gitsshkey" , api . agentGitSSHKey )
2024-06-03 12:29:50 -05:00
r . Post ( "/log-source" , api . workspaceAgentPostLogSource )
2025-05-14 14:15:36 +02:00
r . Get ( "/reinit" , api . workspaceAgentReinit )
2026-01-27 11:09:24 +02:00
r . Route ( "/tasks/{task}" , func ( r chi . Router ) {
r . Post ( "/log-snapshot" , api . postWorkspaceAgentTaskLogSnapshot )
})
2022-03-07 11:40:54 -06:00
})
2022-04-11 16:06:15 -05:00
r . Route ( "/{workspaceagent}" , func ( r chi . Router ) {
2022-03-07 11:40:54 -06:00
r . Use (
2023-04-17 14:57:21 -05:00
// Allow either API key or external workspace proxy auth and require it.
apiKeyMiddlewareOptional ,
httpmw . ExtractWorkspaceProxy ( httpmw . ExtractWorkspaceProxyConfig {
DB : options . Database ,
Optional : true ,
}),
httpmw . RequireAPIKeyOrWorkspaceProxyAuth (),
2026-01-19 12:36:33 +00:00
httpmw . ExtractWorkspaceAgentAndWorkspaceParam ( options . Database ),
2022-03-07 11:40:54 -06:00
)
2022-05-25 22:14:08 -05:00
r . Get ( "/" , api . workspaceAgent )
2025-03-28 17:13:20 -04:00
r . Get ( "/watch-metadata" , api . watchWorkspaceAgentMetadataSSE )
r . Get ( "/watch-metadata-ws" , api . watchWorkspaceAgentMetadataWS )
2023-07-28 09:57:23 -06:00
r . Get ( "/startup-logs" , api . workspaceAgentLogsDeprecated )
r . Get ( "/logs" , api . workspaceAgentLogs )
2022-10-06 22:38:22 +10:00
r . Get ( "/listening-ports" , api . workspaceAgentListeningPorts )
2022-08-31 20:09:44 -05:00
r . Get ( "/connection" , api . workspaceAgentConnection )
2025-02-10 11:29:30 +00:00
r . Get ( "/containers" , api . workspaceAgentListContainers )
2025-07-14 21:35:35 +01:00
r . Get ( "/containers/watch" , api . watchWorkspaceAgentContainers )
2025-12-24 12:34:39 +00:00
r . Delete ( "/containers/devcontainers/{devcontainer}" , api . workspaceAgentDeleteDevcontainer )
2025-06-26 11:41:57 +01:00
r . Post ( "/containers/devcontainers/{devcontainer}/recreate" , api . workspaceAgentRecreateDevcontainer )
2022-08-31 20:09:44 -05:00
r . Get ( "/coordinate" , api . workspaceAgentClientCoordinate )
2023-04-06 04:41:55 +10:00
// PTY is part of workspaceAppServer.
2022-01-24 11:07:42 -06:00
})
})
2022-05-18 10:09:07 -05:00
r . Route ( "/workspaces" , func ( r chi . Router ) {
2022-02-12 13:34:04 -06:00
r . Use (
2022-04-23 17:58:57 -05:00
apiKeyMiddleware ,
2022-02-12 13:34:04 -06:00
)
2022-05-25 22:14:08 -05:00
r . Get ( "/" , api . workspaces )
2022-05-18 10:09:07 -05:00
r . Route ( "/{workspace}" , func ( r chi . Router ) {
r . Use (
httpmw . ExtractWorkspaceParam ( options . Database ),
)
2022-05-25 22:14:08 -05:00
r . Get ( "/" , api . workspace )
2022-08-26 12:28:38 +03:00
r . Patch ( "/" , api . patchWorkspace )
2022-05-18 10:09:07 -05:00
r . Route ( "/builds" , func ( r chi . Router ) {
2022-05-25 22:14:08 -05:00
r . Get ( "/" , api . workspaceBuilds )
r . Post ( "/" , api . postWorkspaceBuilds )
2022-05-18 10:09:07 -05:00
})
r . Route ( "/autostart" , func ( r chi . Router ) {
2022-05-25 22:14:08 -05:00
r . Put ( "/" , api . putWorkspaceAutostart )
2022-05-18 10:09:07 -05:00
})
2022-05-19 20:09:27 +01:00
r . Route ( "/ttl" , func ( r chi . Router ) {
2022-05-25 22:14:08 -05:00
r . Put ( "/" , api . putWorkspaceTTL )
2022-05-18 10:09:07 -05:00
})
2025-03-28 17:13:20 -04:00
r . Get ( "/watch" , api . watchWorkspaceSSE )
r . Get ( "/watch-ws" , api . watchWorkspaceWS )
2022-05-26 18:08:11 +01:00
r . Put ( "/extend" , api . putExtendWorkspace )
2024-03-20 16:44:12 +00:00
r . Post ( "/usage" , api . postWorkspaceUsage )
2023-08-24 13:25:54 -05:00
r . Put ( "/dormant" , api . putWorkspaceDormant )
2024-01-24 13:39:19 +00:00
r . Put ( "/favorite" , api . putFavoriteWorkspace )
r . Delete ( "/favorite" , api . deleteFavoriteWorkspace )
2023-10-06 13:27:12 +04:00
r . Put ( "/autoupdates" , api . putWorkspaceAutoupdates )
2023-11-08 23:24:56 -06:00
r . Get ( "/resolve-autostart" , api . resolveAutostart )
2024-02-13 09:31:20 -05:00
r . Route ( "/port-share" , func ( r chi . Router ) {
r . Get ( "/" , api . workspaceAgentPortShares )
r . Post ( "/" , api . postWorkspaceAgentPortShare )
r . Delete ( "/" , api . deleteWorkspaceAgentPortShare )
})
2024-09-16 16:31:05 -03:00
r . Get ( "/timings" , api . workspaceTimings )
2025-07-31 09:05:09 -06:00
r . Route ( "/acl" , func ( r chi . Router ) {
2025-08-25 06:11:18 -06:00
r . Get ( "/" , api . workspaceACL )
2025-07-31 09:05:09 -06:00
r . Patch ( "/" , api . patchWorkspaceACL )
2025-09-12 12:21:01 -04:00
r . Delete ( "/" , api . deleteWorkspaceACL )
2025-07-31 09:05:09 -06:00
})
2022-04-07 10:03:35 +01:00
})
2022-02-12 13:34:04 -06:00
})
2022-03-07 11:40:54 -06:00
r . Route ( "/workspacebuilds/{workspacebuild}" , func ( r chi . Router ) {
2022-02-12 13:34:04 -06:00
r . Use (
2022-04-23 17:58:57 -05:00
apiKeyMiddleware ,
2022-03-07 11:40:54 -06:00
httpmw . ExtractWorkspaceBuildParam ( options . Database ),
httpmw . ExtractWorkspaceParam ( options . Database ),
2022-02-12 13:34:04 -06:00
)
2022-05-25 22:14:08 -05:00
r . Get ( "/" , api . workspaceBuild )
r . Patch ( "/cancel" , api . patchCancelWorkspaceBuild )
r . Get ( "/logs" , api . workspaceBuildLogs )
2023-01-17 16:24:45 +01:00
r . Get ( "/parameters" , api . workspaceBuildParameters )
2024-02-15 17:13:44 +01:00
r . Get ( "/resources" , api . workspaceBuildResourcesDeprecated )
2022-05-25 22:14:08 -05:00
r . Get ( "/state" , api . workspaceBuildState )
2026-01-12 15:16:59 +01:00
r . Put ( "/state" , api . workspaceBuildUpdateState )
2024-10-14 09:31:03 -03:00
r . Get ( "/timings" , api . workspaceBuildTimings )
2022-02-12 13:34:04 -06:00
})
2022-09-23 08:30:32 +10:00
r . Route ( "/authcheck" , func ( r chi . Router ) {
r . Use ( apiKeyMiddleware )
r . Post ( "/" , api . checkAuthorization )
})
r . Route ( "/applications" , func ( r chi . Router ) {
r . Route ( "/host" , func ( r chi . Router ) {
// Don't leak the hostname to unauthenticated users.
r . Use ( apiKeyMiddleware )
r . Get ( "/" , api . appHost )
})
r . Route ( "/auth-redirect" , func ( r chi . Router ) {
// We want to redirect to login if they are not authenticated.
r . Use ( apiKeyMiddlewareRedirect )
// This is a GET request as it's redirected to by the subdomain app
// handler and the login page.
r . Get ( "/" , api . workspaceApplicationAuth )
})
})
2023-01-25 20:03:47 -05:00
r . Route ( "/insights" , func ( r chi . Router ) {
r . Use ( apiKeyMiddleware )
2025-12-13 18:00:03 -09:00
r . Group ( func ( r chi . Router ) {
r . Use (
func ( next http . Handler ) http . Handler {
return http . HandlerFunc ( func ( rw http . ResponseWriter , r * http . Request ) {
2026-01-05 11:44:06 -09:00
// Template insights depend on the usage stats.
if ! options . DeploymentValues . StatsCollection . UsageStats . Enable . Value () {
2025-12-13 18:00:03 -09:00
httpapi . Write ( context . Background (), rw , http . StatusNotFound , codersdk . Response {
Message : "Not Found." ,
Detail : "Template insights are disabled." ,
})
return
}
next . ServeHTTP ( rw , r )
})
},
)
r . Get ( "/daus" , api . deploymentDAUs )
r . Get ( "/user-activity" , api . insightsUserActivity )
r . Get ( "/user-latency" , api . insightsUserLatency )
r . Get ( "/templates" , api . insightsTemplates )
})
2025-01-13 13:08:16 +02:00
r . Get ( "/user-status-counts" , api . insightsUserStatusCounts )
2023-01-25 20:03:47 -05:00
})
2023-01-25 15:27:36 -06:00
r . Route ( "/debug" , func ( r chi . Router ) {
r . Use (
apiKeyMiddleware ,
2025-10-21 14:13:11 +11:00
// Ensure only users with the debug_info:read (e.g. only owners)
// can view debug endpoints.
2023-01-25 15:27:36 -06:00
func ( next http . Handler ) http . Handler {
return http . HandlerFunc ( func ( rw http . ResponseWriter , r * http . Request ) {
2024-05-15 09:46:35 -05:00
if ! api . Authorize ( r , policy . ActionRead , rbac . ResourceDebugInfo ) {
2025-02-13 17:05:20 -05:00
httpapi . Forbidden ( rw )
2023-01-25 15:27:36 -06:00
return
}
next . ServeHTTP ( rw , r )
})
},
)
r . Get ( "/coordinator" , api . debugCoordinator )
2023-11-13 17:14:12 -06:00
r . Get ( "/tailnet" , api . debugTailnet )
2023-11-28 18:15:17 +01:00
r . Route ( "/health" , func ( r chi . Router ) {
r . Get ( "/" , api . debugDeploymentHealth )
r . Route ( "/settings" , func ( r chi . Router ) {
r . Get ( "/" , api . deploymentHealthSettings )
r . Put ( "/" , api . putDeploymentHealthSettings )
})
})
2023-05-30 14:22:32 -05:00
r . Get ( "/ws" , ( & healthcheck . WebsocketEchoServer {}). ServeHTTP )
2023-11-27 10:47:23 -06:00
r . Route ( "/{user}" , func ( r chi . Router ) {
r . Use ( httpmw . ExtractUserParam ( options . Database ))
r . Get ( "/debug-link" , api . userDebugOIDC )
})
2024-03-21 16:53:41 -05:00
if options . DERPServer != nil {
r . Route ( "/derp" , func ( r chi . Router ) {
r . Get ( "/traffic" , options . DERPServer . ServeDebugTraffic )
})
}
2024-02-14 15:11:45 +04:00
r . Method ( "GET" , "/expvar" , expvar . Handler ()) // contains DERP metrics as well as cmdline and memstats
2025-10-21 14:13:11 +11:00
2026-03-13 15:09:39 +01:00
r . Post ( "/profile" , api . debugCollectProfile )
2025-10-21 14:13:11 +11:00
r . Route ( "/pprof" , func ( r chi . Router ) {
r . Use ( func ( next http . Handler ) http . Handler {
// Some of the pprof handlers strip the `/debug/pprof`
// prefix, so we need to strip our additional prefix as
// well.
return http . StripPrefix ( "/api/v2" , next )
})
// Serve the index HTML page.
r . Get ( "/" , func ( w http . ResponseWriter , r * http . Request ) {
// Redirect to include a trailing slash, otherwise links on
// the generated HTML page will be broken.
if ! strings . HasSuffix ( r . URL . Path , "/" ) {
http . Redirect ( w , r , "/api/v2/debug/pprof/" , http . StatusTemporaryRedirect )
return
}
httppprof . Index ( w , r )
})
// Handle any out of the box pprof handlers that don't get
// dealt with by the default index handler. See httppprof.init.
r . Get ( "/cmdline" , httppprof . Cmdline )
r . Get ( "/profile" , httppprof . Profile )
r . Get ( "/symbol" , httppprof . Symbol )
r . Get ( "/trace" , httppprof . Trace )
// Index will handle any standard and custom runtime/pprof
// profiles.
r . Get ( "/*" , httppprof . Index )
})
r . Get ( "/metrics" , promhttp . InstrumentMetricHandler (
options . PrometheusRegistry , promhttp . HandlerFor ( options . PrometheusRegistry , promhttp . HandlerOpts {}),
). ServeHTTP )
2023-01-25 15:27:36 -06:00
})
2024-03-25 11:52:22 -08:00
// Manage OAuth2 applications that can use Coder as an OAuth2 provider.
r . Route ( "/oauth2-provider" , func ( r chi . Router ) {
r . Use (
apiKeyMiddleware ,
2025-07-03 20:09:18 +02:00
httpmw . RequireExperimentWithDevBypass ( api . Experiments , codersdk . ExperimentOAuth2 ),
2024-03-25 11:52:22 -08:00
)
r . Route ( "/apps" , func ( r chi . Router ) {
2025-07-03 20:24:45 +02:00
r . Get ( "/" , api . oAuth2ProviderApps ())
r . Post ( "/" , api . postOAuth2ProviderApp ())
2024-03-25 11:52:22 -08:00
r . Route ( "/{app}" , func ( r chi . Router ) {
r . Use ( httpmw . ExtractOAuth2ProviderApp ( options . Database ))
2025-07-03 20:24:45 +02:00
r . Get ( "/" , api . oAuth2ProviderApp ())
r . Put ( "/" , api . putOAuth2ProviderApp ())
r . Delete ( "/" , api . deleteOAuth2ProviderApp ())
2024-03-25 11:52:22 -08:00
r . Route ( "/secrets" , func ( r chi . Router ) {
2025-07-03 20:24:45 +02:00
r . Get ( "/" , api . oAuth2ProviderAppSecrets ())
r . Post ( "/" , api . postOAuth2ProviderAppSecret ())
2024-03-25 11:52:22 -08:00
r . Route ( "/{secretID}" , func ( r chi . Router ) {
r . Use ( httpmw . ExtractOAuth2ProviderAppSecret ( options . Database ))
2025-07-03 20:24:45 +02:00
r . Delete ( "/" , api . deleteOAuth2ProviderAppSecret ())
2024-03-25 11:52:22 -08:00
})
})
})
})
})
2024-07-10 16:15:06 +02:00
r . Route ( "/notifications" , func ( r chi . Router ) {
2024-10-01 15:43:47 +02:00
r . Use ( apiKeyMiddleware )
2025-03-18 00:02:47 +01:00
r . Route ( "/inbox" , func ( r chi . Router ) {
r . Get ( "/" , api . listInboxNotifications )
2025-03-20 13:41:54 +01:00
r . Put ( "/mark-all-as-read" , api . markAllInboxNotificationsAsRead )
2025-03-18 00:02:47 +01:00
r . Get ( "/watch" , api . watchInboxNotifications )
r . Put ( "/{id}/read-status" , api . updateInboxNotificationReadStatus )
})
2024-07-10 16:15:06 +02:00
r . Get ( "/settings" , api . notificationsSettings )
r . Put ( "/settings" , api . putNotificationsSettings )
2024-08-05 16:18:45 +02:00
r . Route ( "/templates" , func ( r chi . Router ) {
r . Get ( "/system" , api . systemNotificationTemplates )
2025-09-11 15:08:57 +02:00
r . Get ( "/custom" , api . customNotificationTemplates )
2024-08-05 16:18:45 +02:00
})
r . Get ( "/dispatch-methods" , api . notificationDispatchMethods )
2025-02-19 14:08:38 +01:00
r . Post ( "/test" , api . postTestNotification )
2025-09-11 15:08:57 +02:00
r . Post ( "/custom" , api . postCustomNotification )
2024-07-10 16:15:06 +02:00
})
2024-11-01 14:53:53 +11:00
r . Route ( "/tailnet" , func ( r chi . Router ) {
r . Use ( apiKeyMiddleware )
r . Get ( "/" , api . tailnetRPCConn )
})
2025-08-19 10:41:33 +02:00
r . Route ( "/init-script" , func ( r chi . Router ) {
r . Get ( "/{os}/{arch}" , api . initScript )
})
2025-11-25 15:24:25 +00:00
r . Route ( "/tasks" , func ( r chi . Router ) {
r . Use ( apiKeyMiddleware )
r . Get ( "/" , api . tasksList )
r . Route ( "/{user}" , func ( r chi . Router ) {
r . Use ( httpmw . ExtractOrganizationMembersParam ( options . Database , api . HTTPAuth . Authorize ))
r . Post ( "/" , api . tasksCreate )
r . Route ( "/{task}" , func ( r chi . Router ) {
r . Use ( httpmw . ExtractTaskParam ( options . Database ))
r . Get ( "/" , api . taskGet )
r . Delete ( "/" , api . taskDelete )
r . Patch ( "/input" , api . taskUpdateInput )
r . Post ( "/send" , api . taskSend )
r . Get ( "/logs" , api . taskLogs )
2026-03-03 16:34:33 +03:00
r . Post ( "/pause" , api . pauseTask )
r . Post ( "/resume" , api . resumeTask )
2025-11-25 15:24:25 +00:00
})
})
})
2022-01-13 16:55:28 -06:00
})
2022-06-13 13:14:22 -05:00
2022-12-19 18:43:46 +01:00
if options . SwaggerEndpoint {
// Swagger UI requires the URL trailing slash. Otherwise, the browser tries to load /assets
// from http://localhost:8080/assets instead of http://localhost:8080/swagger/assets.
r . Get ( "/swagger" , http . RedirectHandler ( "/swagger/" , http . StatusTemporaryRedirect ). ServeHTTP )
2023-01-11 12:42:49 +02:00
// See globalHTTPSwaggerHandler comment as to why we use a package
// global variable here.
r . Get ( "/swagger/*" , globalHTTPSwaggerHandler )
2024-02-20 15:50:30 -06:00
} else {
2025-03-26 01:56:39 -05:00
swaggerDisabled := http . HandlerFunc ( func ( rw http . ResponseWriter , _ * http . Request ) {
2024-02-20 15:50:30 -06:00
httpapi . Write ( context . Background (), rw , http . StatusNotFound , codersdk . Response {
Message : "Swagger documentation is disabled." ,
})
})
r . Get ( "/swagger" , swaggerDisabled )
r . Get ( "/swagger/*" , swaggerDisabled )
2022-12-19 18:43:46 +01:00
}
2024-11-21 11:53:53 -06:00
additionalCSPHeaders := make ( map [ httpmw . CSPFetchDirective ][] string , len ( api . DeploymentValues . AdditionalCSPPolicy ))
var cspParseErrors error
for _ , v := range api . DeploymentValues . AdditionalCSPPolicy {
// Format is "<directive> <value> <value> ..."
v = strings . TrimSpace ( v )
parts := strings . Split ( v , " " )
if len ( parts ) < 2 {
cspParseErrors = errors . Join ( cspParseErrors , xerrors . Errorf ( "invalid CSP header %q, not enough parts to be valid" , v ))
continue
}
additionalCSPHeaders [ httpmw . CSPFetchDirective ( strings . ToLower ( parts [ 0 ]))] = parts [ 1 :]
}
if cspParseErrors != nil {
// Do not fail Coder deployment startup because of this. Just log an error
// and continue
api . Logger . Error ( context . Background (),
"parsing additional CSP headers" , slog . Error ( cspParseErrors ))
}
2026-03-06 21:05:26 +02:00
// Add blob: to img-src for chat file attachment previews when
// the agents experiment is enabled.
if api . Experiments . Enabled ( codersdk . ExperimentAgents ) {
additionalCSPHeaders [ httpmw . CSPDirectiveImgSrc ] = append (
additionalCSPHeaders [ httpmw . CSPDirectiveImgSrc ], "blob:" ,
)
}
2023-05-02 08:30:44 -05:00
// Add CSP headers to all static assets and pages. CSP headers only affect
// browsers, so these don't make sense on api routes.
2025-05-29 10:07:57 -05:00
cspMW := httpmw . CSPHeaders (
2025-06-17 09:00:32 -08:00
options . Telemetry . Enabled (), func () [] * proxyhealth . ProxyHost {
2025-05-29 10:07:57 -05:00
if api . DeploymentValues . Dangerous . AllowAllCors {
2025-06-17 09:00:32 -08:00
// In this mode, allow all external requests.
return [] * proxyhealth . ProxyHost {
{
Host : "*" ,
AppHost : "*" ,
},
}
}
// Always add the primary, since the app host may be on a sub-domain.
proxies := [] * proxyhealth . ProxyHost {
{
Host : api . AccessURL . Host ,
AppHost : appurl . ConvertAppHostForCSP ( api . AccessURL . Host , api . AppHostname ),
},
2025-05-29 10:07:57 -05:00
}
if f := api . WorkspaceProxyHostsFn . Load (); f != nil {
2025-06-17 09:00:32 -08:00
proxies = append ( proxies , ( * f )() ... )
2025-05-29 10:07:57 -05:00
}
2025-06-17 09:00:32 -08:00
return proxies
2025-05-29 10:07:57 -05:00
}, additionalCSPHeaders )
2023-06-18 13:57:27 -05:00
// Static file handler must be wrapped with HSTS handler if the
// StrictTransportSecurityAge is set. We only need to set this header on
// static files since it only affects browsers.
r . NotFound ( cspMW ( compressHandler ( httpmw . HSTS ( api . SiteHandler , options . StrictTransportSecurityCfg ))). ServeHTTP )
2023-05-11 15:42:30 -05:00
2024-03-28 15:49:43 -05:00
api . RootHandler = r
2023-05-11 15:42:30 -05:00
2022-05-25 22:14:08 -05:00
return api
2022-05-19 15:47:45 -07:00
}
2022-05-25 22:14:08 -05:00
type API struct {
2023-02-10 20:23:02 +02:00
// ctx is canceled immediately on shutdown, it can be used to abort
// interruptible tasks.
ctx context . Context
cancel context . CancelFunc
2023-06-30 08:38:48 -04:00
// DeploymentID is loaded from the database on startup.
DeploymentID string
2022-02-20 16:29:16 -06:00
* Options
2022-11-06 13:27:09 -08:00
// ID is a uniquely generated ID on initialization.
// This is used to associate objects with a specific
// Coder API instance, like workspace agents to a
// specific replica.
ID uuid . UUID
2022-09-22 10:14:22 -05:00
Auditor atomic . Pointer [ audit . Auditor ]
2025-07-15 14:36:06 +10:00
ConnectionLogger atomic . Pointer [ connectionlog . ConnectionLogger ]
2022-09-22 10:14:22 -05:00
WorkspaceClientCoordinateOverride atomic . Pointer [ func ( rw http . ResponseWriter ) bool ]
2022-10-17 08:43:30 -05:00
TailnetCoordinator atomic . Pointer [ tailnet . Coordinator ]
2024-07-02 01:50:52 +10:00
NetworkTelemetryBatcher * tailnet . NetworkTelemetryBatcher
2023-12-15 14:10:24 +04:00
TailnetClientService * tailnet . ClientService
2025-03-27 10:03:53 +00:00
// WebpushDispatcher is a way to send notifications to users via Web Push.
WebpushDispatcher webpush . Dispatcher
QuotaCommitter atomic . Pointer [ proto . QuotaCommitter ]
AppearanceFetcher atomic . Pointer [ appearance . Fetcher ]
2023-05-02 08:30:44 -05:00
// WorkspaceProxyHostsFn returns the hosts of healthy workspace proxies
// for header reasons.
2025-06-17 09:00:32 -08:00
WorkspaceProxyHostsFn atomic . Pointer [ func () [] * proxyhealth . ProxyHost ]
2023-05-02 08:30:44 -05:00
// TemplateScheduleStore is a pointer to an atomic pointer because this is
// passed to another struct, and we want them all to be the same reference.
TemplateScheduleStore * atomic . Pointer [ schedule . TemplateScheduleStore ]
2023-07-20 06:35:41 -07:00
// UserQuietHoursScheduleStore is a pointer to an atomic pointer for the
// same reason as TemplateScheduleStore.
UserQuietHoursScheduleStore * atomic . Pointer [ schedule . UserQuietHoursScheduleStore ]
2023-07-26 09:21:04 -07:00
// DERPMapper mutates the DERPMap to include workspace proxies.
DERPMapper atomic . Pointer [ func ( derpMap * tailcfg . DERPMap ) * tailcfg . DERPMap ]
2023-10-18 17:07:21 -05:00
// AccessControlStore is a pointer to an atomic pointer since it is
// passed to dbauthz.
2025-04-25 11:07:15 +02:00
AccessControlStore * atomic . Pointer [ dbauthz . AccessControlStore ]
PortSharer atomic . Pointer [ portsharing . PortSharer ]
2025-05-16 11:47:59 -05:00
FileCache * files . Cache
2025-04-25 11:07:15 +02:00
PrebuildsClaimer atomic . Pointer [ prebuilds . Claimer ]
PrebuildsReconciler atomic . Pointer [ prebuilds . ReconciliationOrchestrator ]
2025-07-22 13:39:26 +10:00
// BuildUsageChecker is a pointer as it's passed around to multiple
// components.
BuildUsageChecker * atomic . Pointer [ wsbuilder . UsageChecker ]
2025-08-20 23:38:09 +10:00
// UsageInserter is a pointer to an atomic pointer because it is passed to
// multiple components.
UsageInserter * atomic . Pointer [ usage . Inserter ]
2023-02-04 04:38:36 +11:00
2024-11-01 14:53:53 +11:00
UpdatesProvider tailnet . WorkspaceUpdatesProvider
2023-02-04 04:38:36 +11:00
HTTPAuth * HTTPAuthorizer
2022-02-20 16:29:16 -06:00
2022-09-19 23:11:01 -05:00
// APIHandler serves "/api/v2"
APIHandler chi . Router
2025-09-26 16:20:33 +02:00
// ExperimentalHandler serves "/api/experimental"
ExperimentalHandler chi . Router
2022-09-19 23:11:01 -05:00
// RootHandler serves "/"
RootHandler chi . Router
2022-08-31 20:09:44 -05:00
2023-06-18 13:57:27 -05:00
// SiteHandler serves static files for the dashboard.
SiteHandler * site . Handler
2022-11-16 16:34:06 -06:00
WebsocketWaitMutex sync . Mutex
WebsocketWaitGroup sync . WaitGroup
2023-03-01 16:18:14 -06:00
derpCloseFunc func ()
2022-11-16 16:34:06 -06:00
2023-03-08 06:38:11 +11:00
metricsCache * metricscache . Cache
updateChecker * updatecheck . Checker
2023-04-04 10:59:41 +10:00
WorkspaceAppsProvider workspaceapps . SignedTokenProvider
2023-04-06 04:41:55 +10:00
workspaceAppServer * workspaceapps . Server
2023-07-12 17:37:31 -05:00
agentProvider workspaceapps . AgentProvider
2023-01-18 19:12:53 +00:00
// Experiments contains the list of experiments currently enabled.
// This is used to gate features that are not yet ready for production.
Experiments codersdk . Experiments
2023-04-03 01:28:42 -05:00
2026-01-15 16:37:05 +00:00
healthCheckGroup * singleflight . Group [ string , * healthsdk . HealthcheckReport ]
healthCheckCache atomic . Pointer [ healthsdk . HealthcheckReport ]
healthCheckProgress healthcheck . Progress
2023-08-04 17:00:42 +01:00
2026-02-06 16:26:02 -06:00
statsReporter * workspacestats . Reporter
metadataBatcher * metadatabatcher . Batcher
lifecycleMetrics * agentapi . LifecycleMetrics
2023-09-19 10:25:57 +04:00
Acquirer * provisionerdserver . Acquirer
2024-03-22 18:42:43 +02:00
// dbRolluper rolls up template usage stats from raw agent and app
// stats. This is used to provide insights in the WebUI.
2024-06-10 15:35:23 -04:00
dbRolluper * dbrollup . Rolluper
2026-02-27 11:50:56 -05:00
// chatDaemon handles background processing of pending chats.
chatDaemon * chatd . Server
2026-03-16 12:36:26 -05:00
// AISeatTracker records AI seat usage.
AISeatTracker aiseats . SeatTracker
2026-03-10 18:46:01 +00:00
// gitSyncWorker refreshes stale chat diff statuses in the
// background.
gitSyncWorker * gitsync . Worker
2026-03-13 15:09:39 +01:00
// ProfileCollector abstracts the runtime/pprof and runtime/trace
// calls used by the /debug/profile endpoint. Tests override this
// with a stub to avoid process-global side-effects.
ProfileCollector ProfileCollector
// ProfileCollecting is used as a concurrency guard so that only one
// profile collection (via /debug/profile) can run at a time. The CPU
// profiler is process-global, so concurrent collections would fail.
ProfileCollecting atomic . Bool
2022-02-01 16:15:26 -06:00
}
2022-04-08 15:35:29 +01:00
2022-05-25 22:14:08 -05:00
// Close waits for all WebSocket connections to drain before returning.
2022-06-04 15:13:37 -05:00
func ( api * API ) Close () error {
2024-07-02 01:50:52 +10:00
select {
case <- api . ctx . Done ():
return xerrors . New ( "API already closed" )
default :
api . cancel ()
}
2023-02-10 20:23:02 +02:00
2024-03-25 22:04:15 -05:00
wsDone := make ( chan struct {})
timer := time . NewTimer ( 10 * time . Second )
defer timer . Stop ()
go func () {
api . WebsocketWaitMutex . Lock ()
defer api . WebsocketWaitMutex . Unlock ()
api . WebsocketWaitGroup . Wait ()
close ( wsDone )
}()
// This will technically leak the above func if the timer fires, but this is
// maintly a last ditch effort to un-stuck coderd on shutdown. This
// shouldn't affect tests at all.
select {
case <- wsDone :
case <- timer . C :
api . Logger . Warn ( api . ctx , "websocket shutdown timed out after 10 seconds" )
}
2024-03-22 18:42:43 +02:00
api . dbRolluper . Close ()
2026-03-10 18:46:01 +00:00
// chatDiffWorker is unconditionally initialized in New().
select {
case <- api . gitSyncWorker . Done ():
case <- time . After ( 10 * time . Second ):
api . Logger . Warn ( context . Background (),
"chat diff refresh worker did not exit in time" )
}
2026-02-27 11:50:56 -05:00
if err := api . chatDaemon . Close (); err != nil {
api . Logger . Warn ( api . ctx , "close chat processor" , slog . Error ( err ))
}
2022-09-01 14:58:23 -05:00
api . metricsCache . Close ()
2022-12-01 19:43:28 +02:00
if api . updateChecker != nil {
api . updateChecker . Close ()
}
2023-08-16 15:22:00 +03:00
_ = api . workspaceAppServer . Close ()
2024-11-20 17:04:33 +10:00
_ = api . agentProvider . Close ()
if api . derpCloseFunc != nil {
api . derpCloseFunc ()
}
// The coordinator should be closed after the agent provider, and the DERP
// handler.
2022-10-17 08:43:30 -05:00
coordinator := api . TailnetCoordinator . Load ()
if coordinator != nil {
_ = ( * coordinator ). Close ()
}
2024-06-10 15:35:23 -04:00
_ = api . statsReporter . Close ()
2026-01-22 22:47:49 -08:00
if api . metadataBatcher != nil {
api . metadataBatcher . Close ()
}
2024-07-02 01:50:52 +10:00
_ = api . NetworkTelemetryBatcher . Close ()
2024-10-25 17:14:35 +01:00
_ = api . OIDCConvertKeyCache . Close ()
_ = api . AppSigningKeyCache . Close ()
_ = api . AppEncryptionKeyCache . Close ()
2024-11-01 14:53:53 +11:00
_ = api . UpdatesProvider . Close ()
2025-04-25 11:07:15 +02:00
if current := api . PrebuildsReconciler . Load (); current != nil {
ctx , giveUp := context . WithTimeoutCause ( context . Background (), time . Second * 30 , xerrors . New ( "gave up waiting for reconciler to stop before shutdown" ))
defer giveUp ()
( * current ). Stop ( ctx , nil )
}
2023-07-12 17:37:31 -05:00
return nil
2022-05-25 22:14:08 -05:00
}
2022-06-13 13:14:22 -05:00
func compressHandler ( h http . Handler ) http . Handler {
2023-05-11 14:30:51 -05:00
level := 5
if flag . Lookup ( "test.v" ) != nil {
level = 1
}
cmp := middleware . NewCompressor ( level ,
2022-06-13 13:14:22 -05:00
"text/*" ,
"application/*" ,
"image/*" ,
)
2026-02-06 11:28:08 +04:00
for encoding := range site . StandardEncoders {
writeCloserFn := site . StandardEncoders [ encoding ]
cmp . SetEncoder ( encoding , func ( w io . Writer , level int ) io . Writer {
writeCloser := writeCloserFn ( w , level )
return writeCloser
})
}
2022-06-13 13:14:22 -05:00
return cmp . Handler ( h )
}
2022-11-16 16:34:06 -06:00
2025-05-16 11:47:59 -05:00
type MemoryProvisionerDaemonOption func ( * memoryProvisionerDaemonOptions )
func MemoryProvisionerWithVersionOverride ( version string ) MemoryProvisionerDaemonOption {
return func ( opts * memoryProvisionerDaemonOptions ) {
opts . versionOverride = version
}
}
2026-02-04 08:29:44 -06:00
func MemoryProvisionerWithHeartbeatOverride ( heartbeatFN func ( context . Context ) error ) MemoryProvisionerDaemonOption {
return func ( opts * memoryProvisionerDaemonOptions ) {
opts . heartbeatFn = heartbeatFN
}
}
2025-05-16 11:47:59 -05:00
type memoryProvisionerDaemonOptions struct {
versionOverride string
2026-02-04 08:29:44 -06:00
heartbeatFn func ( context . Context ) error
2025-05-16 11:47:59 -05:00
}
2022-12-01 16:54:53 -06:00
// CreateInMemoryProvisionerDaemon is an in-memory connection to a provisionerd.
// Useful when starting coderd and provisionerd in the same process.
2024-05-03 10:14:26 -05:00
func ( api * API ) CreateInMemoryProvisionerDaemon ( dialCtx context . Context , name string , provisionerTypes [] codersdk . ProvisionerType ) ( client proto . DRPCProvisionerDaemonClient , err error ) {
2024-06-04 13:59:54 +02:00
return api . CreateInMemoryTaggedProvisionerDaemon ( dialCtx , name , provisionerTypes , nil )
}
2025-05-16 11:47:59 -05:00
func ( api * API ) CreateInMemoryTaggedProvisionerDaemon ( dialCtx context . Context , name string , provisionerTypes [] codersdk . ProvisionerType , provisionerTags map [ string ] string , opts ... MemoryProvisionerDaemonOption ) ( client proto . DRPCProvisionerDaemonClient , err error ) {
options := & memoryProvisionerDaemonOptions {}
for _ , opt := range opts {
opt ( options )
}
2023-05-03 18:02:35 -05:00
tracer := api . TracerProvider . Tracer ( tracing . TracerName )
2025-05-12 10:31:38 -05:00
clientSession , serverSession := drpcsdk . MemTransportPipe ()
2022-11-16 16:34:06 -06:00
defer func () {
if err != nil {
_ = clientSession . Close ()
_ = serverSession . Close ()
}
}()
2024-03-06 12:04:50 -06:00
// All in memory provisioners will be part of the default org for now.
//nolint:gocritic // in-memory provisioners are owned by system
defaultOrg , err := api . Database . GetDefaultOrganization ( dbauthz . AsSystemRestricted ( dialCtx ))
if err != nil {
return nil , xerrors . Errorf ( "unable to fetch default org for in memory provisioner: %w" , err )
}
2024-05-03 10:14:26 -05:00
dbTypes := make ([] database . ProvisionerType , 0 , len ( provisionerTypes ))
for _ , tp := range provisionerTypes {
dbTypes = append ( dbTypes , database . ProvisionerType ( tp ))
}
2024-09-16 16:02:08 -04:00
keyID , err := uuid . Parse ( string ( codersdk . ProvisionerKeyIDBuiltIn ))
if err != nil {
return nil , xerrors . Errorf ( "failed to parse built-in provisioner key ID: %w" , err )
}
2025-05-16 11:47:59 -05:00
apiVersion := proto . CurrentVersion . String ()
if options . versionOverride != "" && flag . Lookup ( "test.v" ) != nil {
// This should only be usable for unit testing. To fake a different provisioner version
apiVersion = options . versionOverride
}
2023-12-18 16:44:52 +00:00
//nolint:gocritic // in-memory provisioners are owned by system
2024-01-10 15:29:57 +04:00
daemon , err := api . Database . UpsertProvisionerDaemon ( dbauthz . AsSystemRestricted ( dialCtx ), database . UpsertProvisionerDaemonParams {
2024-03-06 12:04:50 -06:00
Name : name ,
OrganizationID : defaultOrg . ID ,
CreatedAt : dbtime . Now (),
2024-05-03 10:14:26 -05:00
Provisioners : dbTypes ,
2024-06-04 13:59:54 +02:00
Tags : provisionersdk . MutateTags ( uuid . Nil , provisionerTags ),
2024-05-03 10:14:26 -05:00
LastSeenAt : sql . NullTime { Time : dbtime . Now (), Valid : true },
Version : buildinfo . Version (),
2025-05-16 11:47:59 -05:00
APIVersion : apiVersion ,
2024-09-16 16:02:08 -04:00
KeyID : keyID ,
2023-12-18 16:44:52 +00:00
})
if err != nil {
return nil , xerrors . Errorf ( "failed to create in-memory provisioner daemon: %w" , err )
2022-11-16 16:34:06 -06:00
}
mux := drpcmux . New ()
2024-09-24 13:16:36 +10:00
api . Logger . Debug ( dialCtx , "starting in-memory provisioner daemon" , slog . F ( "name" , name ))
2023-09-08 14:37:36 +04:00
logger := api . Logger . Named ( fmt . Sprintf ( "inmem-provisionerd-%s" , name ))
2023-08-30 14:48:35 +04:00
srv , err := provisionerdserver . NewServer (
2023-12-18 16:44:52 +00:00
api . ctx , // use the same ctx as the API
2025-05-14 12:21:36 -05:00
daemon . APIVersion ,
2023-08-30 14:48:35 +04:00
api . AccessURL ,
2023-12-18 16:44:52 +00:00
daemon . ID ,
2024-03-18 12:48:13 -05:00
defaultOrg . ID ,
2023-09-08 14:37:36 +04:00
logger ,
2023-12-18 16:44:52 +00:00
daemon . Provisioners ,
provisionerdserver . Tags ( daemon . Tags ),
2023-08-30 14:48:35 +04:00
api . Database ,
api . Pubsub ,
2023-09-19 10:25:57 +04:00
api . Acquirer ,
2023-08-30 14:48:35 +04:00
api . Telemetry ,
tracer ,
& api . QuotaCommitter ,
& api . Auditor ,
api . TemplateScheduleStore ,
api . UserQuietHoursScheduleStore ,
2025-08-20 23:38:09 +10:00
api . UsageInserter ,
2023-08-30 14:48:35 +04:00
api . DeploymentValues ,
provisionerdserver . Options {
2023-09-29 14:13:20 -05:00
OIDCConfig : api . OIDCConfig ,
ExternalAuthConfigs : api . ExternalAuthConfigs ,
2026-03-16 12:36:26 -05:00
AISeatTracker : api . AISeatTracker ,
2024-11-25 16:25:36 +00:00
Clock : api . Clock ,
2026-02-04 08:29:44 -06:00
HeartbeatFn : options . heartbeatFn ,
2023-08-30 14:48:35 +04:00
},
2024-07-08 15:38:50 +02:00
api . NotificationsEnqueuer ,
2025-05-14 14:52:22 +02:00
& api . PrebuildsReconciler ,
2025-08-28 15:00:26 +01:00
api . ProvisionerdServerMetrics ,
2025-11-12 14:26:15 -06:00
api . Experiments ,
2023-08-30 14:48:35 +04:00
)
if err != nil {
return nil , err
}
err = proto . DRPCRegisterProvisionerDaemon ( mux , srv )
2022-11-16 16:34:06 -06:00
if err != nil {
return nil , err
}
2023-05-03 18:02:35 -05:00
server := drpcserver . NewWithOptions ( & tracing . DRPCHandler { Handler : mux },
drpcserver . Options {
2025-05-13 11:24:51 -05:00
Manager : drpcsdk . DefaultDRPCOptions ( nil ),
2023-05-03 18:02:35 -05:00
Log : func ( err error ) {
if xerrors . Is ( err , io . EOF ) {
return
}
2024-01-10 15:29:57 +04:00
logger . Debug ( dialCtx , "drpc server error" , slog . Error ( err ))
2023-05-03 18:02:35 -05:00
},
2022-11-16 16:34:06 -06:00
},
2023-05-03 18:02:35 -05:00
)
2024-01-10 15:29:57 +04:00
// in-mem pipes aren't technically "websockets" but they have the same properties as far as the
// API is concerned: they are long-lived connections that we need to close before completing
// shutdown of the API.
api . WebsocketWaitMutex . Lock ()
api . WebsocketWaitGroup . Add ( 1 )
api . WebsocketWaitMutex . Unlock ()
2022-11-16 16:34:06 -06:00
go func () {
2024-01-10 15:29:57 +04:00
defer api . WebsocketWaitGroup . Done ()
// here we pass the background context, since we want the server to keep serving until the
// client hangs up. If we, say, pass the API context, then when it is canceled, we could
// drop a job that we locked in the database but never passed to the provisionerd. The
// provisionerd is local, in-mem, so there isn't a danger of losing contact with it and
// having a dead connection we don't know the status of.
err := server . Serve ( context . Background (), serverSession )
logger . Info ( dialCtx , "provisioner daemon disconnected" , slog . Error ( err ))
2023-09-08 14:37:36 +04:00
// close the sessions, so we don't leak goroutines serving them.
2022-11-16 16:34:06 -06:00
_ = clientSession . Close ()
_ = serverSession . Close ()
}()
2022-11-22 12:19:32 -06:00
return proto . NewDRPCProvisionerDaemonClient ( clientSession ), nil
2022-11-16 16:34:06 -06:00
}
2023-01-18 19:12:53 +00:00
2023-07-26 09:21:04 -07:00
func ( api * API ) DERPMap () * tailcfg . DERPMap {
fn := api . DERPMapper . Load ()
if fn != nil {
return ( * fn )( api . Options . BaseDERPMap )
}
return api . Options . BaseDERPMap
}
2023-01-18 19:12:53 +00:00
// nolint:revive
2023-07-19 11:11:11 -05:00
func ReadExperiments ( log slog . Logger , raw [] string ) codersdk . Experiments {
2023-01-18 19:12:53 +00:00
exps := make ([] codersdk . Experiment , 0 , len ( raw ))
for _ , v := range raw {
switch v {
case "*" :
2025-04-22 11:21:15 -05:00
exps = append ( exps , codersdk . ExperimentsSafe ... )
2023-01-18 19:12:53 +00:00
default :
ex := codersdk . Experiment ( strings . ToLower ( v ))
2025-06-24 09:14:41 +01:00
if ! slice . Contains ( codersdk . ExperimentsKnown , ex ) {
log . Warn ( context . Background (), "ignoring unknown experiment" , slog . F ( "experiment" , ex ))
} else if ! slice . Contains ( codersdk . ExperimentsSafe , ex ) {
2023-01-18 19:12:53 +00:00
log . Warn ( context . Background (), "🐉 HERE BE DRAGONS: opting into hidden experiment" , slog . F ( "experiment" , ex ))
}
exps = append ( exps , ex )
}
}
return exps
}
2025-02-12 09:23:28 +01:00
var multipleSlashesRe = regexp . MustCompile ( `/+` )
func singleSlashMW ( next http . Handler ) http . Handler {
fn := func ( w http . ResponseWriter , r * http . Request ) {
var path string
rctx := chi . RouteContext ( r . Context ())
if rctx != nil && rctx . RoutePath != "" {
path = rctx . RoutePath
} else {
path = r . URL . Path
}
// Normalize multiple slashes to a single slash
newPath := multipleSlashesRe . ReplaceAllString ( path , "/" )
// Apply the cleaned path
// The approach is consistent with: https://github.com/go-chi/chi/blob/e846b8304c769c4f1a51c9de06bebfaa4576bd88/middleware/strip.go#L24-L28
if rctx != nil {
rctx . RoutePath = newPath
} else {
r . URL . Path = newPath
}
next . ServeHTTP ( w , r )
}
return http . HandlerFunc ( fn )
}