/
handler.go
168 lines (150 loc) · 5.66 KB
/
handler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
// Copyright 2017 The LUCI Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cfgmodule
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"go.chromium.org/luci/common/errors"
"go.chromium.org/luci/common/logging"
"go.chromium.org/luci/common/proto/config"
"go.chromium.org/luci/config/validation"
"go.chromium.org/luci/server/router"
)
const (
// paths for handlers
metadataPath = "/api/config/v1/metadata"
validationPath = "/api/config/v1/validate"
// Taken from
// https://chromium.googlesource.com/infra/luci/luci-py/+/3efc60daef6bf6669f9211f63e799db47a0478c0/appengine/components/components/config/endpoint.py
metaDataFormatVersion = "1.0"
)
// InstallHandlers installs the metadata and validation handlers that use
// the given validation rules.
//
// It does not implement any authentication checks, thus the passed in
// router.MiddlewareChain should implement any necessary authentication checks.
//
// TODO(vadimsh): Move this to serverModule.Initialize once it is the only user.
func InstallHandlers(r *router.Router, base router.MiddlewareChain, rules *validation.RuleSet) {
r.GET(metadataPath, base, metadataRequestHandler(rules))
r.POST(validationPath, base, validationRequestHandler(rules))
}
func badRequestStatus(c context.Context, w http.ResponseWriter, msg string, err error) {
if err != nil {
logging.WithError(err).Warningf(c, "%s", msg)
} else {
logging.Warningf(c, "%s", msg)
}
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(msg))
}
func internalErrStatus(c context.Context, w http.ResponseWriter, msg string, err error) {
logging.WithError(err).Errorf(c, "%s", msg)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(msg))
}
// validationRequestHandler handles the validation request from luci-config and
// responds with the corresponding results.
func validationRequestHandler(rules *validation.RuleSet) router.Handler {
return func(ctx *router.Context) {
c, w, r := ctx.Context, ctx.Writer, ctx.Request
var reqBody config.ValidationRequestMessage
switch err := json.NewDecoder(r.Body).Decode(&reqBody); {
case err != nil:
badRequestStatus(c, w, "Validation: error decoding request body", err)
return
case reqBody.GetConfigSet() == "":
badRequestStatus(c, w, "Must specify the config_set of the file to validate", nil)
return
case reqBody.GetPath() == "":
badRequestStatus(c, w, "Must specify the path of the file to validate", nil)
return
}
vc := &validation.Context{Context: c}
vc.SetFile(reqBody.GetPath())
err := rules.ValidateConfig(vc, reqBody.GetConfigSet(), reqBody.GetPath(), reqBody.GetContent())
if err != nil {
internalErrStatus(c, w, "Validation: transient failure", err)
return
}
var errors errors.MultiError
verdict := vc.Finalize()
if verr, _ := verdict.(*validation.Error); verr != nil {
errors = verr.Errors
} else if verdict != nil {
errors = append(errors, verdict)
}
w.Header().Set("Content-Type", "application/json")
var msgList []*config.ValidationResponseMessage_Message
if len(errors) == 0 {
logging.Infof(c, "No validation errors")
} else {
var errorBuffer bytes.Buffer
for _, error := range errors {
// validation.Context supports just 2 severities now,
// but defensively default to ERROR level in unexpected cases.
msgSeverity := config.ValidationResponseMessage_ERROR
switch severity, ok := validation.SeverityTag.In(error); {
case !ok:
logging.Errorf(c, "unset validation.Severity in %s", error)
case severity == validation.Warning:
msgSeverity = config.ValidationResponseMessage_WARNING
case severity != validation.Blocking:
logging.Errorf(c, "unrecognized validation.Severity %d in %s", severity, error)
}
err := error.Error()
msgList = append(msgList, &config.ValidationResponseMessage_Message{
Severity: msgSeverity,
Text: err,
})
errorBuffer.WriteString("\n " + err)
}
logging.Warningf(c, "Validation errors%s", errorBuffer.String())
}
if err := json.NewEncoder(w).Encode(config.ValidationResponseMessage{Messages: msgList}); err != nil {
internalErrStatus(c, w, "Validation: failed to JSON encode output", err)
}
}
}
// metadataRequestHandler handles the metadata request from luci-config and
// responds with the necessary metadata defined by the given Validator.
func metadataRequestHandler(rules *validation.RuleSet) router.Handler {
return func(ctx *router.Context) {
c, w := ctx.Context, ctx.Writer
patterns, err := rules.ConfigPatterns(c)
if err != nil {
internalErrStatus(c, w, "Metadata: failed to collect the list of validation patterns", err)
return
}
meta := config.ServiceDynamicMetadata{
Version: metaDataFormatVersion,
Validation: &config.Validator{
Url: fmt.Sprintf("https://%s%s", ctx.Request.Host, validationPath),
},
}
for _, p := range patterns {
meta.Validation.Patterns = append(meta.Validation.Patterns, &config.ConfigPattern{
ConfigSet: p.ConfigSet.String(),
Path: p.Path.String(),
})
}
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(&meta); err != nil {
internalErrStatus(c, w, "Metadata: failed to JSON encode output", err)
}
}
}