-
Notifications
You must be signed in to change notification settings - Fork 0
/
httpcontext.go
254 lines (229 loc) · 8.05 KB
/
httpcontext.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
244
245
246
247
248
249
250
251
252
253
254
// Copyright 2013 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package apiserver
import (
"encoding/json"
"fmt"
"net/http"
"github.com/juju/errors"
"github.com/juju/names/v4"
"github.com/juju/juju/apiserver/common"
apiservererrors "github.com/juju/juju/apiserver/errors"
"github.com/juju/juju/apiserver/httpcontext"
"github.com/juju/juju/apiserver/stateauthenticator"
"github.com/juju/juju/core/permission"
"github.com/juju/juju/rpc/params"
"github.com/juju/juju/state"
)
// httpContext provides context for HTTP handlers.
type httpContext struct {
// srv holds the API server instance.
srv *Server
}
// stateForRequestUnauthenticated returns a state instance appropriate for
// using for the model implicit in the given request
// without checking any authentication information.
func (ctxt *httpContext) stateForRequestUnauthenticated(r *http.Request) (*state.PooledState, error) {
modelUUID := httpcontext.RequestModelUUID(r)
st, err := ctxt.srv.shared.statePool.Get(modelUUID)
if err != nil {
return nil, errors.Trace(err)
}
return st, nil
}
// statePool returns the StatePool for this controller.
func (ctxt *httpContext) statePool() *state.StatePool {
return ctxt.srv.shared.statePool
}
// stateForRequestAuthenticated returns a state instance appropriate for
// using for the model implicit in the given request.
// It also returns the authenticated entity.
func (ctxt *httpContext) stateForRequestAuthenticated(r *http.Request) (
resultSt *state.PooledState,
resultEntity state.Entity,
err error,
) {
authInfo, ok := httpcontext.RequestAuthInfo(r)
if !ok {
return nil, nil, apiservererrors.ErrPerm
}
st, err := ctxt.stateForRequestUnauthenticated(r)
if err != nil {
return nil, nil, errors.Trace(err)
}
defer func() {
// Here err is the named return arg.
if err != nil {
st.Release()
}
}()
return st, authInfo.Entity, nil
}
// checkPermissions verifies that given tag passes authentication check.
// For example, if only user tags are accepted, all other tags will be denied access.
func checkPermissions(tag names.Tag, acceptFunc common.GetAuthFunc) (bool, error) {
accept, err := acceptFunc()
if err != nil {
return false, errors.Trace(err)
}
if accept(tag) {
return true, nil
}
return false, errors.NotValidf("tag kind %v", tag.Kind())
}
// stateForMigration asserts that the incoming connection is from a user that
// has admin permissions on the controller model. The method also gets the
// model uuid for the model being migrated from a request header, and returns
// the state instance for that model.
func (ctxt *httpContext) stateForMigration(
r *http.Request,
requiredMode state.MigrationMode,
) (_ *state.PooledState, err error) {
modelUUID := r.Header.Get(params.MigrationModelHTTPHeader)
migrationSt, err := ctxt.srv.shared.statePool.Get(modelUUID)
if err != nil {
return nil, errors.Trace(err)
}
defer func() {
// Here err is the named return arg.
if err != nil {
migrationSt.Release()
}
}()
model, err := migrationSt.Model()
if errors.IsNotFound(err) {
return nil, fmt.Errorf("%w: %q", apiservererrors.UnknownModelError, modelUUID)
}
if err != nil {
return nil, errors.Trace(err)
}
if model.MigrationMode() != requiredMode {
return nil, errors.BadRequestf(
"model migration mode is %q instead of %q", model.MigrationMode(), requiredMode)
}
return migrationSt, nil
}
func (ctxt *httpContext) stateForMigrationImporting(r *http.Request) (*state.PooledState, error) {
return ctxt.stateForMigration(r, state.MigrationModeImporting)
}
// stateForRequestAuthenticatedUser is like stateAndEntityForRequestAuthenticatedUser
// but doesn't return the entity.
func (ctxt *httpContext) stateForRequestAuthenticatedUser(r *http.Request) (*state.PooledState, error) {
st, _, err := ctxt.stateAndEntityForRequestAuthenticatedUser(r)
return st, err
}
// stateAndEntityForRequestAuthenticatedUser is like stateForRequestAuthenticated
// except that it also verifies that the authenticated entity is a user.
func (ctxt *httpContext) stateAndEntityForRequestAuthenticatedUser(r *http.Request) (
*state.PooledState, state.Entity, error,
) {
return ctxt.stateForRequestAuthenticatedTag(r, names.UserTagKind)
}
// stateForRequestAuthenticatedAgent is like stateForRequestAuthenticated
// except that it also verifies that the authenticated entity is an agent.
func (ctxt *httpContext) stateForRequestAuthenticatedAgent(r *http.Request) (
*state.PooledState, state.Entity, error,
) {
return ctxt.stateForRequestAuthenticatedTag(r, stateauthenticator.AgentTags...)
}
// stateForRequestAuthenticatedTag checks that the request is
// correctly authenticated, and that the authenticated entity making
// the request is of one of the specified kinds.
func (ctxt *httpContext) stateForRequestAuthenticatedTag(r *http.Request, kinds ...string) (
*state.PooledState, state.Entity, error,
) {
funcs := make([]common.GetAuthFunc, len(kinds))
for i, kind := range kinds {
funcs[i] = common.AuthFuncForTagKind(kind)
}
st, entity, err := ctxt.stateForRequestAuthenticated(r)
if err != nil {
return nil, nil, errors.Trace(err)
}
if ok, err := checkPermissions(entity.Tag(), common.AuthAny(funcs...)); !ok {
st.Release()
return nil, nil, err
}
return st, entity, nil
}
// stop returns a channel which will be closed when a handler should
// exit.
func (ctxt *httpContext) stop() <-chan struct{} {
return ctxt.srv.tomb.Dying()
}
// sendStatusAndJSON sends an HTTP status code and
// a JSON-encoded response to a client.
func sendStatusAndJSON(w http.ResponseWriter, statusCode int, response interface{}) error {
body, err := json.Marshal(response)
if err != nil {
return errors.Errorf("cannot marshal JSON result %#v: %v", response, err)
}
if statusCode == http.StatusUnauthorized {
w.Header().Set("WWW-Authenticate", `Basic realm="juju"`)
}
w.Header().Set("Content-Type", params.ContentTypeJSON)
w.Header().Set("Content-Length", fmt.Sprint(len(body)))
w.WriteHeader(statusCode)
if _, err := w.Write(body); err != nil {
return errors.Annotate(err, "cannot write response")
}
return nil
}
// sendError sends a JSON-encoded error response
// for errors encountered during processing.
func sendError(w http.ResponseWriter, errToSend error) error {
paramsErr, statusCode := apiservererrors.ServerErrorAndStatus(errToSend)
logger.Debugf("sending error: %d %v", statusCode, paramsErr)
return errors.Trace(sendStatusAndJSON(w, statusCode, ¶ms.ErrorResult{
Error: paramsErr,
}))
}
type tagKindAuthorizer []string
// Authorize is part of the httpcontext.Authorizer interface.
func (a tagKindAuthorizer) Authorize(authInfo httpcontext.AuthInfo) error {
tagKind := authInfo.Entity.Tag().Kind()
for _, kind := range a {
if tagKind == kind {
return nil
}
}
return errors.NotValidf("tag kind %v", tagKind)
}
type controllerAuthorizer struct{}
// Authorize is part of the httpcontext.Authorizer interface.
func (controllerAuthorizer) Authorize(authInfo httpcontext.AuthInfo) error {
if authInfo.Controller {
return nil
}
return errors.Errorf("%s is not a controller", names.ReadableString(authInfo.Entity.Tag()))
}
type controllerAdminAuthorizer struct {
hasPermission hasPermissionFunc
}
// Authorize is part of the httpcontext.Authorizer interface.
func (a controllerAdminAuthorizer) Authorize(authInfo httpcontext.AuthInfo) error {
if authInfo.Token != nil {
access, err := permissionFromToken(authInfo.Token, names.ControllerTagKind)
if err != nil {
return errors.Trace(err)
}
if access != permission.SuperuserAccess {
return errors.Errorf("%s is not a controller admin", names.ReadableString(authInfo.Entity.Tag()))
}
}
if a.hasPermission == nil {
return errors.New("no permission checker configured")
}
userTag, ok := authInfo.Entity.Tag().(names.UserTag)
if !ok {
return errors.Errorf("%s is not a user", names.ReadableString(authInfo.Entity.Tag()))
}
isControllerAdmin, err := a.hasPermission(permission.SuperuserAccess, userTag)
if err != nil {
return errors.Trace(err)
}
if !isControllerAdmin {
return errors.Errorf("%s is not a controller admin", names.ReadableString(authInfo.Entity.Tag()))
}
return nil
}