Skip to content

Commit 5ed0c7a

Browse files
authored
chore: improve dynamic parameter validation errors (#18501)
`BuildError` response from `wsbuilder` does not support rich errors from validation. Changed this to use the `Validations` block of codersdk responses to return all errors for invalid parameters.
1 parent f6e4ba6 commit 5ed0c7a

File tree

6 files changed

+168
-56
lines changed

6 files changed

+168
-56
lines changed

coderd/dynamicparameters/resolver.go

Lines changed: 65 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,45 @@ type parameterValue struct {
2626
Source parameterValueSource
2727
}
2828

29+
type ResolverError struct {
30+
Diagnostics hcl.Diagnostics
31+
Parameter map[string]hcl.Diagnostics
32+
}
33+
34+
// Error is a pretty bad format for these errors. Try to avoid using this.
35+
func (e *ResolverError) Error() string {
36+
var diags hcl.Diagnostics
37+
diags = diags.Extend(e.Diagnostics)
38+
for _, d := range e.Parameter {
39+
diags = diags.Extend(d)
40+
}
41+
42+
return diags.Error()
43+
}
44+
45+
func (e *ResolverError) HasError() bool {
46+
if e.Diagnostics.HasErrors() {
47+
return true
48+
}
49+
50+
for _, diags := range e.Parameter {
51+
if diags.HasErrors() {
52+
return true
53+
}
54+
}
55+
return false
56+
}
57+
58+
func (e *ResolverError) Extend(parameterName string, diag hcl.Diagnostics) {
59+
if e.Parameter == nil {
60+
e.Parameter = make(map[string]hcl.Diagnostics)
61+
}
62+
if _, ok := e.Parameter[parameterName]; !ok {
63+
e.Parameter[parameterName] = hcl.Diagnostics{}
64+
}
65+
e.Parameter[parameterName] = e.Parameter[parameterName].Extend(diag)
66+
}
67+
2968
//nolint:revive // firstbuild is a control flag to turn on immutable validation
3069
func ResolveParameters(
3170
ctx context.Context,
@@ -35,7 +74,7 @@ func ResolveParameters(
3574
previousValues []database.WorkspaceBuildParameter,
3675
buildValues []codersdk.WorkspaceBuildParameter,
3776
presetValues []database.TemplateVersionPresetParameter,
38-
) (map[string]string, hcl.Diagnostics) {
77+
) (map[string]string, error) {
3978
previousValuesMap := slice.ToMapFunc(previousValues, func(p database.WorkspaceBuildParameter) (string, string) {
4079
return p.Name, p.Value
4180
})
@@ -73,7 +112,10 @@ func ResolveParameters(
73112
// always be valid. If there is a case where this is not true, then this has to
74113
// be changed to allow the build to continue with a different set of values.
75114

76-
return nil, diags
115+
return nil, &ResolverError{
116+
Diagnostics: diags,
117+
Parameter: nil,
118+
}
77119
}
78120

79121
// The user's input now needs to be validated against the parameters.
@@ -113,12 +155,16 @@ func ResolveParameters(
113155
// are fatal. Additional validation for immutability has to be done manually.
114156
output, diags = renderer.Render(ctx, ownerID, values.ValuesMap())
115157
if diags.HasErrors() {
116-
return nil, diags
158+
return nil, &ResolverError{
159+
Diagnostics: diags,
160+
Parameter: nil,
161+
}
117162
}
118163

119164
// parameterNames is going to be used to remove any excess values that were left
120165
// around without a parameter.
121166
parameterNames := make(map[string]struct{}, len(output.Parameters))
167+
parameterError := &ResolverError{}
122168
for _, parameter := range output.Parameters {
123169
parameterNames[parameter.Name] = struct{}{}
124170

@@ -132,20 +178,22 @@ func ResolveParameters(
132178
}
133179

134180
// An immutable parameter was changed, which is not allowed.
135-
// Add the failed diagnostic to the output.
136-
diags = diags.Append(&hcl.Diagnostic{
137-
Severity: hcl.DiagError,
138-
Summary: "Immutable parameter changed",
139-
Detail: fmt.Sprintf("Parameter %q is not mutable, so it can't be updated after creating a workspace.", parameter.Name),
140-
Subject: src,
181+
// Add a failed diagnostic to the output.
182+
parameterError.Extend(parameter.Name, hcl.Diagnostics{
183+
&hcl.Diagnostic{
184+
Severity: hcl.DiagError,
185+
Summary: "Immutable parameter changed",
186+
Detail: fmt.Sprintf("Parameter %q is not mutable, so it can't be updated after creating a workspace.", parameter.Name),
187+
Subject: src,
188+
},
141189
})
142190
}
143191
}
144192

145193
// TODO: Fix the `hcl.Diagnostics(...)` type casting. It should not be needed.
146194
if hcl.Diagnostics(parameter.Diagnostics).HasErrors() {
147-
// All validation errors are raised here.
148-
diags = diags.Extend(hcl.Diagnostics(parameter.Diagnostics))
195+
// All validation errors are raised here for each parameter.
196+
parameterError.Extend(parameter.Name, hcl.Diagnostics(parameter.Diagnostics))
149197
}
150198

151199
// If the parameter has a value, but it was not set explicitly by the user at any
@@ -174,8 +222,13 @@ func ResolveParameters(
174222
}
175223
}
176224

225+
if parameterError.HasError() {
226+
// If there are any errors, return them.
227+
return nil, parameterError
228+
}
229+
177230
// Return the values to be saved for the build.
178-
return values.ValuesMap(), diags
231+
return values.ValuesMap(), nil
179232
}
180233

181234
type parameterValueMap map[string]parameterValue

coderd/httpapi/httperror/doc.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
// Package httperror handles formatting and writing some sentinel errors returned
2+
// within coder to the API.
3+
// This package exists outside httpapi to avoid some cyclic dependencies
4+
package httperror

coderd/httpapi/httperror/wsbuild.go

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
package httperror
2+
3+
import (
4+
"context"
5+
"errors"
6+
"fmt"
7+
"net/http"
8+
"sort"
9+
10+
"github.com/hashicorp/hcl/v2"
11+
12+
"github.com/coder/coder/v2/coderd/dynamicparameters"
13+
"github.com/coder/coder/v2/coderd/httpapi"
14+
"github.com/coder/coder/v2/coderd/wsbuilder"
15+
"github.com/coder/coder/v2/codersdk"
16+
)
17+
18+
func WriteWorkspaceBuildError(ctx context.Context, rw http.ResponseWriter, err error) {
19+
var buildErr wsbuilder.BuildError
20+
if errors.As(err, &buildErr) {
21+
if httpapi.IsUnauthorizedError(err) {
22+
buildErr.Status = http.StatusForbidden
23+
}
24+
25+
httpapi.Write(ctx, rw, buildErr.Status, codersdk.Response{
26+
Message: buildErr.Message,
27+
Detail: buildErr.Error(),
28+
})
29+
return
30+
}
31+
32+
var parameterErr *dynamicparameters.ResolverError
33+
if errors.As(err, &parameterErr) {
34+
resp := codersdk.Response{
35+
Message: "Unable to validate parameters",
36+
Validations: nil,
37+
}
38+
39+
// Sort the parameter names so that the order is consistent.
40+
sortedNames := make([]string, 0, len(parameterErr.Parameter))
41+
for name := range parameterErr.Parameter {
42+
sortedNames = append(sortedNames, name)
43+
}
44+
sort.Strings(sortedNames)
45+
46+
for _, name := range sortedNames {
47+
diag := parameterErr.Parameter[name]
48+
resp.Validations = append(resp.Validations, codersdk.ValidationError{
49+
Field: name,
50+
Detail: DiagnosticsErrorString(diag),
51+
})
52+
}
53+
54+
if parameterErr.Diagnostics.HasErrors() {
55+
resp.Detail = DiagnosticsErrorString(parameterErr.Diagnostics)
56+
}
57+
58+
httpapi.Write(ctx, rw, http.StatusBadRequest, resp)
59+
return
60+
}
61+
62+
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
63+
Message: "Internal error creating workspace build.",
64+
Detail: err.Error(),
65+
})
66+
}
67+
68+
func DiagnosticError(d *hcl.Diagnostic) string {
69+
return fmt.Sprintf("%s; %s", d.Summary, d.Detail)
70+
}
71+
72+
func DiagnosticsErrorString(d hcl.Diagnostics) string {
73+
count := len(d)
74+
switch {
75+
case count == 0:
76+
return "no diagnostics"
77+
case count == 1:
78+
return DiagnosticError(d[0])
79+
default:
80+
for _, d := range d {
81+
// Render the first error diag.
82+
// If there are warnings, do not priority them over errors.
83+
if d.Severity == hcl.DiagError {
84+
return fmt.Sprintf("%s, and %d other diagnostic(s)", DiagnosticError(d), count-1)
85+
}
86+
}
87+
88+
// All warnings? ok...
89+
return fmt.Sprintf("%s, and %d other diagnostic(s)", DiagnosticError(d[0]), count-1)
90+
}
91+
}

coderd/workspacebuilds.go

Lines changed: 2 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ import (
2727
"github.com/coder/coder/v2/coderd/database/dbtime"
2828
"github.com/coder/coder/v2/coderd/database/provisionerjobs"
2929
"github.com/coder/coder/v2/coderd/httpapi"
30+
"github.com/coder/coder/v2/coderd/httpapi/httperror"
3031
"github.com/coder/coder/v2/coderd/httpmw"
3132
"github.com/coder/coder/v2/coderd/notifications"
3233
"github.com/coder/coder/v2/coderd/provisionerdserver"
@@ -406,28 +407,8 @@ func (api *API) postWorkspaceBuilds(rw http.ResponseWriter, r *http.Request) {
406407
)
407408
return err
408409
}, nil)
409-
var buildErr wsbuilder.BuildError
410-
if xerrors.As(err, &buildErr) {
411-
var authErr dbauthz.NotAuthorizedError
412-
if xerrors.As(err, &authErr) {
413-
buildErr.Status = http.StatusForbidden
414-
}
415-
416-
if buildErr.Status == http.StatusInternalServerError {
417-
api.Logger.Error(ctx, "workspace build error", slog.Error(buildErr.Wrapped))
418-
}
419-
420-
httpapi.Write(ctx, rw, buildErr.Status, codersdk.Response{
421-
Message: buildErr.Message,
422-
Detail: buildErr.Error(),
423-
})
424-
return
425-
}
426410
if err != nil {
427-
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
428-
Message: "Error posting new build",
429-
Detail: err.Error(),
430-
})
411+
httperror.WriteWorkspaceBuildError(ctx, rw, err)
431412
return
432413
}
433414

