codersdk

package
v2.21.3 Latest Latest
Warning

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

Go to latest
Published: Apr 29, 2025 License: AGPL-3.0 Imports: 51 Imported by: 8

Documentation

Overview

Code generated by typegen/main.go. DO NOT EDIT.

Index

Constants

View Source
const (
	// SessionTokenCookie represents the name of the cookie or query parameter the API key is stored in.
	SessionTokenCookie = "coder_session_token"
	// SessionTokenHeader is the custom header to use for authentication.
	SessionTokenHeader = "Coder-Session-Token"
	// OAuth2StateCookie is the name of the cookie that stores the oauth2 state.
	OAuth2StateCookie = "oauth_state"
	// OAuth2RedirectCookie is the name of the cookie that stores the oauth2 redirect.
	OAuth2RedirectCookie = "oauth_redirect"

	// PathAppSessionTokenCookie is the name of the cookie that stores an
	// application-scoped API token on workspace proxy path app domains.
	//nolint:gosec
	PathAppSessionTokenCookie = "coder_path_app_session_token"
	// SubdomainAppSessionTokenCookie is the name of the cookie that stores an
	// application-scoped API token on subdomain app domains (both the primary
	// and proxies).
	//nolint:gosec
	SubdomainAppSessionTokenCookie = "coder_subdomain_app_session_token"
	// SignedAppTokenCookie is the name of the cookie that stores a temporary
	// JWT that can be used to authenticate instead of the app session token.
	//nolint:gosec
	SignedAppTokenCookie = "coder_signed_app_token"
	// SignedAppTokenQueryParameter is the name of the query parameter that
	// stores a temporary JWT that can be used to authenticate instead of the
	// session token. This is only acceptable on reconnecting-pty requests, not
	// apps.
	//
	// It has a random suffix to avoid conflict with user query parameters on
	// apps.
	//nolint:gosec
	SignedAppTokenQueryParameter = "coder_signed_app_token_23db1dde"

	// BypassRatelimitHeader is the custom header to use to bypass ratelimits.
	// Only owners can bypass rate limits. This is typically used for scale testing.
	// nolint: gosec
	BypassRatelimitHeader = "X-Coder-Bypass-Ratelimit"

	// CLITelemetryHeader contains a base64-encoded representation of the CLI
	// command that was invoked to produce the request. It is for internal use
	// only.
	CLITelemetryHeader = "Coder-CLI-Telemetry"

	// CoderDesktopTelemetryHeader contains a JSON-encoded representation of Desktop telemetry
	// fields, including device ID, OS, and Desktop version.
	CoderDesktopTelemetryHeader = "Coder-Desktop-Telemetry"

	// ProvisionerDaemonPSK contains the authentication pre-shared key for an external provisioner daemon
	ProvisionerDaemonPSK = "Coder-Provisioner-Daemon-PSK"

	// ProvisionerDaemonKey contains the authentication key for an external provisioner daemon
	ProvisionerDaemonKey = "Coder-Provisioner-Daemon-Key"

	// BuildVersionHeader contains build information of Coder.
	BuildVersionHeader = "X-Coder-Build-Version"

	// EntitlementsWarnings contains active warnings for the user's entitlements.
	EntitlementsWarningHeader = "X-Coder-Entitlements-Warning"
)

These cookies are Coder-specific. If a new one is added or changed, the name shouldn't be likely to conflict with any user-application set cookies. Be sure to strip additional cookies in httpapi.StripCoderCookies!

View Source
const (
	ContentTypeTar = "application/x-tar"
	ContentTypeZip = "application/zip"

	FormatZip = "zip"
)
View Source
const (
	InboxNotificationFallbackIconWorkspace = "DEFAULT_ICON_WORKSPACE"
	InboxNotificationFallbackIconAccount   = "DEFAULT_ICON_ACCOUNT"
	InboxNotificationFallbackIconTemplate  = "DEFAULT_ICON_TEMPLATE"
	InboxNotificationFallbackIconOther     = "DEFAULT_ICON_OTHER"
)
View Source
const (
	TemplateBuiltinAppDisplayNameVSCode      string = "Visual Studio Code"
	TemplateBuiltinAppDisplayNameJetBrains   string = "JetBrains"
	TemplateBuiltinAppDisplayNameWebTerminal string = "Web Terminal"
	TemplateBuiltinAppDisplayNameSSH         string = "SSH"
	TemplateBuiltinAppDisplayNameSFTP        string = "SFTP"
)

Enums define the display name of the builtin app reported.

View Source
const (
	LicenseExpiryClaim                = "license_expires"
	LicenseTelemetryRequiredErrorText = "License requires telemetry but telemetry is disabled"
)
View Source
const (
	LogSourceProvisionerDaemon LogSource = "provisioner_daemon"
	LogSourceProvisioner       LogSource = "provisioner"

	LogLevelTrace LogLevel = "trace"
	LogLevelDebug LogLevel = "debug"
	LogLevelInfo  LogLevel = "info"
	LogLevelWarn  LogLevel = "warn"
	LogLevelError LogLevel = "error"
)
View Source
const (
	ProvisionerKeyIDBuiltIn  = "00000000-0000-0000-0000-000000000001"
	ProvisionerKeyIDUserAuth = "00000000-0000-0000-0000-000000000002"
	ProvisionerKeyIDPSK      = "00000000-0000-0000-0000-000000000003"
)
View Source
const (
	ProvisionerKeyNameBuiltIn  = "built-in"
	ProvisionerKeyNameUserAuth = "user-auth"
	ProvisionerKeyNamePSK      = "psk"
)
View Source
const (
	RoleOwner         string = "owner"
	RoleMember        string = "member"
	RoleTemplateAdmin string = "template-admin"
	RoleUserAdmin     string = "user-admin"
	RoleAuditor       string = "auditor"

	RoleOrganizationAdmin                string = "organization-admin"
	RoleOrganizationMember               string = "organization-member"
	RoleOrganizationAuditor              string = "organization-auditor"
	RoleOrganizationTemplateAdmin        string = "organization-template-admin"
	RoleOrganizationUserAdmin            string = "organization-user-admin"
	RoleOrganizationWorkspaceCreationBan string = "organization-workspace-creation-ban"
)

Ideally this roles would be generated from the rbac/roles.go package.

View Source
const (
	WorkspaceAgentPortShareLevelOwner         WorkspaceAgentPortShareLevel = "owner"
	WorkspaceAgentPortShareLevelAuthenticated WorkspaceAgentPortShareLevel = "authenticated"
	WorkspaceAgentPortShareLevelPublic        WorkspaceAgentPortShareLevel = "public"

	WorkspaceAgentPortShareProtocolHTTP  WorkspaceAgentPortShareProtocol = "http"
	WorkspaceAgentPortShareProtocolHTTPS WorkspaceAgentPortShareProtocol = "https"
)
View Source
const DatabaseNotReachable = "database not reachable"

Variables

View Source
var (
	ProvisionerKeyUUIDBuiltIn  = uuid.MustParse(ProvisionerKeyIDBuiltIn)
	ProvisionerKeyUUIDUserAuth = uuid.MustParse(ProvisionerKeyIDUserAuth)
	ProvisionerKeyUUIDPSK      = uuid.MustParse(ProvisionerKeyIDPSK)
)
View Source
var AllDaysOfWeek = []string{"monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"}
View Source
var Countries = []Country{}/* 249 elements not displayed */
View Source
var DefaultOrganization = "default"

DefaultOrganization is used as a replacement for the default organization.

View Source
var ErrDatabaseNotReachable = xerrors.New(DatabaseNotReachable)
View Source
var ExperimentsAll = Experiments{}

ExperimentsAll should include all experiments that are safe for users to opt-in to via --experimental='*'. Experiments that are not ready for consumption by all users should not be included here and will be essentially hidden.

FeatureNames must be kept in-sync with the Feature enum above.

View Source
var MapWorkspaceAppOpenIns = map[WorkspaceAppOpenIn]struct{}{
	WorkspaceAppOpenInSlimWindow: {},
	WorkspaceAppOpenInTab:        {},
}
View Source
var Me = "me"

Me is used as a replacement for your own ID.

View Source
var RBACResourceActions = map[RBACResource][]RBACAction{
	ResourceWildcard:                      {},
	ResourceApiKey:                        {ActionCreate, ActionDelete, ActionRead, ActionUpdate},
	ResourceAssignOrgRole:                 {ActionAssign, ActionCreate, ActionDelete, ActionRead, ActionUnassign, ActionUpdate},
	ResourceAssignRole:                    {ActionAssign, ActionRead, ActionUnassign},
	ResourceAuditLog:                      {ActionCreate, ActionRead},
	ResourceCryptoKey:                     {ActionCreate, ActionDelete, ActionRead, ActionUpdate},
	ResourceDebugInfo:                     {ActionRead},
	ResourceDeploymentConfig:              {ActionRead, ActionUpdate},
	ResourceDeploymentStats:               {ActionRead},
	ResourceFile:                          {ActionCreate, ActionRead},
	ResourceGroup:                         {ActionCreate, ActionDelete, ActionRead, ActionUpdate},
	ResourceGroupMember:                   {ActionRead},
	ResourceIdpsyncSettings:               {ActionRead, ActionUpdate},
	ResourceInboxNotification:             {ActionCreate, ActionRead, ActionUpdate},
	ResourceLicense:                       {ActionCreate, ActionDelete, ActionRead},
	ResourceNotificationMessage:           {ActionCreate, ActionDelete, ActionRead, ActionUpdate},
	ResourceNotificationPreference:        {ActionRead, ActionUpdate},
	ResourceNotificationTemplate:          {ActionRead, ActionUpdate},
	ResourceOauth2App:                     {ActionCreate, ActionDelete, ActionRead, ActionUpdate},
	ResourceOauth2AppCodeToken:            {ActionCreate, ActionDelete, ActionRead},
	ResourceOauth2AppSecret:               {ActionCreate, ActionDelete, ActionRead, ActionUpdate},
	ResourceOrganization:                  {ActionCreate, ActionDelete, ActionRead, ActionUpdate},
	ResourceOrganizationMember:            {ActionCreate, ActionDelete, ActionRead, ActionUpdate},
	ResourceProvisionerDaemon:             {ActionCreate, ActionDelete, ActionRead, ActionUpdate},
	ResourceProvisionerJobs:               {ActionRead},
	ResourceReplicas:                      {ActionRead},
	ResourceSystem:                        {ActionCreate, ActionDelete, ActionRead, ActionUpdate},
	ResourceTailnetCoordinator:            {ActionCreate, ActionDelete, ActionRead, ActionUpdate},
	ResourceTemplate:                      {ActionCreate, ActionDelete, ActionRead, ActionUpdate, ActionUse, ActionViewInsights},
	ResourceUser:                          {ActionCreate, ActionDelete, ActionRead, ActionReadPersonal, ActionUpdate, ActionUpdatePersonal},
	ResourceWebpushSubscription:           {ActionCreate, ActionDelete, ActionRead},
	ResourceWorkspace:                     {ActionApplicationConnect, ActionCreate, ActionDelete, ActionRead, ActionSSH, ActionWorkspaceStart, ActionWorkspaceStop, ActionUpdate},
	ResourceWorkspaceAgentDevcontainers:   {ActionCreate},
	ResourceWorkspaceAgentResourceMonitor: {ActionCreate, ActionRead, ActionUpdate},
	ResourceWorkspaceDormant:              {ActionApplicationConnect, ActionCreate, ActionDelete, ActionRead, ActionSSH, ActionWorkspaceStart, ActionWorkspaceStop, ActionUpdate},
	ResourceWorkspaceProxy:                {ActionCreate, ActionDelete, ActionRead, ActionUpdate},
}

RBACResourceActions is the mapping of resources to which actions are valid for said resource type.

View Source
var (
	UsernameValidRegex = regexp.MustCompile("^[a-zA-Z0-9]+(?:-[a-zA-Z0-9]+)*$")
)

WorkspaceAgentLifecycleOrder is the order in which workspace agent lifecycle states are expected to be reported during the lifetime of the agent process. For instance, the agent can go from starting to ready without reporting timeout or error, but it should not go from ready to starting. This is merely a hint for the agent process, and is not enforced by the server.

Functions

func BitmapToWeekdays

func BitmapToWeekdays(bitmap uint8) []string

BitmapToWeekdays converts a bitmap to a list of weekdays in accordance with the schedule package's rules (see above).

func DefaultCacheDir

func DefaultCacheDir() string

func DefaultDocsURL added in v2.16.0

func DefaultDocsURL() string

func DeploymentOptionsWithoutSecrets added in v2.2.1

func DeploymentOptionsWithoutSecrets(set serpent.OptionSet) serpent.OptionSet

DeploymentOptionsWithoutSecrets returns a copy of the OptionSet with secret values omitted.

func DiscoverVarsFiles added in v2.14.0

func DiscoverVarsFiles(workDir string) ([]string, error)

*

  • DiscoverVarsFiles function loads vars files in a predefined order:
  • 1. terraform.tfvars
  • 2. terraform.tfvars.json
  • 3. *.auto.tfvars
  • 4. *.auto.tfvars.json

func DisplayNameValid added in v2.16.0

func DisplayNameValid(str string) error

DisplayNameValid returns whether the input string is a valid template display name.

func ExpectJSONMime added in v2.7.0

func ExpectJSONMime(res *http.Response) error

ExpectJSONMime is a helper function that will assert the content type of the response is application/json.

func GroupNameValid added in v2.16.0

func GroupNameValid(str string) error

GroupNameValid returns whether the input string is a valid group name.

func IsConnectionError

func IsConnectionError(err error) bool

IsConnectionError is a convenience function for checking if the source of an error is due to a 'connection refused', 'no such host', etc.

func IsSecretDeploymentOption

func IsSecretDeploymentOption(opt serpent.Option) bool

func IsWorkspaceProxies

func IsWorkspaceProxies(opt serpent.Option) bool

IsWorkspaceProxies returns true if the cli option is used by workspace proxies.

func JobIsMissingParameterErrorCode added in v2.1.5

func JobIsMissingParameterErrorCode(code JobErrorCode) bool

JobIsMissingParameterErrorCode returns whether the error is a missing parameter error. This can indicate to consumers that they should check parameters.

func NameValid added in v2.16.0

func NameValid(str string) error

NameValid returns whether the input string is a valid name. It is a generic validator for any name (user, workspace, template, role name, etc.).

func NormalizeRealUsername added in v2.16.0

func NormalizeRealUsername(str string) string

NormalizeUserRealName normalizes a user name such that it will pass validation by UserRealNameValid. This is done to avoid blocking little Bobby Whitespace from using Coder.

func ParseSSHConfigOption

func ParseSSHConfigOption(opt string) (key string, value string, err error)

ParseSSHConfigOption parses a single ssh config option into it's key/value pair.

func ProvisionerTypeValid added in v2.11.0

func ProvisionerTypeValid[T ProvisionerType | string](pt T) error

ProvisionerTypeValid accepts string or ProvisionerType for easier usage. Will validate the enum is in the set.

func ReadBodyAsError

func ReadBodyAsError(res *http.Response) error

ReadBodyAsError reads the response as a codersdk.Response, and wraps it in a codersdk.Error type for easy marshaling.

This will always return an error, so only call it if the response failed your expectations. Usually via status code checking. nolint:staticcheck

func ReservedProvisionerKeyNames added in v2.16.0

func ReservedProvisionerKeyNames() []string

func ServerSentEventReader

func ServerSentEventReader(ctx context.Context, rc io.ReadCloser) func() (*ServerSentEvent, error)

func TemplateVersionNameValid added in v2.16.0

func TemplateVersionNameValid(str string) error

TemplateVersionNameValid returns whether the input string is a valid template version name.

func TimezoneOffsetHour

func TimezoneOffsetHour(loc *time.Location) int

func TimezoneOffsetHourWithTime added in v2.8.0

func TimezoneOffsetHourWithTime(now time.Time, loc *time.Location) int

TimezoneOffsetHourWithTime is implemented to match the javascript 'getTimezoneOffset()' function. This is the amount of time between this date evaluated in UTC and evaluated in the 'loc' The trivial case of times being on the same day is: 'time.Now().UTC().Hour() - time.Now().In(loc).Hour()'

func UserRealNameValid added in v2.16.0

func UserRealNameValid(str string) error

UserRealNameValid returns whether the input string is a valid real user name.

func UsernameFrom added in v2.16.0

func UsernameFrom(str string) string

UsernameFrom returns a best-effort username from the provided string.

It first attempts to validate the incoming string, which will be returned if it is valid. It then will attempt to extract the username from an email address. If no success happens during these steps, a random username will be returned.

func ValidateNewWorkspaceParameters

func ValidateNewWorkspaceParameters(richParameters []TemplateVersionParameter, buildParameters []WorkspaceBuildParameter) error

func ValidateWorkspaceBuildParameter

func ValidateWorkspaceBuildParameter(richParameter TemplateVersionParameter, buildParameter *WorkspaceBuildParameter, lastBuildParameter *WorkspaceBuildParameter) error

func ValidateWorkspaceBuildParameters

func ValidateWorkspaceBuildParameters(richParameters []TemplateVersionParameter, buildParameters, lastBuildParameters []WorkspaceBuildParameter) error

func WebsocketNetConn added in v2.9.0

func WebsocketNetConn(ctx context.Context, conn *websocket.Conn, msgType websocket.MessageType) (context.Context, net.Conn)

WebsocketNetConn wraps websocket.NetConn and returns a context that is tied to the parent context and the lifetime of the conn. Any error during read or write will cancel the context, but not close the conn. Close should be called to release context resources.

func WeekdaysToBitmap

func WeekdaysToBitmap(days []string) (uint8, error)

WeekdaysToBitmap converts a list of weekdays to a bitmap in accordance with the schedule package's rules. The 0th bit is Monday, ..., the 6th bit is Sunday. The 7th bit is unused.

func WorkspaceDisplayStatus

func WorkspaceDisplayStatus(jobStatus ProvisionerJobStatus, transition WorkspaceTransition) string

WorkspaceDisplayStatus computes a status to display on CLI/UI based on the workspace transition and the status of the provisioner job. This code is in sync with how we compute the status on frontend. Ref: site/src/util/workspace.ts (getWorkspaceStatus)

Types

type ACLAvailable

type ACLAvailable struct {
	Users  []ReducedUser `json:"users"`
	Groups []Group       `json:"groups"`
}

ACLAvailable is a list of users and groups that can be added to a template ACL.

type APIKey

type APIKey struct {
	ID              string      `json:"id" validate:"required"`
	UserID          uuid.UUID   `json:"user_id" validate:"required" format:"uuid"`
	LastUsed        time.Time   `json:"last_used" validate:"required" format:"date-time"`
	ExpiresAt       time.Time   `json:"expires_at" validate:"required" format:"date-time"`
	CreatedAt       time.Time   `json:"created_at" validate:"required" format:"date-time"`
	UpdatedAt       time.Time   `json:"updated_at" validate:"required" format:"date-time"`
	LoginType       LoginType   `json:"login_type" validate:"required" enums:"password,github,oidc,token"`
	Scope           APIKeyScope `json:"scope" validate:"required" enums:"all,application_connect"`
	TokenName       string      `json:"token_name" validate:"required"`
	LifetimeSeconds int64       `json:"lifetime_seconds" validate:"required"`
}

APIKey: do not ever return the HashedSecret

type APIKeyScope

type APIKeyScope string
const (
	// APIKeyScopeAll is a scope that allows the user to do everything.
	APIKeyScopeAll APIKeyScope = "all"
	// APIKeyScopeApplicationConnect is a scope that allows the user
	// to connect to applications in a workspace.
	APIKeyScopeApplicationConnect APIKeyScope = "application_connect"
)

type APIKeyWithOwner

type APIKeyWithOwner struct {
	APIKey
	Username string `json:"username"`
}

type AddLicenseRequest

type AddLicenseRequest struct {
	License string `json:"license" validate:"required"`
}

type AgentConnectionTiming added in v2.18.0

type AgentConnectionTiming struct {
	StartedAt          time.Time   `json:"started_at" format:"date-time"`
	EndedAt            time.Time   `json:"ended_at" format:"date-time"`
	Stage              TimingStage `json:"stage"`
	WorkspaceAgentID   string      `json:"workspace_agent_id"`
	WorkspaceAgentName string      `json:"workspace_agent_name"`
}

type AgentScriptTiming added in v2.17.0

type AgentScriptTiming struct {
	StartedAt          time.Time   `json:"started_at" format:"date-time"`
	EndedAt            time.Time   `json:"ended_at" format:"date-time"`
	ExitCode           int32       `json:"exit_code"`
	Stage              TimingStage `json:"stage"`
	Status             string      `json:"status"`
	DisplayName        string      `json:"display_name"`
	WorkspaceAgentID   string      `json:"workspace_agent_id"`
	WorkspaceAgentName string      `json:"workspace_agent_name"`
}

type AgentStatsReportRequest

type AgentStatsReportRequest struct{}

AgentStatsReportRequest is a WebSocket request by coderd to the agent for stats. @typescript-ignore AgentStatsReportRequest

type AgentStatsReportResponse

type AgentStatsReportResponse struct {
	NumConns int64 `json:"num_comms"`
	// RxBytes is the number of received bytes.
	RxBytes int64 `json:"rx_bytes"`
	// TxBytes is the number of transmitted bytes.
	TxBytes int64 `json:"tx_bytes"`
}

AgentStatsReportResponse is returned for each report request by the agent.

type AgentSubsystem

type AgentSubsystem string
const (
	AgentSubsystemEnvbox     AgentSubsystem = "envbox"
	AgentSubsystemEnvbuilder AgentSubsystem = "envbuilder"
	AgentSubsystemExectrace  AgentSubsystem = "exectrace"
)

func (AgentSubsystem) Valid

func (s AgentSubsystem) Valid() bool

type AppHostResponse

type AppHostResponse struct {
	// Host is the externally accessible URL for the Coder instance.
	Host string `json:"host"`
}

type AppearanceConfig

type AppearanceConfig struct {
	ApplicationName string `json:"application_name"`
	LogoURL         string `json:"logo_url"`
	DocsURL         string `json:"docs_url"`
	// Deprecated: ServiceBanner has been replaced by AnnouncementBanners.
	ServiceBanner       BannerConfig   `json:"service_banner"`
	AnnouncementBanners []BannerConfig `json:"announcement_banners"`
	SupportLinks        []LinkConfig   `json:"support_links,omitempty"`
}

type ArchiveTemplateVersionsRequest added in v2.3.0

type ArchiveTemplateVersionsRequest struct {
	// By default, only failed versions are archived. Set this to true
	// to archive all unused versions regardless of job status.
	All bool `json:"all"`
}

type ArchiveTemplateVersionsResponse added in v2.3.0

type ArchiveTemplateVersionsResponse struct {
	TemplateID  uuid.UUID   `json:"template_id" format:"uuid"`
	ArchivedIDs []uuid.UUID `json:"archived_ids"`
}

type AssignableRoles

type AssignableRoles struct {
	Role       `table:"r,recursive_inline"`
	Assignable bool `json:"assignable" table:"assignable"`
	// BuiltIn roles are immutable
	BuiltIn bool `json:"built_in" table:"built_in"`
}

type AuditAction

type AuditAction string
const (
	AuditActionCreate               AuditAction = "create"
	AuditActionWrite                AuditAction = "write"
	AuditActionDelete               AuditAction = "delete"
	AuditActionStart                AuditAction = "start"
	AuditActionStop                 AuditAction = "stop"
	AuditActionLogin                AuditAction = "login"
	AuditActionLogout               AuditAction = "logout"
	AuditActionRegister             AuditAction = "register"
	AuditActionRequestPasswordReset AuditAction = "request_password_reset"
	AuditActionConnect              AuditAction = "connect"
	AuditActionDisconnect           AuditAction = "disconnect"
	AuditActionOpen                 AuditAction = "open"
	AuditActionClose                AuditAction = "close"
)

func (AuditAction) Friendly

func (a AuditAction) Friendly() string

type AuditDiff

type AuditDiff map[string]AuditDiffField

type AuditDiffField

type AuditDiffField struct {
	Old    any  `json:"old,omitempty"`
	New    any  `json:"new,omitempty"`
	Secret bool `json:"secret"`
}

type AuditLog

type AuditLog struct {
	ID           uuid.UUID    `json:"id" format:"uuid"`
	RequestID    uuid.UUID    `json:"request_id" format:"uuid"`
	Time         time.Time    `json:"time" format:"date-time"`
	IP           netip.Addr   `json:"ip"`
	UserAgent    string       `json:"user_agent"`
	ResourceType ResourceType `json:"resource_type"`
	ResourceID   uuid.UUID    `json:"resource_id" format:"uuid"`
	// ResourceTarget is the name of the resource.
	ResourceTarget   string          `json:"resource_target"`
	ResourceIcon     string          `json:"resource_icon"`
	Action           AuditAction     `json:"action"`
	Diff             AuditDiff       `json:"diff"`
	StatusCode       int32           `json:"status_code"`
	AdditionalFields json.RawMessage `json:"additional_fields"`
	Description      string          `json:"description"`
	ResourceLink     string          `json:"resource_link"`
	IsDeleted        bool            `json:"is_deleted"`

	// Deprecated: Use 'organization.id' instead.
	OrganizationID uuid.UUID `json:"organization_id" format:"uuid"`

	Organization *MinimalOrganization `json:"organization,omitempty"`

	User *User `json:"user"`
}

type AuditLogResponse

type AuditLogResponse struct {
	AuditLogs []AuditLog `json:"audit_logs"`
	Count     int64      `json:"count"`
}

type AuditLogsRequest

type AuditLogsRequest struct {
	SearchQuery string `json:"q,omitempty"`
	Pagination
}

type AuthMethod

type AuthMethod struct {
	Enabled bool `json:"enabled"`
}

type AuthMethods

type AuthMethods struct {
	TermsOfServiceURL string           `json:"terms_of_service_url,omitempty"`
	Password          AuthMethod       `json:"password"`
	Github            GithubAuthMethod `json:"github"`
	OIDC              OIDCAuthMethod   `json:"oidc"`
}

AuthMethods contains authentication method information like whether they are enabled or not or custom text, etc.

type AuthorizationCheck

type AuthorizationCheck struct {
	// Object can represent a "set" of objects, such as: all workspaces in an organization, all workspaces owned by me, and all workspaces across the entire product.
	// When defining an object, use the most specific language when possible to
	// produce the smallest set. Meaning to set as many fields on 'Object' as
	// you can. Example, if you want to check if you can update all workspaces
	// owned by 'me', try to also add an 'OrganizationID' to the settings.
	// Omitting the 'OrganizationID' could produce the incorrect value, as
	// workspaces have both `user` and `organization` owners.
	Object AuthorizationObject `json:"object"`
	Action RBACAction          `json:"action" enums:"create,read,update,delete"`
}

AuthorizationCheck is used to check if the currently authenticated user (or the specified user) can do a given action to a given set of objects.

@Description AuthorizationCheck is used to check if the currently authenticated user (or the specified user) can do a given action to a given set of objects.

type AuthorizationObject

type AuthorizationObject struct {
	// ResourceType is the name of the resource.
	// `./coderd/rbac/object.go` has the list of valid resource types.
	ResourceType RBACResource `json:"resource_type"`
	// OwnerID (optional) adds the set constraint to all resources owned by a given user.
	OwnerID string `json:"owner_id,omitempty"`
	// OrganizationID (optional) adds the set constraint to all resources owned by a given organization.
	OrganizationID string `json:"organization_id,omitempty"`
	// ResourceID (optional) reduces the set to a singular resource. This assigns
	// a resource ID to the resource type, eg: a single workspace.
	// The rbac library will not fetch the resource from the database, so if you
	// are using this option, you should also set the owner ID and organization ID
	// if possible. Be as specific as possible using all the fields relevant.
	ResourceID string `json:"resource_id,omitempty"`
	// AnyOrgOwner (optional) will disregard the org_owner when checking for permissions.
	// This cannot be set to true if the OrganizationID is set.
	AnyOrgOwner bool `json:"any_org,omitempty"`
}

AuthorizationObject can represent a "set" of objects, such as: all workspaces in an organization, all workspaces owned by me, all workspaces across the entire product.

@Description AuthorizationObject can represent a "set" of objects, such as: all workspaces in an organization, all workspaces owned by me, @Description all workspaces across the entire product.

type AuthorizationRequest

type AuthorizationRequest struct {
	// Checks is a map keyed with an arbitrary string to a permission check.
	// The key can be any string that is helpful to the caller, and allows
	// multiple permission checks to be run in a single request.
	// The key ensures that each permission check has the same key in the
	// response.
	Checks map[string]AuthorizationCheck `json:"checks"`
}

AuthorizationRequest is a structure instead of a map because go-playground/validate can only validate structs. If you attempt to pass a map into `httpapi.Read`, you will get an invalid type error.

type AuthorizationResponse

type AuthorizationResponse map[string]bool

type AutomaticUpdates added in v2.3.0

type AutomaticUpdates string
const (
	AutomaticUpdatesAlways AutomaticUpdates = "always"
	AutomaticUpdatesNever  AutomaticUpdates = "never"
)

type AvailableExperiments added in v2.3.1

type AvailableExperiments struct {
	Safe []Experiment `json:"safe"`
}

AvailableExperiments is an expandable type that returns all safe experiments available to be used with a deployment.

type BannerConfig added in v2.12.0

type BannerConfig struct {
	Enabled         bool   `json:"enabled"`
	Message         string `json:"message,omitempty"`
	BackgroundColor string `json:"background_color,omitempty"`
}

type BuildInfoResponse

type BuildInfoResponse struct {
	// ExternalURL references the current Coder version.
	// For production builds, this will link directly to a release. For development builds, this will link to a commit.
	ExternalURL string `json:"external_url"`
	// Version returns the semantic version of the build.
	Version string `json:"version"`
	// DashboardURL is the URL to hit the deployment's dashboard.
	// For external workspace proxies, this is the coderd they are connected
	// to.
	DashboardURL string `json:"dashboard_url"`
	// Telemetry is a boolean that indicates whether telemetry is enabled.
	Telemetry bool `json:"telemetry"`

	WorkspaceProxy bool `json:"workspace_proxy"`

	// AgentAPIVersion is the current version of the Agent API (back versions
	// MAY still be supported).
	AgentAPIVersion string `json:"agent_api_version"`
	// ProvisionerAPIVersion is the current version of the Provisioner API
	ProvisionerAPIVersion string `json:"provisioner_api_version"`

	// UpgradeMessage is the message displayed to users when an outdated client
	// is detected.
	UpgradeMessage string `json:"upgrade_message"`

	// DeploymentID is the unique identifier for this deployment.
	DeploymentID string `json:"deployment_id"`

	// WebPushPublicKey is the public key for push notifications via Web Push.
	WebPushPublicKey string `json:"webpush_public_key,omitempty"`
}

BuildInfoResponse contains build information for this instance of Coder.

func (BuildInfoResponse) CanonicalVersion

func (b BuildInfoResponse) CanonicalVersion() string

CanonicalVersion trims build information from the version. E.g. 'v0.7.4-devel+11573034' -> 'v0.7.4'.

type BuildReason

type BuildReason string
const (
	// "initiator" is used when a workspace build is triggered by a user.
	// Combined with the initiator id/username, it indicates which user initiated the build.
	BuildReasonInitiator BuildReason = "initiator"
	// "autostart" is used when a build to start a workspace is triggered by Autostart.
	// The initiator id/username in this case is the workspace owner and can be ignored.
	BuildReasonAutostart BuildReason = "autostart"
	// "autostop" is used when a build to stop a workspace is triggered by Autostop.
	// The initiator id/username in this case is the workspace owner and can be ignored.
	BuildReasonAutostop BuildReason = "autostop"
)

type ChangePasswordWithOneTimePasscodeRequest added in v2.17.0

type ChangePasswordWithOneTimePasscodeRequest struct {
	Email           string `json:"email" validate:"required,email" format:"email"`
	Password        string `json:"password" validate:"required"`
	OneTimePasscode string `json:"one_time_passcode" validate:"required"`
}

ChangePasswordWithOneTimePasscodeRequest enables callers to change their password when they've forgotten it.

type Client

type Client struct {
	HTTPClient *http.Client
	URL        *url.URL

	// SessionTokenHeader is an optional custom header to use for setting tokens. By
	// default 'Coder-Session-Token' is used.
	SessionTokenHeader string

	// PlainLogger may be set to log HTTP traffic in a human-readable form.
	// It uses the LogBodies option.
	PlainLogger io.Writer

	// Trace can be enabled to propagate tracing spans to the Coder API.
	// This is useful for tracking a request end-to-end.
	Trace bool

	// DisableDirectConnections forces any connections to workspaces to go
	// through DERP, regardless of the BlockEndpoints setting on each
	// connection.
	DisableDirectConnections bool
	// contains filtered or unexported fields
}

Client is an HTTP caller for methods to the Coder API. @typescript-ignore Client

func New

func New(serverURL *url.URL) *Client

New creates a Coder client for the provided URL.

func (*Client) APIKeyByID

func (c *Client) APIKeyByID(ctx context.Context, userID string, id string) (*APIKey, error)

APIKeyByID returns the api key by id.

func (*Client) APIKeyByName

func (c *Client) APIKeyByName(ctx context.Context, userID string, name string) (*APIKey, error)

APIKeyByName returns the api key by name.

func (*Client) AddLicense

func (c *Client) AddLicense(ctx context.Context, r AddLicenseRequest) (License, error)

func (*Client) AppHost

func (c *Client) AppHost(ctx context.Context) (AppHostResponse, error)

AppHost returns the site-wide application wildcard hostname e.g. "*--apps.coder.com". Apps are accessible at: "<app-name>--<agent-name>--<workspace-name>--<username><app-host>", e.g. "my-app--agent--workspace--username--apps.coder.com".

If the app host is not set, the response will contain an empty string.

func (*Client) Appearance

func (c *Client) Appearance(ctx context.Context) (AppearanceConfig, error)

Appearance returns the configuration that modifies the visual display of the dashboard.

func (*Client) ArchiveTemplateVersions added in v2.3.0

func (c *Client) ArchiveTemplateVersions(ctx context.Context, template uuid.UUID, all bool) (ArchiveTemplateVersionsResponse, error)

func (*Client) AuditLogs

func (c *Client) AuditLogs(ctx context.Context, req AuditLogsRequest) (AuditLogResponse, error)

AuditLogs retrieves audit logs from the given page.

func (*Client) AuthCheck

AuthCheck allows the authenticated user to check if they have the given permissions to a set of resources.

func (*Client) AuthMethods

func (c *Client) AuthMethods(ctx context.Context) (AuthMethods, error)

AuthMethods returns types of authentication available to the user.

func (*Client) BuildInfo

func (c *Client) BuildInfo(ctx context.Context) (BuildInfoResponse, error)

BuildInfo returns build information for this instance of Coder.

func (*Client) CancelTemplateVersion

func (c *Client) CancelTemplateVersion(ctx context.Context, version uuid.UUID) error

CancelTemplateVersion marks a template version job as canceled.

func (*Client) CancelTemplateVersionDryRun

func (c *Client) CancelTemplateVersionDryRun(ctx context.Context, version, job uuid.UUID) error

CancelTemplateVersionDryRun marks a template version dry-run job as canceled.

func (*Client) CancelWorkspaceBuild

func (c *Client) CancelWorkspaceBuild(ctx context.Context, id uuid.UUID) error

CancelWorkspaceBuild marks a workspace build job as canceled.

func (*Client) ChangePasswordWithOneTimePasscode added in v2.17.0

func (c *Client) ChangePasswordWithOneTimePasscode(ctx context.Context, req ChangePasswordWithOneTimePasscodeRequest) error

func (*Client) ConvertLoginType

func (c *Client) ConvertLoginType(ctx context.Context, req ConvertLoginRequest) (OAuthConversionResponse, error)

ConvertLoginType will send a request to convert the user from password based authentication to oauth based. The response has the oauth state code to use in the oauth flow.

func (*Client) CreateAPIKey

func (c *Client) CreateAPIKey(ctx context.Context, user string) (GenerateAPIKeyResponse, error)

CreateAPIKey generates an API key for the user ID provided. CreateToken should be used over CreateAPIKey. CreateToken allows better tracking of the token's usage and allows for custom expiration. Only use CreateAPIKey if you want to emulate the session created for a browser like login.

func (*Client) CreateFirstUser

CreateFirstUser attempts to create the first user on a Coder deployment. This initial user has superadmin privileges. If >0 users exist, this request will fail.

func (*Client) CreateGroup

func (c *Client) CreateGroup(ctx context.Context, orgID uuid.UUID, req CreateGroupRequest) (Group, error)

func (*Client) CreateOrganization

func (c *Client) CreateOrganization(ctx context.Context, req CreateOrganizationRequest) (Organization, error)

CreateOrganization creates an organization and adds the user making the request as an owner.

func (*Client) CreateOrganizationRole added in v2.15.0

func (c *Client) CreateOrganizationRole(ctx context.Context, role Role) (Role, error)

CreateOrganizationRole will create a custom organization role

func (*Client) CreateProvisionerKey added in v2.14.0

func (c *Client) CreateProvisionerKey(ctx context.Context, organizationID uuid.UUID, req CreateProvisionerKeyRequest) (CreateProvisionerKeyResponse, error)

CreateProvisionerKey creates a new provisioner key for an organization.

func (*Client) CreateTemplate

func (c *Client) CreateTemplate(ctx context.Context, organizationID uuid.UUID, request CreateTemplateRequest) (Template, error)

CreateTemplate creates a new template inside an organization.

func (*Client) CreateTemplateVersion

func (c *Client) CreateTemplateVersion(ctx context.Context, organizationID uuid.UUID, req CreateTemplateVersionRequest) (TemplateVersion, error)

CreateTemplateVersion processes source-code and optionally associates the version with a template. Executing without a template is useful for validating source-code.

func (*Client) CreateTemplateVersionDryRun

func (c *Client) CreateTemplateVersionDryRun(ctx context.Context, version uuid.UUID, req CreateTemplateVersionDryRunRequest) (ProvisionerJob, error)

CreateTemplateVersionDryRun begins a dry-run provisioner job against the given template version with the given parameter values.

func (*Client) CreateTestAuditLog

func (c *Client) CreateTestAuditLog(ctx context.Context, req CreateTestAuditLogRequest) error

CreateTestAuditLog creates a fake audit log. Only owners of the organization can perform this action. It's used for testing purposes.

func (*Client) CreateToken

func (c *Client) CreateToken(ctx context.Context, userID string, req CreateTokenRequest) (GenerateAPIKeyResponse, error)

CreateToken generates an API key for the user ID provided with custom expiration. These tokens can be used for long-lived access, like for use with CI.

func (*Client) CreateUser

func (c *Client) CreateUser(ctx context.Context, req CreateUserRequest) (User, error)

CreateUser Deprecated: Use CreateUserWithOrgs instead. This will be removed. TODO: When removing, we should rename CreateUserWithOrgs -> CreateUser with an alias of CreateUserWithOrgs.

func (*Client) CreateUserWithOrgs added in v2.15.0

func (c *Client) CreateUserWithOrgs(ctx context.Context, req CreateUserRequestWithOrgs) (User, error)

CreateUserWithOrgs creates a new user.

func (*Client) CreateUserWorkspace added in v2.14.0

func (c *Client) CreateUserWorkspace(ctx context.Context, user string, request CreateWorkspaceRequest) (Workspace, error)

CreateUserWorkspace creates a new workspace for the template specified.

func (*Client) CreateWorkspace deprecated

func (c *Client) CreateWorkspace(ctx context.Context, _ uuid.UUID, user string, request CreateWorkspaceRequest) (Workspace, error)

CreateWorkspace creates a new workspace for the template specified.

Deprecated: Use CreateUserWorkspace instead.

func (*Client) CreateWorkspaceBuild

func (c *Client) CreateWorkspaceBuild(ctx context.Context, workspace uuid.UUID, request CreateWorkspaceBuildRequest) (WorkspaceBuild, error)

CreateWorkspaceBuild queues a new build to occur for a workspace.

func (*Client) CreateWorkspaceProxy

func (*Client) DeleteAPIKey

func (c *Client) DeleteAPIKey(ctx context.Context, userID string, id string) error

DeleteAPIKey deletes API key by id.

func (*Client) DeleteGroup

func (c *Client) DeleteGroup(ctx context.Context, group uuid.UUID) error

func (*Client) DeleteLicense

func (c *Client) DeleteLicense(ctx context.Context, id int32) error

func (*Client) DeleteOAuth2ProviderApp added in v2.6.0

func (c *Client) DeleteOAuth2ProviderApp(ctx context.Context, id uuid.UUID) error

DeleteOAuth2ProviderApp deletes an application, also invalidating any tokens that were generated from it.

func (*Client) DeleteOAuth2ProviderAppSecret added in v2.6.0

func (c *Client) DeleteOAuth2ProviderAppSecret(ctx context.Context, appID uuid.UUID, secretID uuid.UUID) error

DeleteOAuth2ProviderAppSecret deletes a secret from an OAuth2 application, also invalidating any tokens that generated from it.

func (*Client) DeleteOrganization added in v2.12.0

func (c *Client) DeleteOrganization(ctx context.Context, orgID string) error

DeleteOrganization will remove the corresponding organization from the deployment, based on the UUID/name provided as `orgID`.

func (*Client) DeleteOrganizationMember added in v2.13.0

func (c *Client) DeleteOrganizationMember(ctx context.Context, organizationID uuid.UUID, user string) error

DeleteOrganizationMember removes a user from an organization

func (*Client) DeleteOrganizationRole added in v2.15.0

func (c *Client) DeleteOrganizationRole(ctx context.Context, organizationID uuid.UUID, roleName string) error

DeleteOrganizationRole will delete a custom organization role

func (*Client) DeleteProvisionerKey added in v2.14.0

func (c *Client) DeleteProvisionerKey(ctx context.Context, organizationID uuid.UUID, name string) error

DeleteProvisionerKey deletes a provisioner key.

func (*Client) DeleteTemplate

func (c *Client) DeleteTemplate(ctx context.Context, template uuid.UUID) error

func (*Client) DeleteUser

func (c *Client) DeleteUser(ctx context.Context, id uuid.UUID) error

DeleteUser deletes a user.

func (*Client) DeleteWebpushSubscription added in v2.21.0

func (c *Client) DeleteWebpushSubscription(ctx context.Context, user string, req DeleteWebpushSubscription) error

DeleteWebpushSubscription deletes a push notification subscription for a given user. Think of this as an unsubscribe, but for a specific push notification subscription.

func (*Client) DeleteWorkspaceAgentPortShare added in v2.9.0

func (c *Client) DeleteWorkspaceAgentPortShare(ctx context.Context, workspaceID uuid.UUID, req DeleteWorkspaceAgentPortShareRequest) error

func (*Client) DeleteWorkspaceProxyByID

func (c *Client) DeleteWorkspaceProxyByID(ctx context.Context, id uuid.UUID) error

func (*Client) DeleteWorkspaceProxyByName

func (c *Client) DeleteWorkspaceProxyByName(ctx context.Context, name string) error

func (*Client) DeletedWorkspace

func (c *Client) DeletedWorkspace(ctx context.Context, id uuid.UUID) (Workspace, error)

DeletedWorkspace returns a single workspace that was deleted.

func (*Client) DeploymentConfig

func (c *Client) DeploymentConfig(ctx context.Context) (*DeploymentConfig, error)

DeploymentConfig returns the deployment config for the coder server.

func (*Client) DeploymentDAUs

func (c *Client) DeploymentDAUs(ctx context.Context, tzOffset int) (*DAUsResponse, error)

DeploymentDAUs requires a tzOffset in hours. Use 0 for UTC, and TimezoneOffsetHour(time.Local) for the local timezone.

func (*Client) DeploymentDAUsLocalTZ

func (c *Client) DeploymentDAUsLocalTZ(ctx context.Context) (*DAUsResponse, error)

func (*Client) DeploymentStats

func (c *Client) DeploymentStats(ctx context.Context) (DeploymentStats, error)

func (*Client) Download

func (c *Client) Download(ctx context.Context, id uuid.UUID) ([]byte, string, error)

Download fetches a file by uploaded hash.

func (*Client) DownloadWithFormat added in v2.8.0

func (c *Client) DownloadWithFormat(ctx context.Context, id uuid.UUID, format string) ([]byte, string, error)

Download fetches a file by uploaded hash, but it forces format conversion.

func (*Client) Entitlements

func (c *Client) Entitlements(ctx context.Context) (Entitlements, error)

func (*Client) Experiments

func (c *Client) Experiments(ctx context.Context) (Experiments, error)

func (*Client) ExternalAuthByID added in v2.2.1

func (c *Client) ExternalAuthByID(ctx context.Context, provider string) (ExternalAuth, error)

ExternalAuthByID returns the external auth for the given provider by ID.

func (*Client) ExternalAuthDeviceByID added in v2.2.1

func (c *Client) ExternalAuthDeviceByID(ctx context.Context, provider string) (ExternalAuthDevice, error)

func (*Client) ExternalAuthDeviceExchange added in v2.2.1

func (c *Client) ExternalAuthDeviceExchange(ctx context.Context, provider string, req ExternalAuthDeviceExchange) error

ExchangeGitAuth exchanges a device code for an external auth token.

func (*Client) FavoriteWorkspace added in v2.8.0

func (c *Client) FavoriteWorkspace(ctx context.Context, workspaceID uuid.UUID) error

func (*Client) GetAvailableIDPSyncFields added in v2.18.0

func (c *Client) GetAvailableIDPSyncFields(ctx context.Context) ([]string, error)

func (*Client) GetIDPSyncFieldValues added in v2.19.0

func (c *Client) GetIDPSyncFieldValues(ctx context.Context, claimField string) ([]string, error)

func (*Client) GetNotificationDispatchMethods added in v2.15.0

func (c *Client) GetNotificationDispatchMethods(ctx context.Context) (NotificationMethodsResponse, error)

GetNotificationDispatchMethods the available and default notification dispatch methods.

func (*Client) GetNotificationsSettings added in v2.14.0

func (c *Client) GetNotificationsSettings(ctx context.Context) (NotificationsSettings, error)

GetNotificationsSettings retrieves the notifications settings, which currently just describes whether all notifications are paused from sending.

func (*Client) GetOrganizationAvailableIDPSyncFields added in v2.18.0

func (c *Client) GetOrganizationAvailableIDPSyncFields(ctx context.Context, orgID string) ([]string, error)

func (*Client) GetOrganizationIDPSyncFieldValues added in v2.19.0

func (c *Client) GetOrganizationIDPSyncFieldValues(ctx context.Context, orgID string, claimField string) ([]string, error)

func (*Client) GetProvisionerKey added in v2.18.0

func (c *Client) GetProvisionerKey(ctx context.Context, pk string) (ProvisionerKey, error)

GetProvisionerKey returns the provisioner key.

func (*Client) GetSystemNotificationTemplates added in v2.15.0

func (c *Client) GetSystemNotificationTemplates(ctx context.Context) ([]NotificationTemplate, error)

GetSystemNotificationTemplates retrieves all notification templates pertaining to internal system events.

func (*Client) GetTokenConfig

func (c *Client) GetTokenConfig(ctx context.Context, userID string) (TokenConfig, error)

GetTokenConfig returns deployment options related to token management

func (*Client) GetUserNotificationPreferences added in v2.15.0

func (c *Client) GetUserNotificationPreferences(ctx context.Context, userID uuid.UUID) ([]NotificationPreference, error)

GetUserNotificationPreferences retrieves notification preferences for a given user.

func (*Client) GetUserStatusCounts added in v2.19.0

func (*Client) GetWorkspaceAgentPortShares added in v2.9.0

func (c *Client) GetWorkspaceAgentPortShares(ctx context.Context, workspaceID uuid.UUID) (WorkspaceAgentPortShares, error)

func (*Client) GitSSHKey

func (c *Client) GitSSHKey(ctx context.Context, user string) (GitSSHKey, error)

GitSSHKey returns the user's git SSH public key.

func (*Client) Group

func (c *Client) Group(ctx context.Context, group uuid.UUID) (Group, error)

func (*Client) GroupByOrgAndName

func (c *Client) GroupByOrgAndName(ctx context.Context, orgID uuid.UUID, name string) (Group, error)

func (*Client) GroupIDPSyncSettings added in v2.16.0

func (c *Client) GroupIDPSyncSettings(ctx context.Context, orgID string) (GroupSyncSettings, error)

func (*Client) Groups added in v2.15.0

func (c *Client) Groups(ctx context.Context, args GroupArguments) ([]Group, error)

func (*Client) GroupsByOrganization

func (c *Client) GroupsByOrganization(ctx context.Context, orgID uuid.UUID) ([]Group, error)

GroupsByOrganization Deprecated: use Groups with GroupArguments instead.

func (*Client) HasFirstUser

func (c *Client) HasFirstUser(ctx context.Context) (bool, error)

HasFirstUser returns whether the first user has been created.

func (*Client) JFrogXRayScan added in v2.8.0

func (c *Client) JFrogXRayScan(ctx context.Context, workspaceID, agentID uuid.UUID) (JFrogXrayScan, error)

func (*Client) Licenses

func (c *Client) Licenses(ctx context.Context) ([]License, error)

func (*Client) ListExternalAuths added in v2.5.0

func (c *Client) ListExternalAuths(ctx context.Context) (ListUserExternalAuthResponse, error)

ListExternalAuths returns the available external auth providers and the user's authenticated links if they exist.

func (*Client) ListInboxNotifications added in v2.21.0

func (*Client) ListOrganizationRoles

func (c *Client) ListOrganizationRoles(ctx context.Context, org uuid.UUID) ([]AssignableRoles, error)

ListOrganizationRoles lists all assignable roles for a given organization.

func (*Client) ListProvisionerKeyDaemons added in v2.16.0

func (c *Client) ListProvisionerKeyDaemons(ctx context.Context, organizationID uuid.UUID) ([]ProvisionerKeyDaemons, error)

ListProvisionerKeyDaemons lists all provisioner keys with their associated daemons for an organization.

func (*Client) ListProvisionerKeys added in v2.14.0

func (c *Client) ListProvisionerKeys(ctx context.Context, organizationID uuid.UUID) ([]ProvisionerKey, error)

ListProvisionerKeys lists all provisioner keys for an organization.

func (*Client) ListSiteRoles

func (c *Client) ListSiteRoles(ctx context.Context) ([]AssignableRoles, error)

ListSiteRoles lists all assignable site wide roles.

func (*Client) LogBodies

func (c *Client) LogBodies() bool

LogBodies returns whether requests and response bodies are logged.

func (*Client) Logger

func (c *Client) Logger() slog.Logger

Logger returns the logger for the client.

func (*Client) LoginWithPassword

LoginWithPassword creates a session token authenticating with an email and password. Call `SetSessionToken()` to apply the newly acquired token to the client.

func (*Client) Logout

func (c *Client) Logout(ctx context.Context) error

Logout calls the /logout API Call `ClearSessionToken()` to clear the session token of the client.

func (*Client) MarkAllInboxNotificationsAsRead added in v2.21.0

func (c *Client) MarkAllInboxNotificationsAsRead(ctx context.Context) error

func (*Client) OAuth2ProviderApp added in v2.6.0

func (c *Client) OAuth2ProviderApp(ctx context.Context, id uuid.UUID) (OAuth2ProviderApp, error)

OAuth2ProviderApp returns an application configured to authenticate using Coder as an OAuth2 provider.

func (*Client) OAuth2ProviderAppSecrets added in v2.6.0

func (c *Client) OAuth2ProviderAppSecrets(ctx context.Context, appID uuid.UUID) ([]OAuth2ProviderAppSecret, error)

OAuth2ProviderAppSecrets returns the truncated secrets for an OAuth2 application.

func (*Client) OAuth2ProviderApps added in v2.6.0

func (c *Client) OAuth2ProviderApps(ctx context.Context, filter OAuth2ProviderAppFilter) ([]OAuth2ProviderApp, error)

OAuth2ProviderApps returns the applications configured to authenticate using Coder as an OAuth2 provider.

func (*Client) Organization

func (c *Client) Organization(ctx context.Context, id uuid.UUID) (Organization, error)

func (*Client) OrganizationByName

func (c *Client) OrganizationByName(ctx context.Context, name string) (Organization, error)

func (*Client) OrganizationByUserAndName added in v2.9.0

func (c *Client) OrganizationByUserAndName(ctx context.Context, user string, name string) (Organization, error)

func (*Client) OrganizationIDPSyncSettings added in v2.18.0

func (c *Client) OrganizationIDPSyncSettings(ctx context.Context) (OrganizationSyncSettings, error)

func (*Client) OrganizationMembers added in v2.13.0

func (c *Client) OrganizationMembers(ctx context.Context, organizationID uuid.UUID) ([]OrganizationMemberWithUserData, error)

OrganizationMembers lists all members in an organization

func (*Client) OrganizationProvisionerDaemons added in v2.14.0

func (c *Client) OrganizationProvisionerDaemons(ctx context.Context, organizationID uuid.UUID, opts *OrganizationProvisionerDaemonsOptions) ([]ProvisionerDaemon, error)

func (*Client) OrganizationProvisionerJob added in v2.19.0

func (c *Client) OrganizationProvisionerJob(ctx context.Context, organizationID, jobID uuid.UUID) (job ProvisionerJob, err error)

func (*Client) OrganizationProvisionerJobs added in v2.19.0

func (c *Client) OrganizationProvisionerJobs(ctx context.Context, organizationID uuid.UUID, opts *OrganizationProvisionerJobsOptions) ([]ProvisionerJob, error)

func (*Client) Organizations added in v2.14.0

func (c *Client) Organizations(ctx context.Context) ([]Organization, error)

func (*Client) OrganizationsByUser

func (c *Client) OrganizationsByUser(ctx context.Context, user string) ([]Organization, error)

OrganizationsByUser returns all organizations the user is a member of.

func (*Client) PatchGroup

func (c *Client) PatchGroup(ctx context.Context, group uuid.UUID, req PatchGroupRequest) (Group, error)

func (*Client) PatchGroupIDPSyncConfig added in v2.19.0

func (c *Client) PatchGroupIDPSyncConfig(ctx context.Context, orgID string, req PatchGroupIDPSyncConfigRequest) (GroupSyncSettings, error)

func (*Client) PatchGroupIDPSyncMapping added in v2.19.0

func (c *Client) PatchGroupIDPSyncMapping(ctx context.Context, orgID string, req PatchGroupIDPSyncMappingRequest) (GroupSyncSettings, error)

func (*Client) PatchGroupIDPSyncSettings added in v2.16.0

func (c *Client) PatchGroupIDPSyncSettings(ctx context.Context, orgID string, req GroupSyncSettings) (GroupSyncSettings, error)

func (*Client) PatchOrganizationIDPSyncConfig added in v2.19.0

func (c *Client) PatchOrganizationIDPSyncConfig(ctx context.Context, req PatchOrganizationIDPSyncConfigRequest) (OrganizationSyncSettings, error)

func (*Client) PatchOrganizationIDPSyncMapping added in v2.19.0

func (c *Client) PatchOrganizationIDPSyncMapping(ctx context.Context, req PatchOrganizationIDPSyncMappingRequest) (OrganizationSyncSettings, error)

func (*Client) PatchOrganizationIDPSyncSettings added in v2.18.0

func (c *Client) PatchOrganizationIDPSyncSettings(ctx context.Context, req OrganizationSyncSettings) (OrganizationSyncSettings, error)

func (*Client) PatchRoleIDPSyncConfig added in v2.19.0

func (c *Client) PatchRoleIDPSyncConfig(ctx context.Context, orgID string, req PatchRoleIDPSyncConfigRequest) (RoleSyncSettings, error)

func (*Client) PatchRoleIDPSyncMapping added in v2.19.0

func (c *Client) PatchRoleIDPSyncMapping(ctx context.Context, orgID string, req PatchRoleIDPSyncMappingRequest) (RoleSyncSettings, error)

func (*Client) PatchRoleIDPSyncSettings added in v2.16.0

func (c *Client) PatchRoleIDPSyncSettings(ctx context.Context, orgID string, req RoleSyncSettings) (RoleSyncSettings, error)

func (*Client) PatchWorkspaceProxy

func (c *Client) PatchWorkspaceProxy(ctx context.Context, req PatchWorkspaceProxy) (UpdateWorkspaceProxyResponse, error)

func (*Client) PostJFrogXrayScan added in v2.8.0

func (c *Client) PostJFrogXrayScan(ctx context.Context, req JFrogXrayScan) error

func (*Client) PostOAuth2ProviderApp added in v2.6.0

func (c *Client) PostOAuth2ProviderApp(ctx context.Context, app PostOAuth2ProviderAppRequest) (OAuth2ProviderApp, error)

PostOAuth2ProviderApp adds an application that can authenticate using Coder as an OAuth2 provider.

func (*Client) PostOAuth2ProviderAppSecret added in v2.6.0

func (c *Client) PostOAuth2ProviderAppSecret(ctx context.Context, appID uuid.UUID) (OAuth2ProviderAppSecretFull, error)

PostOAuth2ProviderAppSecret creates a new secret for an OAuth2 application. This is the only time the full secret will be revealed.

func (*Client) PostOrganizationMember added in v2.13.0

func (c *Client) PostOrganizationMember(ctx context.Context, organizationID uuid.UUID, user string) (OrganizationMember, error)

PostOrganizationMember adds a user to an organization

func (*Client) PostTestNotification added in v2.20.0

func (c *Client) PostTestNotification(ctx context.Context) error

func (*Client) PostTestWebpushMessage added in v2.21.0

func (c *Client) PostTestWebpushMessage(ctx context.Context) error

func (*Client) PostWebpushSubscription added in v2.21.0

func (c *Client) PostWebpushSubscription(ctx context.Context, user string, req WebpushSubscription) error

PostWebpushSubscription creates a push notification subscription for a given user.

func (*Client) PostWorkspaceUsage added in v2.10.0

func (c *Client) PostWorkspaceUsage(ctx context.Context, id uuid.UUID) error

PostWorkspaceUsage marks the workspace as having been used recently. Deprecated: use PostWorkspaceUsageWithBody instead

func (*Client) PostWorkspaceUsageWithBody added in v2.13.0

func (c *Client) PostWorkspaceUsageWithBody(ctx context.Context, id uuid.UUID, req PostWorkspaceUsageRequest) error

PostWorkspaceUsage marks the workspace as having been used recently and records an app stat.

func (*Client) PreviousTemplateVersion

func (c *Client) PreviousTemplateVersion(ctx context.Context, organization uuid.UUID, templateName, versionName string) (TemplateVersion, error)

func (*Client) ProvisionerDaemons

func (c *Client) ProvisionerDaemons(ctx context.Context) ([]ProvisionerDaemon, error)

ProvisionerDaemons returns provisioner daemons available.

func (*Client) PutExtendWorkspace

func (c *Client) PutExtendWorkspace(ctx context.Context, id uuid.UUID, req PutExtendWorkspaceRequest) error

PutExtendWorkspace updates the deadline for resources of the latest workspace build.

func (*Client) PutNotificationsSettings added in v2.14.0

func (c *Client) PutNotificationsSettings(ctx context.Context, settings NotificationsSettings) error

PutNotificationsSettings modifies the notifications settings, which currently just controls whether all notifications are paused from sending.

func (*Client) PutOAuth2ProviderApp added in v2.6.0

func (c *Client) PutOAuth2ProviderApp(ctx context.Context, id uuid.UUID, app PutOAuth2ProviderAppRequest) (OAuth2ProviderApp, error)

PutOAuth2ProviderApp updates an application that can authenticate using Coder as an OAuth2 provider.

func (*Client) RegenerateGitSSHKey

func (c *Client) RegenerateGitSSHKey(ctx context.Context, user string) (GitSSHKey, error)

RegenerateGitSSHKey will create a new SSH key pair for the user and return it.

func (*Client) Regions

func (c *Client) Regions(ctx context.Context) ([]Region, error)

func (*Client) Replicas

func (c *Client) Replicas(ctx context.Context) ([]Replica, error)

Replicas fetches the list of replicas.

func (*Client) Request

func (c *Client) Request(ctx context.Context, method, path string, body interface{}, opts ...RequestOption) (*http.Response, error)

Request performs a HTTP request with the body provided. The caller is responsible for closing the response body.

func (*Client) RequestOneTimePasscode added in v2.17.0

func (c *Client) RequestOneTimePasscode(ctx context.Context, req RequestOneTimePasscodeRequest) error

func (*Client) ResolveAutostart added in v2.4.0

func (c *Client) ResolveAutostart(ctx context.Context, workspaceID string) (ResolveAutostartResponse, error)

func (*Client) RevokeOAuth2ProviderApp added in v2.9.0

func (c *Client) RevokeOAuth2ProviderApp(ctx context.Context, appID uuid.UUID) error

RevokeOAuth2ProviderApp completely revokes an app's access for the authenticated user.

func (*Client) RoleIDPSyncSettings added in v2.16.0

func (c *Client) RoleIDPSyncSettings(ctx context.Context, orgID string) (RoleSyncSettings, error)

func (*Client) SSHConfiguration

func (c *Client) SSHConfiguration(ctx context.Context) (SSHConfigResponse, error)

SSHConfiguration returns information about the SSH configuration for the Coder instance.

func (*Client) SafeExperiments added in v2.3.1

func (c *Client) SafeExperiments(ctx context.Context) (AvailableExperiments, error)

func (*Client) ServeProvisionerDaemon

ServeProvisionerDaemon returns the gRPC service for a provisioner daemon implementation. The context is during dial, not during the lifetime of the client. Client should be closed after use.

