/
handlers.go
243 lines (206 loc) · 7.33 KB
/
handlers.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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
// Copyright 2023 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package controlsocket
import (
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"github.com/gorilla/mux"
"github.com/juju/errors"
"github.com/juju/names/v5"
"github.com/juju/juju/core/permission"
"github.com/juju/juju/environs/bootstrap"
"github.com/juju/juju/state"
stateerrors "github.com/juju/juju/state/errors"
)
const (
// jujuMetricsUserPrefix defines the "namespace" in which this worker is
// allowed to create/remove users.
jujuMetricsUserPrefix = "juju-metrics-"
// userCreator is the listed "creator" of metrics users in state.
// This user CANNOT be a local user (it must have a domain), otherwise the
// model addUser code will complain about the user not existing.
userCreator = "controller@juju"
)
func (w *Worker) registerHandlers(r *mux.Router) {
r.HandleFunc("/metrics-users", w.handleAddMetricsUser).
Methods(http.MethodPost)
r.HandleFunc("/metrics-users/{username}", w.handleRemoveMetricsUser).
Methods(http.MethodDelete)
}
type addMetricsUserBody struct {
Username string `json:"username"`
Password string `json:"password"`
}
func (w *Worker) handleAddMetricsUser(resp http.ResponseWriter, req *http.Request) {
var parsedBody addMetricsUserBody
defer req.Body.Close()
err := json.NewDecoder(req.Body).Decode(&parsedBody)
if errors.Is(err, io.EOF) {
w.writeResponse(resp, http.StatusBadRequest, errorf("missing request body"))
return
} else if err != nil {
w.writeResponse(resp, http.StatusBadRequest, errorf("request body is not valid JSON: %v", err))
return
}
code, err := w.addMetricsUser(parsedBody.Username, parsedBody.Password)
if err != nil {
w.writeResponse(resp, code, errorf("%v", err))
return
}
w.writeResponse(resp, code, infof("created user %q", parsedBody.Username))
}
func (w *Worker) addMetricsUser(username, password string) (int, error) {
err := validateMetricsUsername(username)
if err != nil {
return http.StatusBadRequest, err
}
if password == "" {
return http.StatusBadRequest, errors.NotValidf("empty password")
}
user, err := w.config.State.AddUser(username, username, password, userCreator)
cleanup := true
// Error handling here is a bit subtle.
switch {
case errors.Is(err, errors.AlreadyExists):
// Retrieve existing user
user, err = w.config.State.User(names.NewUserTag(username))
if err != nil {
return http.StatusInternalServerError,
fmt.Errorf("retrieving existing user %q: %v", username, err)
}
// We want this operation to be idempotent, but at the same time, this
// worker shouldn't mess with users that have not been created by it.
// So ensure the user is identical to what we would have created, and
// otherwise error.
if user.CreatedBy() != userCreator {
return http.StatusConflict, errors.AlreadyExistsf("user %q (created by %q)", user.Name(), user.CreatedBy())
}
if !user.PasswordValid(password) {
return http.StatusConflict, errors.AlreadyExistsf("user %q", user.Name())
}
case err == nil:
// At this point, the operation is in a partially completed state - we've
// added the user, but haven't granted them the correct model permissions.
// If there is an error granting permissions, we should attempt to "rollback"
// and remove the user again.
defer func() {
if cleanup == false {
// Operation successful - nothing to clean up
return
}
err := w.config.State.RemoveUser(user.UserTag())
if err != nil {
// Best we can do here is log an error.
w.config.Logger.Warningf("add metrics user failed, but could not clean up user %q: %v",
username, err)
}
}()
default:
return http.StatusInternalServerError, errors.Annotatef(err, "failed to create user %q: %v", username, err)
}
// Give the new user permission to access the metrics endpoint.
var model model
model, err = w.config.State.Model()
if err != nil {
return http.StatusInternalServerError, errors.Annotatef(err, "retrieving current model: %v", err)
}
_, err = model.AddUser(state.UserAccessSpec{
User: user.UserTag(),
CreatedBy: names.NewUserTag(userCreator),
Access: permission.ReadAccess,
})
if err != nil && !errors.Is(err, errors.AlreadyExists) {
return http.StatusInternalServerError, errors.Annotatef(err, "adding user %q to model %q: %v", username, bootstrap.ControllerModelName, err)
}
cleanup = false
return http.StatusOK, nil
}
func (w *Worker) handleRemoveMetricsUser(resp http.ResponseWriter, req *http.Request) {
username := mux.Vars(req)["username"]
code, err := w.removeMetricsUser(username)
if err != nil {
w.writeResponse(resp, code, errorf("%v", err))
return
}
w.writeResponse(resp, code, infof("deleted user %q", username))
}
func (w *Worker) removeMetricsUser(username string) (int, error) {
err := validateMetricsUsername(username)
if err != nil {
return http.StatusBadRequest, err
}
userTag := names.NewUserTag(username)
// We shouldn't mess with users that weren't created by us.
user, err := w.config.State.User(userTag)
if errors.Is(err, errors.NotFound) || errors.Is(err, errors.UserNotFound) || stateerrors.IsDeletedUserError(err) {
// succeed as no-op
return http.StatusOK, nil
} else if err != nil {
return http.StatusInternalServerError, err
}
if user.CreatedBy() != userCreator {
return http.StatusForbidden, errors.Forbiddenf("cannot remove user %q created by %q", user.Name(), user.CreatedBy())
}
err = w.config.State.RemoveUser(userTag)
// Any "not found" errors should have been caught above, so fail here.
if err != nil {
return http.StatusInternalServerError, err
}
return http.StatusOK, nil
}
func validateMetricsUsername(username string) error {
if username == "" {
return errors.BadRequestf("missing username")
}
if !names.IsValidUserName(username) {
return errors.NotValidf("username %q", username)
}
if !strings.HasPrefix(username, jujuMetricsUserPrefix) {
return errors.BadRequestf("metrics username %q should have prefix %q", username, jujuMetricsUserPrefix)
}
return nil
}
func (w *Worker) writeResponse(resp http.ResponseWriter, statusCode int, body any) {
w.config.Logger.Debugf("operation finished with HTTP status %v", statusCode)
resp.Header().Set("Content-Type", "application/json")
message, err := json.Marshal(body)
if err != nil {
w.config.Logger.Errorf("error marshalling response body to JSON: %v", err)
w.config.Logger.Errorf("response body was %#v", body)
// Mark this as an "internal server error"
statusCode = http.StatusInternalServerError
// Just write an empty response
message = []byte("{}")
}
resp.WriteHeader(statusCode)
w.config.Logger.Tracef("returning response %q", message)
_, err = resp.Write(message)
if err != nil {
w.config.Logger.Warningf("error writing HTTP response: %v", err)
}
}
// infof returns an informational response body that can be marshalled into
// JSON (in the case of a successful operation). It has the form
//
// {"message": <provided info message>}
func infof(format string, args ...any) any {
return struct {
Message string `json:"message"`
}{
Message: fmt.Sprintf(format, args...),
}
}
// errorf returns an error response body that can be marshalled into JSON (in
// the case of a failed operation). It has the form
//
// {"error": <provided error message>}
func errorf(format string, args ...any) any {
return struct {
Error string `json:"error"`
}{
Error: fmt.Sprintf(format, args...),
}
}