Skip to content

feat: add template setting to require active template version #10277

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 32 commits into from
Oct 18, 2023
Merged
Show file tree
Hide file tree
Changes from 16 commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions coderd/apidoc/docs.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions coderd/apidoc/swagger.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 5 additions & 1 deletion coderd/autobuild/lifecycle_executor.go
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ func (e *Executor) runOnce(t time.Time) Stats {
Reason(reason)
log.Debug(e.ctx, "auto building workspace", slog.F("transition", nextTransition))
if nextTransition == database.WorkspaceTransitionStart &&
ws.AutomaticUpdates == database.AutomaticUpdatesAlways {
useActiveVersion(templateSchedule, ws) {
log.Debug(e.ctx, "autostarting with active version")
builder = builder.ActiveVersion()
}
Expand Down Expand Up @@ -469,3 +469,7 @@ func auditBuild(ctx context.Context, log slog.Logger, auditor audit.Auditor, par
AdditionalFields: raw,
})
}

func useActiveVersion(opts schedule.TemplateScheduleOptions, ws database.Workspace) bool {
return opts.RequireActiveVersion || ws.AutomaticUpdates == database.AutomaticUpdatesAlways
}
15 changes: 12 additions & 3 deletions coderd/coderdtest/coderdtest.go
Original file line number Diff line number Diff line change
Expand Up @@ -915,7 +915,7 @@ func CreateWorkspace(t testing.TB, client *codersdk.Client, organization uuid.UU
}