func (*Client) SessionToken

func (c *Client) SessionToken() string

SessionToken returns the currently set token for the client.

func (*Client) SetArchiveTemplateVersion added in v2.3.0

func (c *Client) SetArchiveTemplateVersion(ctx context.Context, templateVersion uuid.UUID, archive bool) error

func (*Client) SetLogBodies

func (c *Client) SetLogBodies(logBodies bool)

SetLogBodies sets whether to log request and response bodies.

func (*Client) SetLogger

func (c *Client) SetLogger(logger slog.Logger)

SetLogger sets the logger for the client.

func (*Client) SetSessionToken

func (c *Client) SetSessionToken(token string)

SetSessionToken returns the currently set token for the client.

func (*Client) StarterTemplates added in v2.15.0

func (c *Client) StarterTemplates(ctx context.Context) ([]TemplateExample, error)

StarterTemplates lists example templates available in Coder.

func (*Client) Template

func (c *Client) Template(ctx context.Context, template uuid.UUID) (Template, error)

Template returns a single template.

func (*Client) TemplateACL

func (c *Client) TemplateACL(ctx context.Context, templateID uuid.UUID) (TemplateACL, error)

func (*Client) TemplateACLAvailable

func (c *Client) TemplateACLAvailable(ctx context.Context, templateID uuid.UUID) (ACLAvailable, error)

TemplateACLAvailable returns available users + groups that can be assigned template perms

func (*Client) TemplateByName

func (c *Client) TemplateByName(ctx context.Context, organizationID uuid.UUID, name string) (Template, error)

TemplateByName finds a template inside the organization provided with a case-insensitive name.

func (*Client) TemplateDAUs

func (c *Client) TemplateDAUs(ctx context.Context, templateID uuid.UUID, tzOffset int) (*DAUsResponse, error)

TemplateDAUs requires a tzOffset in hours. Use 0 for UTC, and TimezoneOffsetHour(time.Local) for the local timezone.

func (*Client) TemplateDAUsLocalTZ

func (c *Client) TemplateDAUsLocalTZ(ctx context.Context, templateID uuid.UUID) (*DAUsResponse, error)

func (*Client) TemplateExamples deprecated

func (c *Client) TemplateExamples(ctx context.Context, _ uuid.UUID) ([]TemplateExample, error)

TemplateExamples lists example templates available in Coder.

Deprecated: Use StarterTemplates instead.

func (*Client) TemplateInsights

func (*Client) TemplateVersion

func (c *Client) TemplateVersion(ctx context.Context, id uuid.UUID) (TemplateVersion, error)

TemplateVersion returns a template version by ID.

func (*Client) TemplateVersionByName

func (c *Client) TemplateVersionByName(ctx context.Context, template uuid.UUID, name string) (TemplateVersion, error)

TemplateVersionByName returns a template version by it's friendly name. This is used for path-based routing. Like: /templates/example/versions/helloworld

func (*Client) TemplateVersionByOrganizationAndName

func (c *Client) TemplateVersionByOrganizationAndName(ctx context.Context, organizationID uuid.UUID, templateName, versionName string) (TemplateVersion, error)

func (*Client) TemplateVersionDryRun

func (c *Client) TemplateVersionDryRun(ctx context.Context, version, job uuid.UUID) (ProvisionerJob, error)

TemplateVersionDryRun returns the current state of a template version dry-run job.

func (*Client) TemplateVersionDryRunLogsAfter

func (c *Client) TemplateVersionDryRunLogsAfter(ctx context.Context, version, job uuid.UUID, after int64) (<-chan ProvisionerJobLog, io.Closer, error)

TemplateVersionDryRunLogsAfter streams logs for a template version dry-run that occurred after a specific log ID.

func (*Client) TemplateVersionDryRunMatchedProvisioners added in v2.18.1

func (c *Client) TemplateVersionDryRunMatchedProvisioners(ctx context.Context, version, job uuid.UUID) (MatchedProvisioners, error)

TemplateVersionDryRunMatchedProvisioners returns the matched provisioners for a template version dry-run job.

func (*Client) TemplateVersionDryRunResources

func (c *Client) TemplateVersionDryRunResources(ctx context.Context, version, job uuid.UUID) ([]WorkspaceResource, error)

TemplateVersionDryRunResources returns the resources of a finished template version dry-run job.

func (*Client) TemplateVersionExternalAuth added in v2.2.1

func (c *Client) TemplateVersionExternalAuth(ctx context.Context, version uuid.UUID) ([]TemplateVersionExternalAuth, error)

TemplateVersionExternalAuth returns authentication providers for the requested template version.

func (*Client) TemplateVersionLogsAfter

func (c *Client) TemplateVersionLogsAfter(ctx context.Context, version uuid.UUID, after int64) (<-chan ProvisionerJobLog, io.Closer, error)

TemplateVersionLogsAfter streams logs for a template version that occurred after a specific log ID.

func (*Client) TemplateVersionPresets added in v2.20.0

func (c *Client) TemplateVersionPresets(ctx context.Context, templateVersionID uuid.UUID) ([]Preset, error)

TemplateVersionPresets returns the presets associated with a template version.

func (*Client) TemplateVersionResources

func (c *Client) TemplateVersionResources(ctx context.Context, version uuid.UUID) ([]WorkspaceResource, error)

TemplateVersionResources returns resources a template version declares.

func (*Client) TemplateVersionRichParameters

func (c *Client) TemplateVersionRichParameters(ctx context.Context, version uuid.UUID) ([]TemplateVersionParameter, error)

TemplateVersionParameters returns parameters a template version exposes.

func (*Client) TemplateVersionVariables

func (c *Client) TemplateVersionVariables(ctx context.Context, version uuid.UUID) ([]TemplateVersionVariable, error)

TemplateVersionVariables returns resources a template version variables.

func (*Client) TemplateVersionsByTemplate

func (c *Client) TemplateVersionsByTemplate(ctx context.Context, req TemplateVersionsByTemplateRequest) ([]TemplateVersion, error)

TemplateVersionsByTemplate lists versions associated with a template.

func (*Client) Templates added in v2.13.0

func (c *Client) Templates(ctx context.Context, filter TemplateFilter) ([]Template, error)

Templates lists all viewable templates

func (*Client) TemplatesByOrganization

func (c *Client) TemplatesByOrganization(ctx context.Context, organizationID uuid.UUID) ([]Template, error)

TemplatesByOrganization lists all templates inside of an organization.

func (*Client) Tokens

func (c *Client) Tokens(ctx context.Context, userID string, filter TokensFilter) ([]APIKeyWithOwner, error)

Tokens list machine API keys.

func (*Client) UnfavoriteWorkspace added in v2.8.0

func (c *Client) UnfavoriteWorkspace(ctx context.Context, workspaceID uuid.UUID) error

func (*Client) UnlinkExternalAuthByID added in v2.5.0

func (c *Client) UnlinkExternalAuthByID(ctx context.Context, provider string) error

UnlinkExternalAuthByID deletes the external auth for the given provider by ID for the user. This does not revoke the token from the IDP.

func (*Client) UpdateActiveTemplateVersion

func (c *Client) UpdateActiveTemplateVersion(ctx context.Context, template uuid.UUID, req UpdateActiveTemplateVersion) error

UpdateActiveTemplateVersion updates the active template version to the ID provided. The template version must be attached to the template.

func (*Client) UpdateAppearance

func (c *Client) UpdateAppearance(ctx context.Context, appearance UpdateAppearanceConfig) error

func (*Client) UpdateCheck

func (c *Client) UpdateCheck(ctx context.Context) (UpdateCheckResponse, error)

UpdateCheck returns information about the latest release version of Coder and whether or not the server is running the latest release.

func (*Client) UpdateInboxNotificationReadStatus added in v2.21.0

func (*Client) UpdateNotificationTemplateMethod added in v2.15.0

func (c *Client) UpdateNotificationTemplateMethod(ctx context.Context, notificationTemplateID uuid.UUID, method string) error

UpdateNotificationTemplateMethod modifies a notification template to use a specific notification method, overriding the method set in the deployment configuration.

func (*Client) UpdateOrganization added in v2.12.0

func (c *Client) UpdateOrganization(ctx context.Context, orgID string, req UpdateOrganizationRequest) (Organization, error)

UpdateOrganization will update information about the corresponding organization, based on the UUID/name provided as `orgID`.

func (*Client) UpdateOrganizationMemberRoles

func (c *Client) UpdateOrganizationMemberRoles(ctx context.Context, organizationID uuid.UUID, user string, req UpdateRoles) (OrganizationMember, error)

UpdateOrganizationMemberRoles grants the userID the specified roles in an org. Include ALL roles the user has.

func (*Client) UpdateOrganizationRole added in v2.15.0

func (c *Client) UpdateOrganizationRole(ctx context.Context, role Role) (Role, error)

UpdateOrganizationRole will update an existing custom organization role

func (*Client) UpdateTemplateACL

func (c *Client) UpdateTemplateACL(ctx context.Context, templateID uuid.UUID, req UpdateTemplateACL) error

func (*Client) UpdateTemplateMeta

func (c *Client) UpdateTemplateMeta(ctx context.Context, templateID uuid.UUID, req UpdateTemplateMeta) (Template, error)

func (*Client) UpdateTemplateVersion

func (c *Client) UpdateTemplateVersion(ctx context.Context, versionID uuid.UUID, req PatchTemplateVersionRequest) (TemplateVersion, error)

func (*Client) UpdateUserAppearanceSettings added in v2.5.1

func (c *Client) UpdateUserAppearanceSettings(ctx context.Context, user string, req UpdateUserAppearanceSettingsRequest) (User, error)

UpdateUserAppearanceSettings updates the appearance settings for a user.

func (*Client) UpdateUserNotificationPreferences added in v2.15.0

func (c *Client) UpdateUserNotificationPreferences(ctx context.Context, userID uuid.UUID, req UpdateUserNotificationPreferences) ([]NotificationPreference, error)

UpdateUserNotificationPreferences updates notification preferences for a given user.

func (*Client) UpdateUserPassword

func (c *Client) UpdateUserPassword(ctx context.Context, user string, req UpdateUserPasswordRequest) error

UpdateUserPassword updates a user password. It calls PUT /users/{user}/password

func (*Client) UpdateUserProfile

func (c *Client) UpdateUserProfile(ctx context.Context, user string, req UpdateUserProfileRequest) (User, error)

UpdateUserProfile updates the username of a user.

func (*Client) UpdateUserQuietHoursSchedule

func (c *Client) UpdateUserQuietHoursSchedule(ctx context.Context, userIdent string, req UpdateUserQuietHoursScheduleRequest) (UserQuietHoursScheduleResponse, error)

UpdateUserQuietHoursSchedule updates the quiet hours settings for the user. This endpoint only exists in enterprise editions.

func (*Client) UpdateUserRoles

func (c *Client) UpdateUserRoles(ctx context.Context, user string, req UpdateRoles) (User, error)

UpdateUserRoles grants the userID the specified roles. Include ALL roles the user has.

func (*Client) UpdateUserStatus

func (c *Client) UpdateUserStatus(ctx context.Context, user string, status UserStatus) (User, error)

UpdateUserStatus sets the user status to the given status

func (*Client) UpdateWorkspace

func (c *Client) UpdateWorkspace(ctx context.Context, id uuid.UUID, req UpdateWorkspaceRequest) error

func (*Client) UpdateWorkspaceAutomaticUpdates added in v2.3.0

func (c *Client) UpdateWorkspaceAutomaticUpdates(ctx context.Context, id uuid.UUID, req UpdateWorkspaceAutomaticUpdatesRequest) error

UpdateWorkspaceAutomaticUpdates sets the automatic updates setting for workspace by id.

func (*Client) UpdateWorkspaceAutostart

func (c *Client) UpdateWorkspaceAutostart(ctx context.Context, id uuid.UUID, req UpdateWorkspaceAutostartRequest) error

UpdateWorkspaceAutostart sets the autostart schedule for workspace by id. If the provided schedule is empty, autostart is disabled for the workspace.

func (*Client) UpdateWorkspaceDormancy added in v2.1.4

func (c *Client) UpdateWorkspaceDormancy(ctx context.Context, id uuid.UUID, req UpdateWorkspaceDormancy) error

UpdateWorkspaceDormancy sets a workspace as dormant if dormant=true and activates a dormant workspace if dormant=false.

func (*Client) UpdateWorkspaceTTL

func (c *Client) UpdateWorkspaceTTL(ctx context.Context, id uuid.UUID, req UpdateWorkspaceTTLRequest) error

UpdateWorkspaceTTL sets the ttl for workspace by id. If the provided duration is nil, autostop is disabled for the workspace.

func (*Client) UpdateWorkspaceUsageContext added in v2.10.0

func (c *Client) UpdateWorkspaceUsageContext(ctx context.Context, workspaceID uuid.UUID) func()

UpdateWorkspaceUsageContext periodically posts workspace usage for the workspace with the given id in the background. The caller is responsible for calling the returned function to stop the background process. Deprecated: use UpdateWorkspaceUsageContextWithBody instead

func (*Client) UpdateWorkspaceUsageWithBodyContext added in v2.13.0

func (c *Client) UpdateWorkspaceUsageWithBodyContext(ctx context.Context, workspaceID uuid.UUID, req PostWorkspaceUsageRequest) func()

UpdateWorkspaceUsageWithBodyContext periodically posts workspace usage for the workspace with the given id and app name in the background. The caller is responsible for calling the returned function to stop the background process.

func (*Client) Upload

func (c *Client) Upload(ctx context.Context, contentType string, rd io.Reader) (UploadResponse, error)

Upload uploads an arbitrary file with the content type provided. This is used to upload a source-code archive.

func (*Client) UpsertWorkspaceAgentPortShare added in v2.9.0

func (c *Client) UpsertWorkspaceAgentPortShare(ctx context.Context, workspaceID uuid.UUID, req UpsertWorkspaceAgentPortShareRequest) (WorkspaceAgentPortShare, error)

func (*Client) User

func (c *Client) User(ctx context.Context, userIdent string) (User, error)

User returns a user for the ID/username provided.

func (*Client) UserActivityInsights added in v2.2.0

func (*Client) UserAutofillParameters added in v2.8.0

func (c *Client) UserAutofillParameters(ctx context.Context, user string, templateID uuid.UUID) ([]UserParameter, error)

UserAutofillParameters returns all recently used parameters for the given user.

func (*Client) UserLatencyInsights

func (*Client) UserQuietHoursSchedule

func (c *Client) UserQuietHoursSchedule(ctx context.Context, userIdent string) (UserQuietHoursScheduleResponse, error)

UserQuietHoursSchedule returns the quiet hours settings for the user. This endpoint only exists in enterprise editions.

func (*Client) UserRoles

func (c *Client) UserRoles(ctx context.Context, user string) (UserRoles, error)

UserRoles returns all roles the user has

func (*Client) Users

func (c *Client) Users(ctx context.Context, req UsersRequest) (GetUsersResponse, error)

Users returns all users according to the request parameters. If no parameters are set, the default behavior is to return all users in a single page.

func (*Client) ValidateUserPassword added in v2.18.0

ValidateUserPassword validates the complexity of a user password and that it is secured enough.

func (*Client) WatchWorkspace

func (c *Client) WatchWorkspace(ctx context.Context, id uuid.UUID) (<-chan Workspace, error)

func (*Client) WatchWorkspaceAgentMetadata

func (c *Client) WatchWorkspaceAgentMetadata(ctx context.Context, id uuid.UUID) (<-chan []WorkspaceAgentMetadata, <-chan error)

WatchWorkspaceAgentMetadata watches the metadata of a workspace agent. The returned channel will be closed when the context is canceled. Exactly one error will be sent on the error channel. The metadata channel is never closed.

func (*Client) Workspace

func (c *Client) Workspace(ctx context.Context, id uuid.UUID) (Workspace, error)

Workspace returns a single workspace.

func (*Client) WorkspaceAgent

func (c *Client) WorkspaceAgent(ctx context.Context, id uuid.UUID) (WorkspaceAgent, error)

WorkspaceAgent returns an agent by ID.

func (*Client) WorkspaceAgentListContainers added in v2.20.0

func (c *Client) WorkspaceAgentListContainers(ctx context.Context, agentID uuid.UUID, labels map[string]string) (WorkspaceAgentListContainersResponse, error)

WorkspaceAgentListContainers returns a list of containers that are currently running on a Docker daemon accessible to the workspace agent.

func (*Client) WorkspaceAgentListeningPorts

func (c *Client) WorkspaceAgentListeningPorts(ctx context.Context, agentID uuid.UUID) (WorkspaceAgentListeningPortsResponse, error)

WorkspaceAgentListeningPorts returns a list of ports that are currently being listened on inside the workspace agent's network namespace.

func (*Client) WorkspaceAgentLogsAfter

func (c *Client) WorkspaceAgentLogsAfter(ctx context.Context, agentID uuid.UUID, after int64, follow bool) (<-chan []WorkspaceAgentLog, io.Closer, error)

func (*Client) WorkspaceBuild

func (c *Client) WorkspaceBuild(ctx context.Context, id uuid.UUID) (WorkspaceBuild, error)

WorkspaceBuild returns a single workspace build for a workspace. If history is "", the latest version is returned.

func (*Client) WorkspaceBuildByUsernameAndWorkspaceNameAndBuildNumber

func (c *Client) WorkspaceBuildByUsernameAndWorkspaceNameAndBuildNumber(ctx context.Context, username string, workspaceName string, buildNumber string) (WorkspaceBuild, error)

func (*Client) WorkspaceBuildLogsAfter

func (c *Client) WorkspaceBuildLogsAfter(ctx context.Context, build uuid.UUID, after int64) (<-chan ProvisionerJobLog, io.Closer, error)

WorkspaceBuildLogsAfter streams logs for a workspace build that occurred after a specific log ID.

func (*Client) WorkspaceBuildParameters

func (c *Client) WorkspaceBuildParameters(ctx context.Context, build uuid.UUID) ([]WorkspaceBuildParameter, error)

func (*Client) WorkspaceBuildState

func (c *Client) WorkspaceBuildState(ctx context.Context, build uuid.UUID) ([]byte, error)

WorkspaceBuildState returns the provisioner state of the build.

func (*Client) WorkspaceBuildTimings added in v2.17.0

func (c *Client) WorkspaceBuildTimings(ctx context.Context, build uuid.UUID) (WorkspaceBuildTimings, error)

func (*Client) WorkspaceBuilds

func (c *Client) WorkspaceBuilds(ctx context.Context, req WorkspaceBuildsRequest) ([]WorkspaceBuild, error)

func (*Client) WorkspaceByOwnerAndName

func (c *Client) WorkspaceByOwnerAndName(ctx context.Context, owner string, name string, params WorkspaceOptions) (Workspace, error)

WorkspaceByOwnerAndName returns a workspace by the owner's UUID and the workspace's name.

func (*Client) WorkspaceProxies

func (c *Client) WorkspaceProxies(ctx context.Context) (RegionsResponse[WorkspaceProxy], error)

func (*Client) WorkspaceProxyByID

func (c *Client) WorkspaceProxyByID(ctx context.Context, id uuid.UUID) (WorkspaceProxy, error)

func (*Client) WorkspaceProxyByName

func (c *Client) WorkspaceProxyByName(ctx context.Context, name string) (WorkspaceProxy, error)

func (*Client) WorkspaceQuota

func (c *Client) WorkspaceQuota(ctx context.Context, organizationID string, userID string) (WorkspaceQuota, error)

func (*Client) WorkspaceTimings added in v2.16.0

func (c *Client) WorkspaceTimings(ctx context.Context, id uuid.UUID) (WorkspaceBuildTimings, error)

func (*Client) Workspaces

func (c *Client) Workspaces(ctx context.Context, filter WorkspaceFilter) (WorkspacesResponse, error)

Workspaces returns all workspaces the authenticated user has access to.

type CoderDesktopTelemetry added in v2.21.0

type CoderDesktopTelemetry struct {
	DeviceID            string `json:"device_id"`
	DeviceOS            string `json:"device_os"`
	CoderDesktopVersion string `json:"coder_desktop_version"`
}

CoderDesktopTelemetry represents the telemetry data sent from Coder Desktop clients. @typescript-ignore CoderDesktopTelemetry

func (*CoderDesktopTelemetry) FromHeader added in v2.21.0

func (t *CoderDesktopTelemetry) FromHeader(headerValue string) error

FromHeader parses the desktop telemetry from the provided header value. Returns nil if the header is empty or if parsing fails.

func (*CoderDesktopTelemetry) IsEmpty added in v2.21.0

func (t *CoderDesktopTelemetry) IsEmpty() bool

IsEmpty returns true if all fields in the telemetry data are empty.

type ConnectionLatency

type ConnectionLatency struct {
	P50 float64 `json:"p50" example:"31.312"`
	P95 float64 `json:"p95" example:"119.832"`
}

ConnectionLatency shows the latency for a connection.

type ConvertLoginRequest

type ConvertLoginRequest struct {
	// ToType is the login type to convert to.
	ToType   LoginType `json:"to_type" validate:"required"`
	Password string    `json:"password" validate:"required"`
}

type Country added in v2.18.0

type Country struct {
	Name string `json:"name"`
	Flag string `json:"flag"`
}

@typescript-ignore Country

type CreateFirstUserRequest

type CreateFirstUserRequest struct {
	Email     string                   `json:"email" validate:"required,email"`
	Username  string                   `json:"username" validate:"required,username"`
	Name      string                   `json:"name" validate:"user_real_name"`
	Password  string                   `json:"password" validate:"required"`
	Trial     bool                     `json:"trial"`
	TrialInfo CreateFirstUserTrialInfo `json:"trial_info"`
}

type CreateFirstUserResponse

type CreateFirstUserResponse struct {
	UserID         uuid.UUID `json:"user_id" format:"uuid"`
	OrganizationID uuid.UUID `json:"organization_id" format:"uuid"`
}

CreateFirstUserResponse contains IDs for newly created user info.

type CreateFirstUserTrialInfo added in v2.7.0

type CreateFirstUserTrialInfo struct {
	FirstName   string `json:"first_name"`
	LastName    string `json:"last_name"`
	PhoneNumber string `json:"phone_number"`
	JobTitle    string `json:"job_title"`
	CompanyName string `json:"company_name"`
	Country     string `json:"country"`
	Developers  string `json:"developers"`
}

type CreateGroupRequest

type CreateGroupRequest struct {
	Name           string `json:"name" validate:"required,group_name"`
	DisplayName    string `json:"display_name" validate:"omitempty,group_display_name"`
	AvatarURL      string `json:"avatar_url"`
	QuotaAllowance int    `json:"quota_allowance"`
}

type CreateOrganizationRequest

type CreateOrganizationRequest struct {
	Name string `json:"name" validate:"required,organization_name"`
	// DisplayName will default to the same value as `Name` if not provided.
	DisplayName string `json:"display_name,omitempty" validate:"omitempty,organization_display_name"`
	Description string `json:"description,omitempty"`
	Icon        string `json:"icon,omitempty"`
}

type CreateProvisionerKeyRequest added in v2.14.0

type CreateProvisionerKeyRequest struct {
	Name string            `json:"name"`
	Tags map[string]string `json:"tags"`
}

type CreateProvisionerKeyResponse added in v2.14.0

type CreateProvisionerKeyResponse struct {
	Key string `json:"key"`
}

type CreateTemplateRequest

type CreateTemplateRequest struct {
	// Name is the name of the template.
	Name string `json:"name" validate:"template_name,required"`
	// DisplayName is the displayed name of the template.
	DisplayName string `json:"display_name,omitempty" validate:"template_display_name"`
	// Description is a description of what the template contains. It must be
	// less than 128 bytes.
	Description string `json:"description,omitempty" validate:"lt=128"`
	// Icon is a relative path or external URL that specifies
	// an icon to be displayed in the dashboard.
	Icon string `json:"icon,omitempty"`

	// VersionID is an in-progress or completed job to use as an initial version
	// of the template.
	//
	// This is required on creation to enable a user-flow of validating a
	// template works. There is no reason the data-model cannot support empty
	// templates, but it doesn't make sense for users.
	VersionID uuid.UUID `json:"template_version_id" validate:"required" format:"uuid"`

	// DefaultTTLMillis allows optionally specifying the default TTL
	// for all workspaces created from this template.
	DefaultTTLMillis *int64 `json:"default_ttl_ms,omitempty"`
	// ActivityBumpMillis allows optionally specifying the activity bump
	// duration for all workspaces created from this template. Defaults to 1h
	// but can be set to 0 to disable activity bumping.
	ActivityBumpMillis *int64 `json:"activity_bump_ms,omitempty"`
	// AutostopRequirement allows optionally specifying the autostop requirement
	// for workspaces created from this template. This is an enterprise feature.
	AutostopRequirement *TemplateAutostopRequirement `json:"autostop_requirement,omitempty"`
	// AutostartRequirement allows optionally specifying the autostart allowed days
	// for workspaces created from this template. This is an enterprise feature.
	AutostartRequirement *TemplateAutostartRequirement `json:"autostart_requirement,omitempty"`

	// Allow users to cancel in-progress workspace jobs.
	// *bool as the default value is "true".
	AllowUserCancelWorkspaceJobs *bool `json:"allow_user_cancel_workspace_jobs"`

	// AllowUserAutostart allows users to set a schedule for autostarting their
	// workspace. By default this is true. This can only be disabled when using
	// an enterprise license.
	AllowUserAutostart *bool `json:"allow_user_autostart,omitempty"`

	// AllowUserAutostop allows users to set a custom workspace TTL to use in
	// place of the template's DefaultTTL field. By default this is true. If
	// false, the DefaultTTL will always be used. This can only be disabled when
	// using an enterprise license.
	AllowUserAutostop *bool `json:"allow_user_autostop,omitempty"`

	// FailureTTLMillis allows optionally specifying the max lifetime before Coder
	// stops all resources for failed workspaces created from this template.
	FailureTTLMillis *int64 `json:"failure_ttl_ms,omitempty"`
	// TimeTilDormantMillis allows optionally specifying the max lifetime before Coder
	// locks inactive workspaces created from this template.
	TimeTilDormantMillis *int64 `json:"dormant_ttl_ms,omitempty"`
	// TimeTilDormantAutoDeleteMillis allows optionally specifying the max lifetime before Coder
	// permanently deletes dormant workspaces created from this template.
	TimeTilDormantAutoDeleteMillis *int64 `json:"delete_ttl_ms,omitempty"`

	// DisableEveryoneGroupAccess allows optionally disabling the default
	// behavior of granting the 'everyone' group access to use the template.
	// If this is set to true, the template will not be available to all users,
	// and must be explicitly granted to users or groups in the permissions settings
	// of the template.
	DisableEveryoneGroupAccess bool `json:"disable_everyone_group_access"`

	// RequireActiveVersion mandates that workspaces are built with the active
	// template version.
	RequireActiveVersion bool `json:"require_active_version"`

	// MaxPortShareLevel allows optionally specifying the maximum port share level
	// for workspaces created from the template.
	MaxPortShareLevel *WorkspaceAgentPortShareLevel `json:"max_port_share_level"`
}

CreateTemplateRequest provides options when creating a template.

type CreateTemplateVersionDryRunRequest

type CreateTemplateVersionDryRunRequest struct {
	WorkspaceName       string                    `json:"workspace_name"`
	RichParameterValues []WorkspaceBuildParameter `json:"rich_parameter_values"`
	UserVariableValues  []VariableValue           `json:"user_variable_values,omitempty"`
}

CreateTemplateVersionDryRunRequest defines the request parameters for CreateTemplateVersionDryRun.

type CreateTemplateVersionRequest

type CreateTemplateVersionRequest struct {
	Name    string `json:"name,omitempty" validate:"omitempty,template_version_name"`
	Message string `json:"message,omitempty" validate:"lt=1048577"`
	// TemplateID optionally associates a version with a template.
	TemplateID      uuid.UUID                `json:"template_id,omitempty" format:"uuid"`
	StorageMethod   ProvisionerStorageMethod `json:"storage_method" validate:"oneof=file,required" enums:"file"`
	FileID          uuid.UUID                `json:"file_id,omitempty" validate:"required_without=ExampleID" format:"uuid"`
	ExampleID       string                   `json:"example_id,omitempty" validate:"required_without=FileID"`
	Provisioner     ProvisionerType          `json:"provisioner" validate:"oneof=terraform echo,required"`
	ProvisionerTags map[string]string        `json:"tags"`

	UserVariableValues []VariableValue `json:"user_variable_values,omitempty"`
}

CreateTemplateVersionRequest enables callers to create a new Template Version.

type CreateTestAuditLogRequest

type CreateTestAuditLogRequest struct {
	Action           AuditAction     `json:"action,omitempty" enums:"create,write,delete,start,stop"`
	ResourceType     ResourceType    `json:"resource_type,omitempty" enums:"template,template_version,user,workspace,workspace_build,git_ssh_key,auditable_group"`
	ResourceID       uuid.UUID       `json:"resource_id,omitempty" format:"uuid"`
	AdditionalFields json.RawMessage `json:"additional_fields,omitempty"`
	Time             time.Time       `json:"time,omitempty" format:"date-time"`
	BuildReason      BuildReason     `json:"build_reason,omitempty" enums:"autostart,autostop,initiator"`
	OrganizationID   uuid.UUID       `json:"organization_id,omitempty" format:"uuid"`
	RequestID        uuid.UUID       `json:"request_id,omitempty" format:"uuid"`
}

type CreateTokenRequest

type CreateTokenRequest struct {
	Lifetime  time.Duration `json:"lifetime"`
	Scope     APIKeyScope   `json:"scope" enums:"all,application_connect"`
	TokenName string        `json:"token_name"`
}

type CreateUserRequest

type CreateUserRequest struct {
	Email    string `json:"email" validate:"required,email" format:"email"`
	Username string `json:"username" validate:"required,username"`
	Name     string `json:"name" validate:"user_real_name"`
	Password string `json:"password"`
	// UserLoginType defaults to LoginTypePassword.
	UserLoginType LoginType `json:"login_type"`
	// DisableLogin sets the user's login type to 'none'. This prevents the user
	// from being able to use a password or any other authentication method to login.
	// Deprecated: Set UserLoginType=LoginTypeDisabled instead.
	DisableLogin   bool      `json:"disable_login"`
	OrganizationID uuid.UUID `json:"organization_id" validate:"" format:"uuid"`
}

CreateUserRequest Deprecated: Use CreateUserRequestWithOrgs instead. This will be removed. TODO: When removing, we should rename CreateUserRequestWithOrgs -> CreateUserRequest Then alias CreateUserRequestWithOrgs to CreateUserRequest. @typescript-ignore CreateUserRequest

type CreateUserRequestWithOrgs added in v2.15.0

type CreateUserRequestWithOrgs struct {
	Email    string `json:"email" validate:"required,email" format:"email"`
	Username string `json:"username" validate:"required,username"`
	Name     string `json:"name" validate:"user_real_name"`
	Password string `json:"password"`
	// UserLoginType defaults to LoginTypePassword.
	UserLoginType LoginType `json:"login_type"`
	// UserStatus defaults to UserStatusDormant.
	UserStatus *UserStatus `json:"user_status"`
	// OrganizationIDs is a list of organization IDs that the user should be a member of.
	OrganizationIDs []uuid.UUID `json:"organization_ids" validate:"" format:"uuid"`
}

func (*CreateUserRequestWithOrgs) UnmarshalJSON added in v2.15.0

func (r *CreateUserRequestWithOrgs) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the unmarshal for the legacy param "organization_id". To accommodate multiple organizations, the field has been switched to a slice. The previous field will just be appended to the slice. Note in the previous behavior, omitting the field would result in the default org being applied, but that is no longer the case. TODO: Remove this method in it's entirety after some period of time. This will be released in v1.16.0, and is associated with the multiple orgs feature.

type CreateWorkspaceBuildRequest

type CreateWorkspaceBuildRequest struct {
	TemplateVersionID uuid.UUID           `json:"template_version_id,omitempty" format:"uuid"`
	Transition        WorkspaceTransition `json:"transition" validate:"oneof=start stop delete,required"`
	DryRun            bool                `json:"dry_run,omitempty"`
	ProvisionerState  []byte              `json:"state,omitempty"`
	// Orphan may be set for the Destroy transition.
	Orphan bool `json:"orphan,omitempty"`
	// ParameterValues are optional. It will write params to the 'workspace' scope.
	// This will overwrite any existing parameters with the same name.
	// This will not delete old params not included in this list.
	RichParameterValues []WorkspaceBuildParameter `json:"rich_parameter_values,omitempty"`

	// Log level changes the default logging verbosity of a provider ("info" if empty).
	LogLevel ProvisionerLogLevel `json:"log_level,omitempty" validate:"omitempty,oneof=debug"`
}

CreateWorkspaceBuildRequest provides options to update the latest workspace build.

type CreateWorkspaceProxyRequest

type CreateWorkspaceProxyRequest struct {
	Name        string `json:"name" validate:"required"`
	DisplayName string `json:"display_name"`
	Icon        string `json:"icon"`
}

type CreateWorkspaceRequest

type CreateWorkspaceRequest struct {
	// TemplateID specifies which template should be used for creating the workspace.
	TemplateID uuid.UUID `json:"template_id,omitempty" validate:"required_without=TemplateVersionID,excluded_with=TemplateVersionID" format:"uuid"`
	// TemplateVersionID can be used to specify a specific version of a template for creating the workspace.
	TemplateVersionID uuid.UUID `json:"template_version_id,omitempty" validate:"required_without=TemplateID,excluded_with=TemplateID" format:"uuid"`
	Name              string    `json:"name" validate:"workspace_name,required"`
	AutostartSchedule *string   `json:"autostart_schedule,omitempty"`
	TTLMillis         *int64    `json:"ttl_ms,omitempty"`
	// RichParameterValues allows for additional parameters to be provided
	// during the initial provision.
	RichParameterValues []WorkspaceBuildParameter `json:"rich_parameter_values,omitempty"`
	AutomaticUpdates    AutomaticUpdates          `json:"automatic_updates,omitempty"`
}

CreateWorkspaceRequest provides options for creating a new workspace. Either TemplateID or TemplateVersionID must be specified. They cannot both be present. @Description CreateWorkspaceRequest provides options for creating a new workspace. @Description Only one of TemplateID or TemplateVersionID can be specified, not both. @Description If TemplateID is specified, the active version of the template will be used.

type CryptoKey added in v2.17.0

type CryptoKey struct {
	Feature   CryptoKeyFeature `json:"feature"`
	Secret    string           `json:"secret"`
	DeletesAt time.Time        `json:"deletes_at" format:"date-time"`
	Sequence  int32            `json:"sequence"`
	StartsAt  time.Time        `json:"starts_at" format:"date-time"`
}

func (CryptoKey) CanSign added in v2.17.0

func (c CryptoKey) CanSign(now time.Time) bool

func (CryptoKey) CanVerify added in v2.17.0

func (c CryptoKey) CanVerify(now time.Time) bool

type CryptoKeyFeature added in v2.17.0

type CryptoKeyFeature string
const (
	CryptoKeyFeatureWorkspaceAppsAPIKey CryptoKeyFeature = "workspace_apps_api_key"
	//nolint:gosec // This denotes a type of key, not a literal.
	CryptoKeyFeatureWorkspaceAppsToken CryptoKeyFeature = "workspace_apps_token"
	CryptoKeyFeatureOIDCConvert        CryptoKeyFeature = "oidc_convert"
	CryptoKeyFeatureTailnetResume      CryptoKeyFeature = "tailnet_resume"
)

type CustomRoleRequest added in v2.15.0

type CustomRoleRequest struct {
	Name            string       `json:"name" table:"name,default_sort" validate:"username"`
	DisplayName     string       `json:"display_name" table:"display name"`
	SitePermissions []Permission `json:"site_permissions" table:"site permissions"`
	// OrganizationPermissions are specific to the organization the role belongs to.
	OrganizationPermissions []Permission `json:"organization_permissions" table:"organization permissions"`
	UserPermissions         []Permission `json:"user_permissions" table:"user permissions"`
}

CustomRoleRequest is used to edit custom roles.

type DAUEntry

type DAUEntry struct {
	// Date is a string formatted as 2024-01-31.
	// Timezone and time information is not included.
	Date   string `json:"date"`
	Amount int    `json:"amount"`
}

type DAURequest

type DAURequest struct {
	TZHourOffset int
}

type DAUsResponse

type DAUsResponse struct {
	Entries      []DAUEntry `json:"entries"`
	TZHourOffset int        `json:"tz_hour_offset"`
}

type DERP

type DERP struct {
	Server DERPServerConfig `json:"server" typescript:",notnull"`
	Config DERPConfig       `json:"config" typescript:",notnull"`
}

type DERPConfig

type DERPConfig struct {
	BlockDirect     serpent.Bool   `json:"block_direct" typescript:",notnull"`
	ForceWebSockets serpent.Bool   `json:"force_websockets" typescript:",notnull"`
	URL             serpent.String `json:"url" typescript:",notnull"`
	Path            serpent.String `json:"path" typescript:",notnull"`
}

type DERPRegion

type DERPRegion struct {
	Preferred           bool    `json:"preferred"`
	LatencyMilliseconds float64 `json:"latency_ms"`
}

type DERPServerConfig

type DERPServerConfig struct {
	Enable        serpent.Bool        `json:"enable" typescript:",notnull"`
	RegionID      serpent.Int64       `json:"region_id" typescript:",notnull"`
	RegionCode    serpent.String      `json:"region_code" typescript:",notnull"`
	RegionName    serpent.String      `json:"region_name" typescript:",notnull"`
	STUNAddresses serpent.StringArray `json:"stun_addresses" typescript:",notnull"`
	RelayURL      serpent.URL         `json:"relay_url" typescript:",notnull"`
}

type DangerousConfig

type DangerousConfig struct {
	AllowPathAppSharing         serpent.Bool `json:"allow_path_app_sharing" typescript:",notnull"`
	AllowPathAppSiteOwnerAccess serpent.Bool `json:"allow_path_app_site_owner_access" typescript:",notnull"`
	AllowAllCors                serpent.Bool `json:"allow_all_cors" typescript:",notnull"`
}

type DeleteWebpushSubscription added in v2.21.0

type DeleteWebpushSubscription struct {
	Endpoint string `json:"endpoint"`
}

type DeleteWorkspaceAgentPortShareRequest added in v2.9.0

type DeleteWorkspaceAgentPortShareRequest struct {
	AgentName string `json:"agent_name"`
	Port      int32  `json:"port"`
}

type DeploymentConfig

type DeploymentConfig struct {
	Values  *DeploymentValues `json:"config,omitempty"`
	Options serpent.OptionSet `json:"options,omitempty"`
}

DeploymentConfig contains both the deployment values and how they're set.

type DeploymentStats

type DeploymentStats struct {
	// AggregatedFrom is the time in which stats are aggregated from.
	// This might be back in time a specific duration or interval.
	AggregatedFrom time.Time `json:"aggregated_from" format:"date-time"`
	// CollectedAt is the time in which stats are collected at.
	CollectedAt time.Time `json:"collected_at" format:"date-time"`
	// NextUpdateAt is the time when the next batch of stats will
	// be updated.
	NextUpdateAt time.Time `json:"next_update_at" format:"date-time"`

	Workspaces   WorkspaceDeploymentStats    `json:"workspaces"`
	SessionCount SessionCountDeploymentStats `json:"session_count"`
}

type DeploymentValues

type DeploymentValues struct {
	Verbose             serpent.Bool   `json:"verbose,omitempty"`
	AccessURL           serpent.URL    `json:"access_url,omitempty"`
	WildcardAccessURL   serpent.String `json:"wildcard_access_url,omitempty"`
	DocsURL             serpent.URL    `json:"docs_url,omitempty"`
	RedirectToAccessURL serpent.Bool   `json:"redirect_to_access_url,omitempty"`
	// HTTPAddress is a string because it may be set to zero to disable.
	HTTPAddress                     serpent.String                       `json:"http_address,omitempty" typescript:",notnull"`
	AutobuildPollInterval           serpent.Duration                     `json:"autobuild_poll_interval,omitempty"`
	JobHangDetectorInterval         serpent.Duration                     `json:"job_hang_detector_interval,omitempty"`
	DERP                            DERP                                 `json:"derp,omitempty" typescript:",notnull"`
	Prometheus                      PrometheusConfig                     `json:"prometheus,omitempty" typescript:",notnull"`
	Pprof                           PprofConfig                          `json:"pprof,omitempty" typescript:",notnull"`
	ProxyTrustedHeaders             serpent.StringArray                  `json:"proxy_trusted_headers,omitempty" typescript:",notnull"`
	ProxyTrustedOrigins             serpent.StringArray                  `json:"proxy_trusted_origins,omitempty" typescript:",notnull"`
	CacheDir                        serpent.String                       `json:"cache_directory,omitempty" typescript:",notnull"`
	InMemoryDatabase                serpent.Bool                         `json:"in_memory_database,omitempty" typescript:",notnull"`
	EphemeralDeployment             serpent.Bool                         `json:"ephemeral_deployment,omitempty" typescript:",notnull"`
	PostgresURL                     serpent.String                       `json:"pg_connection_url,omitempty" typescript:",notnull"`
	PostgresAuth                    string                               `json:"pg_auth,omitempty" typescript:",notnull"`
	OAuth2                          OAuth2Config                         `json:"oauth2,omitempty" typescript:",notnull"`
	OIDC                            OIDCConfig                           `json:"oidc,omitempty" typescript:",notnull"`
	Telemetry                       TelemetryConfig                      `json:"telemetry,omitempty" typescript:",notnull"`
	TLS                             TLSConfig                            `json:"tls,omitempty" typescript:",notnull"`
	Trace                           TraceConfig                          `json:"trace,omitempty" typescript:",notnull"`
	SecureAuthCookie                serpent.Bool                         `json:"secure_auth_cookie,omitempty" typescript:",notnull"`
	StrictTransportSecurity         serpent.Int64                        `json:"strict_transport_security,omitempty" typescript:",notnull"`
	StrictTransportSecurityOptions  serpent.StringArray                  `json:"strict_transport_security_options,omitempty" typescript:",notnull"`
	SSHKeygenAlgorithm              serpent.String                       `json:"ssh_keygen_algorithm,omitempty" typescript:",notnull"`
	MetricsCacheRefreshInterval     serpent.Duration                     `json:"metrics_cache_refresh_interval,omitempty" typescript:",notnull"`
	AgentStatRefreshInterval        serpent.Duration                     `json:"agent_stat_refresh_interval,omitempty" typescript:",notnull"`
	AgentFallbackTroubleshootingURL serpent.URL                          `json:"agent_fallback_troubleshooting_url,omitempty" typescript:",notnull"`
	BrowserOnly                     serpent.Bool                         `json:"browser_only,omitempty" typescript:",notnull"`
	SCIMAPIKey                      serpent.String                       `json:"scim_api_key,omitempty" typescript:",notnull"`
	ExternalTokenEncryptionKeys     serpent.StringArray                  `json:"external_token_encryption_keys,omitempty" typescript:",notnull"`
	Provisioner                     ProvisionerConfig                    `json:"provisioner,omitempty" typescript:",notnull"`
	RateLimit                       RateLimitConfig                      `json:"rate_limit,omitempty" typescript:",notnull"`
	Experiments                     serpent.StringArray                  `json:"experiments,omitempty" typescript:",notnull"`
	UpdateCheck                     serpent.Bool                         `json:"update_check,omitempty" typescript:",notnull"`
	Swagger                         SwaggerConfig                        `json:"swagger,omitempty" typescript:",notnull"`
	Logging                         LoggingConfig                        `json:"logging,omitempty" typescript:",notnull"`
	Dangerous                       DangerousConfig                      `json:"dangerous,omitempty" typescript:",notnull"`
	DisablePathApps                 serpent.Bool                         `json:"disable_path_apps,omitempty" typescript:",notnull"`
	Sessions                        SessionLifetime                      `json:"session_lifetime,omitempty" typescript:",notnull"`
	DisablePasswordAuth             serpent.Bool                         `json:"disable_password_auth,omitempty" typescript:",notnull"`
	Support                         SupportConfig                        `json:"support,omitempty" typescript:",notnull"`
	ExternalAuthConfigs             serpent.Struct[[]ExternalAuthConfig] `json:"external_auth,omitempty" typescript:",notnull"`
	SSHConfig                       SSHConfig                            `json:"config_ssh,omitempty" typescript:",notnull"`
	WgtunnelHost                    serpent.String                       `json:"wgtunnel_host,omitempty" typescript:",notnull"`
	DisableOwnerWorkspaceExec       serpent.Bool                         `json:"disable_owner_workspace_exec,omitempty" typescript:",notnull"`
	ProxyHealthStatusInterval       serpent.Duration                     `json:"proxy_health_status_interval,omitempty" typescript:",notnull"`
	EnableTerraformDebugMode        serpent.Bool                         `json:"enable_terraform_debug_mode,omitempty" typescript:",notnull"`
	UserQuietHoursSchedule          UserQuietHoursScheduleConfig         `json:"user_quiet_hours_schedule,omitempty" typescript:",notnull"`
	WebTerminalRenderer             serpent.String                       `json:"web_terminal_renderer,omitempty" typescript:",notnull"`
	AllowWorkspaceRenames           serpent.Bool                         `json:"allow_workspace_renames,omitempty" typescript:",notnull"`
	Healthcheck                     HealthcheckConfig                    `json:"healthcheck,omitempty" typescript:",notnull"`
	CLIUpgradeMessage               serpent.String                       `json:"cli_upgrade_message,omitempty" typescript:",notnull"`
	TermsOfServiceURL               serpent.String                       `json:"terms_of_service_url,omitempty" typescript:",notnull"`
	Notifications                   NotificationsConfig                  `json:"notifications,omitempty" typescript:",notnull"`
	AdditionalCSPPolicy             serpent.StringArray                  `json:"additional_csp_policy,omitempty" typescript:",notnull"`

	Config      serpent.YAMLConfigPath `json:"config,omitempty" typescript:",notnull"`
	WriteConfig serpent.Bool           `json:"write_config,omitempty" typescript:",notnull"`

	// Deprecated: Use HTTPAddress or TLS.Address instead.
	Address serpent.HostPort `json:"address,omitempty" typescript:",notnull"`
}

DeploymentValues is the central configuration values the coder server.

func (*DeploymentValues) Options

func (c *DeploymentValues) Options() serpent.OptionSet

func (*DeploymentValues) WithoutSecrets

func (c *DeploymentValues) WithoutSecrets() (*DeploymentValues, error)

WithoutSecrets returns a copy of the config without secret values.

type DisplayApp added in v2.1.5

type DisplayApp string
const (
	DisplayAppVSCodeDesktop  DisplayApp = "vscode"
	DisplayAppVSCodeInsiders DisplayApp = "vscode_insiders"
	DisplayAppWebTerminal    DisplayApp = "web_terminal"
	DisplayAppPortForward    DisplayApp = "port_forwarding_helper"
	DisplayAppSSH            DisplayApp = "ssh_helper"
)

type EnhancedExternalAuthProvider added in v2.2.1

type EnhancedExternalAuthProvider string

EnhancedExternalAuthProvider is a constant that represents enhanced support for a type of external authentication. All of the Git providers are examples of enhanced, because they support intercepting "git clone".

const (
	EnhancedExternalAuthProviderAzureDevops EnhancedExternalAuthProvider = "azure-devops"
	// Authenticate to ADO using an app registration in Entra ID
	EnhancedExternalAuthProviderAzureDevopsEntra EnhancedExternalAuthProvider = "azure-devops-entra"
	EnhancedExternalAuthProviderGitHub           EnhancedExternalAuthProvider = "github"
	EnhancedExternalAuthProviderGitLab           EnhancedExternalAuthProvider = "gitlab"
	// EnhancedExternalAuthProviderBitBucketCloud is the Bitbucket Cloud provider.
	// Not to be confused with the self-hosted 'EnhancedExternalAuthProviderBitBucketServer'
	EnhancedExternalAuthProviderBitBucketCloud  EnhancedExternalAuthProvider = "bitbucket-cloud"
	EnhancedExternalAuthProviderBitBucketServer EnhancedExternalAuthProvider = "bitbucket-server"
	EnhancedExternalAuthProviderSlack           EnhancedExternalAuthProvider = "slack"
	EnhancedExternalAuthProviderJFrog           EnhancedExternalAuthProvider = "jfrog"
	EnhancedExternalAuthProviderGitea           EnhancedExternalAuthProvider = "gitea"
)

func (EnhancedExternalAuthProvider) Git added in v2.2.1

Git returns whether the provider is a Git provider.

func (EnhancedExternalAuthProvider) String added in v2.2.1

type Entitlement

type Entitlement string

Entitlement represents whether a feature is licensed.

const (
	EntitlementEntitled    Entitlement = "entitled"
	EntitlementGracePeriod Entitlement = "grace_period"
	EntitlementNotEntitled Entitlement = "not_entitled"
)

func (Entitlement) Entitled added in v2.15.0

func (e Entitlement) Entitled() bool

Entitled returns if the entitlement can be used. So this is true if it is entitled or still in it's grace period.

func (Entitlement) Weight added in v2.14.0

func (e Entitlement) Weight() int

Weight converts the enum types to a numerical value for easier comparisons. Easier than sets of if statements.

type Entitlements

type Entitlements struct {
	Features         map[FeatureName]Feature `json:"features"`
	Warnings         []string                `json:"warnings"`
	Errors           []string                `json:"errors"`
	HasLicense       bool                    `json:"has_license"`
	Trial            bool                    `json:"trial"`
	RequireTelemetry bool                    `json:"require_telemetry"`
	RefreshedAt      time.Time               `json:"refreshed_at" format:"date-time"`
}

func (*Entitlements) AddFeature added in v2.14.0

func (e *Entitlements) AddFeature(name FeatureName, add Feature)

AddFeature will add the feature to the entitlements iff it expands the set of features granted by the entitlements. If it does not, it will be ignored and the existing feature with the same name will remain.

All features should be added as atomic items, and not merged in any way. Merging entitlements could lead to unexpected behavior, like a larger user limit in grace period merging with a smaller one in an "entitled" state. This could lead to the larger limit being extended as "entitled", which is not correct.

type Error

type Error struct {
	Response

	Helper string
	// contains filtered or unexported fields
}

Error represents an unaccepted or invalid request to the API. @typescript-ignore Error

func AsError

func AsError(err error) (*Error, bool)

func (*Error) Error

func (e *Error) Error() string

func (*Error) Friendly

func (e *Error) Friendly() string

func (*Error) Method added in v2.2.1

func (e *Error) Method() string

func (*Error) StatusCode

func (e *Error) StatusCode() int

func (*Error) URL added in v2.2.1

func (e *Error) URL() string

type Experiment

type Experiment string
const (
	// Add new experiments here!
	ExperimentExample            Experiment = "example"              // This isn't used for anything.
	ExperimentAutoFillParameters Experiment = "auto-fill-parameters" // This should not be taken out of experiments until we have redesigned the feature.
	ExperimentNotifications      Experiment = "notifications"        // Sends notifications via SMTP and webhooks following certain events.
	ExperimentWorkspaceUsage     Experiment = "workspace-usage"      // Enables the new workspace usage tracking.
	ExperimentWebPush            Experiment = "web-push"             // Enables web push notifications through the browser.
)

type Experiments

type Experiments []Experiment

Experiments is a list of experiments. Multiple experiments may be enabled at the same time. Experiments are not safe for production use, and are not guaranteed to be backwards compatible. They may be removed or renamed at any time.

func (Experiments) Enabled

func (e Experiments) Enabled(ex Experiment) bool

Returns a list of experiments that are enabled for the deployment.

type ExternalAuth added in v2.2.1

type ExternalAuth struct {
	Authenticated bool   `json:"authenticated"`
	Device        bool   `json:"device"`
	DisplayName   string `json:"display_name"`

	// User is the user that authenticated with the provider.
	User *ExternalAuthUser `json:"user"`
	// AppInstallable is true if the request for app installs was successful.
	AppInstallable bool `json:"app_installable"`
	// AppInstallations are the installations that the user has access to.
	AppInstallations []ExternalAuthAppInstallation `json:"installations"`
	// AppInstallURL is the URL to install the app.
	AppInstallURL string `json:"app_install_url"`
}

type ExternalAuthAppInstallation added in v2.2.1

type ExternalAuthAppInstallation struct {
	ID           int              `json:"id"`
	Account      ExternalAuthUser `json:"account"`
	ConfigureURL string           `json:"configure_url"`
}

type ExternalAuthConfig added in v2.2.1

type ExternalAuthConfig struct {
	// Type is the type of external auth config.
	Type         string `json:"type" yaml:"type"`
	ClientID     string `json:"client_id" yaml:"client_id"`
	ClientSecret string `json:"-" yaml:"client_secret"`
	// ID is a unique identifier for the auth config.
	// It defaults to `type` when not provided.
	ID                  string   `json:"id" yaml:"id"`
	AuthURL             string   `json:"auth_url" yaml:"auth_url"`
	TokenURL            string   `json:"token_url" yaml:"token_url"`
	ValidateURL         string   `json:"validate_url" yaml:"validate_url"`
	AppInstallURL       string   `json:"app_install_url" yaml:"app_install_url"`
	AppInstallationsURL string   `json:"app_installations_url" yaml:"app_installations_url"`
	NoRefresh           bool     `json:"no_refresh" yaml:"no_refresh"`
	Scopes              []string `json:"scopes" yaml:"scopes"`
	ExtraTokenKeys      []string `json:"-" yaml:"extra_token_keys"`
	DeviceFlow          bool     `json:"device_flow" yaml:"device_flow"`
	DeviceCodeURL       string   `json:"device_code_url" yaml:"device_code_url"`
	// Regex allows API requesters to match an auth config by
	// a string (e.g. coder.com) instead of by it's type.
	//
	// Git clone makes use of this by parsing the URL from:
	// 'Username for "https://github.com":'
	// And sending it to the Coder server to match against the Regex.
	Regex string `json:"regex" yaml:"regex"`
	// DisplayName is shown in the UI to identify the auth config.
	DisplayName string `json:"display_name" yaml:"display_name"`
	// DisplayIcon is a URL to an icon to display in the UI.
	DisplayIcon string `json:"display_icon" yaml:"display_icon"`
}

type ExternalAuthDevice added in v2.2.1

type ExternalAuthDevice struct {
	DeviceCode      string `json:"device_code"`
	UserCode        string `json:"user_code"`
	VerificationURI string `json:"verification_uri"`
	ExpiresIn       int    `json:"expires_in"`
	Interval        int    `json:"interval"`
}

ExternalAuthDevice is the response from the device authorization endpoint. See: https://tools.ietf.org/html/rfc8628#section-3.2

type ExternalAuthDeviceExchange added in v2.2.1

type ExternalAuthDeviceExchange struct {
	DeviceCode string `json:"device_code"`
}
type ExternalAuthLink struct {
	ProviderID      string    `json:"provider_id"`
	CreatedAt       time.Time `json:"created_at" format:"date-time"`
	UpdatedAt       time.Time `json:"updated_at" format:"date-time"`
	HasRefreshToken bool      `json:"has_refresh_token"`
	Expires         time.Time `json:"expires" format:"date-time"`
	Authenticated   bool      `json:"authenticated"`
	ValidateError   string    `json:"validate_error"`
}

ExternalAuthLink is a link between a user and an external auth provider. It excludes information that requires a token to access, so can be statically built from the database and configs.

type ExternalAuthLinkProvider added in v2.5.0

type ExternalAuthLinkProvider struct {
	ID            string `json:"id"`
	Type          string `json:"type"`
	Device        bool   `json:"device"`
	DisplayName   string `json:"display_name"`
	DisplayIcon   string `json:"display_icon"`
	AllowRefresh  bool   `json:"allow_refresh"`
	AllowValidate bool   `json:"allow_validate"`
}

ExternalAuthLinkProvider are the static details of a provider.

type ExternalAuthUser added in v2.2.1

type ExternalAuthUser struct {
	ID         int64  `json:"id"`
	Login      string `json:"login"`
	AvatarURL  string `json:"avatar_url"`
	ProfileURL string `json:"profile_url"`
	Name       string `json:"name"`
}

type Feature

type Feature struct {
	Entitlement Entitlement `json:"entitlement"`
	Enabled     bool        `json:"enabled"`
	Limit       *int64      `json:"limit,omitempty"`
	Actual      *int64      `json:"actual,omitempty"`
}

func (Feature) Capable added in v2.14.0

func (f Feature) Capable() bool

Capable is a helper function that returns if a given feature has a limit that is greater than or equal to the actual. If this condition is not true, then the feature is not capable of being used since the limit is not high enough.

func (Feature) Compare added in v2.14.0

func (f Feature) Compare(b Feature) int

Compare compares two features and returns an integer representing if the first feature (f) is greater than, equal to, or less than the second feature (b). "Greater than" means the first feature has more functionality than the second feature. It is assumed the features are for the same FeatureName.

A feature is considered greater than another feature if: 1. Graceful & capable > Entitled & not capable 2. The entitlement is greater 3. The limit is greater 4. Enabled is greater than disabled 5. The actual is greater

type FeatureName

type FeatureName string

FeatureName represents the internal name of a feature. To add a new feature, add it to this set of enums as well as the FeatureNames array below.

const (
	FeatureUserLimit                  FeatureName = "user_limit"
	FeatureAuditLog                   FeatureName = "audit_log"
	FeatureBrowserOnly                FeatureName = "browser_only"
	FeatureSCIM                       FeatureName = "scim"
	FeatureTemplateRBAC               FeatureName = "template_rbac"
	FeatureUserRoleManagement         FeatureName = "user_role_management"
	FeatureHighAvailability           FeatureName = "high_availability"
	FeatureMultipleExternalAuth       FeatureName = "multiple_external_auth"
	FeatureExternalProvisionerDaemons FeatureName = "external_provisioner_daemons"
	FeatureAppearance                 FeatureName = "appearance"
	FeatureAdvancedTemplateScheduling FeatureName = "advanced_template_scheduling"
	FeatureWorkspaceProxy             FeatureName = "workspace_proxy"
	FeatureExternalTokenEncryption    FeatureName = "external_token_encryption"
	FeatureWorkspaceBatchActions      FeatureName = "workspace_batch_actions"
	FeatureAccessControl              FeatureName = "access_control"
	FeatureControlSharedPorts         FeatureName = "control_shared_ports"
	FeatureCustomRoles                FeatureName = "custom_roles"
	FeatureMultipleOrganizations      FeatureName = "multiple_organizations"
)

func (FeatureName) AlwaysEnable

func (n FeatureName) AlwaysEnable() bool

AlwaysEnable returns if the feature is always enabled if entitled. This is required because some features are only enabled if they are entitled and not required. E.g: "multiple-organizations" is disabled by default in AGPL and enterprise deployments. This feature should only be enabled for premium deployments when it is entitled.

func (FeatureName) Enterprise added in v2.15.0

func (n FeatureName) Enterprise() bool

Enterprise returns true if the feature is an enterprise feature.

func (FeatureName) Humanize

func (n FeatureName) Humanize() string

Humanize returns the feature name in a human-readable format.

type FeatureSet added in v2.14.0

type FeatureSet string

FeatureSet represents a grouping of features. Rather than manually assigning features al-la-carte when making a license, a set can be specified. Sets are dynamic in the sense a feature can be added to a set, granting the feature to existing licenses out in the wild. If features were granted al-la-carte, we would need to reissue the existing old licenses to include the new feature.

const (
	FeatureSetNone       FeatureSet = ""
	FeatureSetEnterprise FeatureSet = "enterprise"
	FeatureSetPremium    FeatureSet = "premium"
)

func (FeatureSet) Features added in v2.14.0

func (set FeatureSet) Features() []FeatureName

type GenerateAPIKeyResponse

type GenerateAPIKeyResponse struct {
	Key string `json:"key"`
}

GenerateAPIKeyResponse contains an API key for a user.

type GetInboxNotificationResponse added in v2.21.0

type GetInboxNotificationResponse struct {
	Notification InboxNotification `json:"notification"`
	UnreadCount  int               `json:"unread_count"`
}

type GetUserStatusCountsRequest added in v2.19.0

type GetUserStatusCountsRequest struct {
	Offset time.Time `json:"offset" format:"date-time"`
}

type GetUserStatusCountsResponse added in v2.19.0

type GetUserStatusCountsResponse struct {
	StatusCounts map[UserStatus][]UserStatusChangeCount `json:"status_counts"`
}

type GetUsersResponse

type GetUsersResponse struct {
	Users []User `json:"users"`
	Count int    `json:"count"`
}

type GitSSHKey

type GitSSHKey struct {
	UserID    uuid.UUID `json:"user_id" format:"uuid"`
	CreatedAt time.Time `json:"created_at" format:"date-time"`
	UpdatedAt time.Time `json:"updated_at" format:"date-time"`
	// PublicKey is the SSH public key in OpenSSH format.
	// Example: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAID3OmYJvT7q1cF1azbybYy0OZ9yrXfA+M6Lr4vzX5zlp\n"
	// Note: The key includes a trailing newline (\n).
	PublicKey string `json:"public_key"`
}

type GithubAuthMethod added in v2.20.0

type GithubAuthMethod struct {
	Enabled                   bool `json:"enabled"`
	DefaultProviderConfigured bool `json:"default_provider_configured"`
}

type Group

