Skip to content

feat: implement dynamic parameter validation #18482

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 1 commit into from
Jun 23, 2025
Merged
Show file tree
Hide file tree
Changes from all 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
2 changes: 1 addition & 1 deletion cli/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -1125,7 +1125,7 @@ func (r *RootCmd) Server(newAPI func(context.Context, *coderd.Options) (*coderd.
autobuildTicker := time.NewTicker(vals.AutobuildPollInterval.Value())
defer autobuildTicker.Stop()
autobuildExecutor := autobuild.NewExecutor(
ctx, options.Database, options.Pubsub, options.PrometheusRegistry, coderAPI.TemplateScheduleStore, &coderAPI.Auditor, coderAPI.AccessControlStore, logger, autobuildTicker.C, options.NotificationsEnqueuer, coderAPI.Experiments)
ctx, options.Database, options.Pubsub, coderAPI.FileCache, options.PrometheusRegistry, coderAPI.TemplateScheduleStore, &coderAPI.Auditor, coderAPI.AccessControlStore, logger, autobuildTicker.C, options.NotificationsEnqueuer, coderAPI.Experiments)
autobuildExecutor.Run()

jobReaperTicker := time.NewTicker(vals.JobReaperDetectorInterval.Value())
Expand Down
7 changes: 5 additions & 2 deletions coderd/autobuild/lifecycle_executor.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import (
"golang.org/x/xerrors"

"cdr.dev/slog"
"github.com/coder/coder/v2/coderd/files"

"github.com/coder/coder/v2/coderd/audit"
"github.com/coder/coder/v2/coderd/database"
Expand All @@ -35,6 +36,7 @@ type Executor struct {
ctx context.Context
db database.Store
ps pubsub.Pubsub
fileCache *files.Cache
Copy link
Member

Choose a reason for hiding this comment

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

TIL this is a thing!

templateScheduleStore *atomic.Pointer[schedule.TemplateScheduleStore]
accessControlStore *atomic.Pointer[dbauthz.AccessControlStore]
auditor *atomic.Pointer[audit.Auditor]
Expand All @@ -61,13 +63,14 @@ type Stats struct {
}

// New returns a new wsactions executor.
func NewExecutor(ctx context.Context, db database.Store, ps pubsub.Pubsub, reg prometheus.Registerer, tss *atomic.Pointer[schedule.TemplateScheduleStore], auditor *atomic.Pointer[audit.Auditor], acs *atomic.Pointer[dbauthz.AccessControlStore], log slog.Logger, tick <-chan time.Time, enqueuer notifications.Enqueuer, exp codersdk.Experiments) *Executor {
func NewExecutor(ctx context.Context, db database.Store, ps pubsub.Pubsub, fc *files.Cache, reg prometheus.Registerer, tss *atomic.Pointer[schedule.TemplateScheduleStore], auditor *atomic.Pointer[audit.Auditor], acs *atomic.Pointer[dbauthz.AccessControlStore], log slog.Logger, tick <-chan time.Time, enqueuer notifications.Enqueuer, exp codersdk.Experiments) *Executor {
factory := promauto.With(reg)
le := &Executor{
//nolint:gocritic // Autostart has a limited set of permissions.
ctx: dbauthz.AsAutostart(ctx),
db: db,
ps: ps,
fileCache: fc,
templateScheduleStore: tss,
tick: tick,
log: log.Named("autobuild"),
Expand Down Expand Up @@ -276,7 +279,7 @@ func (e *Executor) runOnce(t time.Time) Stats {
}
}

nextBuild, job, _, err = builder.Build(e.ctx, tx, nil, audit.WorkspaceBuildBaggage{IP: "127.0.0.1"})
nextBuild, job, _, err = builder.Build(e.ctx, tx, e.fileCache, nil, audit.WorkspaceBuildBaggage{IP: "127.0.0.1"})
if err != nil {
return xerrors.Errorf("build workspace with transition %q: %w", nextTransition, err)
}
Expand Down
2 changes: 2 additions & 0 deletions coderd/coderdtest/coderdtest.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ import (
"cdr.dev/slog"
"cdr.dev/slog/sloggers/sloghuman"
"cdr.dev/slog/sloggers/slogtest"
"github.com/coder/coder/v2/coderd/files"
"github.com/coder/quartz"

"github.com/coder/coder/v2/coderd"
Expand Down Expand Up @@ -359,6 +360,7 @@ func NewOptions(t testing.TB, options *Options) (func(http.Handler), context.Can
ctx,
options.Database,
options.Pubsub,
files.New(prometheus.NewRegistry(), options.Authorizer),
prometheus.NewRegistry(),
&templateScheduleStore,
&auditor,
Expand Down
4 changes: 2 additions & 2 deletions coderd/dynamicparameters/render.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ type loader struct {
// Prepare is the entrypoint for this package. It loads the necessary objects &
// files from the database and returns a Renderer that can be used to render the
// template version's parameters.
func Prepare(ctx context.Context, db database.Store, cache *files.Cache, versionID uuid.UUID, options ...func(r *loader)) (Renderer, error) {
func Prepare(ctx context.Context, db database.Store, cache files.FileAcquirer, versionID uuid.UUID, options ...func(r *loader)) (Renderer, error) {
l := &loader{
templateVersionID: versionID,
}
Expand Down Expand Up @@ -137,7 +137,7 @@ func (r *loader) loadData(ctx context.Context, db database.Store) error {
// Static parameter rendering is required to support older template versions that
// do not have the database state to support dynamic parameters. A constant
// warning will be displayed for these template versions.
func (r *loader) Renderer(ctx context.Context, db database.Store, cache *files.Cache) (Renderer, error) {
func (r *loader) Renderer(ctx context.Context, db database.Store, cache files.FileAcquirer) (Renderer, error) {
err := r.loadData(ctx, db)
if err != nil {
return nil, xerrors.Errorf("load data: %w", err)
Expand Down
35 changes: 35 additions & 0 deletions coderd/dynamicparameters/render_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package dynamicparameters_test

import (
"testing"

"github.com/stretchr/testify/require"

"github.com/coder/coder/v2/coderd/dynamicparameters"
)

func TestProvisionerVersionSupportsDynamicParameters(t *testing.T) {
Copy link
Member Author

Choose a reason for hiding this comment

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

This test is just moved

t.Parallel()

for v, dyn := range map[string]bool{
"": false,
"na": false,
"0.0": false,
"0.10": false,
"1.4": false,
"1.5": false,
"1.6": true,
"1.7": true,
"1.8": true,
"2.0": true,
"2.17": true,
"4.0": true,
} {
t.Run(v, func(t *testing.T) {
t.Parallel()

does := dynamicparameters.ProvisionerVersionSupportsDynamicParameters(v)
require.Equal(t, dyn, does)
})
}
}
189 changes: 189 additions & 0 deletions coderd/dynamicparameters/resolver.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
package dynamicparameters

import (
"context"
"fmt"

"github.com/google/uuid"
"github.com/hashicorp/hcl/v2"

"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/util/slice"
"github.com/coder/coder/v2/codersdk"
)

type parameterValueSource int

const (
sourceDefault parameterValueSource = iota
sourcePrevious
sourceBuild
sourcePreset
)

type parameterValue struct {
Value string
Source parameterValueSource
}

//nolint:revive // firstbuild is a control flag to turn on immutable validation
func ResolveParameters(
ctx context.Context,
ownerID uuid.UUID,
renderer Renderer,
firstBuild bool,
previousValues []database.WorkspaceBuildParameter,
buildValues []codersdk.WorkspaceBuildParameter,
presetValues []database.TemplateVersionPresetParameter,
) (map[string]string, hcl.Diagnostics) {
previousValuesMap := slice.ToMapFunc(previousValues, func(p database.WorkspaceBuildParameter) (string, string) {
return p.Name, p.Value
})

// Start with previous
values := parameterValueMap(slice.ToMapFunc(previousValues, func(p database.WorkspaceBuildParameter) (string, parameterValue) {
return p.Name, parameterValue{Source: sourcePrevious, Value: p.Value}
}))

// Add build values (overwrite previous values if they exist)
for _, buildValue := range buildValues {
values[buildValue.Name] = parameterValue{Source: sourceBuild, Value: buildValue.Value}
}

// Add preset values (overwrite previous and build values if they exist)
for _, preset := range presetValues {
values[preset.Name] = parameterValue{Source: sourcePreset, Value: preset.Value}
}

// originalValues is going to be used to detect if a user tried to change
// an immutable parameter after the first build.
originalValues := make(map[string]parameterValue, len(values))
for name, value := range values {
// Store the original values for later use.
originalValues[name] = value
}

// Render the parameters using the values that were supplied to the previous build.
//
// This is how the form should look to the user on their workspace settings page.
// This is the original form truth that our validations should initially be based on.
output, diags := renderer.Render(ctx, ownerID, values.ValuesMap())
if diags.HasErrors() {
// Top level diagnostics should break the build. Previous values (and new) should
// always be valid. If there is a case where this is not true, then this has to
// be changed to allow the build to continue with a different set of values.

return nil, diags
}

// The user's input now needs to be validated against the parameters.
// Mutability & Ephemeral parameters depend on sequential workspace builds.
//
// To enforce these, the user's input values are trimmed based on the
// mutability and ephemeral parameters defined in the template version.
for _, parameter := range output.Parameters {
// Ephemeral parameters should not be taken from the previous build.
// They must always be explicitly set in every build.
// So remove their values if they are sourced from the previous build.
if parameter.Ephemeral {
v := values[parameter.Name]
if v.Source == sourcePrevious {
delete(values, parameter.Name)
}
}

// Immutable parameters should also not be allowed to be changed from
// the previous build. Remove any values taken from the preset or
// new build params. This forces the value to be the same as it was before.
//
// We do this so the next form render uses the original immutable value.
if !firstBuild && !parameter.Mutable {
delete(values, parameter.Name)
prev, ok := previousValuesMap[parameter.Name]
if ok {
values[parameter.Name] = parameterValue{
Value: prev,
Source: sourcePrevious,
}
}
}
}

// This is the final set of values that will be used. Any errors at this stage
// are fatal. Additional validation for immutability has to be done manually.
output, diags = renderer.Render(ctx, ownerID, values.ValuesMap())
if diags.HasErrors() {
return nil, diags
}

// parameterNames is going to be used to remove any excess values that were left
// around without a parameter.
parameterNames := make(map[string]struct{}, len(output.Parameters))
for _, parameter := range output.Parameters {
parameterNames[parameter.Name] = struct{}{}

if !firstBuild && !parameter.Mutable {
// Immutable parameters should not be changed after the first build.
// They can match the original value though!
if parameter.Value.AsString() != originalValues[parameter.Name].Value {
var src *hcl.Range
if parameter.Source != nil {
src = &parameter.Source.HCLBlock().TypeRange
}

// An immutable parameter was changed, which is not allowed.
// Add the failed diagnostic to the output.
diags = diags.Append(&hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "Immutable parameter changed",
Detail: fmt.Sprintf("Parameter %q is not mutable, so it can't be updated after creating a workspace.", parameter.Name),
Subject: src,
Copy link
Member

Choose a reason for hiding this comment

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

Nice 👍

})
}
}

// TODO: Fix the `hcl.Diagnostics(...)` type casting. It should not be needed.
if hcl.Diagnostics(parameter.Diagnostics).HasErrors() {
// All validation errors are raised here.
diags = diags.Extend(hcl.Diagnostics(parameter.Diagnostics))
}
Comment on lines +145 to +149
Copy link
Member

Choose a reason for hiding this comment

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

follow-up issue?

Copy link
Member Author

Choose a reason for hiding this comment

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

I'll do you one better: #18501

Just trying to break out some of the diffs


// If the parameter has a value, but it was not set explicitly by the user at any
// build, then save the default value. An example where this is important is if a
// template has a default value of 'region = us-west-2', but the user never sets
// it. If the default value changes to 'region = us-east-1', we want to preserve
// the original value of 'us-west-2' for the existing workspaces.
//
// parameter.Value will be populated from the default at this point. So grab it
// from there.
if _, ok := values[parameter.Name]; !ok && parameter.Value.IsKnown() && parameter.Value.Valid() {
values[parameter.Name] = parameterValue{
Value: parameter.Value.AsString(),
Source: sourceDefault,
}
}
}

// Delete any values that do not belong to a parameter. This is to not save
// parameter values that have no effect. These leaky parameter values can cause
// problems in the future, as it makes it challenging to remove values from the
// database
for k := range values {
if _, ok := parameterNames[k]; !ok {
delete(values, k)
}
}

// Return the values to be saved for the build.
return values.ValuesMap(), diags
}

type parameterValueMap map[string]parameterValue

func (p parameterValueMap) ValuesMap() map[string]string {
values := make(map[string]string, len(p))
for name, paramValue := range p {
values[name] = paramValue.Value
}
return values
}
40 changes: 24 additions & 16 deletions coderd/parameters_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,10 +100,11 @@ func TestDynamicParametersWithTerraformValues(t *testing.T) {
require.Equal(t, -1, preview.ID)
require.Empty(t, preview.Diagnostics)

require.Len(t, preview.Parameters, 1)
require.Equal(t, "jetbrains_ide", preview.Parameters[0].Name)
require.True(t, preview.Parameters[0].Value.Valid)
require.Equal(t, "CL", preview.Parameters[0].Value.Value)
require.Len(t, preview.Parameters, 2)
coderdtest.AssertParameter(t, "jetbrains_ide", preview.Parameters).
Exists().Value("CL")
coderdtest.AssertParameter(t, "region", preview.Parameters).
Exists().Value("na")
})

// OldProvisioners use the static parameters in the dynamic param flow
Expand Down Expand Up @@ -241,10 +242,11 @@ func TestDynamicParametersWithTerraformValues(t *testing.T) {
require.Equal(t, -1, preview.ID)
require.Empty(t, preview.Diagnostics)

require.Len(t, preview.Parameters, 1)
require.Equal(t, "jetbrains_ide", preview.Parameters[0].Name)
require.True(t, preview.Parameters[0].Value.Valid)
require.Equal(t, "CL", preview.Parameters[0].Value.Value)
require.Len(t, preview.Parameters, 2)
coderdtest.AssertParameter(t, "jetbrains_ide", preview.Parameters).
Exists().Value("CL")
coderdtest.AssertParameter(t, "region", preview.Parameters).
Exists().Value("na")
_ = stream.Close(websocket.StatusGoingAway)

wrk := coderdtest.CreateWorkspace(t, setup.client, setup.template.ID, func(request *codersdk.CreateWorkspaceRequest) {
Expand All @@ -253,29 +255,35 @@ func TestDynamicParametersWithTerraformValues(t *testing.T) {
Name: preview.Parameters[0].Name,
Value: "GO",
},
{
Name: preview.Parameters[1].Name,
Value: "eu",
},
}
request.EnableDynamicParameters = true
})
coderdtest.AwaitWorkspaceBuildJobCompleted(t, setup.client, wrk.LatestBuild.ID)

params, err := setup.client.WorkspaceBuildParameters(ctx, wrk.LatestBuild.ID)
require.NoError(t, err)
require.Len(t, params, 1)
require.Equal(t, "jetbrains_ide", params[0].Name)
require.Equal(t, "GO", params[0].Value)
require.ElementsMatch(t, []codersdk.WorkspaceBuildParameter{
{Name: "jetbrains_ide", Value: "GO"}, {Name: "region", Value: "eu"},
}, params)

regionOptions := []string{"na", "af", "sa", "as"}

// A helper function to assert params
doTransition := func(t *testing.T, trans codersdk.WorkspaceTransition) {
t.Helper()

fooVal := coderdtest.RandomUsername(t)
regionVal := regionOptions[0]
regionOptions = regionOptions[1:] // Choose the next region on the next build

bld, err := setup.client.CreateWorkspaceBuild(ctx, wrk.ID, codersdk.CreateWorkspaceBuildRequest{
TemplateVersionID: setup.template.ActiveVersionID,
Transition: trans,
RichParameterValues: []codersdk.WorkspaceBuildParameter{
// No validation, so this should work as is.
// Overwrite the value on each transition
{Name: "foo", Value: fooVal},
{Name: "region", Value: regionVal},
},
EnableDynamicParameters: ptr.Ref(true),
})
Expand All @@ -286,7 +294,7 @@ func TestDynamicParametersWithTerraformValues(t *testing.T) {
require.NoError(t, err)
require.ElementsMatch(t, latestParams, []codersdk.WorkspaceBuildParameter{
{Name: "jetbrains_ide", Value: "GO"},
{Name: "foo", Value: fooVal},
{Name: "region", Value: regionVal},
})
}

Expand Down
Loading
Loading