Debian Codegraph @

api/v0/auth/sasl/authenticatee.go

raw symbols SCIP
1 package sasl
2
3 import (
4 "errors"
5 "fmt"
6 "sync/atomic"
7
8 "github.com/gogo/protobuf/proto"
9 log "github.com/golang/glog"
10 "github.com/mesos/mesos-go/api/v0/auth"
11 "github.com/mesos/mesos-go/api/v0/auth/callback"
12 "github.com/mesos/mesos-go/api/v0/auth/sasl/mech"
13 mesos "github.com/mesos/mesos-go/api/v0/mesosproto"
14 "github.com/mesos/mesos-go/api/v0/mesosutil/process"
15 "github.com/mesos/mesos-go/api/v0/messenger"
16 "github.com/mesos/mesos-go/api/v0/upid"
17 "golang.org/x/net/context"
18 )
19
20 var (
21 UnexpectedAuthenticationMechanisms = errors.New("Unexpected authentication 'mechanisms' received")
22 UnexpectedAuthenticationStep = errors.New("Unexpected authentication 'step' received")
23 UnexpectedAuthenticationCompleted = errors.New("Unexpected authentication 'completed' received")
24 UnexpectedAuthenticatorPid = errors.New("Unexpected authentator pid") // authenticator pid changed mid-process
25 UnsupportedMechanism = errors.New("failed to identify a compatible mechanism")
26 )
27
28 type statusType int32
29
30 const (
31 statusReady statusType = iota
32 statusStarting
33 statusStepping
34 _statusTerminal // meta status, should never be assigned: all status types following are "terminal"
35 statusCompleted
36 statusFailed
37 statusError
38 statusDiscarded
39
40 // this login provider name is automatically registered with the auth package; see init()
41 ProviderName = "SASL"
42 )
43
44 type authenticateeProcess struct {
45 transport messenger.Messenger
46 client upid.UPID
47 status statusType
48 done chan struct{}
49 err error
50 mech mech.Interface
51 stepFn mech.StepFunc
52 from *upid.UPID
53 handler callback.Handler
54 }
55
56 type authenticateeConfig struct {
57 client upid.UPID // pid of the client we're attempting to authenticate
58 handler callback.Handler
59 transport messenger.Messenger // mesos communications transport
60 }
61
62 type transportFactory interface {
63 makeTransport() messenger.Messenger
64 }
65
66 type transportFactoryFunc func() messenger.Messenger
67
68 func (f transportFactoryFunc) makeTransport() messenger.Messenger {
69 return f()
70 }
71
72 func init() {
73 factory := func(ctx context.Context) transportFactoryFunc {
74 return transportFactoryFunc(func() messenger.Messenger {
75 parent := auth.ParentUPID(ctx)
76 if parent == nil {
77 log.Fatal("expected to have a parent UPID in context")
78 }
79
80 process := process.New("sasl_authenticatee")
81 tpid := upid.UPID{
82 ID: process.Label(),
83 Host: parent.Host,
84 Port: BindingPortFrom(ctx),
85 }
86
87 return messenger.NewHttpWithBindingAddress(tpid, BindingAddressFrom(ctx))
88 })
89 }
90 delegate := auth.AuthenticateeFunc(func(ctx context.Context, handler callback.Handler) error {
91 if impl, err := makeAuthenticatee(handler, factory(ctx)); err != nil {
92 return err
93 } else {
94 return impl.Authenticate(ctx, handler)
95 }
96 })
97 if err := auth.RegisterAuthenticateeProvider(ProviderName, delegate); err != nil {
98 log.Error(err)
99 }
100 }
101
102 func (s *statusType) get() statusType {
103 return statusType(atomic.LoadInt32((*int32)(s)))
104 }
105
106 func (s *statusType) swap(old, new statusType) bool {
107 return old != new && atomic.CompareAndSwapInt32((*int32)(s), int32(old), int32(new))
108 }
109
110 // build a new authenticatee implementation using the given callbacks and a new transport instance
111 func makeAuthenticatee(handler callback.Handler, factory transportFactory) (auth.Authenticatee, error) {
112
113 ip := callback.NewInterprocess()
114 if err := handler.Handle(ip); err != nil {
115 return nil, err
116 }
117 config := &authenticateeConfig{
118 client: ip.Client(),
119 handler: handler,
120 transport: factory.makeTransport(),
121 }
122 return auth.AuthenticateeFunc(func(ctx context.Context, handler callback.Handler) error {
123 ctx, auth := newAuthenticatee(ctx, config)
124 auth.authenticate(ctx, ip.Server())
125
126 select {
127 case <-ctx.Done():
128 return auth.discard(ctx)
129 case <-auth.done:
130 return auth.err
131 }
132 }), nil
133 }
134
135 // Terminate the authentication process upon context cancellation;
136 // only to be called if/when ctx.Done() has been signalled.
137 func (self *authenticateeProcess) discard(ctx context.Context) error {
138 err := ctx.Err()
139 status := statusFrom(ctx)
140 for ; status < _statusTerminal; status = (&self.status).get() {
141 if self.terminate(status, statusDiscarded, err) {
142 break
143 }
144 }
145 return err
146 }
147
148 func newAuthenticatee(ctx context.Context, config *authenticateeConfig) (context.Context, *authenticateeProcess) {
149 initialStatus := statusReady
150 proc := &authenticateeProcess{
151 transport: config.transport,
152 client: config.client,
153 handler: config.handler,
154 status: initialStatus,
155 done: make(chan struct{}),
156 }
157 ctx = withStatus(ctx, initialStatus)
158 err := proc.installHandlers(ctx)
159 if err == nil {
160 err = proc.startTransport()
161 }
162 if err != nil {
163 proc.terminate(initialStatus, statusError, err)
164 }
165 return ctx, proc
166 }
167
168 func (self *authenticateeProcess) startTransport() error {
169 if err := self.transport.Start(); err != nil {
170 return err
171 } else {
172 go func() {
173 // stop the authentication transport upon termination of the
174 // authenticator process
175 select {
176 case <-self.done:
177 log.V(2).Infof("stopping authenticator transport: %v", self.transport.UPID())
178 self.transport.Stop()
179 }
180 }()
181 }
182 return nil
183 }
184
185 // returns true when handlers are installed without error, otherwise terminates the
186 // authentication process.
187 func (self *authenticateeProcess) installHandlers(ctx context.Context) error {
188
189 type handlerFn func(ctx context.Context, from *upid.UPID, pbMsg proto.Message)
190
191 withContext := func(f handlerFn) messenger.MessageHandler {
192 return func(from *upid.UPID, m proto.Message) {
193 status := (&self.status).get()
194 if self.from != nil && !self.from.Equal(from) {
195 self.terminate(status, statusError, UnexpectedAuthenticatorPid)
196 } else {
197 f(withStatus(ctx, status), from, m)
198 }
199 }
200 }
201
202 // Anticipate mechanisms and steps from the server
203 handlers := []struct {
204 f handlerFn
205 m proto.Message
206 }{
207 {self.mechanisms, &mesos.AuthenticationMechanismsMessage{}},
208 {self.step, &mesos.AuthenticationStepMessage{}},
209 {self.completed, &mesos.AuthenticationCompletedMessage{}},
210 {self.failed, &mesos.AuthenticationFailedMessage{}},
211 {self.errored, &mesos.AuthenticationErrorMessage{}},
212 }
213 for _, h := range handlers {
214 if err := self.transport.Install(withContext(h.f), h.m); err != nil {
215 return err
216 }
217 }
218 return nil
219 }
220
221 // return true if the authentication status was updated (if true, self.done will have been closed)
222 func (self *authenticateeProcess) terminate(old, new statusType, err error) bool {
223 if (&self.status).swap(old, new) {
224 self.err = err
225 if self.mech != nil {
226 self.mech.Discard()
227 }
228 close(self.done)
229 return true
230 }
231 return false
232 }
233
234 func (self *authenticateeProcess) authenticate(ctx context.Context, pid upid.UPID) {
235 status := statusFrom(ctx)
236 if status != statusReady {
237 return
238 }
239 message := &mesos.AuthenticateMessage{
240 Pid: proto.String(self.client.String()),
241 }
242 if err := self.transport.Send(ctx, &pid, message); err != nil {
243 self.terminate(status, statusError, err)
244 } else {
245 (&self.status).swap(status, statusStarting)
246 }
247 }
248
249 func (self *authenticateeProcess) mechanisms(ctx context.Context, from *upid.UPID, pbMsg proto.Message) {
250 status := statusFrom(ctx)
251 if status != statusStarting {
252 self.terminate(status, statusError, UnexpectedAuthenticationMechanisms)
253 return
254 }
255
256 msg, ok := pbMsg.(*mesos.AuthenticationMechanismsMessage)
257 if !ok {
258 self.terminate(status, statusError, fmt.Errorf("Expected AuthenticationMechanismsMessage, not %T", pbMsg))
259 return
260 }
261
262 mechanisms := msg.GetMechanisms()
263 log.Infof("Received SASL authentication mechanisms: %v", mechanisms)
264
265 selectedMech, factory := mech.SelectSupported(mechanisms)
266 if selectedMech == "" {
267 self.terminate(status, statusError, UnsupportedMechanism)
268 return
269 }
270
271 if m, f, err := factory(self.handler); err != nil {
272 self.terminate(status, statusError, err)
273 return
274 } else {
275 self.mech = m
276 self.stepFn = f
277 self.from = from
278 }
279
280 // execute initialization step...
281 nextf, data, err := self.stepFn(self.mech, nil)
282 if err != nil {
283 self.terminate(status, statusError, err)
284 return
285 } else {
286 self.stepFn = nextf
287 }
288
289 message := &mesos.AuthenticationStartMessage{
290 Mechanism: proto.String(selectedMech),
291 Data: data, // may be nil, depends on init step
292 }
293
294 if err := self.transport.Send(ctx, from, message); err != nil {
295 self.terminate(status, statusError, err)
296 } else {
297 (&self.status).swap(status, statusStepping)
298 }
299 }
300
301 func (self *authenticateeProcess) step(ctx context.Context, from *upid.UPID, pbMsg proto.Message) {
302 status := statusFrom(ctx)
303 if status != statusStepping {
304 self.terminate(status, statusError, UnexpectedAuthenticationStep)
305 return
306 }
307
308 log.Info("Received SASL authentication step")
309
310 msg, ok := pbMsg.(*mesos.AuthenticationStepMessage)
311 if !ok {
312 self.terminate(status, statusError, fmt.Errorf("Expected AuthenticationStepMessage, not %T", pbMsg))
313 return
314 }
315
316 input := msg.GetData()
317 fn, output, err := self.stepFn(self.mech, input)
318
319 if err != nil {
320 self.terminate(status, statusError, fmt.Errorf("failed to perform authentication step: %v", err))
321 return
322 }
323 self.stepFn = fn
324
325 // We don't start the client with SASL_SUCCESS_DATA so we may
326 // need to send one more "empty" message to the server.
327 message := &mesos.AuthenticationStepMessage{}
328 if len(output) > 0 {
329 message.Data = output
330 }
331 if err := self.transport.Send(ctx, from, message); err != nil {
332 self.terminate(status, statusError, err)
333 }
334 }
335
336 func (self *authenticateeProcess) completed(ctx context.Context, from *upid.UPID, pbMsg proto.Message) {
337 status := statusFrom(ctx)
338 if status != statusStepping {
339 self.terminate(status, statusError, UnexpectedAuthenticationCompleted)
340 return
341 }
342
343 log.Info("Authentication success")
344 self.terminate(status, statusCompleted, nil)
345 }
346
347 func (self *authenticateeProcess) failed(ctx context.Context, from *upid.UPID, pbMsg proto.Message) {
348 status := statusFrom(ctx)
349 self.terminate(status, statusFailed, auth.AuthenticationFailed)
350 }
351
352 func (self *authenticateeProcess) errored(ctx context.Context, from *upid.UPID, pbMsg proto.Message) {
353 var err error
354 if msg, ok := pbMsg.(*mesos.AuthenticationErrorMessage); !ok {
355 err = fmt.Errorf("Expected AuthenticationErrorMessage, not %T", pbMsg)
356 } else {
357 err = fmt.Errorf("Authentication error: %s", msg.GetError())
358 }
359 status := statusFrom(ctx)
360 self.terminate(status, statusError, err)
361 }