type Group struct {
	ID             uuid.UUID     `json:"id" format:"uuid"`
	Name           string        `json:"name"`
	DisplayName    string        `json:"display_name"`
	OrganizationID uuid.UUID     `json:"organization_id" format:"uuid"`
	Members        []ReducedUser `json:"members"`
	// How many members are in this group. Shows the total count,
	// even if the user is not authorized to read group member details.
	// May be greater than `len(Group.Members)`.
	TotalMemberCount        int         `json:"total_member_count"`
	AvatarURL               string      `json:"avatar_url"`
	QuotaAllowance          int         `json:"quota_allowance"`
	Source                  GroupSource `json:"source"`
	OrganizationName        string      `json:"organization_name"`
	OrganizationDisplayName string      `json:"organization_display_name"`
}

func (Group) IsEveryone

func (g Group) IsEveryone() bool

type GroupArguments added in v2.15.0

type GroupArguments struct {
	// Organization can be an org UUID or name
	Organization string
	// HasMember can be a user uuid or username
	HasMember string
	// GroupIDs is a list of group UUIDs to filter by.
	// If not set, all groups will be returned.
	GroupIDs []uuid.UUID
}

type GroupSource

type GroupSource string
const (
	GroupSourceUser GroupSource = "user"
	GroupSourceOIDC GroupSource = "oidc"
)

type GroupSyncSettings added in v2.16.0

type GroupSyncSettings struct {
	// Field is the name of the claim field that specifies what groups a user
	// should be in. If empty, no groups will be synced.
	Field string `json:"field"`
	// Mapping is a map from OIDC groups to Coder group IDs
	Mapping map[string][]uuid.UUID `json:"mapping"`
	// RegexFilter 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.
	RegexFilter *regexp.Regexp `json:"regex_filter"`
	// AutoCreateMissing controls whether groups returned by the OIDC provider
	// are automatically created in Coder if they are missing.
	AutoCreateMissing bool `json:"auto_create_missing_groups"`
	// LegacyNameMapping is deprecated. It remaps an IDP group name to
	// a Coder group name. Since configuration is now done at runtime,
	// group IDs are used to account for group renames.
	// For legacy configurations, this config option has to remain.
	// Deprecated: Use Mapping instead.
	LegacyNameMapping map[string]string `json:"legacy_group_name_mapping,omitempty"`
}

type HeaderTransport added in v2.5.0

type HeaderTransport struct {
	Transport http.RoundTripper
	Header    http.Header
}

HeaderTransport is a http.RoundTripper that adds some headers to all requests. @typescript-ignore HeaderTransport

func (*HeaderTransport) CloseIdleConnections added in v2.5.0

func (h *HeaderTransport) CloseIdleConnections()

func (*HeaderTransport) RoundTrip added in v2.5.0

func (h *HeaderTransport) RoundTrip(req *http.Request) (*http.Response, error)

type Healthcheck

type Healthcheck struct {
	// URL specifies the endpoint to check for the app health.
	URL string `json:"url"`
	// Interval specifies the seconds between each health check.
	Interval int32 `json:"interval"`
	// Threshold specifies the number of consecutive failed health checks before returning "unhealthy".
	Threshold int32 `json:"threshold"`
}

type HealthcheckConfig added in v2.4.0

type HealthcheckConfig struct {
	Refresh           serpent.Duration `json:"refresh" typescript:",notnull"`
	ThresholdDatabase serpent.Duration `json:"threshold_database" typescript:",notnull"`
}

HealthcheckConfig contains configuration for healthchecks.

type IDPSyncMapping added in v2.19.0

type IDPSyncMapping[ResourceIdType uuid.UUID | string] struct {
	// The IdP claim the user has
	Given string
	// The ID of the Coder resource the user should be added to
	Gets ResourceIdType
}

type InboxNotification added in v2.21.0

type InboxNotification struct {
	ID         uuid.UUID                 `json:"id" format:"uuid"`
	UserID     uuid.UUID                 `json:"user_id" format:"uuid"`
	TemplateID uuid.UUID                 `json:"template_id" format:"uuid"`
	Targets    []uuid.UUID               `json:"targets" format:"uuid"`
	Title      string                    `json:"title"`
	Content    string                    `json:"content"`
	Icon       string                    `json:"icon"`
	Actions    []InboxNotificationAction `json:"actions"`
	ReadAt     *time.Time                `json:"read_at"`
	CreatedAt  time.Time                 `json:"created_at" format:"date-time"`
}

type InboxNotificationAction added in v2.21.0

type InboxNotificationAction struct {
	Label string `json:"label"`
	URL   string `json:"url"`
}

type InsightsReportInterval

type InsightsReportInterval string

InsightsReportInterval is the interval of time over which to generate a smaller insights report within a time range.

const (
	InsightsReportIntervalDay  InsightsReportInterval = "day"
	InsightsReportIntervalWeek InsightsReportInterval = "week"
)

InsightsReportInterval enums.

func (InsightsReportInterval) Days added in v2.2.0

func (interval InsightsReportInterval) Days() int32

Days returns the duration of the interval in days.

type IssueReconnectingPTYSignedTokenRequest

type IssueReconnectingPTYSignedTokenRequest struct {
	// URL is the URL of the reconnecting-pty endpoint you are connecting to.
	URL     string    `json:"url" validate:"required"`
	AgentID uuid.UUID `json:"agentID" format:"uuid" validate:"required"`
}

type IssueReconnectingPTYSignedTokenResponse

type IssueReconnectingPTYSignedTokenResponse struct {
	SignedToken string `json:"signed_token"`
}

type JFrogXrayScan added in v2.8.0

type JFrogXrayScan struct {
	WorkspaceID uuid.UUID `json:"workspace_id" format:"uuid"`
	AgentID     uuid.UUID `json:"agent_id" format:"uuid"`
	Critical    int       `json:"critical"`
	High        int       `json:"high"`
	Medium      int       `json:"medium"`
	ResultsURL  string    `json:"results_url"`
}

type JobErrorCode

type JobErrorCode string

JobErrorCode defines the error code returned by job runner.

const (
	RequiredTemplateVariables JobErrorCode = "REQUIRED_TEMPLATE_VARIABLES"
)

type License

type License struct {
	ID         int32     `json:"id"`
	UUID       uuid.UUID `json:"uuid" format:"uuid"`
	UploadedAt time.Time `json:"uploaded_at" format:"date-time"`
	// Claims are the JWT claims asserted by the license.  Here we use
	// a generic string map to ensure that all data from the server is
	// parsed verbatim, not just the fields this version of Coder
	// understands.
	Claims map[string]interface{} `json:"claims" table:"claims"`
}

func (*License) AllFeaturesClaim

func (l *License) AllFeaturesClaim() bool

func (*License) ExpiresAt

func (l *License) ExpiresAt() (time.Time, error)

ExpiresAt returns the expiration time of the license. If the claim is missing or has an unexpected type, an error is returned.

func (*License) FeaturesClaims

func (l *License) FeaturesClaims() (map[FeatureName]int64, error)

FeaturesClaims provides the feature claims in license. This only returns the explicit claims. If checking for actual usage, also check `AllFeaturesClaim`.

func (*License) Trial

func (l *License) Trial() bool

type LicensorTrialRequest added in v2.7.0

type LicensorTrialRequest struct {
	DeploymentID string `json:"deployment_id"`
	Email        string `json:"email"`
	Source       string `json:"source"`

	// Personal details.
	FirstName   string `json:"first_name"`
	LastName    string `json:"last_name"`
	PhoneNumber string `json:"phone_number"`
	JobTitle    string `json:"job_title"`
	CompanyName string `json:"company_name"`
	Country     string `json:"country"`
	Developers  string `json:"developers"`
}

@typescript-ignore LicensorTrialRequest

type LinkConfig

type LinkConfig struct {
	Name   string `json:"name" yaml:"name"`
	Target string `json:"target" yaml:"target"`
	Icon   string `json:"icon" yaml:"icon" enums:"bug,chat,docs"`
}
func DefaultSupportLinks(docsURL string) []LinkConfig

type ListInboxNotificationsRequest added in v2.21.0

type ListInboxNotificationsRequest struct {
	Targets        string `json:"targets,omitempty"`
	Templates      string `json:"templates,omitempty"`
	ReadStatus     string `json:"read_status,omitempty"`
	StartingBefore string `json:"starting_before,omitempty"`
}

type ListInboxNotificationsResponse added in v2.21.0

type ListInboxNotificationsResponse struct {
	Notifications []InboxNotification `json:"notifications"`
	UnreadCount   int                 `json:"unread_count"`
}

type ListUserExternalAuthResponse added in v2.5.0

type ListUserExternalAuthResponse struct {
	Providers []ExternalAuthLinkProvider `json:"providers"`
	// Links are all the authenticated links for the user.
	// If a link has a provider ID that does not exist, then that provider
	// is no longer configured, rendering it unusable. It is still valuable
	// to include these links so that the user can unlink them.
	Links []ExternalAuthLink `json:"links"`
}

type LogLevel

type LogLevel string

type LogSource

type LogSource string

type LoggingConfig

type LoggingConfig struct {
	Filter      serpent.StringArray `json:"log_filter" typescript:",notnull"`
	Human       serpent.String      `json:"human" typescript:",notnull"`
	JSON        serpent.String      `json:"json" typescript:",notnull"`
	Stackdriver serpent.String      `json:"stackdriver" typescript:",notnull"`
}

type LoginType

type LoginType string

LoginType is the type of login used to create the API key.

const (
	LoginTypeUnknown  LoginType = ""
	LoginTypePassword LoginType = "password"
	LoginTypeGithub   LoginType = "github"
	LoginTypeOIDC     LoginType = "oidc"
	LoginTypeToken    LoginType = "token"
	// LoginTypeNone is used if no login method is available for this user.
	// If this is set, the user has no method of logging in.
	// API keys can still be created by an owner and used by the user.
	// These keys would use the `LoginTypeToken` type.
	LoginTypeNone LoginType = "none"
)

type LoginWithPasswordRequest

type LoginWithPasswordRequest struct {
	Email    string `json:"email" validate:"required,email" format:"email"`
	Password string `json:"password" validate:"required"`
}

LoginWithPasswordRequest enables callers to authenticate with email and password.

type LoginWithPasswordResponse

type LoginWithPasswordResponse struct {
	SessionToken string `json:"session_token" validate:"required"`
}

LoginWithPasswordResponse contains a session token for the newly authenticated user.

type MatchedProvisioners added in v2.18.0

type MatchedProvisioners struct {
	// Count is the number of provisioner daemons that matched the given
	// tags. If the count is 0, it means no provisioner daemons matched the
	// requested tags.
	Count int `json:"count"`
	// Available is the number of provisioner daemons that are available to
	// take jobs. This may be less than the count if some provisioners are
	// busy or have been stopped.
	Available int `json:"available"`
	// MostRecentlySeen is the most recently seen time of the set of matched
	// provisioners. If no provisioners matched, this field will be null.
	MostRecentlySeen NullTime `json:"most_recently_seen,omitempty" format:"date-time"`
}

MatchedProvisioners represents the number of provisioner daemons available to take a job at a specific point in time. Introduced in Coder version 2.18.0.

type MinimalOrganization added in v2.14.0

type MinimalOrganization struct {
	ID          uuid.UUID `table:"id" json:"id" validate:"required" format:"uuid"`
	Name        string    `table:"name,default_sort" json:"name"`
	DisplayName string    `table:"display name" json:"display_name"`
	Icon        string    `table:"icon" json:"icon"`
}

type MinimalUser

type MinimalUser struct {
	ID        uuid.UUID `json:"id" validate:"required" table:"id" format:"uuid"`
	Username  string    `json:"username" validate:"required" table:"username,default_sort"`
	AvatarURL string    `json:"avatar_url" format:"uri"`
}

MinimalUser is the minimal information needed to identify a user and show them on the UI.

type NotificationMethodsResponse added in v2.15.0

type NotificationMethodsResponse struct {
	AvailableNotificationMethods []string `json:"available"`
	DefaultNotificationMethod    string   `json:"default"`
}

type NotificationPreference added in v2.15.0

type NotificationPreference struct {
	NotificationTemplateID uuid.UUID `json:"id" format:"uuid"`
	Disabled               bool      `json:"disabled"`
	UpdatedAt              time.Time `json:"updated_at" format:"date-time"`
}

type NotificationTemplate added in v2.15.0

type NotificationTemplate struct {
	ID               uuid.UUID `json:"id" format:"uuid"`
	Name             string    `json:"name"`
	TitleTemplate    string    `json:"title_template"`
	BodyTemplate     string    `json:"body_template"`
	Actions          string    `json:"actions" format:""`
	Group            string    `json:"group"`
	Method           string    `json:"method"`
	Kind             string    `json:"kind"`
	EnabledByDefault bool      `json:"enabled_by_default"`
}

type NotificationsConfig added in v2.14.0

type NotificationsConfig struct {
	// The upper limit of attempts to send a notification.
	MaxSendAttempts serpent.Int64 `json:"max_send_attempts" typescript:",notnull"`
	// The minimum time between retries.
	RetryInterval serpent.Duration `json:"retry_interval" typescript:",notnull"`

	// The notifications system buffers message updates in memory to ease pressure on the database.
	// This option controls how often it synchronizes its state with the database. The shorter this value the
	// lower the change of state inconsistency in a non-graceful shutdown - but it also increases load on the
	// database. It is recommended to keep this option at its default value.
	StoreSyncInterval serpent.Duration `json:"sync_interval" typescript:",notnull"`
	// The notifications system buffers message updates in memory to ease pressure on the database.
	// This option controls how many updates are kept in memory. The lower this value the
	// lower the change of state inconsistency in a non-graceful shutdown - but it also increases load on the
	// database. It is recommended to keep this option at its default value.
	StoreSyncBufferSize serpent.Int64 `json:"sync_buffer_size" typescript:",notnull"`

	// How long a notifier should lease a message. This is effectively how long a notification is 'owned'
	// by a notifier, and once this period expires it will be available for lease by another notifier. Leasing
	// is important in order for multiple running notifiers to not pick the same messages to deliver concurrently.
	// This lease period will only expire if a notifier shuts down ungracefully; a dispatch of the notification
	// releases the lease.
	LeasePeriod serpent.Duration `json:"lease_period"`
	// How many notifications a notifier should lease per fetch interval.
	LeaseCount serpent.Int64 `json:"lease_count"`
	// How often to query the database for queued notifications.
	FetchInterval serpent.Duration `json:"fetch_interval"`

	// Which delivery method to use (available options: 'smtp', 'webhook').
	Method serpent.String `json:"method"`
	// How long to wait while a notification is being sent before giving up.
	DispatchTimeout serpent.Duration `json:"dispatch_timeout"`
	// SMTP settings.
	SMTP NotificationsEmailConfig `json:"email" typescript:",notnull"`
	// Webhook settings.
	Webhook NotificationsWebhookConfig `json:"webhook" typescript:",notnull"`
	// Inbox settings.
	Inbox NotificationsInboxConfig `json:"inbox" typescript:",notnull"`
}

func (*NotificationsConfig) Enabled added in v2.18.0

func (n *NotificationsConfig) Enabled() bool

Are either of the notification methods enabled?

type NotificationsEmailAuthConfig added in v2.14.0

type NotificationsEmailAuthConfig struct {
	// Identity for PLAIN auth.
	Identity serpent.String `json:"identity" typescript:",notnull"`
	// Username for LOGIN/PLAIN auth.
	Username serpent.String `json:"username" typescript:",notnull"`
	// Password for LOGIN/PLAIN auth.
	Password serpent.String `json:"password" typescript:",notnull"`
	// File from which to load the password for LOGIN/PLAIN auth.
	PasswordFile serpent.String `json:"password_file" typescript:",notnull"`
}

func (*NotificationsEmailAuthConfig) Empty added in v2.14.0

type NotificationsEmailConfig added in v2.14.0

type NotificationsEmailConfig struct {
	// The sender's address.
	From serpent.String `json:"from" typescript:",notnull"`
	// The intermediary SMTP host through which emails are sent (host:port).
	Smarthost serpent.String `json:"smarthost" typescript:",notnull"`
	// The hostname identifying the SMTP server.
	Hello serpent.String `json:"hello" typescript:",notnull"`

	// Authentication details.
	Auth NotificationsEmailAuthConfig `json:"auth" typescript:",notnull"`
	// TLS details.
	TLS NotificationsEmailTLSConfig `json:"tls" typescript:",notnull"`
	// ForceTLS causes a TLS connection to be attempted.
	ForceTLS serpent.Bool `json:"force_tls" typescript:",notnull"`
}

type NotificationsEmailTLSConfig added in v2.14.0

type NotificationsEmailTLSConfig struct {
	// StartTLS attempts to upgrade plain connections to TLS.
	StartTLS serpent.Bool `json:"start_tls" typescript:",notnull"`
	// ServerName to verify the hostname for the targets.
	ServerName serpent.String `json:"server_name" typescript:",notnull"`
	// InsecureSkipVerify skips target certificate validation.
	InsecureSkipVerify serpent.Bool `json:"insecure_skip_verify" typescript:",notnull"`
	// CAFile specifies the location of the CA certificate to use.
	CAFile serpent.String `json:"ca_file" typescript:",notnull"`
	// CertFile specifies the location of the certificate to use.
	CertFile serpent.String `json:"cert_file" typescript:",notnull"`
	// KeyFile specifies the location of the key to use.
	KeyFile serpent.String `json:"key_file" typescript:",notnull"`
}

func (*NotificationsEmailTLSConfig) Empty added in v2.14.0

func (c *NotificationsEmailTLSConfig) Empty() bool

type NotificationsInboxConfig added in v2.21.0

type NotificationsInboxConfig struct {
	Enabled serpent.Bool `json:"enabled" typescript:",notnull"`
}

type NotificationsSettings added in v2.14.0

type NotificationsSettings struct {
	NotifierPaused bool `json:"notifier_paused"`
}

type NotificationsWebhookConfig added in v2.14.0

type NotificationsWebhookConfig struct {
	// The URL to which the payload will be sent with an HTTP POST request.
	Endpoint serpent.URL `json:"endpoint" typescript:",notnull"`
}

type NullTime

type NullTime struct {
	sql.NullTime
}

NullTime represents a nullable time.Time. @typescript-ignore NullTime

func NewNullTime

func NewNullTime(t time.Time, valid bool) NullTime

NewNullTime returns a new NullTime with the given time.Time.

func (NullTime) IsZero

func (t NullTime) IsZero() bool

IsZero return true if the time is null or zero.

func (NullTime) MarshalJSON

func (t NullTime) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (*NullTime) UnmarshalJSON

func (t *NullTime) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

type OAuth2AppEndpoints added in v2.8.0

type OAuth2AppEndpoints struct {
	Authorization string `json:"authorization"`
	Token         string `json:"token"`
	// DeviceAuth is optional.
	DeviceAuth string `json:"device_authorization"`
}

type OAuth2Config

type OAuth2Config struct {
	Github OAuth2GithubConfig `json:"github" typescript:",notnull"`
}

type OAuth2DeviceFlowCallbackResponse added in v2.20.0

type OAuth2DeviceFlowCallbackResponse struct {
	RedirectURL string `json:"redirect_url"`
}

type OAuth2GithubConfig

type OAuth2GithubConfig struct {
	ClientID              serpent.String      `json:"client_id" typescript:",notnull"`
	ClientSecret          serpent.String      `json:"client_secret" typescript:",notnull"`
	DeviceFlow            serpent.Bool        `json:"device_flow" typescript:",notnull"`
	DefaultProviderEnable serpent.Bool        `json:"default_provider_enable" typescript:",notnull"`
	AllowedOrgs           serpent.StringArray `json:"allowed_orgs" typescript:",notnull"`
	AllowedTeams          serpent.StringArray `json:"allowed_teams" typescript:",notnull"`
	AllowSignups          serpent.Bool        `json:"allow_signups" typescript:",notnull"`
	AllowEveryone         serpent.Bool        `json:"allow_everyone" typescript:",notnull"`
	EnterpriseBaseURL     serpent.String      `json:"enterprise_base_url" typescript:",notnull"`
}

type OAuth2ProviderApp added in v2.6.0

type OAuth2ProviderApp struct {
	ID          uuid.UUID `json:"id" format:"uuid"`
	Name        string    `json:"name"`
	CallbackURL string    `json:"callback_url"`
	Icon        string    `json:"icon"`

	// Endpoints are included in the app response for easier discovery. The OAuth2
	// spec does not have a defined place to find these (for comparison, OIDC has
	// a '/.well-known/openid-configuration' endpoint).
	Endpoints OAuth2AppEndpoints `json:"endpoints"`
}

type OAuth2ProviderAppFilter added in v2.9.0

type OAuth2ProviderAppFilter struct {
	UserID uuid.UUID `json:"user_id,omitempty" format:"uuid"`
}

type OAuth2ProviderAppSecret added in v2.6.0

type OAuth2ProviderAppSecret struct {
	ID                    uuid.UUID `json:"id" format:"uuid"`
	LastUsedAt            NullTime  `json:"last_used_at"`
	ClientSecretTruncated string    `json:"client_secret_truncated"`
}

type OAuth2ProviderAppSecretFull added in v2.6.0

type OAuth2ProviderAppSecretFull struct {
	ID               uuid.UUID `json:"id" format:"uuid"`
	ClientSecretFull string    `json:"client_secret_full"`
}

type OAuth2ProviderGrantType added in v2.9.0

type OAuth2ProviderGrantType string
const (
	OAuth2ProviderGrantTypeAuthorizationCode OAuth2ProviderGrantType = "authorization_code"
	OAuth2ProviderGrantTypeRefreshToken      OAuth2ProviderGrantType = "refresh_token"
)

func (OAuth2ProviderGrantType) Valid added in v2.9.0

func (e OAuth2ProviderGrantType) Valid() bool

type OAuth2ProviderResponseType added in v2.9.0

type OAuth2ProviderResponseType string
const (
	OAuth2ProviderResponseTypeCode OAuth2ProviderResponseType = "code"
)

func (OAuth2ProviderResponseType) Valid added in v2.9.0

func (e OAuth2ProviderResponseType) Valid() bool

type OAuthConversionResponse

type OAuthConversionResponse struct {
	StateString string    `json:"state_string"`
	ExpiresAt   time.Time `json:"expires_at" format:"date-time"`
	ToType      LoginType `json:"to_type"`
	UserID      uuid.UUID `json:"user_id" format:"uuid"`
}

type OIDCAuthMethod

type OIDCAuthMethod struct {
	AuthMethod
	SignInText string `json:"signInText"`
	IconURL    string `json:"iconUrl"`
}

type OIDCConfig

type OIDCConfig struct {
	AllowSignups serpent.Bool   `json:"allow_signups" typescript:",notnull"`
	ClientID     serpent.String `json:"client_id" typescript:",notnull"`
	ClientSecret serpent.String `json:"client_secret" typescript:",notnull"`
	// ClientKeyFile & ClientCertFile are used in place of ClientSecret for PKI auth.
	ClientKeyFile       serpent.String                    `json:"client_key_file" typescript:",notnull"`
	ClientCertFile      serpent.String                    `json:"client_cert_file" typescript:",notnull"`
	EmailDomain         serpent.StringArray               `json:"email_domain" typescript:",notnull"`
	IssuerURL           serpent.String                    `json:"issuer_url" typescript:",notnull"`
	Scopes              serpent.StringArray               `json:"scopes" typescript:",notnull"`
	IgnoreEmailVerified serpent.Bool                      `json:"ignore_email_verified" typescript:",notnull"`
	UsernameField       serpent.String                    `json:"username_field" typescript:",notnull"`
	NameField           serpent.String                    `json:"name_field" typescript:",notnull"`
	EmailField          serpent.String                    `json:"email_field" typescript:",notnull"`
	AuthURLParams       serpent.Struct[map[string]string] `json:"auth_url_params" typescript:",notnull"`
	// IgnoreUserInfo & UserInfoFromAccessToken are mutually exclusive. Only 1
	// can be set to true. Ideally this would be an enum with 3 states, ['none',
	// 'userinfo', 'access_token']. However, for backward compatibility,
	// `ignore_user_info` must remain. And `access_token` is a niche, non-spec
	// compliant edge case. So it's use is rare, and should not be advised.
	IgnoreUserInfo serpent.Bool `json:"ignore_user_info" typescript:",notnull"`
	// UserInfoFromAccessToken as mentioned above is an edge case. This allows
	// sourcing the user_info from the access token itself instead of a user_info
	// endpoint. This assumes the access token is a valid JWT with a set of claims to
	// be merged with the id_token.
	UserInfoFromAccessToken   serpent.Bool                           `json:"source_user_info_from_access_token" typescript:",notnull"`
	OrganizationField         serpent.String                         `json:"organization_field" typescript:",notnull"`
	OrganizationMapping       serpent.Struct[map[string][]uuid.UUID] `json:"organization_mapping" typescript:",notnull"`
	OrganizationAssignDefault serpent.Bool                           `json:"organization_assign_default" typescript:",notnull"`
	GroupAutoCreate           serpent.Bool                           `json:"group_auto_create" typescript:",notnull"`
	GroupRegexFilter          serpent.Regexp                         `json:"group_regex_filter" typescript:",notnull"`
	GroupAllowList            serpent.StringArray                    `json:"group_allow_list" typescript:",notnull"`
	GroupField                serpent.String                         `json:"groups_field" typescript:",notnull"`
	GroupMapping              serpent.Struct[map[string]string]      `json:"group_mapping" typescript:",notnull"`
	UserRoleField             serpent.String                         `json:"user_role_field" typescript:",notnull"`
	UserRoleMapping           serpent.Struct[map[string][]string]    `json:"user_role_mapping" typescript:",notnull"`
	UserRolesDefault          serpent.StringArray                    `json:"user_roles_default" typescript:",notnull"`
	SignInText                serpent.String                         `json:"sign_in_text" typescript:",notnull"`
	IconURL                   serpent.URL                            `json:"icon_url" typescript:",notnull"`
	SignupsDisabledText       serpent.String                         `json:"signups_disabled_text" typescript:",notnull"`
	SkipIssuerChecks          serpent.Bool                           `json:"skip_issuer_checks" typescript:",notnull"`
}

type Organization

type Organization struct {
	MinimalOrganization `table:"m,recursive_inline"`
	Description         string    `table:"description" json:"description"`
	CreatedAt           time.Time `table:"created at" json:"created_at" validate:"required" format:"date-time"`
	UpdatedAt           time.Time `table:"updated at" json:"updated_at" validate:"required" format:"date-time"`
	IsDefault           bool      `table:"default" json:"is_default" validate:"required"`
}

Organization is the JSON representation of a Coder organization.

func (Organization) HumanName added in v2.13.0

func (o Organization) HumanName() string

type OrganizationMember

type OrganizationMember struct {
	UserID         uuid.UUID  `table:"user id" json:"user_id" format:"uuid"`
	OrganizationID uuid.UUID  `table:"organization id" json:"organization_id" format:"uuid"`
	CreatedAt      time.Time  `table:"created at" json:"created_at" format:"date-time"`
	UpdatedAt      time.Time  `table:"updated at" json:"updated_at" format:"date-time"`
	Roles          []SlimRole `table:"organization roles" json:"roles"`
}

type OrganizationMemberWithUserData added in v2.14.0

type OrganizationMemberWithUserData struct {
	Username           string     `table:"username,default_sort" json:"username"`
	Name               string     `table:"name" json:"name"`
	AvatarURL          string     `json:"avatar_url"`
	Email              string     `json:"email"`
	GlobalRoles        []SlimRole `json:"global_roles"`
	OrganizationMember `table:"m,recursive_inline"`
}

type OrganizationProvisionerDaemonsOptions added in v2.20.0

type OrganizationProvisionerDaemonsOptions struct {
	Limit int
	IDs   []uuid.UUID
	Tags  map[string]string
}

type OrganizationProvisionerJobsOptions added in v2.19.0

type OrganizationProvisionerJobsOptions struct {
	Limit  int
	IDs    []uuid.UUID
	Status []ProvisionerJobStatus
	Tags   map[string]string
}

type OrganizationSyncSettings added in v2.18.0

type OrganizationSyncSettings struct {
	// Field selects the claim field to be used as the created user's
	// organizations. If the field is the empty string, then no organization
	// updates will ever come from the OIDC provider.
	Field string `json:"field"`
	// Mapping maps from an OIDC claim --> Coder organization uuid
	Mapping map[string][]uuid.UUID `json:"mapping"`
	// AssignDefault will ensure the default org is always included
	// for every user, regardless of their claims. This preserves legacy behavior.
	AssignDefault bool `json:"organization_assign_default"`
}

type PaginatedMembersRequest added in v2.21.0

type PaginatedMembersRequest struct {
	Limit  int `json:"limit,omitempty"`
	Offset int `json:"offset,omitempty"`
}

type PaginatedMembersResponse added in v2.21.0

type PaginatedMembersResponse struct {
	Members []OrganizationMemberWithUserData `json:"members"`
	Count   int                              `json:"count"`
}

type Pagination

type Pagination struct {
	// AfterID returns all or up to Limit results after the given
	// UUID. This option can be used with or as an alternative to
	// Offset for better performance. To use it as an alternative,
	// set AfterID to the last UUID returned by the previous
	// request.
	AfterID uuid.UUID `json:"after_id,omitempty" format:"uuid"`
	// Limit sets the maximum number of users to be returned
	// in a single page. If the limit is <= 0, there is no limit
	// and all users are returned.
	Limit int `json:"limit,omitempty"`
	// Offset is used to indicate which page to return. An offset of 0
	// returns the first 'limit' number of users.
	// To get the next page, use offset=<limit>*<page_number>.
	// Offset is 0 indexed, so the first record sits at offset 0.
	Offset int `json:"offset,omitempty"`
}

Pagination sets pagination options for the endpoints that support it.

type ParameterResolver

type ParameterResolver struct {
	Rich []WorkspaceBuildParameter
}

ParameterResolver should be populated with legacy workload and rich parameter values from the previous build. It then supports queries against a current TemplateVersionParameter to determine whether a new value is required, or a value correctly validates. @typescript-ignore ParameterResolver

func (*ParameterResolver) ValidateResolve

func (r *ParameterResolver) ValidateResolve(p TemplateVersionParameter, v *WorkspaceBuildParameter) (value string, err error)

ValidateResolve checks the provided value, v, against the parameter, p, and the previous build. If v is nil, it also resolves the correct value. It returns the value of the parameter, if valid, and an error if invalid.

type PatchGroupIDPSyncConfigRequest added in v2.19.0

type PatchGroupIDPSyncConfigRequest struct {
	Field             string         `json:"field"`
	RegexFilter       *regexp.Regexp `json:"regex_filter"`
	AutoCreateMissing bool           `json:"auto_create_missing_groups"`
}

type PatchGroupIDPSyncMappingRequest added in v2.19.0

type PatchGroupIDPSyncMappingRequest struct {
	Add    []IDPSyncMapping[uuid.UUID]
	Remove []IDPSyncMapping[uuid.UUID]
}

If the same mapping is present in both Add and Remove, Remove will take presidence.

