coderd

package
v2.10.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 22, 2024 License: AGPL-3.0 Imports: 126 Imported by: 0

Documentation

Index

Constants

View Source
const AgentAPIVersionREST = "1.0"
View Source
const (
	OAuthConvertCookieValue = "coder_oauth_convert_jwt"
)

Variables

This section is empty.

Functions

func AuthorizeFilter

func AuthorizeFilter[O rbac.Objecter](h *HTTPAuthorizer, r *http.Request, action rbac.Action, objects []O) ([]O, error)

AuthorizeFilter takes a list of objects and returns the filtered list of objects that the user is authorized to perform the given action on. This is faster than calling Authorize() on each object.

func CreateTarFromZip added in v2.8.0

func CreateTarFromZip(zipReader *zip.Reader) ([]byte, error)

func CreateZipFromTar added in v2.8.0

func CreateZipFromTar(tarReader *tar.Reader) ([]byte, error)

func ExternalAuthConfig added in v2.5.0

func ExternalAuthConfig(cfg *externalauth.Config) codersdk.ExternalAuthLinkProvider

func ExternalAuthConfigs added in v2.5.0

func ExternalAuthConfigs(auths []*externalauth.Config) []codersdk.ExternalAuthLinkProvider

func LatencyCheck

func LatencyCheck() http.HandlerFunc

LatencyCheck is an endpoint for the web ui to measure latency with. allowAll allows any Origin to get timing information. The allowAll should only be set in dev modes.

func ReadExperiments

func ReadExperiments(log slog.Logger, raw []string) codersdk.Experiments

nolint:revive

func UpdateSiteUserRoles

func UpdateSiteUserRoles(ctx context.Context, db database.Store, args database.UpdateUserRolesParams) (database.User, error)

UpdateSiteUserRoles will ensure only site wide roles are passed in as arguments. If an organization role is included, an error is returned.

func WriteZipArchive added in v2.8.0

func WriteZipArchive(w io.Writer, tarReader *tar.Reader) error

Types

type API

type API struct {

	// DeploymentID is loaded from the database on startup.
	DeploymentID string

	*Options
	// 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
	Auditor                           atomic.Pointer[audit.Auditor]
	WorkspaceClientCoordinateOverride atomic.Pointer[func(rw http.ResponseWriter) bool]
	TailnetCoordinator                atomic.Pointer[tailnet.Coordinator]
	TailnetClientService              *tailnet.ClientService
	QuotaCommitter                    atomic.Pointer[proto.QuotaCommitter]
	AppearanceFetcher                 atomic.Pointer[appearance.Fetcher]
	// WorkspaceProxyHostsFn returns the hosts of healthy workspace proxies
	// for header reasons.
	WorkspaceProxyHostsFn atomic.Pointer[func() []string]
	// 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]
	// UserQuietHoursScheduleStore is a pointer to an atomic pointer for the
	// same reason as TemplateScheduleStore.
	UserQuietHoursScheduleStore *atomic.Pointer[schedule.UserQuietHoursScheduleStore]
	// DERPMapper mutates the DERPMap to include workspace proxies.
	DERPMapper atomic.Pointer[func(derpMap *tailcfg.DERPMap) *tailcfg.DERPMap]
	// AccessControlStore is a pointer to an atomic pointer since it is
	// passed to dbauthz.
	AccessControlStore *atomic.Pointer[dbauthz.AccessControlStore]
	PortSharer         atomic.Pointer[portsharing.PortSharer]

	HTTPAuth *HTTPAuthorizer

	// APIHandler serves "/api/v2"
	APIHandler chi.Router
	// RootHandler serves "/"
	RootHandler chi.Router

	// SiteHandler serves static files for the dashboard.
	SiteHandler *site.Handler

	WebsocketWaitMutex sync.Mutex
	WebsocketWaitGroup sync.WaitGroup

	WorkspaceAppsProvider workspaceapps.SignedTokenProvider

	// Experiments contains the list of experiments currently enabled.
	// This is used to gate features that are not yet ready for production.
	Experiments codersdk.Experiments

	Acquirer *provisionerdserver.Acquirer
	// contains filtered or unexported fields
}

func New

func New(options *Options) *API

@securitydefinitions.apiKey CoderSessionToken @in header @name Coder-Session-Token New constructs a Coder API handler.

func (*API) Authorize