// TransitionWorkspace is a convenience method for transitioning a workspace from one state to another.
func MustTransitionWorkspace(t testing.TB, client *codersdk.Client, workspaceID uuid.UUID, from, to database.WorkspaceTransition) codersdk.Workspace {
func MustTransitionWorkspace(t testing.TB, client *codersdk.Client, workspaceID uuid.UUID, from, to database.WorkspaceTransition, muts ...func(req *codersdk.CreateWorkspaceBuildRequest)) codersdk.Workspace {
t.Helper()
ctx := context.Background()
workspace, err := client.Workspace(ctx, workspaceID)
Expand All @@ -925,10 +925,19 @@ func MustTransitionWorkspace(t testing.TB, client *codersdk.Client, workspaceID
template, err := client.Template(ctx, workspace.TemplateID)
require.NoError(t, err, "fetch workspace template")

build, err := client.CreateWorkspaceBuild(ctx, workspace.ID, codersdk.CreateWorkspaceBuildRequest{
req := codersdk.CreateWorkspaceBuildRequest{
// TODO (JonA): I get this is for convenience but we should probably
// change this. Tripped me up why my test was passing when it shouldn't
// have.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't really understand this comment --- change how?

Copy link
Collaborator Author

@sreya sreya Oct 18, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Currently the behavior when calling MustTransitionWorkspace is to submit a workspace build with the template's active version as opposed to the the workspace's template version. That's kinda at odds with how it behaves in production.

TemplateVersionID: template.ActiveVersionID,
Transition: codersdk.WorkspaceTransition(to),
})
}

for _, mut := range muts {
mut(&req)
}

build, err := client.CreateWorkspaceBuild(ctx, workspace.ID, req)
require.NoError(t, err, "unexpected error transitioning workspace to %s", to)

_ = AwaitWorkspaceBuildJobCompleted(t, client, build.ID)
Expand Down
25 changes: 23 additions & 2 deletions coderd/database/dbauthz/dbauthz.go
Original file line number Diff line number Diff line change
Expand Up @@ -2200,7 +2200,7 @@ func (q *querier) InsertWorkspaceAppStats(ctx context.Context, arg database.Inse
func (q *querier) InsertWorkspaceBuild(ctx context.Context, arg database.InsertWorkspaceBuildParams) error {
w, err := q.db.GetWorkspaceByID(ctx, arg.WorkspaceID)
if err != nil {
return err
return xerrors.Errorf("get workspace by id: %w", err)
}

var action rbac.Action = rbac.ActionUpdate
Expand All @@ -2209,7 +2209,28 @@ func (q *querier) InsertWorkspaceBuild(ctx context.Context, arg database.InsertW
}

if err = q.authorizeContext(ctx, action, w.WorkspaceBuildRBAC(arg.Transition)); err != nil {
return err
return xerrors.Errorf("authorize context: %w", err)
}

// If we're starting a workspace we need to check the template.
if arg.Transition == database.WorkspaceTransitionStart {
// Fetch the template. We have to ensure that the request
// abides by the update policy of the templates.
t, err := q.db.GetTemplateByID(ctx, w.TemplateID)
if err != nil {
return xerrors.Errorf("get template by id: %w", err)
}

// If the template requires the active version we need to check if
// the user is a template admin. If they aren't and are attempting
// to use a non-active version then we must fail the request.
if t.RequireActiveVersion {
if arg.TemplateVersionID != t.ActiveVersionID {
if err = q.authorizeContext(ctx, rbac.ActionUpdate, t); err != nil {
return xerrors.Errorf("cannot use non-active version: %w", err)
}
}
}
}

return q.db.InsertWorkspaceBuild(ctx, arg)
Expand Down
5 changes: 4 additions & 1 deletion coderd/database/dbauthz/dbauthz_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1213,7 +1213,10 @@ func (s *MethodTestSuite) TestWorkspace() {
}).Asserts(rbac.ResourceWorkspace.WithOwner(u.ID.String()).InOrg(o.ID), rbac.ActionCreate)
}))
s.Run("Start/InsertWorkspaceBuild", s.Subtest(func(db database.Store, check *expects) {
w := dbgen.Workspace(s.T(), db, database.Workspace{})
t := dbgen.Template(s.T(), db, database.Template{})
w := dbgen.Workspace(s.T(), db, database.Workspace{
TemplateID: t.ID,
})
check.Args(database.InsertWorkspaceBuildParams{
WorkspaceID: w.ID,
Transition: database.WorkspaceTransitionStart,
Expand Down
1 change: 1 addition & 0 deletions coderd/database/dbfake/dbfake.go
Original file line number Diff line number Diff line change
Expand Up @@ -5729,6 +5729,7 @@ func (q *FakeQuerier) UpdateTemplateScheduleByID(_ context.Context, arg database
tpl.FailureTTL = arg.FailureTTL
tpl.TimeTilDormant = arg.TimeTilDormant
tpl.TimeTilDormantAutoDelete = arg.TimeTilDormantAutoDelete
tpl.RequireActiveVersion = arg.RequireActiveVersion
q.templates[idx] = tpl
return nil
}
Expand Down
4 changes: 3 additions & 1 deletion coderd/database/dump.sql

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

25 changes: 25 additions & 0 deletions coderd/database/migrations/000166_template_active_version.down.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
BEGIN;

-- Update the template_with_users view;
DROP VIEW template_with_users;

ALTER TABLE templates DROP COLUMN require_active_version;

-- If you need to update this view, put 'DROP VIEW template_with_users;' before this.
CREATE VIEW
template_with_users
AS
SELECT
templates.*,
coalesce(visible_users.avatar_url, '') AS created_by_avatar_url,
coalesce(visible_users.username, '') AS created_by_username
FROM
templates
LEFT JOIN
visible_users
ON
templates.created_by = visible_users.id;

COMMENT ON VIEW template_with_users IS 'Joins in the username + avatar url of the created by user.';

COMMIT;
23 changes: 23 additions & 0 deletions coderd/database/migrations/000166_template_active_version.up.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
BEGIN;

DROP VIEW template_with_users;

ALTER TABLE templates ADD COLUMN require_active_version boolean NOT NULL DEFAULT 'f';

CREATE VIEW
template_with_users
AS
SELECT
templates.*,
coalesce(visible_users.avatar_url, '') AS created_by_avatar_url,
coalesce(visible_users.username, '') AS created_by_username
FROM
templates
LEFT JOIN
visible_users
ON
templates.created_by = visible_users.id;

COMMENT ON VIEW template_with_users IS 'Joins in the username + avatar url of the created by user.';

COMMIT;
2 changes: 1 addition & 1 deletion coderd/database/modelmethods.go
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ func (w Workspace) ApplicationConnectRBAC() rbac.Object {
}

func (w Workspace) WorkspaceBuildRBAC(transition WorkspaceTransition) rbac.Object {
// If a workspace is locked it cannot be built.
// If a workspace is dormant it cannot be built.
// However we need to allow stopping a workspace by a caller once a workspace
// is locked (e.g. for autobuild). Additionally, if a user wants to delete
// a locked workspace, they shouldn't have to have it unlocked first.
Expand Down
1 change: 1 addition & 0 deletions coderd/database/modelqueries.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ func (q *sqlQuerier) GetAuthorizedTemplates(ctx context.Context, arg GetTemplate
&i.AutostopRequirementDaysOfWeek,
&i.AutostopRequirementWeeks,
&i.AutostartBlockDaysOfWeek,
&i.RequireActiveVersion,
&i.CreatedByAvatarURL,
&i.CreatedByUsername,
); err != nil {
Expand Down
2 changes: 2 additions & 0 deletions coderd/database/models.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

17 changes: 12 additions & 5 deletions coderd/database/queries.sql.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion coderd/database/queries/templates.sql
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,8 @@ SET
autostart_block_days_of_week = $9,
failure_ttl = $10,
time_til_dormant = $11,
time_til_dormant_autodelete = $12
time_til_dormant_autodelete = $12,
require_active_version = $13
WHERE
id = $1
;
Expand Down
5 changes: 5 additions & 0 deletions coderd/schedule/template.go
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,9 @@ type TemplateScheduleOptions struct {
// workspaces whose dormant_at field violates the new template time_til_dormant_autodelete
// threshold.
UpdateWorkspaceDormantAt bool `json:"update_workspace_dormant_at"`
// RequireActiveVersion requires that a starting a workspace uses the active
// version for a template.
RequireActiveVersion bool `json:"require_active_version"`
}

// TemplateScheduleStore provides an interface for retrieving template
Expand Down Expand Up @@ -200,6 +203,7 @@ func (*agplTemplateScheduleStore) Get(ctx context.Context, db database.Store, te
FailureTTL: 0,
TimeTilDormant: 0,
TimeTilDormantAutoDelete: 0,
RequireActiveVersion: false,
}, nil
}

Expand Down Expand Up @@ -229,6 +233,7 @@ func (*agplTemplateScheduleStore) Set(ctx context.Context, db database.Store, tp
FailureTTL: tpl.FailureTTL,
TimeTilDormant: tpl.TimeTilDormant,
TimeTilDormantAutoDelete: tpl.TimeTilDormantAutoDelete,
RequireActiveVersion: tpl.RequireActiveVersion,
})
if err != nil {
return xerrors.Errorf("update template schedule: %w", err)
Expand Down
8 changes: 6 additions & 2 deletions coderd/templates.go
Original file line number Diff line number Diff line change
Expand Up @@ -613,7 +613,8 @@ func (api *API) patchTemplateMeta(rw http.ResponseWriter, r *http.Request) {
req.AutostopRequirement.Weeks == scheduleOpts.AutostopRequirement.Weeks &&
req.FailureTTLMillis == time.Duration(template.FailureTTL).Milliseconds() &&
req.TimeTilDormantMillis == time.Duration(template.TimeTilDormant).Milliseconds() &&
req.TimeTilDormantAutoDeleteMillis == time.Duration(template.TimeTilDormantAutoDelete).Milliseconds() {
req.TimeTilDormantAutoDeleteMillis == time.Duration(template.TimeTilDormantAutoDelete).Milliseconds() &&
req.RequireActiveVersion == template.RequireActiveVersion {
return nil
}

Expand Down Expand Up @@ -657,7 +658,8 @@ func (api *API) patchTemplateMeta(rw http.ResponseWriter, r *http.Request) {
inactivityTTL != time.Duration(template.TimeTilDormant) ||
timeTilDormantAutoDelete != time.Duration(template.TimeTilDormantAutoDelete) ||
req.AllowUserAutostart != template.AllowUserAutostart ||
req.AllowUserAutostop != template.AllowUserAutostop {
req.AllowUserAutostop != template.AllowUserAutostop ||
req.RequireActiveVersion != template.RequireActiveVersion {
updated, err = (*api.TemplateScheduleStore.Load()).Set(ctx, tx, updated, schedule.TemplateScheduleOptions{
// Some of these values are enterprise-only, but the
// TemplateScheduleStore will handle avoiding setting them if
Expand All @@ -678,6 +680,7 @@ func (api *API) patchTemplateMeta(rw http.ResponseWriter, r *http.Request) {
TimeTilDormantAutoDelete: timeTilDormantAutoDelete,
UpdateWorkspaceLastUsedAt: req.UpdateWorkspaceLastUsedAt,
UpdateWorkspaceDormantAt: req.UpdateWorkspaceDormantAt,
RequireActiveVersion: req.RequireActiveVersion,
})
if err != nil {
return xerrors.Errorf("set template schedule options: %w", err)
Expand Down Expand Up @@ -823,5 +826,6 @@ func (api *API) convertTemplate(
AutostartRequirement: codersdk.TemplateAutostartRequirement{
DaysOfWeek: codersdk.BitmapToWeekdays(template.AutostartAllowedDays()),
},
RequireActiveVersion: template.RequireActiveVersion,
}
}
Loading