type PatchGroupRequest

type PatchGroupRequest struct {
	AddUsers       []string `json:"add_users"`
	RemoveUsers    []string `json:"remove_users"`
	Name           string   `json:"name" validate:"omitempty,group_name"`
	DisplayName    *string  `json:"display_name" validate:"omitempty,group_display_name"`
	AvatarURL      *string  `json:"avatar_url"`
	QuotaAllowance *int     `json:"quota_allowance"`
}

type PatchOrganizationIDPSyncConfigRequest added in v2.19.0

type PatchOrganizationIDPSyncConfigRequest struct {
	Field         string `json:"field"`
	AssignDefault bool   `json:"assign_default"`
}

type PatchOrganizationIDPSyncMappingRequest added in v2.19.0

type PatchOrganizationIDPSyncMappingRequest struct {
	Add    []IDPSyncMapping[uuid.UUID]
	Remove []IDPSyncMapping[uuid.UUID]
}

If the same mapping is present in both Add and Remove, Remove will take presidence.

type PatchRoleIDPSyncConfigRequest added in v2.19.0

type PatchRoleIDPSyncConfigRequest struct {
	Field string `json:"field"`
}

type PatchRoleIDPSyncMappingRequest added in v2.19.0

type PatchRoleIDPSyncMappingRequest struct {
	Add    []IDPSyncMapping[string]
	Remove []IDPSyncMapping[string]
}

If the same mapping is present in both Add and Remove, Remove will take presidence.

type PatchTemplateVersionRequest

type PatchTemplateVersionRequest struct {
	Name    string  `json:"name" validate:"omitempty,template_version_name"`
	Message *string `json:"message,omitempty" validate:"omitempty,lt=1048577"`
}

type PatchWorkspaceProxy

type PatchWorkspaceProxy struct {
	ID              uuid.UUID `json:"id" format:"uuid" validate:"required"`
	Name            string    `json:"name" validate:"required"`
	DisplayName     string    `json:"display_name" validate:"required"`
	Icon            string    `json:"icon" validate:"required"`
	RegenerateToken bool      `json:"regenerate_token"`
}

type Permission added in v2.12.0

type Permission struct {
	// Negate makes this a negative permission
	Negate       bool         `json:"negate"`
	ResourceType RBACResource `json:"resource_type"`
	Action       RBACAction   `json:"action"`
}

Permission is the format passed into the rego.

func CreatePermissions added in v2.12.0

func CreatePermissions(mapping map[RBACResource][]RBACAction) []Permission

CreatePermissions is a helper function to quickly build permissions.

type PostOAuth2ProviderAppRequest added in v2.6.0

type PostOAuth2ProviderAppRequest struct {
	Name        string `json:"name" validate:"required,oauth2_app_name"`
	CallbackURL string `json:"callback_url" validate:"required,http_url"`
	Icon        string `json:"icon" validate:"omitempty"`
}

type PostWorkspaceUsageRequest added in v2.13.0

type PostWorkspaceUsageRequest struct {
	AgentID uuid.UUID    `json:"agent_id" format:"uuid"`
	AppName UsageAppName `json:"app_name"`
}

type PostgresAuth added in v2.10.0

type PostgresAuth string
const (
	PostgresAuthPassword  PostgresAuth = "password"
	PostgresAuthAWSIAMRDS PostgresAuth = "awsiamrds"
)

type PprofConfig

type PprofConfig struct {
	Enable  serpent.Bool     `json:"enable" typescript:",notnull"`
	Address serpent.HostPort `json:"address" typescript:",notnull"`
}

type Preset added in v2.20.0

type Preset struct {
	ID         uuid.UUID
	Name       string
	Parameters []PresetParameter
}

type PresetParameter added in v2.20.0

type PresetParameter struct {
	Name  string
	Value string
}

type PrometheusConfig

type PrometheusConfig struct {
	Enable                serpent.Bool        `json:"enable" typescript:",notnull"`
	Address               serpent.HostPort    `json:"address" typescript:",notnull"`
	CollectAgentStats     serpent.Bool        `json:"collect_agent_stats" typescript:",notnull"`
	CollectDBMetrics      serpent.Bool        `json:"collect_db_metrics" typescript:",notnull"`
	AggregateAgentStatsBy serpent.StringArray `json:"aggregate_agent_stats_by" typescript:",notnull"`
}

type ProvisionerConfig

type ProvisionerConfig struct {
	// Daemons is the number of built-in terraform provisioners.
	Daemons             serpent.Int64       `json:"daemons" typescript:",notnull"`
	DaemonTypes         serpent.StringArray `json:"daemon_types" typescript:",notnull"`
	DaemonPollInterval  serpent.Duration    `json:"daemon_poll_interval" typescript:",notnull"`
	DaemonPollJitter    serpent.Duration    `json:"daemon_poll_jitter" typescript:",notnull"`
	ForceCancelInterval serpent.Duration    `json:"force_cancel_interval" typescript:",notnull"`
	DaemonPSK           serpent.String      `json:"daemon_psk" typescript:",notnull"`
}

type ProvisionerDaemon

type ProvisionerDaemon struct {
	ID             uuid.UUID         `json:"id" format:"uuid" table:"id"`
	OrganizationID uuid.UUID         `json:"organization_id" format:"uuid" table:"organization id"`
	KeyID          uuid.UUID         `json:"key_id" format:"uuid" table:"-"`
	CreatedAt      time.Time         `json:"created_at" format:"date-time" table:"created at"`
	LastSeenAt     NullTime          `json:"last_seen_at,omitempty" format:"date-time" table:"last seen at"`
	Name           string            `json:"name" table:"name,default_sort"`
	Version        string            `json:"version" table:"version"`
	APIVersion     string            `json:"api_version" table:"api version"`
	Provisioners   []ProvisionerType `json:"provisioners" table:"-"`
	Tags           map[string]string `json:"tags" table:"tags"`

	// Optional fields.
	KeyName     *string                  `json:"key_name" table:"key name"`
	Status      *ProvisionerDaemonStatus `json:"status" enums:"offline,idle,busy" table:"status"`
	CurrentJob  *ProvisionerDaemonJob    `json:"current_job" table:"current job,recursive"`
	PreviousJob *ProvisionerDaemonJob    `json:"previous_job" table:"previous job,recursive"`
}

type ProvisionerDaemonJob added in v2.19.0

type ProvisionerDaemonJob struct {
	ID                  uuid.UUID            `json:"id" format:"uuid" table:"id"`
	Status              ProvisionerJobStatus `json:"status" enums:"pending,running,succeeded,canceling,canceled,failed" table:"status"`
	TemplateName        string               `json:"template_name" table:"template name"`
	TemplateIcon        string               `json:"template_icon" table:"template icon"`
	TemplateDisplayName string               `json:"template_display_name" table:"template display name"`
}

type ProvisionerDaemonStatus added in v2.19.0

type ProvisionerDaemonStatus string

ProvisionerDaemonStatus represents the status of a provisioner daemon.

const (
	ProvisionerDaemonOffline ProvisionerDaemonStatus = "offline"
	ProvisionerDaemonIdle    ProvisionerDaemonStatus = "idle"
	ProvisionerDaemonBusy    ProvisionerDaemonStatus = "busy"
)

ProvisionerDaemonStatus enums.

type ProvisionerJob

type ProvisionerJob struct {
	ID               uuid.UUID              `json:"id" format:"uuid" table:"id"`
	CreatedAt        time.Time              `json:"created_at" format:"date-time" table:"created at"`
	StartedAt        *time.Time             `json:"started_at,omitempty" format:"date-time" table:"started at"`
	CompletedAt      *time.Time             `json:"completed_at,omitempty" format:"date-time" table:"completed at"`
	CanceledAt       *time.Time             `json:"canceled_at,omitempty" format:"date-time" table:"canceled at"`
	Error            string                 `json:"error,omitempty" table:"error"`
	ErrorCode        JobErrorCode           `json:"error_code,omitempty" enums:"REQUIRED_TEMPLATE_VARIABLES" table:"error code"`
	Status           ProvisionerJobStatus   `json:"status" enums:"pending,running,succeeded,canceling,canceled,failed" table:"status"`
	WorkerID         *uuid.UUID             `json:"worker_id,omitempty" format:"uuid" table:"worker id"`
	FileID           uuid.UUID              `json:"file_id" format:"uuid" table:"file id"`
	Tags             map[string]string      `json:"tags" table:"tags"`
	QueuePosition    int                    `json:"queue_position" table:"queue position"`
	QueueSize        int                    `json:"queue_size" table:"queue size"`
	OrganizationID   uuid.UUID              `json:"organization_id" format:"uuid" table:"organization id"`
	Input            ProvisionerJobInput    `json:"input" table:"input,recursive_inline"`
	Type             ProvisionerJobType     `json:"type" table:"type"`
	AvailableWorkers []uuid.UUID            `json:"available_workers,omitempty" format:"uuid" table:"available workers"`
	Metadata         ProvisionerJobMetadata `json:"metadata" table:"metadata,recursive_inline"`
}

ProvisionerJob describes the job executed by the provisioning daemon.

type ProvisionerJobInput added in v2.19.0

type ProvisionerJobInput struct {
	TemplateVersionID *uuid.UUID `json:"template_version_id,omitempty" format:"uuid" table:"template version id"`
	WorkspaceBuildID  *uuid.UUID `json:"workspace_build_id,omitempty" format:"uuid" table:"workspace build id"`
	Error             string     `json:"error,omitempty" table:"-"`
}

ProvisionerJobInput represents the input for the job.

type ProvisionerJobLog

type ProvisionerJobLog struct {
	ID        int64     `json:"id"`
	CreatedAt time.Time `json:"created_at" format:"date-time"`
	Source    LogSource `json:"log_source"`
	Level     LogLevel  `json:"log_level" enums:"trace,debug,info,warn,error"`
	Stage     string    `json:"stage"`
	Output    string    `json:"output"`
}

ProvisionerJobLog represents the provisioner log entry annotated with source and level.

type ProvisionerJobMetadata added in v2.20.0

type ProvisionerJobMetadata struct {
	TemplateVersionName string     `json:"template_version_name" table:"template version name"`
	TemplateID          uuid.UUID  `json:"template_id" format:"uuid" table:"template id"`
	TemplateName        string     `json:"template_name" table:"template name"`
	TemplateDisplayName string     `json:"template_display_name" table:"template display name"`
	TemplateIcon        string     `json:"template_icon" table:"template icon"`
	WorkspaceID         *uuid.UUID `json:"workspace_id,omitempty" format:"uuid" table:"workspace id"`
	WorkspaceName       string     `json:"workspace_name,omitempty" table:"workspace name"`
}

ProvisionerJobMetadata contains metadata for the job.

type ProvisionerJobStatus

type ProvisionerJobStatus string

ProvisionerJobStatus represents the at-time state of a job.

const (
	ProvisionerJobPending   ProvisionerJobStatus = "pending"
	ProvisionerJobRunning   ProvisionerJobStatus = "running"
	ProvisionerJobSucceeded ProvisionerJobStatus = "succeeded"
	ProvisionerJobCanceling ProvisionerJobStatus = "canceling"
	ProvisionerJobCanceled  ProvisionerJobStatus = "canceled"
	ProvisionerJobFailed    ProvisionerJobStatus = "failed"
	ProvisionerJobUnknown   ProvisionerJobStatus = "unknown"
)

func ProvisionerJobStatusEnums added in v2.19.0

func ProvisionerJobStatusEnums() []ProvisionerJobStatus

func (ProvisionerJobStatus) Active

func (p ProvisionerJobStatus) Active() bool

Active returns whether the job is still active or not. It returns true if canceling as well, since the job isn't in an entirely inactive state yet.

type ProvisionerJobType added in v2.19.0

type ProvisionerJobType string

ProvisionerJobType represents the type of job.

const (
	ProvisionerJobTypeTemplateVersionImport ProvisionerJobType = "template_version_import"
	ProvisionerJobTypeWorkspaceBuild        ProvisionerJobType = "workspace_build"
	ProvisionerJobTypeTemplateVersionDryRun ProvisionerJobType = "template_version_dry_run"
)

type ProvisionerKey added in v2.14.0

type ProvisionerKey struct {
	ID             uuid.UUID          `json:"id" table:"-" format:"uuid"`
	CreatedAt      time.Time          `json:"created_at" table:"created at" format:"date-time"`
	OrganizationID uuid.UUID          `json:"organization" table:"-" format:"uuid"`
	Name           string             `json:"name" table:"name,default_sort"`
	Tags           ProvisionerKeyTags `json:"tags" table:"tags"`
}

type ProvisionerKeyDaemons added in v2.16.0

type ProvisionerKeyDaemons struct {
	Key     ProvisionerKey      `json:"key"`
	Daemons []ProvisionerDaemon `json:"daemons"`
}

type ProvisionerKeyTags added in v2.16.0

type ProvisionerKeyTags map[string]string

func (ProvisionerKeyTags) String added in v2.16.0

func (p ProvisionerKeyTags) String() string

type ProvisionerLogLevel

type ProvisionerLogLevel string
const (
	ProvisionerLogLevelDebug ProvisionerLogLevel = "debug"
)

type ProvisionerStorageMethod

type ProvisionerStorageMethod string
const (
	ProvisionerStorageMethodFile ProvisionerStorageMethod = "file"
)

type ProvisionerTiming added in v2.16.0

type ProvisionerTiming struct {
	JobID     uuid.UUID   `json:"job_id" format:"uuid"`
	StartedAt time.Time   `json:"started_at" format:"date-time"`
	EndedAt   time.Time   `json:"ended_at" format:"date-time"`
	Stage     TimingStage `json:"stage"`
	Source    string      `json:"source"`
	Action    string      `json:"action"`
	Resource  string      `json:"resource"`
}

type ProvisionerType

type ProvisionerType string
const (
	ProvisionerTypeEcho      ProvisionerType = "echo"
	ProvisionerTypeTerraform ProvisionerType = "terraform"
)

type ProxyHealthReport

type ProxyHealthReport struct {
	// Errors are problems that prevent the workspace proxy from being healthy
	Errors []string `json:"errors"`
	// Warnings do not prevent the workspace proxy from being healthy, but
	// should be addressed.
	Warnings []string `json:"warnings"`
}

ProxyHealthReport is a report of the health of the workspace proxy. A healthy report will have no errors. Warnings are not fatal.

type ProxyHealthStatus

type ProxyHealthStatus string
const (
	// ProxyHealthy means the proxy access url is reachable and returns a healthy
	// status code.
	ProxyHealthy ProxyHealthStatus = "ok"
	// ProxyUnreachable means the proxy access url is not responding.
	ProxyUnreachable ProxyHealthStatus = "unreachable"
	// ProxyUnhealthy means the proxy access url is responding, but there is some
	// problem with the proxy. This problem may or may not be preventing functionality.
	ProxyUnhealthy ProxyHealthStatus = "unhealthy"
	// ProxyUnregistered means the proxy has not registered a url yet. This means
	// the proxy was created with the cli, but has not yet been started.
	ProxyUnregistered ProxyHealthStatus = "unregistered"
)

type PutExtendWorkspaceRequest

type PutExtendWorkspaceRequest struct {
	Deadline time.Time `json:"deadline" validate:"required" format:"date-time"`
}

PutExtendWorkspaceRequest is a request to extend the deadline of the active workspace build.

type PutOAuth2ProviderAppRequest added in v2.6.0

type PutOAuth2ProviderAppRequest struct {
	Name        string `json:"name" validate:"required,oauth2_app_name"`
	CallbackURL string `json:"callback_url" validate:"required,http_url"`
	Icon        string `json:"icon" validate:"omitempty"`
}

type RBACAction added in v2.12.0

type RBACAction string
const (
	ActionApplicationConnect RBACAction = "application_connect"
	ActionAssign             RBACAction = "assign"
	ActionCreate             RBACAction = "create"
	ActionDelete             RBACAction = "delete"
	ActionRead               RBACAction = "read"
	ActionReadPersonal       RBACAction = "read_personal"
	ActionSSH                RBACAction = "ssh"
	ActionUnassign           RBACAction = "unassign"
	ActionUpdate             RBACAction = "update"
	ActionUpdatePersonal     RBACAction = "update_personal"
	ActionUse                RBACAction = "use"
	ActionViewInsights       RBACAction = "view_insights"
	ActionWorkspaceStart     RBACAction = "start"
	ActionWorkspaceStop      RBACAction = "stop"
)

type RBACResource

type RBACResource string
const (
	ResourceWildcard                      RBACResource = "*"
	ResourceApiKey                        RBACResource = "api_key"
	ResourceAssignOrgRole                 RBACResource = "assign_org_role"
	ResourceAssignRole                    RBACResource = "assign_role"
	ResourceAuditLog                      RBACResource = "audit_log"
	ResourceCryptoKey                     RBACResource = "crypto_key"
	ResourceDebugInfo                     RBACResource = "debug_info"
	ResourceDeploymentConfig              RBACResource = "deployment_config"
	ResourceDeploymentStats               RBACResource = "deployment_stats"
	ResourceFile                          RBACResource = "file"
	ResourceGroup                         RBACResource = "group"
	ResourceGroupMember                   RBACResource = "group_member"
	ResourceIdpsyncSettings               RBACResource = "idpsync_settings"
	ResourceInboxNotification             RBACResource = "inbox_notification"
	ResourceLicense                       RBACResource = "license"
	ResourceNotificationMessage           RBACResource = "notification_message"
	ResourceNotificationPreference        RBACResource = "notification_preference"
	ResourceNotificationTemplate          RBACResource = "notification_template"
	ResourceOauth2App                     RBACResource = "oauth2_app"
	ResourceOauth2AppCodeToken            RBACResource = "oauth2_app_code_token"
	ResourceOauth2AppSecret               RBACResource = "oauth2_app_secret"
	ResourceOrganization                  RBACResource = "organization"
	ResourceOrganizationMember            RBACResource = "organization_member"
	ResourceProvisionerDaemon             RBACResource = "provisioner_daemon"
	ResourceProvisionerJobs               RBACResource = "provisioner_jobs"
	ResourceReplicas                      RBACResource = "replicas"
	ResourceSystem                        RBACResource = "system"
	ResourceTailnetCoordinator            RBACResource = "tailnet_coordinator"
	ResourceTemplate                      RBACResource = "template"
	ResourceUser                          RBACResource = "user"
	ResourceWebpushSubscription           RBACResource = "webpush_subscription"
	ResourceWorkspace                     RBACResource = "workspace"
	ResourceWorkspaceAgentDevcontainers   RBACResource = "workspace_agent_devcontainers"
	ResourceWorkspaceAgentResourceMonitor RBACResource = "workspace_agent_resource_monitor"
	ResourceWorkspaceDormant              RBACResource = "workspace_dormant"
	ResourceWorkspaceProxy                RBACResource = "workspace_proxy"
)

type RateLimitConfig

type RateLimitConfig struct {
	DisableAll serpent.Bool  `json:"disable_all" typescript:",notnull"`
	API        serpent.Int64 `json:"api" typescript:",notnull"`
}

type ReducedUser added in v2.9.0

type ReducedUser struct {
	MinimalUser `table:"m,recursive_inline"`
	Name        string    `json:"name"`
	Email       string    `json:"email" validate:"required" table:"email" format:"email"`
	CreatedAt   time.Time `json:"created_at" validate:"required" table:"created at" format:"date-time"`
	UpdatedAt   time.Time `json:"updated_at" table:"updated at" format:"date-time"`
	LastSeenAt  time.Time `json:"last_seen_at" format:"date-time"`

	Status    UserStatus `json:"status" table:"status" enums:"active,suspended"`
	LoginType LoginType  `json:"login_type"`
	// Deprecated: this value should be retrieved from
	// `codersdk.UserPreferenceSettings` instead.
	ThemePreference string `json:"theme_preference,omitempty"`
}

ReducedUser omits role and organization information. Roles are deduced from the user's site and organization roles. This requires fetching the user's organizational memberships. Fetching that is more expensive, and not usually required by the frontend.

type Region

type Region struct {
	ID          uuid.UUID `json:"id" format:"uuid" table:"id"`
	Name        string    `json:"name" table:"name,default_sort"`
	DisplayName string    `json:"display_name" table:"display name"`
	IconURL     string    `json:"icon_url" table:"icon url"`
	Healthy     bool      `json:"healthy" table:"healthy"`

	// PathAppURL is the URL to the base path for path apps. Optional
	// unless wildcard_hostname is set.
	// E.g. https://us.example.com
	PathAppURL string `json:"path_app_url" table:"url"`

	// WildcardHostname is the wildcard hostname for subdomain apps.
	// E.g. *.us.example.com
	// E.g. *--suffix.au.example.com
	// Optional. Does not need to be on the same domain as PathAppURL.
	WildcardHostname string `json:"wildcard_hostname" table:"wildcard hostname"`
}

type RegionTypes

type RegionTypes interface {
	Region | WorkspaceProxy
}

type RegionsResponse

type RegionsResponse[R RegionTypes] struct {
	Regions []R `json:"regions"`
}

type Replica

type Replica struct {
	// ID is the unique identifier for the replica.
	ID uuid.UUID `json:"id" format:"uuid"`
	// Hostname is the hostname of the replica.
	Hostname string `json:"hostname"`
	// CreatedAt is the timestamp when the replica was first seen.
	CreatedAt time.Time `json:"created_at" format:"date-time"`
	// RelayAddress is the accessible address to relay DERP connections.
	RelayAddress string `json:"relay_address"`
	// RegionID is the region of the replica.
	RegionID int32 `json:"region_id"`
	// Error is the replica error.
	Error string `json:"error"`
	// DatabaseLatency is the latency in microseconds to the database.
	DatabaseLatency int32 `json:"database_latency"`
}

type RequestOneTimePasscodeRequest added in v2.17.0

type RequestOneTimePasscodeRequest struct {
	Email string `json:"email" validate:"required,email" format:"email"`
}

RequestOneTimePasscodeRequest enables callers to request a one-time-passcode to change their password.

type RequestOption

type RequestOption func(*http.Request)

RequestOption is a function that can be used to modify an http.Request.

func ListInboxNotificationsRequestToQueryParams added in v2.21.0

func ListInboxNotificationsRequestToQueryParams(req ListInboxNotificationsRequest) []RequestOption

func WithQueryParam

func WithQueryParam(key, value string) RequestOption

WithQueryParam adds a query parameter to the request.

type ResolveAutostartResponse added in v2.4.0

type ResolveAutostartResponse struct {
	ParameterMismatch bool `json:"parameter_mismatch"`
}

type ResourceType

type ResourceType string
const (
	ResourceTypeTemplate              ResourceType = "template"
	ResourceTypeTemplateVersion       ResourceType = "template_version"
	ResourceTypeUser                  ResourceType = "user"
	ResourceTypeWorkspace             ResourceType = "workspace"
	ResourceTypeWorkspaceBuild        ResourceType = "workspace_build"
	ResourceTypeGitSSHKey             ResourceType = "git_ssh_key"
	ResourceTypeAPIKey                ResourceType = "api_key"
	ResourceTypeGroup                 ResourceType = "group"
	ResourceTypeLicense               ResourceType = "license"
	ResourceTypeConvertLogin          ResourceType = "convert_login"
	ResourceTypeHealthSettings        ResourceType = "health_settings"
	ResourceTypeNotificationsSettings ResourceType = "notifications_settings"
	ResourceTypeWorkspaceProxy        ResourceType = "workspace_proxy"
	ResourceTypeOrganization          ResourceType = "organization"
	ResourceTypeOAuth2ProviderApp     ResourceType = "oauth2_provider_app"
	// nolint:gosec // This is not a secret.
	ResourceTypeOAuth2ProviderAppSecret     ResourceType = "oauth2_provider_app_secret"
	ResourceTypeCustomRole                  ResourceType = "custom_role"
	ResourceTypeOrganizationMember          ResourceType = "organization_member"
	ResourceTypeNotificationTemplate        ResourceType = "notification_template"
	ResourceTypeIdpSyncSettingsOrganization ResourceType = "idp_sync_settings_organization"
	ResourceTypeIdpSyncSettingsGroup        ResourceType = "idp_sync_settings_group"
	ResourceTypeIdpSyncSettingsRole         ResourceType = "idp_sync_settings_role"
	ResourceTypeWorkspaceAgent              ResourceType = "workspace_agent"
	ResourceTypeWorkspaceApp                ResourceType = "workspace_app"
)

func (ResourceType) FriendlyString

func (r ResourceType) FriendlyString() string

type Response

type Response struct {
	// Message is an actionable message that depicts actions the request took.
	// These messages should be fully formed sentences with proper punctuation.
	// Examples:
	// - "A user has been created."
	// - "Failed to create a user."
	Message string `json:"message"`
	// Detail is a debug message that provides further insight into why the
	// action failed. This information can be technical and a regular golang
	// err.Error() text.
	// - "database: too many open connections"
	// - "stat: too many open files"
	Detail string `json:"detail,omitempty"`
	// Validations are form field-specific friendly error messages. They will be
	// shown on a form field in the UI. These can also be used to add additional
	// context if there is a set of errors in the primary 'Message'.
	Validations []ValidationError `json:"validations,omitempty"`
}

Response represents a generic HTTP response.

type Role

type Role struct {
	Name            string       `json:"name" table:"name,default_sort" validate:"username"`
	OrganizationID  string       `json:"organization_id,omitempty" table:"organization id" format:"uuid"`
	DisplayName     string       `json:"display_name" table:"display name"`
	SitePermissions []Permission `json:"site_permissions" table:"site permissions"`
	// OrganizationPermissions are specific for the organization in the field 'OrganizationID' above.
	OrganizationPermissions []Permission `json:"organization_permissions" table:"organization permissions"`
	UserPermissions         []Permission `json:"user_permissions" table:"user permissions"`
}

Role is a longer form of SlimRole that includes permissions details.

func (Role) FullName added in v2.12.0

func (r Role) FullName() string

FullName returns the role name scoped to the organization ID. This is useful if printing a set of roles from different scopes, as duplicated names across multiple scopes will become unique. In practice, this is primarily used in testing.

type RoleSyncSettings added in v2.16.0

type RoleSyncSettings struct {
	// Field is the name of the claim field that specifies what organization roles
	// a user should be given. If empty, no roles will be synced.
	Field string `json:"field"`
	// Mapping is a map from OIDC groups to Coder organization roles.
	Mapping map[string][]string `json:"mapping"`
}

type SSHConfig

type SSHConfig struct {
	// DeploymentName is the config-ssh Hostname prefix
	DeploymentName serpent.String
	// SSHConfigOptions are additional options to add to the ssh config file.
	// This will override defaults.
	SSHConfigOptions serpent.StringArray
}

SSHConfig is configuration the cli & vscode extension use for configuring ssh connections.

func (SSHConfig) ParseOptions

func (c SSHConfig) ParseOptions() (map[string]string, error)

type SSHConfigResponse

type SSHConfigResponse struct {
	HostnamePrefix   string            `json:"hostname_prefix"`
	SSHConfigOptions map[string]string `json:"ssh_config_options"`
}

type ServeProvisionerDaemonRequest

type ServeProvisionerDaemonRequest struct {
	// ID is a unique ID for a provisioner daemon.
	// Deprecated: this field has always been ignored.
	ID uuid.UUID `json:"id" format:"uuid"`
	// Name is the human-readable unique identifier for the daemon.
	Name string `json:"name" example:"my-cool-provisioner-daemon"`
	// Organization is the organization for the URL. If no orgID is provided,
	// then it is assumed to use the default organization.
	Organization uuid.UUID `json:"organization" format:"uuid"`
	// Provisioners is a list of provisioner types hosted by the provisioner daemon
	Provisioners []ProvisionerType `json:"provisioners"`
	// Tags is a map of key-value pairs that tag the jobs this provisioner daemon can handle
	Tags map[string]string `json:"tags"`
	// PreSharedKey is an authentication key to use on the API instead of the normal session token from the client.
	PreSharedKey string `json:"pre_shared_key"`
	// ProvisionerKey is an authentication key to use on the API instead of the normal session token from the client.
	ProvisionerKey string `json:"provisioner_key"`
}

ServeProvisionerDaemonRequest are the parameters to call ServeProvisionerDaemon with @typescript-ignore ServeProvisionerDaemonRequest

type ServerSentEvent

type ServerSentEvent struct {
	Type ServerSentEventType `json:"type"`
	Data interface{}         `json:"data"`
}

type ServerSentEventType

type ServerSentEventType string
const (
	ServerSentEventTypePing  ServerSentEventType = "ping"
	ServerSentEventTypeData  ServerSentEventType = "data"
	ServerSentEventTypeError ServerSentEventType = "error"
)

type ServiceBannerConfig deprecated

type ServiceBannerConfig = BannerConfig

Deprecated: ServiceBannerConfig has been renamed to BannerConfig.

type SessionCountDeploymentStats

type SessionCountDeploymentStats struct {
	VSCode          int64 `json:"vscode"`
	SSH             int64 `json:"ssh"`
	JetBrains       int64 `json:"jetbrains"`
	ReconnectingPTY int64 `json:"reconnecting_pty"`
}

type SessionLifetime added in v2.11.0

type SessionLifetime struct {
	// DisableExpiryRefresh will disable automatically refreshing api
	// keys when they are used from the api. This means the api key lifetime at
	// creation is the lifetime of the api key.
	DisableExpiryRefresh serpent.Bool `json:"disable_expiry_refresh,omitempty" typescript:",notnull"`

	// DefaultDuration is only for browser, workspace app and oauth sessions.
	DefaultDuration serpent.Duration `json:"default_duration" typescript:",notnull"`

	DefaultTokenDuration serpent.Duration `json:"default_token_lifetime,omitempty" typescript:",notnull"`

	MaximumTokenDuration serpent.Duration `json:"max_token_lifetime,omitempty" typescript:",notnull"`
}

SessionLifetime refers to "sessions" authenticating into Coderd. Coder has multiple different session types: api keys, tokens, workspace app tokens, agent tokens, etc. This configuration struct should be used to group all settings referring to any of these session lifetime controls. TODO: These config options were created back when coder only had api keys. Today, the config is ambigously used for all of them. For example: - cli based api keys ignore all settings - login uses the default lifetime, not the MaximumTokenDuration - Tokens use the Default & MaximumTokenDuration - ... etc ... The rational behind each decision is undocumented. The naming behind these config options is also confusing without any clear documentation. 'CreateAPIKey' is used to make all sessions, and it's parameters are just 'LifetimeSeconds' and 'DefaultLifetime'. Which does not directly correlate to the config options here.

type SlimRole added in v2.12.0

type SlimRole struct {
	Name           string `json:"name"`
	DisplayName    string `json:"display_name"`
	OrganizationID string `json:"organization_id,omitempty"`
}

SlimRole omits permission information from a role. At present, this is because our apis do not return permission information, and it would require extra db calls to fetch this information. The UI does not need it, so most api calls will use this structure that omits information.

func (SlimRole) String added in v2.13.0