func (api *API) Authorize(r *http.Request, action rbac.Action, object rbac.Objecter) bool

Authorize will return false if the user is not authorized to do the action. This function will log appropriately, but the caller must return an error to the api client. Eg:

if !api.Authorize(...) {
	httpapi.Forbidden(rw)
	return
}

func (*API) Close

func (api *API) Close() error

Close waits for all WebSocket connections to drain before returning.

func (*API) CreateInMemoryProvisionerDaemon

func (api *API) CreateInMemoryProvisionerDaemon(dialCtx context.Context, name string) (client proto.DRPCProvisionerDaemonClient, err error)

CreateInMemoryProvisionerDaemon is an in-memory connection to a provisionerd. Useful when starting coderd and provisionerd in the same process.

func (*API) CreateUser

func (api *API) CreateUser(ctx context.Context, store database.Store, req CreateUserRequest) (database.User, uuid.UUID, error)

func (*API) DERPMap

func (api *API) DERPMap() *tailcfg.DERPMap

func (*API) GetUsers

func (api *API) GetUsers(rw http.ResponseWriter, r *http.Request) ([]database.User, int64, bool)

func (*API) PrimaryRegion

func (api *API) PrimaryRegion(ctx context.Context) (codersdk.Region, error)

PrimaryRegion exposes the user facing values of a workspace proxy to be used by a user.

func (*API) PrimaryWorkspaceProxy

func (api *API) PrimaryWorkspaceProxy(ctx context.Context) (database.WorkspaceProxy, error)

PrimaryWorkspaceProxy returns the primary workspace proxy for the site.

func (*API) ValidWorkspaceAppHostname

func (api *API) ValidWorkspaceAppHostname(ctx context.Context, host string, opts ValidWorkspaceAppHostnameOpts) (string, error)

ValidWorkspaceAppHostname checks if the given host is a valid workspace app hostname based on the provided options. It returns a scheme to force on success. If the hostname is not valid or doesn't match, an empty string is returned. Any error returned is a 500 error.

For hosts that match a wildcard app hostname, the scheme is forced to be the corresponding access URL scheme.

type CreateUserRequest

type CreateUserRequest struct {
	codersdk.CreateUserRequest
	LoginType database.LoginType
}

type GithubOAuth2Config

type GithubOAuth2Config struct {
	promoauth.OAuth2Config
	AuthenticatedUser           func(ctx context.Context, client *http.Client) (*github.User, error)
	ListEmails                  func(ctx context.Context, client *http.Client) ([]*github.UserEmail, error)
	ListOrganizationMemberships func(ctx context.Context, client *http.Client) ([]*github.Membership, error)
	TeamMembership              func(ctx context.Context, client *http.Client, org, team, username string) (*github.Membership, error)

	AllowSignups       bool
	AllowEveryone      bool
	AllowOrganizations []string
	AllowTeams         []GithubOAuth2Team
}

GithubOAuth2Provider exposes required functions for the Github authentication flow.

type GithubOAuth2Team

type GithubOAuth2Team struct {
	Organization string
	Slug         string
}

GithubOAuth2Team represents a team scoped to an organization.

type HTTPAuthorizer

type HTTPAuthorizer struct {
	Authorizer rbac.Authorizer
	Logger     slog.Logger
}

func (*HTTPAuthorizer) Authorize

func (h *HTTPAuthorizer) Authorize(r *http.Request, action rbac.Action, object rbac.Objecter) bool

Authorize will return false if the user is not authorized to do the action. This function will log appropriately, but the caller must return an error to the api client. Eg:

if !h.Authorize(...) {
	httpapi.Forbidden(rw)
	return
}

func (*HTTPAuthorizer) AuthorizeSQLFilter

func (h *HTTPAuthorizer) AuthorizeSQLFilter(r *http.Request, action rbac.Action, objectType string) (rbac.PreparedAuthorized, error)

AuthorizeSQLFilter returns an authorization filter that can used in a SQL 'WHERE' clause. If the filter is used, the resulting rows returned from postgres are already authorized, and the caller does not need to call 'Authorize()' on the returned objects. Note the authorization is only for the given action and object type.

type OAuthConvertStateClaims

type OAuthConvertStateClaims struct {
	jwt.RegisteredClaims

	UserID        uuid.UUID          `json:"user_id"`
	State         string             `json:"state"`
	FromLoginType codersdk.LoginType `json:"from_login_type"`
	ToLoginType   codersdk.LoginType `json:"to_login_type"`
}