coderd/workspaces.go

Lines changed: 3 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ import (
2727
"github.com/coder/coder/v2/coderd/database/dbtime"
2828
"github.com/coder/coder/v2/coderd/database/provisionerjobs"
2929
"github.com/coder/coder/v2/coderd/httpapi"
30+
"github.com/coder/coder/v2/coderd/httpapi/httperror"
3031
"github.com/coder/coder/v2/coderd/httpmw"
3132
"github.com/coder/coder/v2/coderd/notifications"
3233
"github.com/coder/coder/v2/coderd/prebuilds"
@@ -728,21 +729,11 @@ func createWorkspace(
728729
)
729730
return err
730731
}, nil)
731-
var bldErr wsbuilder.BuildError
732-
if xerrors.As(err, &bldErr) {
733-
httpapi.Write(ctx, rw, bldErr.Status, codersdk.Response{
734-
Message: bldErr.Message,
735-
Detail: bldErr.Error(),
736-
})
737-
return
738-
}
739732
if err != nil {
740-
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
741-
Message: "Internal error creating workspace.",
742-
Detail: err.Error(),
743-
})
733+
httperror.WriteWorkspaceBuildError(ctx, rw, err)
744734
return
745735
}
736+
746737
err = provisionerjobs.PostJob(api.Pubsub, *provisionerJob)
747738
if err != nil {
748739
// Client probably doesn't care about this error, so just log it.

coderd/wsbuilder/wsbuilder.go

Lines changed: 3 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -752,20 +752,12 @@ func (b *Builder) getDynamicParameters() (names, values []string, err error) {
752752
return nil, nil, BuildError{http.StatusInternalServerError, "failed to check if first build", err}
753753
}
754754

755-
buildValues, diagnostics := dynamicparameters.ResolveParameters(b.ctx, b.workspace.OwnerID, render, firstBuild,
755+
buildValues, err := dynamicparameters.ResolveParameters(b.ctx, b.workspace.OwnerID, render, firstBuild,
756756
lastBuildParameters,
757757
b.richParameterValues,
758758
presetParameterValues)
759-
760-
if diagnostics.HasErrors() {
761-
// TODO: Improve the error response. The response should include the validations for each failed
762-
// parameter. The response should also indicate it's a validation error or a more general form failure.
763-
// For now, any error is sufficient.
764-
return nil, nil, BuildError{
765-
Status: http.StatusBadRequest,
766-
Message: fmt.Sprintf("%d errors occurred while resolving parameters", len(diagnostics)),
767-
Wrapped: diagnostics,
768-
}
759+
if err != nil {
760+
return nil, nil, xerrors.Errorf("resolve parameters: %w", err)
769761
}
770762

771763
names = make([]string, 0, len(buildValues))

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy