forked from juju/juju
/
admin.go
232 lines (207 loc) · 6.33 KB
/
admin.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
// Copyright 2013 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package apiserver
import (
stderrors "errors"
"sync"
"time"
"github.com/juju/errors"
"github.com/juju/names"
"github.com/juju/utils"
"github.com/juju/juju/rpc"
"github.com/juju/juju/state"
"github.com/juju/juju/state/api/params"
"github.com/juju/juju/state/apiserver/common"
"github.com/juju/juju/state/presence"
)
func newStateServer(srv *Server, rpcConn *rpc.Conn, reqNotifier *requestNotifier, limiter utils.Limiter) *initialRoot {
r := &initialRoot{
srv: srv,
rpcConn: rpcConn,
}
r.admin = &srvAdmin{
root: r,
limiter: limiter,
validator: srv.validator,
reqNotifier: reqNotifier,
}
return r
}
// initialRoot implements the API that a client first sees
// when connecting to the API. We start serving a different
// API once the user has logged in.
type initialRoot struct {
srv *Server
rpcConn *rpc.Conn
admin *srvAdmin
}
// Admin returns an object that provides API access
// to methods that can be called even when not
// authenticated.
func (r *initialRoot) Admin(id string) (*srvAdmin, error) {
if id != "" {
// Safeguard id for possible future use.
return nil, common.ErrBadId
}
return r.admin, nil
}
// srvAdmin is the only object that unlogged-in
// clients can access. It holds any methods
// that are needed to log in.
type srvAdmin struct {
mu sync.Mutex
limiter utils.Limiter
validator LoginValidator
root *initialRoot
loggedIn bool
reqNotifier *requestNotifier
}
var errAlreadyLoggedIn = stderrors.New("already logged in")
// Login logs in with the provided credentials.
// All subsequent requests on the connection will
// act as the authenticated user.
func (a *srvAdmin) Login(c params.Creds) (params.LoginResult, error) {
a.mu.Lock()
defer a.mu.Unlock()
if a.loggedIn {
// This can only happen if Login is called concurrently.
return params.LoginResult{}, errAlreadyLoggedIn
}
// Use the login validation function, if one was specified.
if a.validator != nil {
if err := a.validator(c); err != nil {
return params.LoginResult{}, errors.Trace(err)
}
}
// Users are not rate limited, all other entities are
if kind, err := names.TagKind(c.AuthTag); err != nil || kind != names.UserTagKind {
if !a.limiter.Acquire() {
logger.Debugf("rate limiting, try again later")
return params.LoginResult{}, common.ErrTryAgain
}
defer a.limiter.Release()
}
entity, err := doCheckCreds(a.root.srv.state, c)
if err != nil {
return params.LoginResult{}, err
}
if a.reqNotifier != nil {
a.reqNotifier.login(entity.Tag())
}
// We have authenticated the user; now choose an appropriate API
// to serve to them.
// TODO: consider switching the new root based on who is logging in
newRoot := newSrvRoot(a.root, entity)
if err := a.startPingerIfAgent(newRoot, entity); err != nil {
return params.LoginResult{}, err
}
// Fetch the API server addresses from state.
hostPorts, err := a.root.srv.state.APIHostPorts()
if err != nil {
return params.LoginResult{}, err
}
logger.Debugf("hostPorts: %v", hostPorts)
environ, err := a.root.srv.state.Environment()
if err != nil {
return params.LoginResult{}, err
}
a.root.rpcConn.Serve(newRoot, serverError)
lastConnection := getAndUpdateLastConnectionForEntity(entity)
return params.LoginResult{
Servers: hostPorts,
EnvironTag: environ.Tag(),
LastConnection: lastConnection,
}, nil
}
var doCheckCreds = checkCreds
func checkCreds(st *state.State, c params.Creds) (taggedAuthenticator, error) {
entity0, err := st.FindEntity(c.AuthTag)
if err != nil && !errors.IsNotFound(err) {
return nil, err
}
// We return the same error when an entity
// does not exist as for a bad password, so that
// we don't allow unauthenticated users to find information
// about existing entities.
entity, ok := entity0.(taggedAuthenticator)
if !ok {
return nil, common.ErrBadCreds
}
if err != nil || !entity.PasswordValid(c.Password) {
return nil, common.ErrBadCreds
}
// Check if a machine agent is logging in with the right Nonce
if err := checkForValidMachineAgent(entity, c); err != nil {
return nil, err
}
return entity, nil
}
func getAndUpdateLastConnectionForEntity(entity taggedAuthenticator) *time.Time {
if user, ok := entity.(*state.User); ok {
result := user.LastConnection()
user.UpdateLastConnection()
if result.IsZero() {
return nil
}
return &result
}
return nil
}
func checkForValidMachineAgent(entity taggedAuthenticator, c params.Creds) error {
// If this is a machine agent connecting, we need to check the
// nonce matches, otherwise the wrong agent might be trying to
// connect.
if machine, ok := entity.(*state.Machine); ok {
if !machine.CheckProvisioned(c.Nonce) {
return state.NotProvisionedError(machine.Id())
}
}
return nil
}
// machinePinger wraps a presence.Pinger.
type machinePinger struct {
*presence.Pinger
}
// Stop implements Pinger.Stop() as Pinger.Kill(), needed at
// connection closing time to properly stop the wrapped pinger.
func (p *machinePinger) Stop() error {
if err := p.Pinger.Stop(); err != nil {
return err
}
return p.Pinger.Kill()
}
func (a *srvAdmin) startPingerIfAgent(newRoot *srvRoot, entity taggedAuthenticator) error {
setAgentAliver, ok := entity.(interface {
SetAgentAlive() (*presence.Pinger, error)
})
if !ok {
return nil
}
// A machine or unit agent has connected, so start a pinger to
// announce it's now alive, and set up the API pinger
// so that the connection will be terminated if a sufficient
// interval passes between pings.
pinger, err := setAgentAliver.SetAgentAlive()
if err != nil {
return err
}
newRoot.resources.Register(&machinePinger{pinger})
action := func() {
if err := newRoot.rpcConn.Close(); err != nil {
logger.Errorf("error closing the RPC connection: %v", err)
}
}
pingTimeout := newPingTimeout(action, maxClientPingInterval)
newRoot.resources.RegisterNamed("pingTimeout", pingTimeout)
return nil
}
// errRoot implements the API that a client first sees
// when connecting to the API. It exposes the same API as initialRoot, except
// it returns the requested error when the client makes any request.
type errRoot struct {
err error
}
// Admin conforms to the same API as initialRoot, but we'll always return (nil, err)
func (r *errRoot) Admin(id string) (*srvAdmin, error) {
return nil, r.err
}