type OIDCConfig

type OIDCConfig struct {
	promoauth.OAuth2Config

	Provider *oidc.Provider
	Verifier *oidc.IDTokenVerifier
	// EmailDomains are the domains to enforce when a user authenticates.
	EmailDomain  []string
	AllowSignups bool
	// IgnoreEmailVerified allows ignoring the email_verified claim
	// from an upstream OIDC provider. See #5065 for context.
	IgnoreEmailVerified bool
	// UsernameField selects the claim field to be used as the created user's
	// username.
	UsernameField string
	// EmailField selects the claim field to be used as the created user's
	// email.
	EmailField string
	// AuthURLParams are additional parameters to be passed to the OIDC provider
	// when requesting an access token.
	AuthURLParams map[string]string
	// IgnoreUserInfo causes Coder to only use claims from the ID token to
	// process OIDC logins. This is useful if the OIDC provider does not
	// support the userinfo endpoint, or if the userinfo endpoint causes
	// undesirable behavior.
	IgnoreUserInfo bool
	// GroupField selects the claim field to be used as the created user's
	// groups. If the group field is the empty string, then no group updates
	// will ever come from the OIDC provider.
	GroupField string
	// CreateMissingGroups controls whether groups returned by the OIDC provider
	// are automatically created in Coder if they are missing.
	CreateMissingGroups bool
	// GroupFilter is a regular expression that filters the groups returned by
	// the OIDC provider. Any group not matched by this regex will be ignored.
	// If the group filter is nil, then no group filtering will occur.
	GroupFilter *regexp.Regexp
	// GroupAllowList is a list of groups that are allowed to log in.
	// If the list length is 0, then the allow list will not be applied and
	// this feature is disabled.
	GroupAllowList map[string]bool
	// GroupMapping controls how groups returned by the OIDC provider get mapped
	// to groups within Coder.
	// map[oidcGroupName]coderGroupName
	GroupMapping map[string]string
	// UserRoleField selects the claim field to be used as the created user's
	// roles. If the field is the empty string, then no role updates
	// will ever come from the OIDC provider.
	UserRoleField string
	// UserRoleMapping controls how groups returned by the OIDC provider get mapped
	// to roles within Coder.
	// map[oidcRoleName][]coderRoleName
	UserRoleMapping map[string][]string
	// UserRolesDefault is the default set of roles to assign to a user if role sync
	// is enabled.
	UserRolesDefault []string
	// SignInText is the text to display on the OIDC login button
	SignInText string
	// IconURL points to the URL of an icon to display on the OIDC login button
	IconURL string
	// SignupsDisabledText is the text do display on the static error page.
	SignupsDisabledText string
}

func (OIDCConfig) RoleSyncEnabled

func (cfg OIDCConfig) RoleSyncEnabled() bool

type OauthDebugContext added in v2.5.0

type OauthDebugContext struct {
	IDTokenClaims  map[string]interface{} `json:"id_token_claims"`
	UserInfoClaims map[string]interface{} `json:"user_info_claims"`
}

OauthDebugContext provides helpful information for admins to debug OAuth login issues.

type Options

