2022-04-06 12:42:40 -05:00
package coderd
import (
2024-08-14 14:22:43 -03:00
"context"
2022-04-06 12:42:40 -05:00
"database/sql"
"errors"
"fmt"
"net/http"
2022-08-30 14:27:33 -03:00
"sort"
2025-07-30 13:42:39 -07:00
"strings"
2022-06-07 13:37:45 +01:00
"time"
2022-04-06 12:42:40 -05:00
"github.com/go-chi/chi/v5"
"github.com/google/uuid"
2022-05-16 14:36:27 -05:00
"golang.org/x/xerrors"
2022-04-06 12:42:40 -05:00
2024-08-14 14:22:43 -03:00
"cdr.dev/slog"
2025-01-17 11:55:41 -06:00
"github.com/coder/coder/v2/coderd/database/db2sdk"
2024-08-14 14:22:43 -03:00
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/coderd/audit"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/database/dbauthz"
2023-09-01 19:50:12 +03:00
"github.com/coder/coder/v2/coderd/database/dbtime"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/coderd/httpapi"
"github.com/coder/coder/v2/coderd/httpmw"
2024-08-14 14:22:43 -03:00
"github.com/coder/coder/v2/coderd/notifications"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/coderd/rbac"
2024-05-15 09:46:35 -05:00
"github.com/coder/coder/v2/coderd/rbac/policy"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/coderd/schedule"
2024-07-03 08:42:23 -10:00
"github.com/coder/coder/v2/coderd/searchquery"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/coderd/telemetry"
"github.com/coder/coder/v2/coderd/util/ptr"
2025-07-30 13:42:39 -07:00
"github.com/coder/coder/v2/coderd/util/slice"
2024-05-31 12:26:19 -04:00
"github.com/coder/coder/v2/coderd/workspacestats"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/examples"
2022-04-06 12:42:40 -05:00
)
2023-01-13 12:27:21 +01:00
// Returns a single template.
//
2022-12-19 18:43:46 +01:00
// @Summary Get template metadata by ID
// @ID get-template-metadata-by-id
// @Security CoderSessionToken
// @Produce json
// @Tags Templates
2023-01-13 12:27:21 +01:00
// @Param template path string true "Template ID" format(uuid)
2022-12-19 18:43:46 +01:00
// @Success 200 {object} codersdk.Template
2023-01-13 12:27:21 +01:00
// @Router /templates/{template} [get]
2022-05-25 22:14:08 -05:00
func ( api * API ) template ( rw http . ResponseWriter , r * http . Request ) {
2022-09-21 17:07:00 -05:00
ctx := r . Context ()
2022-04-06 12:42:40 -05:00
template := httpmw . TemplateParam ( r )
2022-05-13 17:54:32 -05:00
2023-07-19 16:07:33 -04:00
httpapi . Write ( ctx , rw , http . StatusOK , api . convertTemplate ( template ))
2022-04-06 12:42:40 -05:00
}
2022-12-19 18:43:46 +01:00
// @Summary Delete template by ID
// @ID delete-template-by-id
// @Security CoderSessionToken
// @Produce json
// @Tags Templates
2023-01-13 12:27:21 +01:00
// @Param template path string true "Template ID" format(uuid)
2022-12-19 18:43:46 +01:00
// @Success 200 {object} codersdk.Response
2023-01-13 12:27:21 +01:00
// @Router /templates/{template} [delete]
2022-05-25 22:14:08 -05:00
func ( api * API ) deleteTemplate ( rw http . ResponseWriter , r * http . Request ) {
2022-09-09 11:34:23 -05:00
var (
2024-08-14 14:22:43 -03:00
apiKey = httpmw . APIKey ( r )
2022-09-21 17:07:00 -05:00
ctx = r . Context ()
2022-09-09 11:34:23 -05:00
template = httpmw . TemplateParam ( r )
2022-09-19 23:11:01 -05:00
auditor = * api . Auditor . Load ()
2022-09-09 11:34:23 -05:00
aReq , commitAudit = audit . InitRequest [ database . Template ]( rw , & audit . RequestParams {
2024-02-26 08:27:33 -06:00
Audit : auditor ,
Log : api . Logger ,
Request : r ,
Action : database . AuditActionDelete ,
OrganizationID : template . OrganizationID ,
2022-09-09 11:34:23 -05:00
})
)
defer commitAudit ()
aReq . Old = template
2023-02-28 12:04:39 -05:00
// This is just to get the workspace count, so we use a system context to
// return ALL workspaces. Not just workspaces the user can view.
// nolint:gocritic
workspaces , err := api . Database . GetWorkspaces ( dbauthz . AsSystemRestricted ( ctx ), database . GetWorkspacesParams {
2023-07-21 21:00:19 +03:00
TemplateIDs : [] uuid . UUID { template . ID },
2022-04-06 12:42:40 -05:00
})
2022-09-09 11:34:23 -05:00
if err != nil && ! errors . Is ( err , sql . ErrNoRows ) {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
2022-06-07 09:33:06 -05:00
Message : "Internal error fetching workspaces by template id." ,
2022-06-03 16:48:09 -05:00
Detail : err . Error (),
2022-04-06 12:42:40 -05:00
})
return
}
if len ( workspaces ) > 0 {
2023-01-13 14:30:48 +00:00
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
2022-04-06 12:42:40 -05:00
Message : "All workspaces must be deleted before a template can be removed." ,
})
return
}
2022-09-21 17:07:00 -05:00
err = api . Database . UpdateTemplateDeletedByID ( ctx , database . UpdateTemplateDeletedByIDParams {
2022-06-30 08:14:51 -04:00
ID : template . ID ,
Deleted : true ,
2023-09-01 19:50:12 +03:00
UpdatedAt : dbtime . Now (),
2022-04-06 12:42:40 -05:00
})
if err != nil {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
2022-06-07 09:33:06 -05:00
Message : "Internal error deleting template." ,
2022-06-03 16:48:09 -05:00
Detail : err . Error (),
2022-04-06 12:42:40 -05:00
})
return
}
2024-08-14 14:22:43 -03:00
admins , err := findTemplateAdmins ( ctx , api . Database )
if err != nil {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error fetching template admins." ,
Detail : err . Error (),
})
return
}
for _ , admin := range admins {
// Don't send notification to user which initiated the event.
if admin . ID == apiKey . UserID {
continue
}
api . notifyTemplateDeleted ( ctx , template , apiKey . UserID , admin . ID )
}
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusOK , codersdk . Response {
2022-04-06 12:42:40 -05:00
Message : "Template has been deleted!" ,
})
}
2024-08-14 14:22:43 -03:00
func ( api * API ) notifyTemplateDeleted ( ctx context . Context , template database . Template , initiatorID uuid . UUID , receiverID uuid . UUID ) {
initiator , err := api . Database . GetUserByID ( ctx , initiatorID )
if err != nil {
api . Logger . Warn ( ctx , "failed to fetch initiator for template deletion notification" , slog . F ( "initiator_id" , initiatorID ), slog . Error ( err ))
return
}
2024-10-15 21:02:02 +02:00
templateNameLabel := template . DisplayName
if templateNameLabel == "" {
templateNameLabel = template . Name
}
2024-11-12 12:40:46 +00:00
// nolint:gocritic // Need notifier actor to enqueue notifications
if _ , err := api . NotificationsEnqueuer . Enqueue ( dbauthz . AsNotifier ( ctx ), receiverID , notifications . TemplateTemplateDeleted ,
2024-08-14 14:22:43 -03:00
map [ string ] string {
2024-10-15 21:02:02 +02:00
"name" : templateNameLabel ,
"initiator" : initiator . Username ,
2024-08-14 14:22:43 -03:00
}, "api-templates-delete" ,
// Associate this notification with all the related entities.
template . ID , template . OrganizationID ,
); err != nil {
api . Logger . Warn ( ctx , "failed to notify of template deletion" , slog . F ( "deleted_template_id" , template . ID ), slog . Error ( err ))
}
}
2023-01-13 12:27:21 +01:00
// Create a new template in an organization.
// Returns a single template.
//
2022-12-19 18:43:46 +01:00
// @Summary Create template by organization
// @ID create-template-by-organization
// @Security CoderSessionToken
2022-12-21 15:37:30 +01:00
// @Accept json
2022-12-19 18:43:46 +01:00
// @Produce json
// @Tags Templates
// @Param request body codersdk.CreateTemplateRequest true "Request body"
2023-01-11 12:16:09 +01:00
// @Param organization path string true "Organization ID"
2022-12-19 18:43:46 +01:00
// @Success 200 {object} codersdk.Template
2023-01-11 12:16:09 +01:00
// @Router /organizations/{organization}/templates [post]
2022-05-25 22:14:08 -05:00
func ( api * API ) postTemplateByOrganization ( rw http . ResponseWriter , r * http . Request ) {
2022-09-09 11:34:23 -05:00
var (
2022-09-21 17:07:00 -05:00
ctx = r . Context ()
2024-08-20 22:48:39 +10:00
portSharer = * api . PortSharer . Load ()
2022-09-09 11:34:23 -05:00
createTemplate codersdk . CreateTemplateRequest
organization = httpmw . OrganizationParam ( r )
apiKey = httpmw . APIKey ( r )
2022-09-19 23:11:01 -05:00
auditor = * api . Auditor . Load ()
2022-09-09 11:34:23 -05:00
templateAudit , commitTemplateAudit = audit . InitRequest [ database . Template ]( rw , & audit . RequestParams {
2024-02-26 08:27:33 -06:00
Audit : auditor ,
Log : api . Logger ,
Request : r ,
Action : database . AuditActionCreate ,
OrganizationID : organization . ID ,
2022-09-09 11:34:23 -05:00
})
templateVersionAudit , commitTemplateVersionAudit = audit . InitRequest [ database . TemplateVersion ]( rw , & audit . RequestParams {
2024-02-26 08:27:33 -06:00
Audit : auditor ,
Log : api . Logger ,
Request : r ,
Action : database . AuditActionWrite ,
OrganizationID : organization . ID ,
2022-09-09 11:34:23 -05:00
})
)
defer commitTemplateAudit ()
defer commitTemplateVersionAudit ()
2022-09-21 17:07:00 -05:00
if ! httpapi . Read ( ctx , rw , r , & createTemplate ) {
2022-05-16 14:36:27 -05:00
return
}
2023-04-27 18:55:34 -05:00
2025-07-29 03:41:49 +02:00
// Default is false as dynamic parameters are now the preferred approach.
useClassicParameterFlow := ptr . NilToDefault ( createTemplate . UseClassicParameterFlow , false )
2025-07-02 09:44:01 -05:00
2023-04-27 18:55:34 -05:00
// Make a temporary struct to represent the template. This is used for
// auditing if any of the following checks fail. It will be overwritten when
// the template is inserted into the db.
templateAudit . New = database . Template {
2025-07-02 09:44:01 -05:00
OrganizationID : organization . ID ,
Name : createTemplate . Name ,
Description : createTemplate . Description ,
CreatedBy : apiKey . UserID ,
Icon : createTemplate . Icon ,
DisplayName : createTemplate . DisplayName ,
UseClassicParameterFlow : useClassicParameterFlow ,
2023-04-27 18:55:34 -05:00
}
2022-09-21 17:07:00 -05:00
_ , err := api . Database . GetTemplateByOrganizationAndName ( ctx , database . GetTemplateByOrganizationAndNameParams {
2022-05-16 14:36:27 -05:00
OrganizationID : organization . ID ,
Name : createTemplate . Name ,
})
if err == nil {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusConflict , codersdk . Response {
2022-06-07 09:33:06 -05:00
Message : fmt . Sprintf ( "Template with name %q already exists." , createTemplate . Name ),
2022-07-12 19:15:02 -05:00
Validations : [] codersdk . ValidationError {{
2022-05-16 14:36:27 -05:00
Field : "name" ,
2022-05-16 15:56:11 -05:00
Detail : "This value is already in use and should be unique." ,
2022-05-16 14:36:27 -05:00
}},
})
return
}
if ! errors . Is ( err , sql . ErrNoRows ) {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
2022-06-07 09:33:06 -05:00
Message : "Internal error fetching template by name." ,
2022-06-03 16:48:09 -05:00
Detail : err . Error (),
2022-05-16 14:36:27 -05:00
})
return
}
2023-04-27 18:55:34 -05:00
2022-09-21 17:07:00 -05:00
templateVersion , err := api . Database . GetTemplateVersionByID ( ctx , createTemplate . VersionID )
2022-05-16 14:36:27 -05:00
if errors . Is ( err , sql . ErrNoRows ) {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusNotFound , codersdk . Response {
2022-06-07 09:33:06 -05:00
Message : fmt . Sprintf ( "Template version %q does not exist." , createTemplate . VersionID ),
2022-07-12 19:15:02 -05:00
Validations : [] codersdk . ValidationError {
2022-06-03 16:48:09 -05:00
{ Field : "template_version_id" , Detail : "Template version does not exist" },
},
2022-05-16 14:36:27 -05:00
})
return
}
if err != nil {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
2022-06-07 09:33:06 -05:00
Message : "Internal error fetching template version." ,
2022-06-03 16:48:09 -05:00
Detail : err . Error (),
2022-05-16 14:36:27 -05:00
})
return
}
2023-10-11 09:26:22 -05:00
if templateVersion . Archived {
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
Message : fmt . Sprintf ( "Template version %s is archived." , createTemplate . VersionID ),
Validations : [] codersdk . ValidationError {
{ Field : "template_version_id" , Detail : "Template version is archived" },
},
})
return
}
2022-09-09 11:34:23 -05:00
templateVersionAudit . Old = templateVersion
2023-05-23 12:06:33 +04:00
if templateVersion . TemplateID . Valid {
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
Message : fmt . Sprintf ( "Template version %s is already part of a template" , createTemplate . VersionID ),
Validations : [] codersdk . ValidationError {
{ Field : "template_version_id" , Detail : "Template version is already part of a template" },
},
})
return
}
2022-09-09 11:34:23 -05:00
2022-09-21 17:07:00 -05:00
importJob , err := api . Database . GetProvisionerJobByID ( ctx , templateVersion . JobID )
2022-05-16 14:36:27 -05:00
if err != nil {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
2022-06-07 09:33:06 -05:00
Message : "Internal error fetching provisioner job." ,
2022-06-03 16:48:09 -05:00
Detail : err . Error (),
2022-05-16 14:36:27 -05:00
})
2022-05-10 10:44:09 +03:00
return
}
2023-03-08 01:14:58 +11:00
var (
2023-12-15 00:27:56 -08:00
defaultTTL time . Duration
2024-02-12 23:00:35 -08:00
activityBump = time . Hour // default
2023-10-13 11:57:18 -05:00
autostopRequirementDaysOfWeek [] string
autostartRequirementDaysOfWeek [] string
autostopRequirementWeeks int64
failureTTL time . Duration
dormantTTL time . Duration
dormantAutoDeletionTTL time . Duration
2023-03-08 01:14:58 +11:00
)
2022-11-09 14:36:25 -05:00
if createTemplate . DefaultTTLMillis != nil {
2023-03-08 01:14:58 +11:00
defaultTTL = time . Duration ( * createTemplate . DefaultTTLMillis ) * time . Millisecond
2022-06-07 13:37:45 +01:00
}
2024-02-12 23:00:35 -08:00
if createTemplate . ActivityBumpMillis != nil {
activityBump = time . Duration ( * createTemplate . ActivityBumpMillis ) * time . Millisecond
}
2023-08-29 11:35:05 -07:00
if createTemplate . AutostopRequirement != nil {
autostopRequirementDaysOfWeek = createTemplate . AutostopRequirement . DaysOfWeek
autostopRequirementWeeks = createTemplate . AutostopRequirement . Weeks
2023-03-08 01:14:58 +11:00
}
2023-10-13 11:57:18 -05:00
if createTemplate . AutostartRequirement != nil {
autostartRequirementDaysOfWeek = createTemplate . AutostartRequirement . DaysOfWeek
} else {
// By default, we want to allow all days of the week to be autostarted.
autostartRequirementDaysOfWeek = codersdk . BitmapToWeekdays ( 0b01111111 )
}
2023-05-10 12:57:11 -07:00
if createTemplate . FailureTTLMillis != nil {
failureTTL = time . Duration ( * createTemplate . FailureTTLMillis ) * time . Millisecond
}
2023-08-24 13:25:54 -05:00
if createTemplate . TimeTilDormantMillis != nil {
dormantTTL = time . Duration ( * createTemplate . TimeTilDormantMillis ) * time . Millisecond
2023-05-10 12:57:11 -07:00
}
2023-08-24 13:25:54 -05:00
if createTemplate . TimeTilDormantAutoDeleteMillis != nil {
dormantAutoDeletionTTL = time . Duration ( * createTemplate . TimeTilDormantAutoDeleteMillis ) * time . Millisecond
2023-07-02 21:29:52 -05:00
}
2023-03-08 01:14:58 +11:00
2023-07-20 06:35:41 -07:00
var (
2023-10-13 11:57:18 -05:00
validErrs [] codersdk . ValidationError
autostopRequirementDaysOfWeekParsed uint8
autostartRequirementDaysOfWeekParsed uint8
2024-08-20 22:48:39 +10:00
maxPortShareLevel = database . AppSharingLevelOwner // default
2025-07-30 13:42:39 -07:00
corsBehavior = database . CorsBehaviorSimple // default
2023-07-20 06:35:41 -07:00
)
2023-03-08 01:14:58 +11:00
if defaultTTL < 0 {
validErrs = append ( validErrs , codersdk . ValidationError { Field : "default_ttl_ms" , Detail : "Must be a positive integer." })
}
2024-02-12 23:00:35 -08:00
if activityBump < 0 {
validErrs = append ( validErrs , codersdk . ValidationError { Field : "activity_bump_ms" , Detail : "Must be a positive integer." })
}
2024-03-20 10:37:57 -05:00
2023-08-29 11:35:05 -07:00
if len ( autostopRequirementDaysOfWeek ) > 0 {
autostopRequirementDaysOfWeekParsed , err = codersdk . WeekdaysToBitmap ( autostopRequirementDaysOfWeek )
2023-07-20 06:35:41 -07:00
if err != nil {
2023-08-29 11:35:05 -07:00
validErrs = append ( validErrs , codersdk . ValidationError { Field : "autostop_requirement.days_of_week" , Detail : err . Error ()})
2023-07-20 06:35:41 -07:00
}
}
2023-10-13 11:57:18 -05:00
if len ( autostartRequirementDaysOfWeek ) > 0 {
autostartRequirementDaysOfWeekParsed , err = codersdk . WeekdaysToBitmap ( autostartRequirementDaysOfWeek )
if err != nil {
validErrs = append ( validErrs , codersdk . ValidationError { Field : "autostart_requirement.days_of_week" , Detail : err . Error ()})
}
}
2024-08-20 22:48:39 +10:00
if createTemplate . MaxPortShareLevel != nil {
err = portSharer . ValidateTemplateMaxLevel ( * createTemplate . MaxPortShareLevel )
if err != nil {
validErrs = append ( validErrs , codersdk . ValidationError { Field : "max_port_share_level" , Detail : err . Error ()})
} else {
maxPortShareLevel = database . AppSharingLevel ( * createTemplate . MaxPortShareLevel )
}
}
2024-03-20 10:37:57 -05:00
2025-07-30 13:42:39 -07:00
// Default the CORS behavior here to Simple so we don't break all existing templates.
val := database . CorsBehaviorSimple
if createTemplate . CORSBehavior != nil {
val = database . CorsBehavior ( * createTemplate . CORSBehavior )
}
if ! val . Valid () {
validErrs = append ( validErrs , codersdk . ValidationError {
Field : "cors_behavior" ,
Detail : fmt . Sprintf ( "Invalid CORS behavior %q. Must be one of [%s]" , * createTemplate . CORSBehavior , strings . Join ( slice . ToStrings ( database . AllCorsBehaviorValues ()), ", " )),
})
} else {
corsBehavior = val
}
2023-08-29 11:35:05 -07:00
if autostopRequirementWeeks < 0 {
validErrs = append ( validErrs , codersdk . ValidationError { Field : "autostop_requirement.weeks" , Detail : "Must be a positive integer." })
2023-07-20 06:35:41 -07:00
}
2023-08-29 11:35:05 -07:00
if autostopRequirementWeeks > schedule . MaxTemplateAutostopRequirementWeeks {
validErrs = append ( validErrs , codersdk . ValidationError { Field : "autostop_requirement.weeks" , Detail : fmt . Sprintf ( "Must be less than %d." , schedule . MaxTemplateAutostopRequirementWeeks )})
2023-07-20 06:35:41 -07:00
}
2023-05-10 12:57:11 -07:00
if failureTTL < 0 {
validErrs = append ( validErrs , codersdk . ValidationError { Field : "failure_ttl_ms" , Detail : "Must be a positive integer." })
}
2023-08-24 13:25:54 -05:00
if dormantTTL < 0 {
validErrs = append ( validErrs , codersdk . ValidationError { Field : "time_til_dormant_autodeletion_ms" , Detail : "Must be a positive integer." })
2023-05-10 12:57:11 -07:00
}
2023-08-24 13:25:54 -05:00
if dormantAutoDeletionTTL < 0 {
validErrs = append ( validErrs , codersdk . ValidationError { Field : "time_til_dormant_autodeletion_ms" , Detail : "Must be a positive integer." })
2023-07-02 21:29:52 -05:00
}
2023-03-08 01:14:58 +11:00
if len ( validErrs ) > 0 {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
2023-03-08 01:14:58 +11:00
Message : "Invalid create template request." ,
Validations : validErrs ,
2022-08-24 15:45:14 +01:00
})
return
}
2023-04-04 22:48:35 +10:00
var (
2023-04-27 18:55:34 -05:00
dbTemplate database . Template
allowUserCancelWorkspaceJobs = ptr . NilToDefault ( createTemplate . AllowUserCancelWorkspaceJobs , false )
allowUserAutostart = ptr . NilToDefault ( createTemplate . AllowUserAutostart , true )
allowUserAutostop = ptr . NilToDefault ( createTemplate . AllowUserAutostop , true )
2023-04-04 22:48:35 +10:00
)
2022-11-21 11:43:53 +01:00
2023-06-14 11:08:58 -05:00
defaultsGroups := database . TemplateACL {}
if ! createTemplate . DisableEveryoneGroupAccess {
// The organization ID is used as the group ID for the everyone group
// in this organization.
2025-01-17 11:55:41 -06:00
defaultsGroups [ organization . ID . String ()] = db2sdk . TemplateRoleActions ( codersdk . TemplateRoleUse )
2023-06-14 11:08:58 -05:00
}
2022-10-10 15:37:06 -05:00
err = api . Database . InTx ( func ( tx database . Store ) error {
2023-09-01 19:50:12 +03:00
now := dbtime . Now ()
2023-07-19 16:07:33 -04:00
id := uuid . New ()
err = tx . InsertTemplate ( ctx , database . InsertTemplateParams {
ID : id ,
2023-06-14 11:08:58 -05:00
CreatedAt : now ,
UpdatedAt : now ,
OrganizationID : organization . ID ,
Name : createTemplate . Name ,
Provisioner : importJob . Provisioner ,
ActiveVersionID : templateVersion . ID ,
Description : createTemplate . Description ,
CreatedBy : apiKey . UserID ,
UserACL : database . TemplateACL {},
GroupACL : defaultsGroups ,
2022-11-21 11:43:53 +01:00
DisplayName : createTemplate . DisplayName ,
Icon : createTemplate . Icon ,
AllowUserCancelWorkspaceJobs : allowUserCancelWorkspaceJobs ,
2024-08-20 22:48:39 +10:00
MaxPortSharingLevel : maxPortShareLevel ,
2025-07-02 09:44:01 -05:00
UseClassicParameterFlow : useClassicParameterFlow ,
2025-07-30 13:42:39 -07:00
CorsBehavior : corsBehavior ,
2022-05-16 14:36:27 -05:00
})
if err != nil {
return xerrors . Errorf ( "insert template: %s" , err )
}
2023-10-18 17:07:21 -05:00
if createTemplate . RequireActiveVersion {
err = ( * api . AccessControlStore . Load ()). SetTemplateAccessControl ( ctx , tx , id , dbauthz . TemplateAccessControl {
RequireActiveVersion : createTemplate . RequireActiveVersion ,
})
if err != nil {
return xerrors . Errorf ( "set template access control: %w" , err )
}
}
2023-07-19 16:07:33 -04:00
dbTemplate , err = tx . GetTemplateByID ( ctx , id )
if err != nil {
return xerrors . Errorf ( "get template by id: %s" , err )
}
2023-07-20 06:35:41 -07:00
dbTemplate , err = ( * api . TemplateScheduleStore . Load ()). Set ( ctx , tx , dbTemplate , schedule . TemplateScheduleOptions {
2023-04-04 22:48:35 +10:00
UserAutostartEnabled : allowUserAutostart ,
UserAutostopEnabled : allowUserAutostop ,
DefaultTTL : defaultTTL ,
2024-02-12 23:00:35 -08:00
ActivityBump : activityBump ,
2023-05-10 12:57:11 -07:00
// Some of these values are enterprise-only, but the
// TemplateScheduleStore will handle avoiding setting them if
// unlicensed.
2023-08-29 11:35:05 -07:00
AutostopRequirement : schedule . TemplateAutostopRequirement {
DaysOfWeek : autostopRequirementDaysOfWeekParsed ,
Weeks : autostopRequirementWeeks ,
2023-07-20 06:35:41 -07:00
},
2023-10-13 11:57:18 -05:00
AutostartRequirement : schedule . TemplateAutostartRequirement {
DaysOfWeek : autostartRequirementDaysOfWeekParsed ,
},
2023-08-24 13:25:54 -05:00
FailureTTL : failureTTL ,
TimeTilDormant : dormantTTL ,
TimeTilDormantAutoDelete : dormantAutoDeletionTTL ,
2023-03-08 01:14:58 +11:00
})
if err != nil {
return xerrors . Errorf ( "set template schedule options: %s" , err )
}
2022-09-09 11:34:23 -05:00
templateAudit . New = dbTemplate
2023-07-25 09:14:38 -04:00
err = tx . UpdateTemplateVersionByID ( ctx , database . UpdateTemplateVersionByIDParams {
2022-05-16 14:36:27 -05:00
ID : templateVersion . ID ,
TemplateID : uuid . NullUUID {
UUID : dbTemplate . ID ,
Valid : true ,
},
2023-09-01 19:50:12 +03:00
UpdatedAt : dbtime . Now (),
2023-03-23 13:26:50 -03:00
Name : templateVersion . Name ,
2023-07-13 10:36:10 -03:00
Message : templateVersion . Message ,
2022-05-16 14:36:27 -05:00
})
if err != nil {
return xerrors . Errorf ( "insert template version: %s" , err )
}
2022-09-09 11:34:23 -05:00
newTemplateVersion := templateVersion
newTemplateVersion . TemplateID = uuid . NullUUID {
UUID : dbTemplate . ID ,
Valid : true ,
}
templateVersionAudit . New = newTemplateVersion
2022-05-16 14:36:27 -05:00
return nil
2024-10-25 12:14:15 -04:00
}, database . DefaultTXOptions (). WithID ( "postTemplate" ))
2022-05-16 14:36:27 -05:00
if err != nil {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
2022-06-07 09:33:06 -05:00
Message : "Internal error inserting template." ,
2022-06-03 16:48:09 -05:00
Detail : err . Error (),
2022-05-16 14:36:27 -05:00
})
return
}
2022-06-17 00:26:40 -05:00
api . Telemetry . Report ( & telemetry . Snapshot {
Templates : [] telemetry . Template { telemetry . ConvertTemplate ( dbTemplate )},
TemplateVersions : [] telemetry . TemplateVersion { telemetry . ConvertTemplateVersion ( templateVersion )},
})
2024-02-12 23:00:35 -08:00
httpapi . Write ( ctx , rw , http . StatusCreated , api . convertTemplate ( dbTemplate ))
2022-05-16 14:36:27 -05:00
}
2022-12-19 18:43:46 +01:00
// @Summary Get templates by organization
2025-05-13 12:44:46 +01:00
// @Description Returns a list of templates for the specified organization.
// @Description By default, only non-deprecated templates are returned.
// @Description To include deprecated templates, specify `deprecated:true` in the search query.
2022-12-19 18:43:46 +01:00
// @ID get-templates-by-organization
// @Security CoderSessionToken
// @Produce json
// @Tags Templates
// @Param organization path string true "Organization ID" format(uuid)
2023-01-11 12:16:09 +01:00
// @Success 200 {array} codersdk.Template
2022-12-19 18:43:46 +01:00
// @Router /organizations/{organization}/templates [get]
2024-06-26 07:50:32 -10:00
func ( api * API ) templatesByOrganization () http . HandlerFunc {
// TODO: Should deprecate this endpoint and make it akin to /workspaces with
// a filter. There isn't a need to make the organization filter argument
// part of the query url.
// mutate the filter to only include templates from the given organization.
return api . fetchTemplates ( func ( r * http . Request , arg * database . GetTemplatesWithFilterParams ) {
organization := httpmw . OrganizationParam ( r )
arg . OrganizationID = organization . ID
})
}
2022-11-28 12:12:34 -06:00
2024-06-26 07:50:32 -10:00
// @Summary Get all templates
2025-05-13 12:44:46 +01:00
// @Description Returns a list of templates.
// @Description By default, only non-deprecated templates are returned.
// @Description To include deprecated templates, specify `deprecated:true` in the search query.
2024-06-26 07:50:32 -10:00
// @ID get-all-templates
// @Security CoderSessionToken
// @Produce json
// @Tags Templates
// @Success 200 {array} codersdk.Template
// @Router /templates [get]
func ( api * API ) fetchTemplates ( mutate func ( r * http . Request , arg * database . GetTemplatesWithFilterParams )) http . HandlerFunc {
return func ( rw http . ResponseWriter , r * http . Request ) {
ctx := r . Context ()
2025-08-06 11:45:07 -05:00
key := httpmw . APIKey ( r )
2023-11-20 13:16:18 -06:00
2024-07-03 08:42:23 -10:00
queryStr := r . URL . Query (). Get ( "q" )
2025-08-06 11:45:07 -05:00
filter , errs := searchquery . Templates ( ctx , api . Database , key . UserID , queryStr )
2024-07-03 08:42:23 -10:00
if len ( errs ) > 0 {
2024-06-26 07:50:32 -10:00
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
2024-07-03 08:42:23 -10:00
Message : "Invalid template search query." ,
Validations : errs ,
2024-06-26 07:50:32 -10:00
})
return
2023-11-20 13:16:18 -06:00
}
2024-06-26 07:50:32 -10:00
prepared , err := api . HTTPAuth . AuthorizeSQLFilter ( r , policy . ActionRead , rbac . ResourceTemplate . Type )
if err != nil {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error preparing sql filter." ,
Detail : err . Error (),
})
return
}
2022-11-28 12:12:34 -06:00
2024-07-03 08:42:23 -10:00
args := filter
2024-06-26 07:50:32 -10:00
if mutate != nil {
mutate ( r , & args )
}
2022-11-28 12:12:34 -06:00
2025-05-13 12:44:46 +01:00
// By default, deprecated templates are excluded unless explicitly requested
if ! args . Deprecated . Valid {
args . Deprecated = sql . NullBool {
Bool : false ,
Valid : true ,
}
}
2024-06-26 07:50:32 -10:00
// Filter templates based on rbac permissions
templates , err := api . Database . GetAuthorizedTemplates ( ctx , args , prepared )
if errors . Is ( err , sql . ErrNoRows ) {
err = nil
}
2022-05-24 08:43:34 -05:00
2024-06-26 07:50:32 -10:00
if err != nil {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error fetching templates in organization." ,
Detail : err . Error (),
})
return
}
httpapi . Write ( ctx , rw , http . StatusOK , api . convertTemplates ( templates ))
}
2022-05-16 14:36:27 -05:00
}
2022-12-19 18:43:46 +01:00
// @Summary Get templates by organization and template name
// @ID get-templates-by-organization-and-template-name
// @Security CoderSessionToken
// @Produce json
// @Tags Templates
// @Param organization path string true "Organization ID" format(uuid)
2023-01-11 12:16:09 +01:00
// @Param templatename path string true "Template name"
2022-12-19 18:43:46 +01:00
// @Success 200 {object} codersdk.Template
2023-01-11 12:16:09 +01:00
// @Router /organizations/{organization}/templates/{templatename} [get]
2022-05-25 22:14:08 -05:00
func ( api * API ) templateByOrganizationAndName ( rw http . ResponseWriter , r * http . Request ) {
2022-09-21 17:07:00 -05:00
ctx := r . Context ()
2022-05-16 14:36:27 -05:00
organization := httpmw . OrganizationParam ( r )
templateName := chi . URLParam ( r , "templatename" )
2022-09-21 17:07:00 -05:00
template , err := api . Database . GetTemplateByOrganizationAndName ( ctx , database . GetTemplateByOrganizationAndNameParams {
2022-05-16 14:36:27 -05:00
OrganizationID : organization . ID ,
Name : templateName ,
})
if err != nil {
2023-04-13 13:06:16 -05:00
if httpapi . Is404Error ( err ) {
2022-06-14 10:14:05 -05:00
httpapi . ResourceNotFound ( rw )
2022-04-06 12:42:40 -05:00
return
}
2022-05-16 14:36:27 -05:00
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
2022-06-07 09:33:06 -05:00
Message : "Internal error fetching template." ,
2022-06-03 16:48:09 -05:00
Detail : err . Error (),
2022-05-16 14:36:27 -05:00
})
return
2022-04-06 12:42:40 -05:00
}
2022-04-12 10:17:33 -05:00
2023-07-19 16:07:33 -04:00
httpapi . Write ( ctx , rw , http . StatusOK , api . convertTemplate ( template ))
2022-04-06 12:42:40 -05:00
}
2022-12-19 18:43:46 +01:00
// @Summary Update template metadata by ID
2023-01-13 12:27:21 +01:00
// @ID update-template-metadata-by-id
2022-12-19 18:43:46 +01:00
// @Security CoderSessionToken
// @Produce json
// @Tags Templates
2023-01-13 12:27:21 +01:00
// @Param template path string true "Template ID" format(uuid)
2022-12-19 18:43:46 +01:00
// @Success 200 {object} codersdk.Template
2023-01-13 12:27:21 +01:00
// @Router /templates/{template} [patch]
2022-06-08 15:14:57 +01:00
func ( api * API ) patchTemplateMeta ( rw http . ResponseWriter , r * http . Request ) {
2022-09-09 11:34:23 -05:00
var (
2022-09-21 17:07:00 -05:00
ctx = r . Context ()
2022-09-09 11:34:23 -05:00
template = httpmw . TemplateParam ( r )
2022-09-19 23:11:01 -05:00
auditor = * api . Auditor . Load ()
2024-02-13 09:31:20 -05:00
portSharer = * api . PortSharer . Load ()
2022-09-09 11:34:23 -05:00
aReq , commitAudit = audit . InitRequest [ database . Template ]( rw , & audit . RequestParams {
2024-02-26 08:27:33 -06:00
Audit : auditor ,
Log : api . Logger ,
Request : r ,
Action : database . AuditActionWrite ,
OrganizationID : template . OrganizationID ,
2022-09-09 11:34:23 -05:00
})
)
defer commitAudit ()
aReq . Old = template
2023-07-20 06:35:41 -07:00
scheduleOpts , err := ( * api . TemplateScheduleStore . Load ()). Get ( ctx , api . Database , template . ID )
if err != nil {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error fetching template schedule options." ,
Detail : err . Error (),
})
return
}
2022-06-08 15:14:57 +01:00
var req codersdk . UpdateTemplateMeta
2022-09-21 17:07:00 -05:00
if ! httpapi . Read ( ctx , rw , r , & req ) {
2022-06-08 15:14:57 +01:00
return
}
2023-07-20 06:35:41 -07:00
var (
2023-10-13 11:57:18 -05:00
validErrs [] codersdk . ValidationError
autostopRequirementDaysOfWeekParsed uint8
autostartRequirementDaysOfWeekParsed uint8
2023-07-20 06:35:41 -07:00
)
2022-11-09 14:36:25 -05:00
if req . DefaultTTLMillis < 0 {
validErrs = append ( validErrs , codersdk . ValidationError { Field : "default_ttl_ms" , Detail : "Must be a positive integer." })
2022-08-24 15:45:14 +01:00
}
2024-02-12 23:00:35 -08:00
if req . ActivityBumpMillis < 0 {
validErrs = append ( validErrs , codersdk . ValidationError { Field : "activity_bump_ms" , Detail : "Must be a positive integer." })
}
2024-03-20 10:37:57 -05:00
2023-08-29 11:35:05 -07:00
if req . AutostopRequirement == nil {
req . AutostopRequirement = & codersdk . TemplateAutostopRequirement {
DaysOfWeek : codersdk . BitmapToWeekdays ( scheduleOpts . AutostopRequirement . DaysOfWeek ),
Weeks : scheduleOpts . AutostopRequirement . Weeks ,
2023-07-20 06:35:41 -07:00
}
}
2023-08-29 11:35:05 -07:00
if len ( req . AutostopRequirement . DaysOfWeek ) > 0 {
autostopRequirementDaysOfWeekParsed , err = codersdk . WeekdaysToBitmap ( req . AutostopRequirement . DaysOfWeek )
2023-07-20 06:35:41 -07:00
if err != nil {
2023-08-29 11:35:05 -07:00
validErrs = append ( validErrs , codersdk . ValidationError { Field : "autostop_requirement.days_of_week" , Detail : err . Error ()})
2023-07-20 06:35:41 -07:00
}
}
2023-10-13 11:57:18 -05:00
if req . AutostartRequirement == nil {
req . AutostartRequirement = & codersdk . TemplateAutostartRequirement {
DaysOfWeek : codersdk . BitmapToWeekdays ( scheduleOpts . AutostartRequirement . DaysOfWeek ),
}
}
if len ( req . AutostartRequirement . DaysOfWeek ) > 0 {
autostartRequirementDaysOfWeekParsed , err = codersdk . WeekdaysToBitmap ( req . AutostartRequirement . DaysOfWeek )
if err != nil {
validErrs = append ( validErrs , codersdk . ValidationError { Field : "autostart_requirement.days_of_week" , Detail : err . Error ()})
}
}
2023-08-29 11:35:05 -07:00
if req . AutostopRequirement . Weeks < 0 {
validErrs = append ( validErrs , codersdk . ValidationError { Field : "autostop_requirement.weeks" , Detail : "Must be a positive integer." })
2023-07-20 06:35:41 -07:00
}
2023-08-30 13:41:27 -07:00
if req . AutostopRequirement . Weeks == 0 {
req . AutostopRequirement . Weeks = 1
}
if template . AutostopRequirementWeeks <= 0 {
template . AutostopRequirementWeeks = 1
}
2023-08-29 11:35:05 -07:00
if req . AutostopRequirement . Weeks > schedule . MaxTemplateAutostopRequirementWeeks {
validErrs = append ( validErrs , codersdk . ValidationError { Field : "autostop_requirement.weeks" , Detail : fmt . Sprintf ( "Must be less than %d." , schedule . MaxTemplateAutostopRequirementWeeks )})
2023-07-20 06:35:41 -07:00
}
2023-11-20 13:16:18 -06:00
// Defaults to the existing.
deprecationMessage := template . Deprecated
if req . DeprecationMessage != nil {
deprecationMessage = * req . DeprecationMessage
}
2023-10-05 13:41:07 -05:00
// The minimum valid value for a dormant TTL is 1 minute. This is
// to ensure an uninformed user does not send an unintentionally
// small number resulting in potentially catastrophic consequences.
const minTTL = 1000 * 60
if req . FailureTTLMillis < 0 || ( req . FailureTTLMillis > 0 && req . FailureTTLMillis < minTTL ) {
validErrs = append ( validErrs , codersdk . ValidationError { Field : "failure_ttl_ms" , Detail : "Value must be at least one minute." })
2023-05-05 08:19:26 -07:00
}
2023-10-05 13:41:07 -05:00
if req . TimeTilDormantMillis < 0 || ( req . TimeTilDormantMillis > 0 && req . TimeTilDormantMillis < minTTL ) {
validErrs = append ( validErrs , codersdk . ValidationError { Field : "time_til_dormant_ms" , Detail : "Value must be at least one minute." })
2023-05-05 08:19:26 -07:00
}
2023-10-05 13:41:07 -05:00
if req . TimeTilDormantAutoDeleteMillis < 0 || ( req . TimeTilDormantAutoDeleteMillis > 0 && req . TimeTilDormantAutoDeleteMillis < minTTL ) {
validErrs = append ( validErrs , codersdk . ValidationError { Field : "time_til_dormant_autodelete_ms" , Detail : "Value must be at least one minute." })
2023-06-19 22:37:55 -04:00
}
2024-02-13 09:31:20 -05:00
maxPortShareLevel := template . MaxPortSharingLevel
2024-05-13 14:37:51 -04:00
if req . MaxPortShareLevel != nil && * req . MaxPortShareLevel != portSharer . ConvertMaxLevel ( template . MaxPortSharingLevel ) {
err := portSharer . ValidateTemplateMaxLevel ( * req . MaxPortShareLevel )
2024-02-13 09:31:20 -05:00
if err != nil {
validErrs = append ( validErrs , codersdk . ValidationError { Field : "max_port_sharing_level" , Detail : err . Error ()})
} else {
maxPortShareLevel = database . AppSharingLevel ( * req . MaxPortShareLevel )
}
}
2022-06-08 15:14:57 +01:00
2025-07-30 13:42:39 -07:00
corsBehavior := template . CorsBehavior
if req . CORSBehavior != nil && * req . CORSBehavior != "" {
val := database . CorsBehavior ( * req . CORSBehavior )
if ! val . Valid () {
validErrs = append ( validErrs , codersdk . ValidationError {
Field : "cors_behavior" ,
Detail : fmt . Sprintf ( "Invalid CORS behavior %q. Must be one of [%s]" , * req . CORSBehavior , strings . Join ( slice . ToStrings ( database . AllCorsBehaviorValues ()), ", " )),
})
} else {
corsBehavior = val
}
}
2022-06-08 15:14:57 +01:00
if len ( validErrs ) > 0 {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
2022-06-08 15:14:57 +01:00
Message : "Invalid request to update template metadata!" ,
Validations : validErrs ,
})
return
}
2025-05-15 17:55:17 -05:00
// Defaults to the existing.
classicTemplateFlow := template . UseClassicParameterFlow
if req . UseClassicParameterFlow != nil {
classicTemplateFlow = * req . UseClassicParameterFlow
}
2022-06-08 15:14:57 +01:00
var updated database . Template
2023-07-20 06:35:41 -07:00
err = api . Database . InTx ( func ( tx database . Store ) error {
2022-08-17 16:04:00 -03:00
if req . Name == template . Name &&
req . Description == template . Description &&
2022-11-10 21:51:09 +01:00
req . DisplayName == template . DisplayName &&
2022-08-19 10:17:35 -03:00
req . Icon == template . Icon &&
2023-04-04 22:48:35 +10:00
req . AllowUserAutostart == template . AllowUserAutostart &&
req . AllowUserAutostop == template . AllowUserAutostop &&
2022-11-21 11:43:53 +01:00
req . AllowUserCancelWorkspaceJobs == template . AllowUserCancelWorkspaceJobs &&
2023-03-08 01:14:58 +11:00
req . DefaultTTLMillis == time . Duration ( template . DefaultTTL ). Milliseconds () &&
2024-02-12 23:00:35 -08:00
req . ActivityBumpMillis == time . Duration ( template . ActivityBump ). Milliseconds () &&
2023-08-29 11:35:05 -07:00
autostopRequirementDaysOfWeekParsed == scheduleOpts . AutostopRequirement . DaysOfWeek &&
2023-10-16 09:29:42 -05:00
autostartRequirementDaysOfWeekParsed == scheduleOpts . AutostartRequirement . DaysOfWeek &&
2023-08-29 11:35:05 -07:00
req . AutostopRequirement . Weeks == scheduleOpts . AutostopRequirement . Weeks &&
2023-05-05 08:19:26 -07:00
req . FailureTTLMillis == time . Duration ( template . FailureTTL ). Milliseconds () &&
2023-08-24 13:25:54 -05:00
req . TimeTilDormantMillis == time . Duration ( template . TimeTilDormant ). Milliseconds () &&
2023-10-18 17:07:21 -05:00
req . TimeTilDormantAutoDeleteMillis == time . Duration ( template . TimeTilDormantAutoDelete ). Milliseconds () &&
2023-11-20 13:16:18 -06:00
req . RequireActiveVersion == template . RequireActiveVersion &&
2024-02-13 09:31:20 -05:00
( deprecationMessage == template . Deprecated ) &&
2025-05-15 17:55:17 -05:00
( classicTemplateFlow == template . UseClassicParameterFlow ) &&
2025-07-30 13:42:39 -07:00
maxPortShareLevel == template . MaxPortSharingLevel &&
corsBehavior == template . CorsBehavior {
2022-06-08 15:14:57 +01:00
return nil
}
2023-05-05 08:19:26 -07:00
// Users should not be able to clear the template name in the UI
2022-08-17 16:04:00 -03:00
name := req . Name
if name == "" {
name = template . Name
}
2022-06-08 15:14:57 +01:00
2024-01-05 16:04:14 -05:00
groupACL := template . GroupACL
if req . DisableEveryoneGroupAccess {
2024-01-11 16:18:46 -06:00
delete ( groupACL , template . OrganizationID . String ())
2024-01-05 16:04:14 -05:00
}
2024-03-05 13:47:01 -05:00
if template . MaxPortSharingLevel != maxPortShareLevel {
switch maxPortShareLevel {
case database . AppSharingLevelOwner :
err = tx . DeleteWorkspaceAgentPortSharesByTemplate ( ctx , template . ID )
if err != nil {
return xerrors . Errorf ( "delete workspace agent port shares by template: %w" , err )
}
case database . AppSharingLevelAuthenticated :
err = tx . ReduceWorkspaceAgentShareLevelToAuthenticatedByTemplate ( ctx , template . ID )
if err != nil {
return xerrors . Errorf ( "reduce workspace agent share level to authenticated by template: %w" , err )
}
}
}
2023-02-02 11:59:43 -06:00
var err error
2023-07-19 16:07:33 -04:00
err = tx . UpdateTemplateMetaByID ( ctx , database . UpdateTemplateMetaByIDParams {
2022-11-21 11:43:53 +01:00
ID : template . ID ,
2023-09-01 19:50:12 +03:00
UpdatedAt : dbtime . Now (),
2022-11-21 11:43:53 +01:00
Name : name ,
2023-05-05 08:19:26 -07:00
DisplayName : req . DisplayName ,
Description : req . Description ,
Icon : req . Icon ,
2023-04-04 22:48:35 +10:00
AllowUserCancelWorkspaceJobs : req . AllowUserCancelWorkspaceJobs ,
2024-01-05 16:04:14 -05:00
GroupACL : groupACL ,
2024-02-13 09:31:20 -05:00
MaxPortSharingLevel : maxPortShareLevel ,
2025-05-15 17:55:17 -05:00
UseClassicParameterFlow : classicTemplateFlow ,
2025-07-30 13:42:39 -07:00
CorsBehavior : corsBehavior ,
2022-09-09 11:34:23 -05:00
})
2022-06-08 15:14:57 +01:00
if err != nil {
2023-03-08 01:14:58 +11:00
return xerrors . Errorf ( "update template metadata: %w" , err )
}
2023-11-20 13:16:18 -06:00
if template . RequireActiveVersion != req . RequireActiveVersion || deprecationMessage != template . Deprecated {
2023-10-18 17:07:21 -05:00
err = ( * api . AccessControlStore . Load ()). SetTemplateAccessControl ( ctx , tx , template . ID , dbauthz . TemplateAccessControl {
RequireActiveVersion : req . RequireActiveVersion ,
2023-11-20 13:16:18 -06:00
Deprecated : deprecationMessage ,
2023-10-18 17:07:21 -05:00
})
if err != nil {
return xerrors . Errorf ( "set template access control: %w" , err )
}
}
2023-07-19 16:07:33 -04:00
updated , err = tx . GetTemplateByID ( ctx , template . ID )
if err != nil {
return xerrors . Errorf ( "fetch updated template metadata: %w" , err )
}
2023-03-08 01:14:58 +11:00
defaultTTL := time . Duration ( req . DefaultTTLMillis ) * time . Millisecond
2024-02-12 23:00:35 -08:00
activityBump := time . Duration ( req . ActivityBumpMillis ) * time . Millisecond
2023-05-05 08:19:26 -07:00
failureTTL := time . Duration ( req . FailureTTLMillis ) * time . Millisecond
2023-08-24 13:25:54 -05:00
inactivityTTL := time . Duration ( req . TimeTilDormantMillis ) * time . Millisecond
timeTilDormantAutoDelete := time . Duration ( req . TimeTilDormantAutoDeleteMillis ) * time . Millisecond
2024-05-31 12:26:19 -04:00
var updateWorkspaceLastUsedAt workspacestats . UpdateTemplateWorkspacesLastUsedAtFunc
if req . UpdateWorkspaceLastUsedAt {
updateWorkspaceLastUsedAt = workspacestats . UpdateTemplateWorkspacesLastUsedAt
}
2023-05-05 08:19:26 -07:00
2023-04-04 22:48:35 +10:00
if defaultTTL != time . Duration ( template . DefaultTTL ) ||
2024-02-12 23:00:35 -08:00
activityBump != time . Duration ( template . ActivityBump ) ||
2023-08-29 11:35:05 -07:00
autostopRequirementDaysOfWeekParsed != scheduleOpts . AutostopRequirement . DaysOfWeek ||
2023-10-13 11:57:18 -05:00
autostartRequirementDaysOfWeekParsed != scheduleOpts . AutostartRequirement . DaysOfWeek ||
2023-08-29 11:35:05 -07:00
req . AutostopRequirement . Weeks != scheduleOpts . AutostopRequirement . Weeks ||
2023-05-05 08:19:26 -07:00
failureTTL != time . Duration ( template . FailureTTL ) ||
2023-08-24 13:25:54 -05:00
inactivityTTL != time . Duration ( template . TimeTilDormant ) ||
timeTilDormantAutoDelete != time . Duration ( template . TimeTilDormantAutoDelete ) ||
2023-04-04 22:48:35 +10:00
req . AllowUserAutostart != template . AllowUserAutostart ||
req . AllowUserAutostop != template . AllowUserAutostop {
2023-07-20 06:35:41 -07:00
updated , err = ( * api . TemplateScheduleStore . Load ()). Set ( ctx , tx , updated , schedule . TemplateScheduleOptions {
2023-04-04 22:48:35 +10:00
// Some of these values are enterprise-only, but the
// TemplateScheduleStore will handle avoiding setting them if
// unlicensed.
UserAutostartEnabled : req . AllowUserAutostart ,
UserAutostopEnabled : req . AllowUserAutostop ,
DefaultTTL : defaultTTL ,
2024-02-12 23:00:35 -08:00
ActivityBump : activityBump ,
2023-08-29 11:35:05 -07:00
AutostopRequirement : schedule . TemplateAutostopRequirement {
DaysOfWeek : autostopRequirementDaysOfWeekParsed ,
Weeks : req . AutostopRequirement . Weeks ,
2023-07-20 06:35:41 -07:00
},
2023-10-13 11:57:18 -05:00
AutostartRequirement : schedule . TemplateAutostartRequirement {
DaysOfWeek : autostartRequirementDaysOfWeekParsed ,
},
2023-08-22 15:15:13 -05:00
FailureTTL : failureTTL ,
2023-08-24 13:25:54 -05:00
TimeTilDormant : inactivityTTL ,
TimeTilDormantAutoDelete : timeTilDormantAutoDelete ,
2024-05-31 12:26:19 -04:00
UpdateWorkspaceLastUsedAt : updateWorkspaceLastUsedAt ,
2023-08-24 13:25:54 -05:00
UpdateWorkspaceDormantAt : req . UpdateWorkspaceDormantAt ,
2023-03-08 01:14:58 +11:00
})
if err != nil {
return xerrors . Errorf ( "set template schedule options: %w" , err )
}
2022-06-08 15:14:57 +01:00
}
2022-09-09 11:34:23 -05:00
2022-06-08 15:14:57 +01:00
return nil
2022-11-14 11:57:33 -06:00
}, nil )
2022-06-08 15:14:57 +01:00
if err != nil {
2024-11-06 01:18:38 +11:00
if database . IsUniqueViolation ( err , database . UniqueTemplatesOrganizationIDNameIndex ) {
httpapi . Write ( ctx , rw , http . StatusConflict , codersdk . Response {
Message : fmt . Sprintf ( "Template with name %q already exists." , req . Name ),
Validations : [] codersdk . ValidationError {{
Field : "name" ,
Detail : "This value is already in use and should be unique." ,
}},
})
} else {
httpapi . InternalServerError ( rw , err )
}
2022-06-08 15:14:57 +01:00
return
}
2024-10-24 13:12:12 +01:00
if template . Deprecated != updated . Deprecated && updated . Deprecated != "" {
if err := api . notifyUsersOfTemplateDeprecation ( ctx , updated ); err != nil {
api . Logger . Error ( ctx , "failed to notify users of template deprecation" , slog . Error ( err ))
}
}
2022-06-08 15:14:57 +01:00
if updated . UpdatedAt . IsZero () {
2022-09-09 11:34:23 -05:00
aReq . New = template
2024-07-11 13:38:33 -06:00
rw . WriteHeader ( http . StatusNotModified )
2022-06-08 15:14:57 +01:00
return
}
2022-09-09 11:34:23 -05:00
aReq . New = updated
2022-06-08 15:14:57 +01:00
2023-07-19 16:07:33 -04:00
httpapi . Write ( ctx , rw , http . StatusOK , api . convertTemplate ( updated ))
2022-06-08 15:14:57 +01:00
}
2024-10-24 13:12:12 +01:00
func ( api * API ) notifyUsersOfTemplateDeprecation ( ctx context . Context , template database . Template ) error {
workspaces , err := api . Database . GetWorkspaces ( ctx , database . GetWorkspacesParams {
TemplateIDs : [] uuid . UUID { template . ID },
})
if err != nil {
return xerrors . Errorf ( "get workspaces by template id: %w" , err )
}
users := make ( map [ uuid . UUID ] struct {})
for _ , workspace := range workspaces {
users [ workspace . OwnerID ] = struct {}{}
}
errs := [] error {}
for userID := range users {
_ , err = api . NotificationsEnqueuer . Enqueue (
2024-10-31 17:01:51 +00:00
//nolint:gocritic // We need the notifier auth context to be able to send the deprecation notification.
dbauthz . AsNotifier ( ctx ),
2024-10-24 13:12:12 +01:00
userID ,
notifications . TemplateTemplateDeprecated ,
map [ string ] string {
"template" : template . Name ,
"message" : template . Deprecated ,
"organization" : template . OrganizationName ,
},
"notify-users-of-template-deprecation" ,
)
if err != nil {
errs = append ( errs , xerrors . Errorf ( "enqueue notification: %w" , err ))
}
}
return errors . Join ( errs ... )
}
2023-01-11 12:16:09 +01:00
// @Summary Get template DAUs by ID
// @ID get-template-daus-by-id
// @Security CoderSessionToken
// @Produce json
// @Tags Templates
2023-01-13 12:27:21 +01:00
// @Param template path string true "Template ID" format(uuid)
2023-05-30 19:18:27 +02:00
// @Success 200 {object} codersdk.DAUsResponse
2023-01-13 12:27:21 +01:00
// @Router /templates/{template}/daus [get]
2022-09-01 14:58:23 -05:00
func ( api * API ) templateDAUs ( rw http . ResponseWriter , r * http . Request ) {
template := httpmw . TemplateParam ( r )
2024-03-27 18:10:14 +02:00
api . returnDAUsInternal ( rw , r , [] uuid . UUID { template . ID })
2022-09-01 14:58:23 -05:00
}
2023-01-11 12:16:09 +01:00
// @Summary Get template examples by organization
// @ID get-template-examples-by-organization
// @Security CoderSessionToken
// @Produce json
// @Tags Templates
// @Param organization path string true "Organization ID" format(uuid)
// @Success 200 {array} codersdk.TemplateExample
// @Router /organizations/{organization}/templates/examples [get]
2024-08-06 11:26:26 -06:00
// @Deprecated Use /templates/examples instead
func ( api * API ) templateExamplesByOrganization ( rw http . ResponseWriter , r * http . Request ) {
2022-12-09 14:29:50 -05:00
var (
ctx = r . Context ()
organization = httpmw . OrganizationParam ( r )
)
2024-05-15 09:46:35 -05:00
if ! api . Authorize ( r , policy . ActionRead , rbac . ResourceTemplate . InOrg ( organization . ID )) {
2022-12-09 14:29:50 -05:00
httpapi . ResourceNotFound ( rw )
return
}
ex , err := examples . List ()
if err != nil {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error fetching examples." ,
Detail : err . Error (),
})
return
}
httpapi . Write ( ctx , rw , http . StatusOK , ex )
}
2024-08-06 11:26:26 -06:00
// @Summary Get template examples
// @ID get-template-examples
// @Security CoderSessionToken
// @Produce json
// @Tags Templates
// @Success 200 {array} codersdk.TemplateExample
// @Router /templates/examples [get]
func ( api * API ) templateExamples ( rw http . ResponseWriter , r * http . Request ) {
ctx := r . Context ()
if ! api . Authorize ( r , policy . ActionRead , rbac . ResourceTemplate . AnyOrganization ()) {
httpapi . ResourceNotFound ( rw )
return
}
ex , err := examples . List ()
if err != nil {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error fetching examples." ,
Detail : err . Error (),
})
return
}
httpapi . Write ( ctx , rw , http . StatusOK , ex )
}
2023-07-19 16:07:33 -04:00
func ( api * API ) convertTemplates ( templates [] database . Template ) [] codersdk . Template {
2022-04-06 12:42:40 -05:00
apiTemplates := make ([] codersdk . Template , 0 , len ( templates ))
2022-08-30 14:27:33 -03:00
2022-04-06 12:42:40 -05:00
for _ , template := range templates {
2023-07-19 16:07:33 -04:00
apiTemplates = append ( apiTemplates , api . convertTemplate ( template ))
2022-04-06 12:42:40 -05:00
}
2022-08-30 14:27:33 -03:00
2022-09-09 14:30:31 -05:00
// Sort templates by ActiveUserCount DESC
2022-08-30 14:27:33 -03:00
sort . SliceStable ( apiTemplates , func ( i , j int ) bool {
2022-09-09 14:30:31 -05:00
return apiTemplates [ i ]. ActiveUserCount > apiTemplates [ j ]. ActiveUserCount
2022-08-30 14:27:33 -03:00
})
2022-04-06 12:42:40 -05:00
return apiTemplates
}
2022-09-09 14:30:31 -05:00
func ( api * API ) convertTemplate (
2023-07-19 16:07:33 -04:00
template database . Template ,
2022-09-09 14:30:31 -05:00
) codersdk . Template {
2023-11-20 13:16:18 -06:00
templateAccessControl := ( * ( api . Options . AccessControlStore . Load ())). GetTemplateAccessControl ( template )
2023-12-07 10:53:15 -05:00
owners := 0
o , ok := api . metricsCache . TemplateWorkspaceOwners ( template . ID )
if ok {
owners = o
}
2022-10-15 15:36:50 -05:00
2022-10-16 23:34:03 -05:00
buildTimeStats := api . metricsCache . TemplateBuildTimeStats ( template . ID )
2022-10-15 15:36:50 -05:00
2023-08-30 13:41:27 -07:00
autostopRequirementWeeks := template . AutostopRequirementWeeks
if autostopRequirementWeeks < 1 {
autostopRequirementWeeks = 1
}
2024-05-13 14:37:51 -04:00
portSharer := * ( api . PortSharer . Load ())
maxPortShareLevel := portSharer . ConvertMaxLevel ( template . MaxPortSharingLevel )
2022-04-06 12:42:40 -05:00
return codersdk . Template {
2023-08-24 13:25:54 -05:00
ID : template . ID ,
CreatedAt : template . CreatedAt ,
UpdatedAt : template . UpdatedAt ,
OrganizationID : template . OrganizationID ,
2024-07-02 04:08:30 -10:00
OrganizationName : template . OrganizationName ,
2024-07-10 05:06:49 -10:00
OrganizationDisplayName : template . OrganizationDisplayName ,
OrganizationIcon : template . OrganizationIcon ,
2023-08-24 13:25:54 -05:00
Name : template . Name ,
DisplayName : template . DisplayName ,
Provisioner : codersdk . ProvisionerType ( template . Provisioner ),
ActiveVersionID : template . ActiveVersionID ,
2023-12-07 10:53:15 -05:00
ActiveUserCount : owners ,
2023-08-24 13:25:54 -05:00
BuildTimeStats : buildTimeStats ,
Description : template . Description ,
Icon : template . Icon ,
DefaultTTLMillis : time . Duration ( template . DefaultTTL ). Milliseconds (),
2024-02-12 23:00:35 -08:00
ActivityBumpMillis : time . Duration ( template . ActivityBump ). Milliseconds (),
2023-08-24 13:25:54 -05:00
CreatedByID : template . CreatedBy ,
CreatedByName : template . CreatedByUsername ,
AllowUserAutostart : template . AllowUserAutostart ,
AllowUserAutostop : template . AllowUserAutostop ,
AllowUserCancelWorkspaceJobs : template . AllowUserCancelWorkspaceJobs ,
FailureTTLMillis : time . Duration ( template . FailureTTL ). Milliseconds (),
TimeTilDormantMillis : time . Duration ( template . TimeTilDormant ). Milliseconds (),
TimeTilDormantAutoDeleteMillis : time . Duration ( template . TimeTilDormantAutoDelete ). Milliseconds (),
2023-08-29 11:35:05 -07:00
AutostopRequirement : codersdk . TemplateAutostopRequirement {
2025-03-26 01:56:39 -05:00
DaysOfWeek : codersdk . BitmapToWeekdays ( uint8 ( template . AutostopRequirementDaysOfWeek )), // #nosec G115 - Safe conversion as AutostopRequirementDaysOfWeek is a 7-bit bitmap
2023-08-30 13:41:27 -07:00
Weeks : autostopRequirementWeeks ,
2023-07-20 06:35:41 -07:00
},
2023-10-13 11:57:18 -05:00
AutostartRequirement : codersdk . TemplateAutostartRequirement {
DaysOfWeek : codersdk . BitmapToWeekdays ( template . AutostartAllowedDays ()),
},
2023-11-20 13:16:18 -06:00
// These values depend on entitlements and come from the templateAccessControl
2025-05-15 17:55:17 -05:00
RequireActiveVersion : templateAccessControl . RequireActiveVersion ,
Deprecated : templateAccessControl . IsDeprecated (),
DeprecationMessage : templateAccessControl . Deprecated ,
MaxPortShareLevel : maxPortShareLevel ,
UseClassicParameterFlow : template . UseClassicParameterFlow ,
2025-07-30 13:42:39 -07:00
CORSBehavior : codersdk . CORSBehavior ( template . CorsBehavior ),
2022-04-06 12:42:40 -05:00
}
}
2024-08-14 14:22:43 -03:00
// findTemplateAdmins fetches all users with template admin permission including owners.
func findTemplateAdmins ( ctx context . Context , store database . Store ) ([] database . GetUsersRow , error ) {
// Notice: we can't scrape the user information in parallel as pq
// fails with: unexpected describe rows response: 'D'
owners , err := store . GetUsers ( ctx , database . GetUsersParams {
RbacRole : [] string { codersdk . RoleOwner },
})
if err != nil {
return nil , xerrors . Errorf ( "get owners: %w" , err )
}
templateAdmins , err := store . GetUsers ( ctx , database . GetUsersParams {
RbacRole : [] string { codersdk . RoleTemplateAdmin },
})
if err != nil {
return nil , xerrors . Errorf ( "get template admins: %w" , err )
}
return append ( owners , templateAdmins ... ), nil
}