func (s SlimRole) String() string

func (SlimRole) UniqueName added in v2.13.0

func (s SlimRole) UniqueName() string

UniqueName concatenates the organization ID to create a globally unique string name for the role.

type SupportConfig

type SupportConfig struct {
	Links serpent.Struct[[]LinkConfig] `json:"links" typescript:",notnull"`
}

type SwaggerConfig

type SwaggerConfig struct {
	Enable serpent.Bool `json:"enable" typescript:",notnull"`
}

type TLSConfig

type TLSConfig struct {
	Enable               serpent.Bool        `json:"enable" typescript:",notnull"`
	Address              serpent.HostPort    `json:"address" typescript:",notnull"`
	RedirectHTTP         serpent.Bool        `json:"redirect_http" typescript:",notnull"`
	CertFiles            serpent.StringArray `json:"cert_file" typescript:",notnull"`
	ClientAuth           serpent.String      `json:"client_auth" typescript:",notnull"`
	ClientCAFile         serpent.String      `json:"client_ca_file" typescript:",notnull"`
	KeyFiles             serpent.StringArray `json:"key_file" typescript:",notnull"`
	MinVersion           serpent.String      `json:"min_version" typescript:",notnull"`
	ClientCertFile       serpent.String      `json:"client_cert_file" typescript:",notnull"`
	ClientKeyFile        serpent.String      `json:"client_key_file" typescript:",notnull"`
	SupportedCiphers     serpent.StringArray `json:"supported_ciphers" typescript:",notnull"`
	AllowInsecureCiphers serpent.Bool        `json:"allow_insecure_ciphers" typescript:",notnull"`
}

type TelemetryConfig

type TelemetryConfig struct {
	Enable serpent.Bool `json:"enable" typescript:",notnull"`
	Trace  serpent.Bool `json:"trace" typescript:",notnull"`
	URL    serpent.URL  `json:"url" typescript:",notnull"`
}

type Template

type Template struct {
	ID                      uuid.UUID       `json:"id" format:"uuid"`
	CreatedAt               time.Time       `json:"created_at" format:"date-time"`
	UpdatedAt               time.Time       `json:"updated_at" format:"date-time"`
	OrganizationID          uuid.UUID       `json:"organization_id" format:"uuid"`
	OrganizationName        string          `json:"organization_name" format:"url"`
	OrganizationDisplayName string          `json:"organization_display_name"`
	OrganizationIcon        string          `json:"organization_icon"`
	Name                    string          `json:"name"`
	DisplayName             string          `json:"display_name"`
	Provisioner             ProvisionerType `json:"provisioner" enums:"terraform"`
	ActiveVersionID         uuid.UUID       `json:"active_version_id" format:"uuid"`
	// ActiveUserCount is set to -1 when loading.
	ActiveUserCount    int                    `json:"active_user_count"`
	BuildTimeStats     TemplateBuildTimeStats `json:"build_time_stats"`
	Description        string                 `json:"description"`
	Deprecated         bool                   `json:"deprecated"`
	DeprecationMessage string                 `json:"deprecation_message"`
	Icon               string                 `json:"icon"`
	DefaultTTLMillis   int64                  `json:"default_ttl_ms"`
	ActivityBumpMillis int64                  `json:"activity_bump_ms"`
	// AutostopRequirement and AutostartRequirement are enterprise features. Its
	// value is only used if your license is entitled to use the advanced template
	// scheduling feature.
	AutostopRequirement  TemplateAutostopRequirement  `json:"autostop_requirement"`
	AutostartRequirement TemplateAutostartRequirement `json:"autostart_requirement"`
	CreatedByID          uuid.UUID                    `json:"created_by_id" format:"uuid"`
	CreatedByName        string                       `json:"created_by_name"`

	// AllowUserAutostart and AllowUserAutostop are enterprise-only. Their
	// values are only used if your license is entitled to use the advanced
	// template scheduling feature.
	AllowUserAutostart           bool `json:"allow_user_autostart"`
	AllowUserAutostop            bool `json:"allow_user_autostop"`
	AllowUserCancelWorkspaceJobs bool `json:"allow_user_cancel_workspace_jobs"`

	// FailureTTLMillis, TimeTilDormantMillis, and TimeTilDormantAutoDeleteMillis are enterprise-only. Their
	// values are used if your license is entitled to use the advanced
	// template scheduling feature.
	FailureTTLMillis               int64 `json:"failure_ttl_ms"`
	TimeTilDormantMillis           int64 `json:"time_til_dormant_ms"`
	TimeTilDormantAutoDeleteMillis int64 `json:"time_til_dormant_autodelete_ms"`

	// RequireActiveVersion mandates that workspaces are built with the active
	// template version.
	RequireActiveVersion bool                         `json:"require_active_version"`
	MaxPortShareLevel    WorkspaceAgentPortShareLevel `json:"max_port_share_level"`
}

Template is the JSON representation of a Coder template. This type matches the database object for now, but is abstracted for ease of change later on.

type TemplateACL

type TemplateACL struct {
	Users  []TemplateUser  `json:"users"`
	Groups []TemplateGroup `json:"group"`
}

type TemplateAppUsage

type TemplateAppUsage struct {
	TemplateIDs []uuid.UUID      `json:"template_ids" format:"uuid"`
	Type        TemplateAppsType `json:"type" example:"builtin"`
	DisplayName string           `json:"display_name" example:"Visual Studio Code"`
	Slug        string           `json:"slug" example:"vscode"`
	Icon        string           `json:"icon"`
	Seconds     int64            `json:"seconds" example:"80500"`
	TimesUsed   int64            `json:"times_used" example:"2"`
}

TemplateAppUsage shows the usage of an app for one or more templates.

type TemplateAppsType

type TemplateAppsType string

TemplateAppsType defines the type of app reported.

const (
	TemplateAppsTypeBuiltin TemplateAppsType = "builtin"
	TemplateAppsTypeApp     TemplateAppsType = "app"
)

TemplateAppsType enums.

type TemplateAutostartRequirement added in v2.3.1

type TemplateAutostartRequirement struct {
	// DaysOfWeek is a list of days of the week in which autostart is allowed
	// to happen. If no days are specified, autostart is not allowed.
	DaysOfWeek []string `json:"days_of_week" enums:"monday,tuesday,wednesday,thursday,friday,saturday,sunday"`
}

type TemplateAutostopRequirement added in v2.1.5

type TemplateAutostopRequirement struct {
	// DaysOfWeek is a list of days of the week on which restarts are required.
	// Restarts happen within the user's quiet hours (in their configured
	// timezone). If no days are specified, restarts are not required. Weekdays
	// cannot be specified twice.
	//
	// Restarts will only happen on weekdays in this list on weeks which line up
	// with Weeks.
	DaysOfWeek []string `json:"days_of_week" enums:"monday,tuesday,wednesday,thursday,friday,saturday,sunday"`
	// Weeks is the number of weeks between required restarts. Weeks are synced
	// across all workspaces (and Coder deployments) using modulo math on a
	// hardcoded epoch week of January 2nd, 2023 (the first Monday of 2023).
	// Values of 0 or 1 indicate weekly restarts. Values of 2 indicate
	// fortnightly restarts, etc.
	Weeks int64 `json:"weeks"`
}

type TemplateBuildTimeStats

type TemplateBuildTimeStats map[WorkspaceTransition]TransitionStats

type TemplateExample

type TemplateExample struct {
	ID          string   `json:"id" format:"uuid"`
	URL         string   `json:"url"`
	Name        string   `json:"name"`
	Description string   `json:"description"`
	Icon        string   `json:"icon"`
	Tags        []string `json:"tags"`
	Markdown    string   `json:"markdown"`
}

type TemplateFilter added in v2.14.0

type TemplateFilter struct {
	OrganizationID uuid.UUID `typescript:"-"`
	ExactName      string    `typescript:"-"`
	FuzzyName      string    `typescript:"-"`
	SearchQuery    string    `json:"q,omitempty"`
}

type TemplateGroup

type TemplateGroup struct {
	Group
	Role TemplateRole `json:"role" enums:"admin,use"`
}

type TemplateInsightsIntervalReport

type TemplateInsightsIntervalReport struct {
	StartTime   time.Time              `json:"start_time" format:"date-time"`
	EndTime     time.Time              `json:"end_time" format:"date-time"`
	TemplateIDs []uuid.UUID            `json:"template_ids" format:"uuid"`
	Interval    InsightsReportInterval `json:"interval" example:"week"`
	ActiveUsers int64                  `json:"active_users" example:"14"`
}

TemplateInsightsIntervalReport is the report from the template insights endpoint for a specific interval.

type TemplateInsightsReport

type TemplateInsightsReport struct {
	StartTime       time.Time                `json:"start_time" format:"date-time"`
	EndTime         time.Time                `json:"end_time" format:"date-time"`
	TemplateIDs     []uuid.UUID              `json:"template_ids" format:"uuid"`
	ActiveUsers     int64                    `json:"active_users" example:"22"`
	AppsUsage       []TemplateAppUsage       `json:"apps_usage"`
	ParametersUsage []TemplateParameterUsage `json:"parameters_usage"`
}

TemplateInsightsReport is the report from the template insights endpoint.

type TemplateInsightsRequest

type TemplateInsightsRequest struct {
	StartTime   time.Time                 `json:"start_time" format:"date-time"`
	EndTime     time.Time                 `json:"end_time" format:"date-time"`
	TemplateIDs []uuid.UUID               `json:"template_ids" format:"uuid"`
	Interval    InsightsReportInterval    `json:"interval" example:"day"`
	Sections    []TemplateInsightsSection `json:"sections" example:"report"`
}

type TemplateInsightsResponse

type TemplateInsightsResponse struct {
	Report          *TemplateInsightsReport          `json:"report,omitempty"`
	IntervalReports []TemplateInsightsIntervalReport `json:"interval_reports,omitempty"`
}

TemplateInsightsResponse is the response from the template insights endpoint.

type TemplateInsightsSection added in v2.2.1

type TemplateInsightsSection string

TemplateInsightsSection defines the section to be included in the template insights response.

const (
	TemplateInsightsSectionIntervalReports TemplateInsightsSection = "interval_reports"
	TemplateInsightsSectionReport          TemplateInsightsSection = "report"
)

TemplateInsightsSection enums.

type TemplateParameterUsage

type TemplateParameterUsage struct {
	TemplateIDs []uuid.UUID                      `json:"template_ids" format:"uuid"`
	DisplayName string                           `json:"display_name"`
	Name        string                           `json:"name"`
	Type        string                           `json:"type"`
	Description string                           `json:"description"`
	Options     []TemplateVersionParameterOption `json:"options,omitempty"`
	Values      []TemplateParameterValue         `json:"values"`
}

TemplateParameterUsage shows the usage of a parameter for one or more templates.

type TemplateParameterValue

type TemplateParameterValue struct {
	Value string `json:"value"`
	Count int64  `json:"count"`
}

TemplateParameterValue shows the usage of a parameter value for one or more templates.

type TemplateRole

type TemplateRole string
const (
	TemplateRoleAdmin   TemplateRole = "admin"
	TemplateRoleUse     TemplateRole = "use"
	TemplateRoleDeleted TemplateRole = ""
)

type TemplateUser

type TemplateUser struct {
	User
	Role TemplateRole `json:"role" enums:"admin,use"`
}

type TemplateVersion

type TemplateVersion struct {
	ID             uuid.UUID      `json:"id" format:"uuid"`
	TemplateID     *uuid.UUID     `json:"template_id,omitempty" format:"uuid"`
	OrganizationID uuid.UUID      `json:"organization_id,omitempty" format:"uuid"`
	CreatedAt      time.Time      `json:"created_at" format:"date-time"`
	UpdatedAt      time.Time      `json:"updated_at" format:"date-time"`
	Name           string         `json:"name"`
	Message        string         `json:"message"`
	Job            ProvisionerJob `json:"job"`
	Readme         string         `json:"readme"`
	CreatedBy      MinimalUser    `json:"created_by"`
	Archived       bool           `json:"archived"`

	Warnings            []TemplateVersionWarning `json:"warnings,omitempty" enums:"DEPRECATED_PARAMETERS"`
	MatchedProvisioners *MatchedProvisioners     `json:"matched_provisioners,omitempty"`
}

TemplateVersion represents a single version of a template.

type TemplateVersionExternalAuth added in v2.2.1

type TemplateVersionExternalAuth struct {
	ID              string `json:"id"`
	Type            string `json:"type"`
	DisplayName     string `json:"display_name"`
	DisplayIcon     string `json:"display_icon"`
	AuthenticateURL string `json:"authenticate_url"`
	Authenticated   bool   `json:"authenticated"`
	Optional        bool   `json:"optional,omitempty"`
}

type TemplateVersionParameter

type TemplateVersionParameter struct {
	Name                 string                           `json:"name"`
	DisplayName          string                           `json:"display_name,omitempty"`
	Description          string                           `json:"description"`
	DescriptionPlaintext string                           `json:"description_plaintext"`
	Type                 string                           `json:"type" enums:"string,number,bool,list(string)"`
	Mutable              bool                             `json:"mutable"`
	DefaultValue         string                           `json:"default_value"`
	Icon                 string                           `json:"icon"`
	Options              []TemplateVersionParameterOption `json:"options"`
	ValidationError      string                           `json:"validation_error,omitempty"`
	ValidationRegex      string                           `json:"validation_regex,omitempty"`
	ValidationMin        *int32                           `json:"validation_min,omitempty"`
	ValidationMax        *int32                           `json:"validation_max,omitempty"`
	ValidationMonotonic  ValidationMonotonicOrder         `json:"validation_monotonic,omitempty" enums:"increasing,decreasing"`
	Required             bool                             `json:"required"`
	Ephemeral            bool                             `json:"ephemeral"`
}

TemplateVersionParameter represents a parameter for a template version.

type TemplateVersionParameterOption

type TemplateVersionParameterOption struct {
	Name        string `json:"name"`
	Description string `json:"description"`
	Value       string `json:"value"`
	Icon        string `json:"icon"`
}

TemplateVersionParameterOption represents a selectable option for a template parameter.

type TemplateVersionVariable

type TemplateVersionVariable struct {
	Name         string `json:"name"`
	Description  string `json:"description"`
	Type         string `json:"type" enums:"string,number,bool"`
	Value        string `json:"value"`
	DefaultValue string `json:"default_value"`
	Required     bool   `json:"required"`
	Sensitive    bool   `json:"sensitive"`
}

TemplateVersionVariable represents a managed template variable.

type TemplateVersionWarning

type TemplateVersionWarning string
const (
	TemplateVersionWarningUnsupportedWorkspaces TemplateVersionWarning = "UNSUPPORTED_WORKSPACES"
)

type TemplateVersionsByTemplateRequest

type TemplateVersionsByTemplateRequest struct {
	TemplateID      uuid.UUID `json:"template_id" validate:"required" format:"uuid"`
	IncludeArchived bool      `json:"include_archived"`
	Pagination
}

TemplateVersionsByTemplateRequest defines the request parameters for TemplateVersionsByTemplate.

type TimingStage added in v2.18.0

type TimingStage string
const (
	// Based on ProvisionerJobTimingStage
	TimingStageInit  TimingStage = "init"
	TimingStagePlan  TimingStage = "plan"
	TimingStageGraph TimingStage = "graph"
	TimingStageApply TimingStage = "apply"
	// Based on  WorkspaceAgentScriptTimingStage
	TimingStageStart TimingStage = "start"
	TimingStageStop  TimingStage = "stop"
	TimingStageCron  TimingStage = "cron"
	// Custom timing stage to represent the time taken to connect to an agent
	TimingStageConnect TimingStage = "connect"
)

type TokenConfig

type TokenConfig struct {
	MaxTokenLifetime time.Duration `json:"max_token_lifetime"`
}

type TokensFilter

type TokensFilter struct {
	IncludeAll bool `json:"include_all"`
}

type TraceConfig

type TraceConfig struct {
	Enable          serpent.Bool   `json:"enable" typescript:",notnull"`
	HoneycombAPIKey serpent.String `json:"honeycomb_api_key" typescript:",notnull"`
	CaptureLogs     serpent.Bool   `json:"capture_logs" typescript:",notnull"`
	DataDog         serpent.Bool   `json:"data_dog" typescript:",notnull"`
}

type TransitionStats

type TransitionStats struct {
	P50 *int64 `example:"123"`
	P95 *int64 `example:"146"`
}

type UpdateActiveTemplateVersion

type UpdateActiveTemplateVersion struct {
	ID uuid.UUID `json:"id" validate:"required" format:"uuid"`
}

type UpdateAppearanceConfig

type UpdateAppearanceConfig struct {
	ApplicationName string `json:"application_name"`
	LogoURL         string `json:"logo_url"`
	// Deprecated: ServiceBanner has been replaced by AnnouncementBanners.
	ServiceBanner       BannerConfig   `json:"service_banner"`
	AnnouncementBanners []BannerConfig `json:"announcement_banners"`
}

type UpdateCheckResponse

type UpdateCheckResponse struct {
	// Current indicates whether the server version is the same as the latest.
	Current bool `json:"current"`
	// Version is the semantic version for the latest release of Coder.
	Version string `json:"version"`
	// URL to download the latest release of Coder.
	URL string `json:"url"`
}

UpdateCheckResponse contains information on the latest release of Coder.

type UpdateInboxNotificationReadStatusRequest added in v2.21.0

type UpdateInboxNotificationReadStatusRequest struct {
	IsRead bool `json:"is_read"`
}

type UpdateInboxNotificationReadStatusResponse added in v2.21.0

type UpdateInboxNotificationReadStatusResponse struct {
	Notification InboxNotification `json:"notification"`
	UnreadCount  int               `json:"unread_count"`
}

type UpdateNotificationTemplateMethod added in v2.15.0

type UpdateNotificationTemplateMethod struct {
	Method string `json:"method,omitempty" example:"webhook"`
}

type UpdateOrganizationRequest added in v2.12.0

type UpdateOrganizationRequest struct {
	Name        string  `json:"name,omitempty" validate:"omitempty,organization_name"`
	DisplayName string  `json:"display_name,omitempty" validate:"omitempty,organization_display_name"`
	Description *string `json:"description,omitempty"`
	Icon        *string `json:"icon,omitempty"`
}

type UpdateRoles

type UpdateRoles struct {
	Roles []string `json:"roles" validate:""`
}

type UpdateTemplateACL

type UpdateTemplateACL struct {
	// UserPerms should be a mapping of user id to role. The user id must be the
	// uuid of the user, not a username or email address.
	UserPerms map[string]TemplateRole `json:"user_perms,omitempty" example:"<group_id>:admin,4df59e74-c027-470b-ab4d-cbba8963a5e9:use"`
	// GroupPerms should be a mapping of group id to role.
	GroupPerms map[string]TemplateRole `json:"group_perms,omitempty" example:"<user_id>>:admin,8bd26b20-f3e8-48be-a903-46bb920cf671:use"`
}

type UpdateTemplateMeta

type UpdateTemplateMeta struct {
	Name             string `json:"name,omitempty" validate:"omitempty,template_name"`
	DisplayName      string `json:"display_name,omitempty" validate:"omitempty,template_display_name"`
	Description      string `json:"description,omitempty"`
	Icon             string `json:"icon,omitempty"`
	DefaultTTLMillis int64  `json:"default_ttl_ms,omitempty"`
	// ActivityBumpMillis allows optionally specifying the activity bump
	// duration for all workspaces created from this template. Defaults to 1h
	// but can be set to 0 to disable activity bumping.
	ActivityBumpMillis int64 `json:"activity_bump_ms,omitempty"`
	// AutostopRequirement and AutostartRequirement can only be set if your license
	// includes the advanced template scheduling feature. If you attempt to set this
	// value while unlicensed, it will be ignored.
	AutostopRequirement            *TemplateAutostopRequirement  `json:"autostop_requirement,omitempty"`
	AutostartRequirement           *TemplateAutostartRequirement `json:"autostart_requirement,omitempty"`
	AllowUserAutostart             bool                          `json:"allow_user_autostart,omitempty"`
	AllowUserAutostop              bool                          `json:"allow_user_autostop,omitempty"`
	AllowUserCancelWorkspaceJobs   bool                          `json:"allow_user_cancel_workspace_jobs,omitempty"`
	FailureTTLMillis               int64                         `json:"failure_ttl_ms,omitempty"`
	TimeTilDormantMillis           int64                         `json:"time_til_dormant_ms,omitempty"`
	TimeTilDormantAutoDeleteMillis int64                         `json:"time_til_dormant_autodelete_ms,omitempty"`
	// UpdateWorkspaceLastUsedAt updates the last_used_at field of workspaces
	// spawned from the template. This is useful for preventing workspaces being
	// immediately locked when updating the inactivity_ttl field to a new, shorter
	// value.
	UpdateWorkspaceLastUsedAt bool `json:"update_workspace_last_used_at"`
	// UpdateWorkspaceDormant updates the dormant_at field of workspaces spawned
	// from the template. This is useful for preventing dormant workspaces being immediately
	// deleted when updating the dormant_ttl field to a new, shorter value.
	UpdateWorkspaceDormantAt bool `json:"update_workspace_dormant_at"`
	// RequireActiveVersion mandates workspaces built using this template
	// use the active version of the template. This option has no
	// effect on template admins.
	RequireActiveVersion bool `json:"require_active_version,omitempty"`
	// DeprecationMessage if set, will mark the template as deprecated and block
	// any new workspaces from using this template.
	// If passed an empty string, will remove the deprecated message, making
	// the template usable for new workspaces again.
	DeprecationMessage *string `json:"deprecation_message,omitempty"`
	// DisableEveryoneGroupAccess allows optionally disabling the default
	// behavior of granting the 'everyone' group access to use the template.
	// If this is set to true, the template will not be available to all users,
	// and must be explicitly granted to users or groups in the permissions settings
	// of the template.
	DisableEveryoneGroupAccess bool                          `json:"disable_everyone_group_access"`
	MaxPortShareLevel          *WorkspaceAgentPortShareLevel `json:"max_port_share_level,omitempty"`
}

type UpdateUserAppearanceSettingsRequest added in v2.5.1

type UpdateUserAppearanceSettingsRequest struct {
	ThemePreference string `json:"theme_preference" validate:"required"`
}

type UpdateUserNotificationPreferences added in v2.15.0

type UpdateUserNotificationPreferences struct {
	TemplateDisabledMap map[string]bool `json:"template_disabled_map"`
}

type UpdateUserPasswordRequest

type UpdateUserPasswordRequest struct {
	OldPassword string `json:"old_password" validate:""`
	Password    string `json:"password" validate:"required"`
}

type UpdateUserProfileRequest

type UpdateUserProfileRequest struct {
	Username string `json:"username" validate:"required,username"`
	Name     string `json:"name" validate:"user_real_name"`
}

type UpdateUserQuietHoursScheduleRequest

type UpdateUserQuietHoursScheduleRequest struct {
	// Schedule is a cron expression that defines when the user's quiet hours
	// window is. Schedule must not be empty. For new users, the schedule is set
	// to 2am in their browser or computer's timezone. The schedule denotes the
	// beginning of a 4 hour window where the workspace is allowed to
	// automatically stop or restart due to maintenance or template schedule.
	//
	// The schedule must be daily with a single time, and should have a timezone
	// specified via a CRON_TZ prefix (otherwise UTC will be used).
	//
	// If the schedule is empty, the user will be updated to use the default
	// schedule.
	Schedule string `json:"schedule" validate:"required"`
}

type UpdateWorkspaceAutomaticUpdatesRequest added in v2.3.0

type UpdateWorkspaceAutomaticUpdatesRequest struct {
	AutomaticUpdates AutomaticUpdates `json:"automatic_updates"`
}

UpdateWorkspaceAutomaticUpdatesRequest is a request to updates a workspace's automatic updates setting.

type UpdateWorkspaceAutostartRequest

type UpdateWorkspaceAutostartRequest struct {
	// Schedule is expected to be of the form `CRON_TZ=<IANA Timezone> <min> <hour> * * <dow>`
	// Example: `CRON_TZ=US/Central 30 9 * * 1-5` represents 0930 in the timezone US/Central
	// on weekdays (Mon-Fri). `CRON_TZ` defaults to UTC if not present.
	Schedule *string `json:"schedule,omitempty"`
}

UpdateWorkspaceAutostartRequest is a request to update a workspace's autostart schedule.

type UpdateWorkspaceDormancy added in v2.1.4

type UpdateWorkspaceDormancy struct {
	Dormant bool `json:"dormant"`
}

UpdateWorkspaceDormancy is a request to activate or make a workspace dormant. A value of false will activate a dormant workspace.

type UpdateWorkspaceProxyResponse

type UpdateWorkspaceProxyResponse struct {
	Proxy      WorkspaceProxy `json:"proxy" table:"p,recursive_inline"`
	ProxyToken string         `json:"proxy_token" table:"proxy token"`
}

type UpdateWorkspaceRequest

type UpdateWorkspaceRequest struct {
	Name string `json:"name,omitempty" validate:"username"`
}

type UpdateWorkspaceTTLRequest

type UpdateWorkspaceTTLRequest struct {
	TTLMillis *int64 `json:"ttl_ms"`
}

UpdateWorkspaceTTLRequest is a request to update a workspace's TTL.

type UploadResponse

type UploadResponse struct {
	ID uuid.UUID `json:"hash" format:"uuid"`
}

UploadResponse contains the hash to reference the uploaded file.

type UpsertWorkspaceAgentPortShareRequest added in v2.9.0

type UpsertWorkspaceAgentPortShareRequest struct {
	AgentName  string                          `json:"agent_name"`
	Port       int32                           `json:"port"`
	ShareLevel WorkspaceAgentPortShareLevel    `json:"share_level" enums:"owner,authenticated,public"`
	Protocol   WorkspaceAgentPortShareProtocol `json:"protocol" enums:"http,https"`
}

type UsageAppName added in v2.13.0

type UsageAppName string
const (
	UsageAppNameVscode          UsageAppName = "vscode"
	UsageAppNameJetbrains       UsageAppName = "jetbrains"
	UsageAppNameReconnectingPty UsageAppName = "reconnecting-pty"
	UsageAppNameSSH             UsageAppName = "ssh"
)

type User

type User struct {
	ReducedUser `table:"r,recursive_inline"`

	OrganizationIDs []uuid.UUID `json:"organization_ids" format:"uuid"`
	Roles           []SlimRole  `json:"roles"`
}

User represents a user in Coder.

type UserActivity added in v2.2.0

type UserActivity struct {
	TemplateIDs []uuid.UUID `json:"template_ids" format:"uuid"`
	UserID      uuid.UUID   `json:"user_id" format:"uuid"`
	Username    string      `json:"username"`
	AvatarURL   string      `json:"avatar_url" format:"uri"`
	Seconds     int64       `json:"seconds" example:"80500"`
}

UserActivity shows the session time for a user.

type UserActivityInsightsReport added in v2.2.0

type UserActivityInsightsReport struct {
	StartTime   time.Time      `json:"start_time" format:"date-time"`
	EndTime     time.Time      `json:"end_time" format:"date-time"`
	TemplateIDs []uuid.UUID    `json:"template_ids" format:"uuid"`
	Users       []UserActivity `json:"users"`
}

UserActivityInsightsReport is the report from the user activity insights endpoint.

type UserActivityInsightsRequest added in v2.2.0

type UserActivityInsightsRequest struct {
	StartTime   time.Time   `json:"start_time" format:"date-time"`
	EndTime     time.Time   `json:"end_time" format:"date-time"`
	TemplateIDs []uuid.UUID `json:"template_ids" format:"uuid"`
}

type UserActivityInsightsResponse added in v2.2.0

type UserActivityInsightsResponse struct {
	Report UserActivityInsightsReport `json:"report"`
}

UserActivityInsightsResponse is the response from the user activity insights endpoint.

type UserAppearanceSettings added in v2.21.0

type UserAppearanceSettings struct {
	ThemePreference string `json:"theme_preference"`
}

type UserLatency

type UserLatency struct {
	TemplateIDs []uuid.UUID       `json:"template_ids" format:"uuid"`
	UserID      uuid.UUID         `json:"user_id" format:"uuid"`
	Username    string            `json:"username"`
	AvatarURL   string            `json:"avatar_url" format:"uri"`
	LatencyMS   ConnectionLatency `json:"latency_ms"`
}

UserLatency shows the connection latency for a user.

type UserLatencyInsightsReport

type UserLatencyInsightsReport struct {
	StartTime   time.Time     `json:"start_time" format:"date-time"`
	EndTime     time.Time     `json:"end_time" format:"date-time"`
	TemplateIDs []uuid.UUID   `json:"template_ids" format:"uuid"`
	Users       []UserLatency `json:"users"`
}

UserLatencyInsightsReport is the report from the user latency insights endpoint.

type UserLatencyInsightsRequest

type UserLatencyInsightsRequest struct {
	StartTime   time.Time   `json:"start_time" format:"date-time"`
	EndTime     time.Time   `json:"end_time" format:"date-time"`
	TemplateIDs []uuid.UUID `json:"template_ids" format:"uuid"`
}

type UserLatencyInsightsResponse

type UserLatencyInsightsResponse struct {
	Report UserLatencyInsightsReport `json:"report"`
}

UserLatencyInsightsResponse is the response from the user latency insights endpoint.

type UserLoginType

type UserLoginType struct {
	LoginType LoginType `json:"login_type"`
}

type UserParameter added in v2.8.0

type UserParameter struct {
	Name  string `json:"name"`
	Value string `json:"value"`
}

type UserQuietHoursScheduleConfig

type UserQuietHoursScheduleConfig struct {
	DefaultSchedule serpent.String `json:"default_schedule" typescript:",notnull"`
	AllowUserCustom serpent.Bool   `json:"allow_user_custom" typescript:",notnull"`
}

type UserQuietHoursScheduleResponse

type UserQuietHoursScheduleResponse struct {
	RawSchedule string `json:"raw_schedule"`
	// UserSet is true if the user has set their own quiet hours schedule. If
	// false, the user is using the default schedule.
	UserSet bool `json:"user_set"`
	// UserCanSet is true if the user is allowed to set their own quiet hours
	// schedule. If false, the user cannot set a custom schedule and the default
	// schedule will always be used.
	UserCanSet bool `json:"user_can_set"`
	// Time is the time of day that the quiet hours window starts in the given
	// Timezone each day.
	Time     string `json:"time"`     // HH:mm (24-hour)
	Timezone string `json:"timezone"` // raw format from the cron expression, UTC if unspecified
	// Next is the next time that the quiet hours window will start.
	Next time.Time `json:"next" format:"date-time"`
}

type UserRoles

type UserRoles struct {
	Roles             []string               `json:"roles"`
	OrganizationRoles map[uuid.UUID][]string `json:"organization_roles"`
}

type UserStatus

type UserStatus string
const (
	UserStatusActive    UserStatus = "active"
	UserStatusDormant   UserStatus = "dormant"
	UserStatusSuspended UserStatus = "suspended"
)

