Skip to content

feat: implement deprecated flag for templates to prevent new workspaces #10745

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 16 commits into from
Nov 20, 2023
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
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
18 changes: 18 additions & 0 deletions cli/templateedit.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
)

func (r *RootCmd) templateEdit() *clibase.Cmd {
const deprecatedFlagName = "deprecated"
var (
name string
displayName string
Expand All @@ -32,6 +33,7 @@ func (r *RootCmd) templateEdit() *clibase.Cmd {
allowUserAutostart bool
allowUserAutostop bool
requireActiveVersion bool
deprecatedMessage string
)
client := new(codersdk.Client)

Expand Down Expand Up @@ -118,6 +120,15 @@ func (r *RootCmd) templateEdit() *clibase.Cmd {
autostopRequirementDaysOfWeek = []string{}
}

// Only pass explicitly set deprecated values since the empty string
// removes the deprecated message. By default if we pass a nil,
// there is no change to this field.
var deprecated *string
opt := inv.Command.Options.ByName(deprecatedFlagName)
if !(opt.ValueSource == "" || opt.ValueSource == clibase.ValueSourceDefault) {
deprecated = &deprecatedMessage
}

// NOTE: coderd will ignore empty fields.
req := codersdk.UpdateTemplateMeta{
Name: name,
Expand All @@ -139,6 +150,7 @@ func (r *RootCmd) templateEdit() *clibase.Cmd {
AllowUserAutostart: allowUserAutostart,
AllowUserAutostop: allowUserAutostop,
RequireActiveVersion: requireActiveVersion,
DeprecatedMessage: deprecated,
}

_, err = client.UpdateTemplateMeta(inv.Context(), template.ID, req)
Expand Down Expand Up @@ -166,6 +178,12 @@ func (r *RootCmd) templateEdit() *clibase.Cmd {
Description: "Edit the template description.",
Value: clibase.StringOf(&description),
},
{
Name: deprecatedFlagName,
Flag: "deprecated",
Description: "Sets the template as deprecated. Must be a message explaining why the template is deprecated.",
Value: clibase.StringOf(&deprecatedMessage),
},
{
Flag: "icon",
Description: "Edit the template icon path.",
Expand Down
4 changes: 4 additions & 0 deletions cli/testdata/coder_templates_edit_--help.golden
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,10 @@ OPTIONS:
from this template default to this value. Maps to "Default autostop"
in the UI.

--deprecated string
Sets the template as deprecated. Must be a message explaining why the
template is deprecated.

--description string
Edit the template description.

Expand Down
12 changes: 11 additions & 1 deletion coderd/database/dbauthz/accesscontrol.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,11 @@ type AccessControlStore interface {

type TemplateAccessControl struct {
RequireActiveVersion bool
Deprecated string
}

func (t TemplateAccessControl) IsDeprecated() bool {
return t.Deprecated != ""
}

// AGPLTemplateAccessControlStore always returns the defaults for access control
Expand All @@ -26,9 +31,14 @@ type AGPLTemplateAccessControlStore struct{}

var _ AccessControlStore = AGPLTemplateAccessControlStore{}

func (AGPLTemplateAccessControlStore) GetTemplateAccessControl(database.Template) TemplateAccessControl {
func (AGPLTemplateAccessControlStore) GetTemplateAccessControl(t database.Template) TemplateAccessControl {
return TemplateAccessControl{
RequireActiveVersion: false,
// AGPL cannot set deprecated templates, but it should return
// existing deprecated templates. This is erroring on the safe side
// if a license expires, we should not allow deprecated templates
// to be used for new workspaces.
Deprecated: t.Deprecated,
}
}

Expand Down
1 change: 1 addition & 0 deletions coderd/database/dbmem/dbmem.go
Original file line number Diff line number Diff line change
Expand Up @@ -5905,6 +5905,7 @@ func (q *FakeQuerier) UpdateTemplateAccessControlByID(_ context.Context, arg dat
continue
}
q.templates[idx].RequireActiveVersion = arg.RequireActiveVersion
q.templates[idx].Deprecated = arg.Deprecated
return nil
}

Expand Down
6 changes: 5 additions & 1 deletion coderd/database/dump.sql

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

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

DROP VIEW template_with_users;

ALTER TABLE templates
DROP COLUMN deprecated;

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;
28 changes: 28 additions & 0 deletions coderd/database/migrations/000169_deprecate_template.up.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
BEGIN;

-- The view will be rebuilt with the new column
DROP VIEW template_with_users;

ALTER TABLE templates
ADD COLUMN deprecated TEXT NOT NULL DEFAULT '';

COMMENT ON COLUMN templates.deprecated IS 'If set to a non empty string, the template will no longer be able to be used. The message will be displayed to the user.';

-- Restore the old version of the template_with_users view.
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;
3 changes: 3 additions & 0 deletions coderd/database/models.go

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

18 changes: 12 additions & 6 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 @@ -174,7 +174,8 @@ FROM build_times
UPDATE
templates
SET
require_active_version = $2
require_active_version = $2,
deprecated = $3
WHERE
id = $1
;
17 changes: 14 additions & 3 deletions coderd/templates.go
Original file line number Diff line number Diff line change
Expand Up @@ -584,6 +584,11 @@ func (api *API) patchTemplateMeta(rw http.ResponseWriter, r *http.Request) {
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)})
}
// Defaults to the existing.
deprecatedMessage := template.Deprecated
if req.DeprecatedMessage != nil {
deprecatedMessage = *req.DeprecatedMessage
}

// The minimum valid value for a dormant TTL is 1 minute. This is
// to ensure an uninformed user does not send an unintentionally
Expand Down Expand Up @@ -624,7 +629,8 @@ func (api *API) patchTemplateMeta(rw http.ResponseWriter, r *http.Request) {
req.FailureTTLMillis == time.Duration(template.FailureTTL).Milliseconds() &&
req.TimeTilDormantMillis == time.Duration(template.TimeTilDormant).Milliseconds() &&
req.TimeTilDormantAutoDeleteMillis == time.Duration(template.TimeTilDormantAutoDelete).Milliseconds() &&
req.RequireActiveVersion == template.RequireActiveVersion {
req.RequireActiveVersion == template.RequireActiveVersion &&
(deprecatedMessage == template.Deprecated) {
return nil
}

Expand All @@ -648,9 +654,10 @@ func (api *API) patchTemplateMeta(rw http.ResponseWriter, r *http.Request) {
return xerrors.Errorf("update template metadata: %w", err)
}

if template.RequireActiveVersion != req.RequireActiveVersion {
if template.RequireActiveVersion != req.RequireActiveVersion || deprecatedMessage != template.Deprecated {
err = (*api.AccessControlStore.Load()).SetTemplateAccessControl(ctx, tx, template.ID, dbauthz.TemplateAccessControl{
RequireActiveVersion: req.RequireActiveVersion,
Deprecated: deprecatedMessage,
})
if err != nil {
return xerrors.Errorf("set template access control: %w", err)
Expand Down Expand Up @@ -804,6 +811,7 @@ func (api *API) convertTemplates(templates []database.Template) []codersdk.Templ
func (api *API) convertTemplate(
template database.Template,
) codersdk.Template {
templateAccessControl := (*(api.Options.AccessControlStore.Load())).GetTemplateAccessControl(template)
activeCount, _ := api.metricsCache.TemplateUniqueUsers(template.ID)

buildTimeStats := api.metricsCache.TemplateBuildTimeStats(template.ID)
Expand Down Expand Up @@ -843,6 +851,9 @@ func (api *API) convertTemplate(
AutostartRequirement: codersdk.TemplateAutostartRequirement{
DaysOfWeek: codersdk.BitmapToWeekdays(template.AutostartAllowedDays()),
},
RequireActiveVersion: template.RequireActiveVersion,
// These values depend on entitlements and come from the templateAccessControl
RequireActiveVersion: templateAccessControl.RequireActiveVersion,
Deprecated: templateAccessControl.IsDeprecated(),
DeprecatedMessage: templateAccessControl.Deprecated,
}
}
23 changes: 23 additions & 0 deletions coderd/templates_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -516,6 +516,29 @@ func TestPatchTemplateMeta(t *testing.T) {
assert.Equal(t, database.AuditActionWrite, auditor.AuditLogs()[4].Action)
})

t.Run("AGPL_Deprecated", func(t *testing.T) {
t.Parallel()

client := coderdtest.New(t, &coderdtest.Options{IncludeProvisionerDaemon: false})
user := coderdtest.CreateFirstUser(t, client)
version := coderdtest.CreateTemplateVersion(t, client, user.OrganizationID, nil)
template := coderdtest.CreateTemplate(t, client, user.OrganizationID, version.ID)

req := codersdk.UpdateTemplateMeta{
DeprecatedMessage: ptr.Ref("APGL cannot deprecate"),
}

ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitLong)
defer cancel()

updated, err := client.UpdateTemplateMeta(ctx, template.ID, req)
require.NoError(t, err)
assert.Greater(t, updated.UpdatedAt, template.UpdatedAt)
// AGPL cannot deprecate, expect no change
assert.False(t, updated.Deprecated)
assert.Empty(t, updated.DeprecatedMessage)
})

t.Run("NoDefaultTTL", func(t *testing.T) {
t.Parallel()

Expand Down
11 changes: 11 additions & 0 deletions coderd/workspaces.go
Original file line number Diff line number Diff line change
Expand Up @@ -394,6 +394,17 @@ func (api *API) postWorkspacesByOrganization(rw http.ResponseWriter, r *http.Req
return
}

templateAccessControl := (*(api.AccessControlStore.Load())).GetTemplateAccessControl(template)
if templateAccessControl.IsDeprecated() {
httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{
Message: fmt.Sprintf("Template %q has been deprecated, and cannot be used to create a new workspace.", template.Name),
// Pass the deprecated message to the user.
Detail: templateAccessControl.Deprecated,
Validations: nil,
})
return
}

if organization.ID != template.OrganizationID {
httpapi.Write(ctx, rw, http.StatusForbidden, codersdk.Response{
Message: fmt.Sprintf("Template is not in organization %q.", organization.Name),
Expand Down
Loading