type Options struct {
	AccessURL *url.URL
	// AppHostname should be the wildcard hostname to use for workspace
	// applications INCLUDING the asterisk, (optional) suffix and leading dot.
	// It will use the same scheme and port number as the access URL.
	// E.g. "*.apps.coder.com" or "*-apps.coder.com" or "*.apps.coder.com:8080".
	AppHostname string
	// AppHostnameRegex contains the regex version of options.AppHostname as
	// generated by appurl.CompileHostnamePattern(). It MUST be set if
	// options.AppHostname is set.
	AppHostnameRegex *regexp.Regexp
	Logger           slog.Logger
	Database         database.Store
	Pubsub           pubsub.Pubsub

	// CacheDir is used for caching files served by the API.
	CacheDir string

	Auditor                        audit.Auditor
	AgentConnectionUpdateFrequency time.Duration
	AgentInactiveDisconnectTimeout time.Duration
	AWSCertificates                awsidentity.Certificates
	Authorizer                     rbac.Authorizer
	AzureCertificates              x509.VerifyOptions
	GoogleTokenValidator           *idtoken.Validator
	GithubOAuth2Config             *GithubOAuth2Config
	OIDCConfig                     *OIDCConfig
	PrometheusRegistry             *prometheus.Registry
	SecureAuthCookie               bool
	StrictTransportSecurityCfg     httpmw.HSTSConfig
	SSHKeygenAlgorithm             gitsshkey.Algorithm
	Telemetry                      telemetry.Reporter
	TracerProvider                 trace.TracerProvider
	ExternalAuthConfigs            []*externalauth.Config
	RealIPConfig                   *httpmw.RealIPConfig
	TrialGenerator                 func(ctx context.Context, body codersdk.LicensorTrialRequest) error
	// RefreshEntitlements is used to set correct entitlements after creating first user and generating trial license.
	RefreshEntitlements func(ctx context.Context) error
	// 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.
	PostAuthAdditionalHeadersFunc func(auth rbac.Subject, header http.Header)

	// TLSCertificates is used to mesh DERP servers securely.
	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.
	BaseDERPMap                 *tailcfg.DERPMap
	DERPMapUpdateFrequency      time.Duration
	SwaggerEndpoint             bool
	SetUserGroups               func(ctx context.Context, logger slog.Logger, tx database.Store, userID uuid.UUID, orgGroupNames map[uuid.UUID][]string, createMissingGroups bool) error
	SetUserSiteRoles            func(ctx context.Context, logger slog.Logger, tx database.Store, userID uuid.UUID, roles []string) error
	TemplateScheduleStore       *atomic.Pointer[schedule.TemplateScheduleStore]
	UserQuietHoursScheduleStore *atomic.Pointer[schedule.UserQuietHoursScheduleStore]
	AccessControlStore          *atomic.Pointer[dbauthz.AccessControlStore]
	// AppSecurityKey is the crypto key used to sign and encrypt tokens related to
	// workspace applications. It consists of both a signing and encryption key.
	AppSecurityKey workspaceapps.SecurityKey

	HealthcheckFunc              func(ctx context.Context, apiKey string) *healthsdk.HealthcheckReport
	HealthcheckTimeout           time.Duration
	HealthcheckRefresh           time.Duration
	WorkspaceProxiesFetchUpdater *atomic.Pointer[healthcheck.WorkspaceProxiesFetchUpdater]

	// 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

	// 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

	MetricsCacheRefreshInterval time.Duration
	AgentStatsRefreshInterval   time.Duration
	DeploymentValues            *codersdk.DeploymentValues
	// 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.
	DeploymentOptions  serpent.OptionSet
	UpdateCheckOptions *updatecheck.Options // Set non-nil to enable update checking.

	// SSHConfig is the response clients use to configure config-ssh locally.
	SSHConfig codersdk.SSHConfigResponse

	HTTPClient *http.Client

	UpdateAgentMetrics func(ctx context.Context, labels prometheusmetrics.AgentMetricLabels, metrics []*agentproto.Stats_Metric)
	StatsBatcher       *batchstats.Batcher

	WorkspaceAppsStatsCollectorOptions workspaceapps.StatsCollectorOptions

	// 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.
	ParseLicenseClaims    func(rawJWT string) (email string, trial bool, err error)
	AllowWorkspaceRenames bool

	// NewTicker is used for unit tests to replace "time.NewTicker".
	NewTicker func(duration time.Duration) (tick <-chan time.Time, done func())

	// DatabaseRolluper rolls up template usage stats from raw agent and app
	// stats. This is used to provide insights in the WebUI.
	DatabaseRolluper *dbrollup.Rolluper
	// WorkspaceUsageTracker tracks workspace usage by the CLI.
	WorkspaceUsageTracker *workspaceusage.Tracker
}

Options are requires parameters for Coder to start.

type ServerTailnet

type ServerTailnet struct {
	// contains filtered or unexported fields
}

func NewServerTailnet

func NewServerTailnet(
	ctx context.Context,
	logger slog.Logger,
	derpServer *derp.Server,
	derpMapFn func() *tailcfg.DERPMap,
	derpForceWebSockets bool,
	getMultiAgent func(context.Context) (tailnet.MultiAgentConn, error),
	blockEndpoints bool,
	traceProvider trace.TracerProvider,
) (*ServerTailnet, error)

NewServerTailnet creates a new tailnet intended for use by coderd.

func (*ServerTailnet) AgentConn