type UserStatusChangeCount added in v2.19.0

type UserStatusChangeCount struct {
	Date  time.Time `json:"date" format:"date-time"`
	Count int64     `json:"count" example:"10"`
}

type UsersRequest

type UsersRequest struct {
	Search string `json:"search,omitempty" typescript:"-"`
	// Filter users by status.
	Status UserStatus `json:"status,omitempty" typescript:"-"`
	// Filter users that have the given role.
	Role string `json:"role,omitempty" typescript:"-"`

	SearchQuery string `json:"q,omitempty"`
	Pagination
}

type ValidateUserPasswordRequest added in v2.18.0

type ValidateUserPasswordRequest struct {
	Password string `json:"password" validate:"required"`
}

type ValidateUserPasswordResponse added in v2.18.0

type ValidateUserPasswordResponse struct {
	Valid   bool   `json:"valid"`
	Details string `json:"details"`
}

type ValidationError

type ValidationError struct {
	Field  string `json:"field" validate:"required"`
	Detail string `json:"detail" validate:"required"`
}

ValidationError represents a scoped error to a user input.

func (ValidationError) Error

func (e ValidationError) Error() string

type ValidationMonotonicOrder

type ValidationMonotonicOrder string
const (
	MonotonicOrderIncreasing ValidationMonotonicOrder = "increasing"
	MonotonicOrderDecreasing ValidationMonotonicOrder = "decreasing"
)

type VariableValue

type VariableValue struct {
	Name  string `json:"name"`
	Value string `json:"value"`
}

func ParseUserVariableValues added in v2.14.0

func ParseUserVariableValues(varsFiles []string, variablesFile string, commandLineVariables []string) ([]VariableValue, error)

type WebpushMessage added in v2.21.0

type WebpushMessage struct {
	Icon    string                 `json:"icon"`
	Title   string                 `json:"title"`
	Body    string                 `json:"body"`
	Actions []WebpushMessageAction `json:"actions"`
}

type WebpushMessageAction added in v2.21.0

type WebpushMessageAction struct {
	Label string `json:"label"`
	URL   string `json:"url"`
}

type WebpushSubscription added in v2.21.0

type WebpushSubscription struct {
	Endpoint  string `json:"endpoint"`
	AuthKey   string `json:"auth_key"`
	P256DHKey string `json:"p256dh_key"`
}

type Workspace

type Workspace struct {
	ID                                   uuid.UUID           `json:"id" format:"uuid"`
	CreatedAt                            time.Time           `json:"created_at" format:"date-time"`
	UpdatedAt                            time.Time           `json:"updated_at" format:"date-time"`
	OwnerID                              uuid.UUID           `json:"owner_id" format:"uuid"`
	OwnerName                            string              `json:"owner_name"`
	OwnerAvatarURL                       string              `json:"owner_avatar_url"`
	OrganizationID                       uuid.UUID           `json:"organization_id" format:"uuid"`
	OrganizationName                     string              `json:"organization_name"`
	TemplateID                           uuid.UUID           `json:"template_id" format:"uuid"`
	TemplateName                         string              `json:"template_name"`
	TemplateDisplayName                  string              `json:"template_display_name"`
	TemplateIcon                         string              `json:"template_icon"`
	TemplateAllowUserCancelWorkspaceJobs bool                `json:"template_allow_user_cancel_workspace_jobs"`
	TemplateActiveVersionID              uuid.UUID           `json:"template_active_version_id" format:"uuid"`
	TemplateRequireActiveVersion         bool                `json:"template_require_active_version"`
	LatestBuild                          WorkspaceBuild      `json:"latest_build"`
	LatestAppStatus                      *WorkspaceAppStatus `json:"latest_app_status"`
	Outdated                             bool                `json:"outdated"`
	Name                                 string              `json:"name"`
	AutostartSchedule                    *string             `json:"autostart_schedule,omitempty"`
	TTLMillis                            *int64              `json:"ttl_ms,omitempty"`
	LastUsedAt                           time.Time           `json:"last_used_at" format:"date-time"`

	// DeletingAt indicates the time at which the workspace will be permanently deleted.
	// A workspace is eligible for deletion if it is dormant (a non-nil dormant_at value)
	// and a value has been specified for time_til_dormant_autodelete on its template.
	DeletingAt *time.Time `json:"deleting_at" format:"date-time"`
	// DormantAt being non-nil indicates a workspace that is dormant.
	// A dormant workspace is no longer accessible must be activated.
	// It is subject to deletion if it breaches
	// the duration of the time_til_ field on its template.
	DormantAt *time.Time `json:"dormant_at" format:"date-time"`
	// Health shows the health of the workspace and information about
	// what is causing an unhealthy status.
	Health           WorkspaceHealth  `json:"health"`
	AutomaticUpdates AutomaticUpdates `json:"automatic_updates" enums:"always,never"`
	AllowRenames     bool             `json:"allow_renames"`
	Favorite         bool             `json:"favorite"`
	NextStartAt      *time.Time       `json:"next_start_at" format:"date-time"`
}

Workspace is a deployment of a template. It references a specific version and can be updated.

func (Workspace) FullName

func (w Workspace) FullName() string

type WorkspaceAgent

type WorkspaceAgent struct {
	ID                   uuid.UUID               `json:"id" format:"uuid"`
	CreatedAt            time.Time               `json:"created_at" format:"date-time"`
	UpdatedAt            time.Time               `json:"updated_at" format:"date-time"`
	FirstConnectedAt     *time.Time              `json:"first_connected_at,omitempty" format:"date-time"`
	LastConnectedAt      *time.Time              `json:"last_connected_at,omitempty" format:"date-time"`
	DisconnectedAt       *time.Time              `json:"disconnected_at,omitempty" format:"date-time"`
	StartedAt            *time.Time              `json:"started_at,omitempty" format:"date-time"`
	ReadyAt              *time.Time              `json:"ready_at,omitempty" format:"date-time"`
	Status               WorkspaceAgentStatus    `json:"status"`
	LifecycleState       WorkspaceAgentLifecycle `json:"lifecycle_state"`
	Name                 string                  `json:"name"`
	ResourceID           uuid.UUID               `json:"resource_id" format:"uuid"`
	InstanceID           string                  `json:"instance_id,omitempty"`
	Architecture         string                  `json:"architecture"`
	EnvironmentVariables map[string]string       `json:"environment_variables"`
	OperatingSystem      string                  `json:"operating_system"`
	LogsLength           int32                   `json:"logs_length"`
	LogsOverflowed       bool                    `json:"logs_overflowed"`
	Directory            string                  `json:"directory,omitempty"`
	ExpandedDirectory    string                  `json:"expanded_directory,omitempty"`
	Version              string                  `json:"version"`
	APIVersion           string                  `json:"api_version"`
	Apps                 []WorkspaceApp          `json:"apps"`
	// DERPLatency is mapped by region name (e.g. "New York City", "Seattle").
	DERPLatency              map[string]DERPRegion     `json:"latency,omitempty"`
	ConnectionTimeoutSeconds int32                     `json:"connection_timeout_seconds"`
	TroubleshootingURL       string                    `json:"troubleshooting_url"`
	Subsystems               []AgentSubsystem          `json:"subsystems"`
	Health                   WorkspaceAgentHealth      `json:"health"` // Health reports the health of the agent.
	DisplayApps              []DisplayApp              `json:"display_apps"`
	LogSources               []WorkspaceAgentLogSource `json:"log_sources"`
	Scripts                  []WorkspaceAgentScript    `json:"scripts"`

	// StartupScriptBehavior is a legacy field that is deprecated in favor
	// of the `coder_script` resource. It's only referenced by old clients.
	// Deprecated: Remove in the future!
	StartupScriptBehavior WorkspaceAgentStartupScriptBehavior `json:"startup_script_behavior"`
}

type WorkspaceAgentContainer added in v2.21.0

type WorkspaceAgentContainer struct {
	// CreatedAt is the time the container was created.
	CreatedAt time.Time `json:"created_at" format:"date-time"`
	// ID is the unique identifier of the container.
	ID string `json:"id"`
	// FriendlyName is the human-readable name of the container.
	FriendlyName string `json:"name"`
	// Image is the name of the container image.
	Image string `json:"image"`
	// Labels is a map of key-value pairs of container labels.
	Labels map[string]string `json:"labels"`
	// Running is true if the container is currently running.
	Running bool `json:"running"`
	// Ports includes ports exposed by the container.
	Ports []WorkspaceAgentContainerPort `json:"ports"`
	// Status is the current status of the container. This is somewhat
	// implementation-dependent, but should generally be a human-readable
	// string.
	Status string `json:"status"`
	// Volumes is a map of "things" mounted into the container. Again, this
	// is somewhat implementation-dependent.
	Volumes map[string]string `json:"volumes"`
}

WorkspaceAgentContainer describes a devcontainer of some sort that is visible to the workspace agent. This struct is an abstraction of potentially multiple implementations, and the fields will be somewhat implementation-dependent.

type WorkspaceAgentContainerPort added in v2.21.0

type WorkspaceAgentContainerPort struct {
	// Port is the port number *inside* the container.
	Port uint16 `json:"port"`
	// Network is the network protocol used by the port (tcp, udp, etc).
	Network string `json:"network"`
	// HostIP is the IP address of the host interface to which the port is
	// bound. Note that this can be an IPv4 or IPv6 address.
	HostIP string `json:"host_ip,omitempty"`
	// HostPort is the port number *outside* the container.
	HostPort uint16 `json:"host_port,omitempty"`
}

WorkspaceAgentContainerPort describes a port as exposed by a container.

type WorkspaceAgentDevcontainer added in v2.20.0

type WorkspaceAgentDevcontainer struct {
	ID              uuid.UUID `json:"id" format:"uuid"`
	Name            string    `json:"name"`
	WorkspaceFolder string    `json:"workspace_folder"`
	ConfigPath      string    `json:"config_path,omitempty"`
}

WorkspaceAgentDevcontainer defines the location of a devcontainer configuration in a workspace that is visible to the workspace agent.

type WorkspaceAgentHealth

type WorkspaceAgentHealth struct {
	Healthy bool   `json:"healthy" example:"false"`                              // Healthy is true if the agent is healthy.
	Reason  string `json:"reason,omitempty" example:"agent has lost connection"` // Reason is a human-readable explanation of the agent's health. It is empty if Healthy is true.
}

type WorkspaceAgentLifecycle

type WorkspaceAgentLifecycle string

WorkspaceAgentLifecycle represents the lifecycle state of a workspace agent.

The agent lifecycle starts in the "created" state, and transitions to "starting" when the agent reports it has begun preparing (e.g. started executing the startup script).

const (
	WorkspaceAgentLifecycleCreated         WorkspaceAgentLifecycle = "created"
	WorkspaceAgentLifecycleStarting        WorkspaceAgentLifecycle = "starting"
	WorkspaceAgentLifecycleStartTimeout    WorkspaceAgentLifecycle = "start_timeout"
	WorkspaceAgentLifecycleStartError      WorkspaceAgentLifecycle = "start_error"
	WorkspaceAgentLifecycleReady           WorkspaceAgentLifecycle = "ready"
	WorkspaceAgentLifecycleShuttingDown    WorkspaceAgentLifecycle = "shutting_down"
	WorkspaceAgentLifecycleShutdownTimeout WorkspaceAgentLifecycle = "shutdown_timeout"
	WorkspaceAgentLifecycleShutdownError   WorkspaceAgentLifecycle = "shutdown_error"
	WorkspaceAgentLifecycleOff             WorkspaceAgentLifecycle = "off"
)

WorkspaceAgentLifecycle enums.

func (WorkspaceAgentLifecycle) ShuttingDown

func (l WorkspaceAgentLifecycle) ShuttingDown() bool

ShuttingDown returns true if the agent is in the process of shutting down or has shut down.

func (WorkspaceAgentLifecycle) Starting

func (l WorkspaceAgentLifecycle) Starting() bool

Starting returns true if the agent is in the process of starting.

type WorkspaceAgentListContainersResponse added in v2.20.0

type WorkspaceAgentListContainersResponse struct {
	// Containers is a list of containers visible to the workspace agent.
	Containers []WorkspaceAgentContainer `json:"containers"`
	// Warnings is a list of warnings that may have occurred during the
	// process of listing containers. This should not include fatal errors.
	Warnings []string `json:"warnings,omitempty"`
}

WorkspaceAgentListContainersResponse is the response to the list containers request.

type WorkspaceAgentListeningPort

type WorkspaceAgentListeningPort struct {
	ProcessName string `json:"process_name"` // may be empty
	Network     string `json:"network"`      // only "tcp" at the moment
	Port        uint16 `json:"port"`
}

type WorkspaceAgentListeningPortsResponse

type WorkspaceAgentListeningPortsResponse struct {
	// If there are no ports in the list, nothing should be displayed in the UI.
	// There must not be a "no ports available" message or anything similar, as
	// there will always be no ports displayed on platforms where our port
	// detection logic is unsupported.
	Ports []WorkspaceAgentListeningPort `json:"ports"`
}

type WorkspaceAgentLog

type WorkspaceAgentLog struct {
	ID        int64     `json:"id"`
	CreatedAt time.Time `json:"created_at" format:"date-time"`
	Output    string    `json:"output"`
	Level     LogLevel  `json:"level"`
	SourceID  uuid.UUID `json:"source_id" format:"uuid"`
}

type WorkspaceAgentLogSource

type WorkspaceAgentLogSource struct {
	WorkspaceAgentID uuid.UUID `json:"workspace_agent_id" format:"uuid"`
	ID               uuid.UUID `json:"id" format:"uuid"`
	CreatedAt        time.Time `json:"created_at" format:"date-time"`
	DisplayName      string    `json:"display_name"`
	Icon             string    `json:"icon"`
}

type WorkspaceAgentMetadata

type WorkspaceAgentMetadata struct {
	Result      WorkspaceAgentMetadataResult      `json:"result"`
	Description WorkspaceAgentMetadataDescription `json:"description"`
}

type WorkspaceAgentMetadataDescription

type WorkspaceAgentMetadataDescription struct {
	DisplayName string `json:"display_name"`
	Key         string `json:"key"`
	Script      string `json:"script"`
	Interval    int64  `json:"interval"`
	Timeout     int64  `json:"timeout"`
}

WorkspaceAgentMetadataDescription is a description of dynamic metadata the agent should report back to coderd. It is provided via the `metadata` list in the `coder_agent` block.

type WorkspaceAgentMetadataResult

type WorkspaceAgentMetadataResult struct {
	CollectedAt time.Time `json:"collected_at" format:"date-time"`
	// Age is the number of seconds since the metadata was collected.
	// It is provided in addition to CollectedAt to protect against clock skew.
	Age   int64  `json:"age"`
	Value string `json:"value"`
	Error string `json:"error"`
}

type WorkspaceAgentPortShare added in v2.9.0

type WorkspaceAgentPortShare struct {
	WorkspaceID uuid.UUID                       `json:"workspace_id" format:"uuid"`
	AgentName   string                          `json:"agent_name"`
	Port        int32                           `json:"port"`
	ShareLevel  WorkspaceAgentPortShareLevel    `json:"share_level" enums:"owner,authenticated,public"`
	Protocol    WorkspaceAgentPortShareProtocol `json:"protocol" enums:"http,https"`
}

type WorkspaceAgentPortShareLevel added in v2.9.0

type WorkspaceAgentPortShareLevel string

func (WorkspaceAgentPortShareLevel) ValidMaxLevel added in v2.9.0

func (l WorkspaceAgentPortShareLevel) ValidMaxLevel() bool

func (WorkspaceAgentPortShareLevel) ValidPortShareLevel added in v2.9.0

func (l WorkspaceAgentPortShareLevel) ValidPortShareLevel() bool

type WorkspaceAgentPortShareProtocol added in v2.9.0

type WorkspaceAgentPortShareProtocol string

func (WorkspaceAgentPortShareProtocol) ValidPortProtocol added in v2.9.0

func (p WorkspaceAgentPortShareProtocol) ValidPortProtocol() bool

type WorkspaceAgentPortShares added in v2.9.0

type WorkspaceAgentPortShares struct {
	Shares []WorkspaceAgentPortShare `json:"shares"`
}

type WorkspaceAgentScript added in v2.2.0

type WorkspaceAgentScript struct {
	ID               uuid.UUID     `json:"id" format:"uuid"`
	LogSourceID      uuid.UUID     `json:"log_source_id" format:"uuid"`
	LogPath          string        `json:"log_path"`
	Script           string        `json:"script"`
	Cron             string        `json:"cron"`
	RunOnStart       bool          `json:"run_on_start"`
	RunOnStop        bool          `json:"run_on_stop"`
	StartBlocksLogin bool          `json:"start_blocks_login"`
	Timeout          time.Duration `json:"timeout"`
	DisplayName      string        `json:"display_name"`
}

type WorkspaceAgentStartupScriptBehavior

type WorkspaceAgentStartupScriptBehavior string

WorkspaceAgentStartupScriptBehavior defines whether or not the startup script should be considered blocking or non-blocking. The blocking behavior means that the agent will not be considered ready until the startup script has completed and, for example, SSH connections will wait for the agent to be ready (can be overridden).

Presently, non-blocking is the default, but this may change in the future. Deprecated: `coder_script` allows configuration on a per-script basis.

const (
	WorkspaceAgentStartupScriptBehaviorBlocking    WorkspaceAgentStartupScriptBehavior = "blocking"
	WorkspaceAgentStartupScriptBehaviorNonBlocking WorkspaceAgentStartupScriptBehavior = "non-blocking"
)

type WorkspaceAgentStatus

type WorkspaceAgentStatus string
const (
	WorkspaceAgentConnecting   WorkspaceAgentStatus = "connecting"
	WorkspaceAgentConnected    WorkspaceAgentStatus = "connected"
	WorkspaceAgentDisconnected WorkspaceAgentStatus = "disconnected"
	WorkspaceAgentTimeout      WorkspaceAgentStatus = "timeout"
)

This is also in database/modelmethods.go and should be kept in sync.

type WorkspaceApp

type WorkspaceApp struct {
	ID uuid.UUID `json:"id" format:"uuid"`
	// URL is the address being proxied to inside the workspace.
	// If external is specified, this will be opened on the client.
	URL string `json:"url"`
	// External specifies whether the URL should be opened externally on
	// the client or not.
	External bool `json:"external"`
	// Slug is a unique identifier within the agent.
	Slug string `json:"slug"`
	// DisplayName is a friendly name for the app.
	DisplayName string `json:"display_name"`
	Command     string `json:"command,omitempty"`
	// Icon is a relative path or external URL that specifies
	// an icon to be displayed in the dashboard.
	Icon string `json:"icon,omitempty"`
	// Subdomain denotes whether the app should be accessed via a path on the
	// `coder server` or via a hostname-based dev URL. If this is set to true
	// and there is no app wildcard configured on the server, the app will not
	// be accessible in the UI.
	Subdomain bool `json:"subdomain"`
	// SubdomainName is the application domain exposed on the `coder server`.
	SubdomainName string                   `json:"subdomain_name,omitempty"`
	SharingLevel  WorkspaceAppSharingLevel `json:"sharing_level" enums:"owner,authenticated,public"`
	// Healthcheck specifies the configuration for checking app health.
	Healthcheck Healthcheck        `json:"healthcheck"`
	Health      WorkspaceAppHealth `json:"health"`
	Hidden      bool               `json:"hidden"`
	OpenIn      WorkspaceAppOpenIn `json:"open_in"`

	// Statuses is a list of statuses for the app.
	Statuses []WorkspaceAppStatus `json:"statuses"`
}

type WorkspaceAppHealth

type WorkspaceAppHealth string
const (
	WorkspaceAppHealthDisabled     WorkspaceAppHealth = "disabled"
	WorkspaceAppHealthInitializing WorkspaceAppHealth = "initializing"
	WorkspaceAppHealthHealthy      WorkspaceAppHealth = "healthy"
	WorkspaceAppHealthUnhealthy    WorkspaceAppHealth = "unhealthy"
)

type WorkspaceAppOpenIn added in v2.19.0

type WorkspaceAppOpenIn string
const (
	WorkspaceAppOpenInSlimWindow WorkspaceAppOpenIn = "slim-window"
	WorkspaceAppOpenInTab        WorkspaceAppOpenIn = "tab"
)

type WorkspaceAppSharingLevel

type WorkspaceAppSharingLevel string
const (
	WorkspaceAppSharingLevelOwner         WorkspaceAppSharingLevel = "owner"
	WorkspaceAppSharingLevelAuthenticated WorkspaceAppSharingLevel = "authenticated"
	WorkspaceAppSharingLevelPublic        WorkspaceAppSharingLevel = "public"
)

type WorkspaceAppStatus added in v2.21.0

type WorkspaceAppStatus struct {
	ID                 uuid.UUID               `json:"id" format:"uuid"`
	CreatedAt          time.Time               `json:"created_at" format:"date-time"`
	WorkspaceID        uuid.UUID               `json:"workspace_id" format:"uuid"`
	AgentID            uuid.UUID               `json:"agent_id" format:"uuid"`
	AppID              uuid.UUID               `json:"app_id" format:"uuid"`
	State              WorkspaceAppStatusState `json:"state"`
	NeedsUserAttention bool                    `json:"needs_user_attention"`
	Message            string                  `json:"message"`
	// URI is the URI of the resource that the status is for.
	// e.g. https://github.com/org/repo/pull/123
	// e.g. file:///path/to/file
	URI string `json:"uri"`
	// Icon is an external URL to an icon that will be rendered in the UI.
	Icon string `json:"icon"`
}

type WorkspaceAppStatusState added in v2.21.0

type WorkspaceAppStatusState string
const (
	WorkspaceAppStatusStateWorking  WorkspaceAppStatusState = "working"
	WorkspaceAppStatusStateComplete WorkspaceAppStatusState = "complete"
	WorkspaceAppStatusStateFailure  WorkspaceAppStatusState = "failure"
)

type WorkspaceBuild

type WorkspaceBuild struct {
	ID                      uuid.UUID            `json:"id" format:"uuid"`
	CreatedAt               time.Time            `json:"created_at" format:"date-time"`
	UpdatedAt               time.Time            `json:"updated_at" format:"date-time"`
	WorkspaceID             uuid.UUID            `json:"workspace_id" format:"uuid"`
	WorkspaceName           string               `json:"workspace_name"`
	WorkspaceOwnerID        uuid.UUID            `json:"workspace_owner_id" format:"uuid"`
	WorkspaceOwnerName      string               `json:"workspace_owner_name"`
	WorkspaceOwnerAvatarURL string               `json:"workspace_owner_avatar_url"`
	TemplateVersionID       uuid.UUID            `json:"template_version_id" format:"uuid"`
	TemplateVersionName     string               `json:"template_version_name"`
	BuildNumber             int32                `json:"build_number"`
	Transition              WorkspaceTransition  `json:"transition" enums:"start,stop,delete"`
	InitiatorID             uuid.UUID            `json:"initiator_id" format:"uuid"`
	InitiatorUsername       string               `json:"initiator_name"`
	Job                     ProvisionerJob       `json:"job"`
	Reason                  BuildReason          `db:"reason" json:"reason" enums:"initiator,autostart,autostop"`
	Resources               []WorkspaceResource  `json:"resources"`
	Deadline                NullTime             `json:"deadline,omitempty" format:"date-time"`
	MaxDeadline             NullTime             `json:"max_deadline,omitempty" format:"date-time"`
	Status                  WorkspaceStatus      `json:"status" enums:"pending,starting,running,stopping,stopped,failed,canceling,canceled,deleting,deleted"`
	DailyCost               int32                `json:"daily_cost"`
	MatchedProvisioners     *MatchedProvisioners `json:"matched_provisioners,omitempty"`
}

WorkspaceBuild is an at-point representation of a workspace state. BuildNumbers start at 1 and increase by 1 for each subsequent build

type WorkspaceBuildParameter

type WorkspaceBuildParameter struct {
	Name  string `json:"name"`
	Value string `json:"value"`
}

WorkspaceBuildParameter represents a parameter specific for a workspace build.

type WorkspaceBuildTimings added in v2.17.0

type WorkspaceBuildTimings struct {
	ProvisionerTimings []ProvisionerTiming `json:"provisioner_timings"`
	// TODO: Consolidate agent-related timing metrics into a single struct when
	// updating the API version
	AgentScriptTimings     []AgentScriptTiming     `json:"agent_script_timings"`
	AgentConnectionTimings []AgentConnectionTiming `json:"agent_connection_timings"`
}

type WorkspaceBuildsRequest

type WorkspaceBuildsRequest struct {
	WorkspaceID uuid.UUID `json:"workspace_id" format:"uuid" typescript:"-"`
	Pagination
	Since time.Time `json:"since,omitempty" format:"date-time"`
}

type WorkspaceConnectionLatencyMS

type WorkspaceConnectionLatencyMS struct {
	P50 float64
	P95 float64
}

type WorkspaceDeploymentStats

type WorkspaceDeploymentStats struct {
	Pending  int64 `json:"pending"`
	Building int64 `json:"building"`
	Running  int64 `json:"running"`
	Failed   int64 `json:"failed"`
	Stopped  int64 `json:"stopped"`

	ConnectionLatencyMS WorkspaceConnectionLatencyMS `json:"connection_latency_ms"`
	RxBytes             int64                        `json:"rx_bytes"`
	TxBytes             int64                        `json:"tx_bytes"`
}

type WorkspaceFilter

type WorkspaceFilter struct {
	// Owner can be "me" or a username
	Owner string `json:"owner,omitempty" typescript:"-"`
	// Template is a template name
	Template string `json:"template,omitempty" typescript:"-"`
	// Name will return partial matches
	Name string `json:"name,omitempty" typescript:"-"`
	// Status is a workspace status, which is really the status of the latest build
	Status string `json:"status,omitempty" typescript:"-"`
	// Offset is the number of workspaces to skip before returning results.
	Offset int `json:"offset,omitempty" typescript:"-"`
	// Limit is a limit on the number of workspaces returned.
	Limit int `json:"limit,omitempty" typescript:"-"`
	// FilterQuery supports a raw filter query string
	FilterQuery string `json:"q,omitempty"`
}

type WorkspaceHealth

type WorkspaceHealth struct {
	Healthy       bool        `json:"healthy" example:"false"`      // Healthy is true if the workspace is healthy.
	FailingAgents []uuid.UUID `json:"failing_agents" format:"uuid"` // FailingAgents lists the IDs of the agents that are failing, if any.
}

type WorkspaceOptions

type WorkspaceOptions struct {
	IncludeDeleted bool `json:"include_deleted,omitempty"`
}

type WorkspaceProxy

type WorkspaceProxy struct {
	// Extends Region with extra information
	Region      `table:"region,recursive_inline"`
	DerpEnabled bool `json:"derp_enabled" table:"derp enabled"`
	DerpOnly    bool `json:"derp_only" table:"derp only"`

	// Status is the latest status check of the proxy. This will be empty for deleted
	// proxies. This value can be used to determine if a workspace proxy is healthy
	// and ready to use.
	Status WorkspaceProxyStatus `json:"status,omitempty" table:"proxy,recursive"`

	CreatedAt time.Time `json:"created_at" format:"date-time" table:"created at"`
	UpdatedAt time.Time `json:"updated_at" format:"date-time" table:"updated at"`
	Deleted   bool      `json:"deleted" table:"deleted"`
	Version   string    `json:"version" table:"version"`
}

type WorkspaceProxyBuildInfo

type WorkspaceProxyBuildInfo struct {
	// TODO: @emyrk what should we include here?
	WorkspaceProxy bool `json:"workspace_proxy"`
	// DashboardURL is the URL of the coderd this proxy is connected to.
	DashboardURL string `json:"dashboard_url"`
}

type WorkspaceProxyStatus

type WorkspaceProxyStatus struct {
	Status ProxyHealthStatus `json:"status" table:"status,default_sort"`
	// Report provides more information about the health of the workspace proxy.
	Report    ProxyHealthReport `json:"report,omitempty" table:"report"`
	CheckedAt time.Time         `json:"checked_at" table:"checked at" format:"date-time"`
}

type WorkspaceQuota

type WorkspaceQuota struct {
	CreditsConsumed int `json:"credits_consumed"`
	Budget          int `json:"budget"`
}

type WorkspaceResource

type WorkspaceResource struct {
	ID         uuid.UUID                   `json:"id" format:"uuid"`
	CreatedAt  time.Time                   `json:"created_at" format:"date-time"`
	JobID      uuid.UUID                   `json:"job_id" format:"uuid"`
	Transition WorkspaceTransition         `json:"workspace_transition" enums:"start,stop,delete"`
	Type       string                      `json:"type"`
	Name       string                      `json:"name"`
	Hide       bool                        `json:"hide"`
	Icon       string                      `json:"icon"`
	Agents     []WorkspaceAgent            `json:"agents,omitempty"`
	Metadata   []WorkspaceResourceMetadata `json:"metadata,omitempty"`
	DailyCost  int32                       `json:"daily_cost"`
}

WorkspaceResource describes resources used to create a workspace, for instance: containers, images, volumes.

type WorkspaceResourceMetadata

type WorkspaceResourceMetadata struct {
	Key       string `json:"key"`
	Value     string `json:"value"`
	Sensitive bool   `json:"sensitive"`
}

WorkspaceResourceMetadata annotates the workspace resource with custom key-value pairs.

type WorkspaceStatus

type WorkspaceStatus string
const (
	WorkspaceStatusPending   WorkspaceStatus = "pending"
	WorkspaceStatusStarting  WorkspaceStatus = "starting"
	WorkspaceStatusRunning   WorkspaceStatus = "running"
	WorkspaceStatusStopping  WorkspaceStatus = "stopping"
	WorkspaceStatusStopped   WorkspaceStatus = "stopped"
	WorkspaceStatusFailed    WorkspaceStatus = "failed"
	WorkspaceStatusCanceling WorkspaceStatus = "canceling"
	WorkspaceStatusCanceled  WorkspaceStatus = "canceled"
	WorkspaceStatusDeleting  WorkspaceStatus = "deleting"
	WorkspaceStatusDeleted   WorkspaceStatus = "deleted"
)

func ConvertWorkspaceStatus added in v2.18.0

func ConvertWorkspaceStatus(jobStatus ProvisionerJobStatus, transition WorkspaceTransition) WorkspaceStatus

type WorkspaceTransition

type WorkspaceTransition string
const (
	WorkspaceTransitionStart  WorkspaceTransition = "start"
	WorkspaceTransitionStop   WorkspaceTransition = "stop"
	WorkspaceTransitionDelete WorkspaceTransition = "delete"
)

type WorkspacesRequest

type WorkspacesRequest struct {
	SearchQuery string `json:"q,omitempty"`
	Pagination
}

type WorkspacesResponse

type WorkspacesResponse struct {
	Workspaces []Workspace `json:"workspaces"`
	Count      int         `json:"count"`
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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