func (s *ServerTailnet) AgentConn(ctx context.Context, agentID uuid.UUID) (*workspacesdk.AgentConn, func(), error)

func (*ServerTailnet) Close

func (s *ServerTailnet) Close() error

func (*ServerTailnet) Collect added in v2.8.0

func (s *ServerTailnet) Collect(metrics chan<- prometheus.Metric)

func (*ServerTailnet) Conn added in v2.9.0

func (s *ServerTailnet) Conn() *tailnet.Conn

Conn is used to access the underlying tailnet conn of the ServerTailnet. It should only be used for read-only purposes.

func (*ServerTailnet) Describe added in v2.8.0

func (s *ServerTailnet) Describe(descs chan<- *prometheus.Desc)

func (*ServerTailnet) DialAgentNetConn

func (s *ServerTailnet) DialAgentNetConn(ctx context.Context, agentID uuid.UUID, network, addr string) (net.Conn, error)

func (*ServerTailnet) ReverseProxy

func (s *ServerTailnet) ReverseProxy(targetURL, dashboardURL *url.URL, agentID uuid.UUID) *httputil.ReverseProxy

func (*ServerTailnet) ServeHTTPDebug added in v2.4.0

func (s *ServerTailnet) ServeHTTPDebug(w http.ResponseWriter, r *http.Request)

type ValidWorkspaceAppHostnameOpts

type ValidWorkspaceAppHostnameOpts struct {
	AllowPrimaryAccessURL bool
	AllowPrimaryWildcard  bool
	AllowProxyAccessURL   bool
	AllowProxyWildcard    bool
}

Directories

Path Synopsis
Package apidoc GENERATED BY SWAG; DO NOT EDIT This file was generated by swaggo/swag
Package apidoc GENERATED BY SWAG; DO NOT EDIT This file was generated by swaggo/swag
Package autobuild contains logic for scheduling workspace builds in the background.
Package autobuild contains logic for scheduling workspace builds in the background.
Package database connects to external services for stateful storage.
Package database connects to external services for stateful storage.
db2sdk
Package db2sdk provides common conversion routines from database types to codersdk types
Package db2sdk provides common conversion routines from database types to codersdk types
dbauthz
Package dbauthz provides an authorization layer on top of the database.
Package dbauthz provides an authorization layer on top of the database.
dbmetrics
Code generated by coderd/database/gen/metrics.
Code generated by coderd/database/gen/metrics.
dbmock
Package dbmock is a generated GoMock package.
Package dbmock is a generated GoMock package.
gentest
Package gentest contains tests that are run at db generate time.
Package gentest contains tests that are run at db generate time.
httpapiconstraints
Package httpapiconstraints contain types that can be used and implemented across the application to return specific HTTP status codes without pulling in large dependency trees.
Package httpapiconstraints contain types that can be used and implemented across the application to return specific HTTP status codes without pulling in large dependency trees.
Package promoauth is for instrumenting oauth2 flows with prometheus metrics.
Package promoauth is for instrumenting oauth2 flows with prometheus metrics.
Code generated by rbacgen/main.go.
Code generated by rbacgen/main.go.
regosql
Package regosql converts rego queries into SQL WHERE clauses.
Package regosql converts rego queries into SQL WHERE clauses.
regosql/sqltypes
Package sqltypes contains the types used to convert rego queries into SQL.
Package sqltypes contains the types used to convert rego queries into SQL.
cron
package schedule provides utilities for managing template and workspace autostart and autostop schedules.
package schedule provides utilities for managing template and workspace autostart and autostop schedules.
Package updatecheck provides a mechanism for periodically checking for updates to Coder.
Package updatecheck provides a mechanism for periodically checking for updates to Coder.
util
lazy
Package lazy provides a lazy value implementation.
Package lazy provides a lazy value implementation.
ptr
Package ptr contains some utility methods related to pointers.
Package ptr contains some utility methods related to pointers.
tz
Package tz includes utilities for cross-platform timezone/location detection.
Package tz includes utilities for cross-platform timezone/location detection.
xio
appurl
Package appurl handles all parsing/validation/etc around application URLs.
Package appurl handles all parsing/validation/etc around application URLs.
Package wsbuilder provides the Builder object, which encapsulates the common business logic of inserting a new workspace build into the database.
Package wsbuilder provides the Builder object, which encapsulates the common business logic of inserting a new workspace build into the database.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL