/
chanllenger.go
109 lines (85 loc) · 2.04 KB
/
chanllenger.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
package pome
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
"github.com/google/uuid"
"golang.org/x/crypto/ssh"
)
func (p *pome) load(ctx context.Context, id string) (*pipe, error) {
req, err := http.NewRequest("GET", p.Config.CheckBaseURL+id, nil)
if err != nil {
return nil, err
}
req = req.WithContext(ctx)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
if resp.StatusCode > 299 {
return nil, fmt.Errorf("bad http state code %v", resp.StatusCode)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
pipe := pipe{}
if err := json.Unmarshal(body, &pipe); err != nil {
return nil, err
}
return &pipe, nil
}
func (p *pome) loadWithRetry(ctx context.Context, id string) <-chan *pipe {
c := make(chan *pipe)
go func() {
for {
select {
case <-ctx.Done():
c <- nil
return
default:
timeout, cancel := context.WithTimeout(context.Background(), time.Millisecond*5000)
defer cancel()
pipe, err := p.load(timeout, id)
if err == nil {
c <- pipe
return
}
time.Sleep(time.Millisecond * 5000)
}
}
}()
return c
}
func (p *pome) challenge(conn ssh.ConnMetadata, client ssh.KeyboardInteractiveChallenge) (ssh.AdditionalChallengeContext, error) {
uid, err := uuid.NewRandom()
if err != nil {
return nil, err
}
id := uid.String()
url := p.Config.LoginBaseURL + id
say := func(msg string) error {
_, err = client(conn.User(), msg, nil, nil)
return err
}
err = say(fmt.Sprintf("Open %v in browser to login (timeout %v senconds)", url, p.Config.Timeout))
if err != nil {
return nil, err
}
d := time.Now().Add(time.Duration(p.Config.Timeout) * time.Second)
ctx, cancel := context.WithDeadline(context.Background(), d)
defer cancel()
c := p.loadWithRetry(ctx, id)
pipe := <-c
if pipe == nil {
say(fmt.Sprintf("Login timeout"))
return nil, fmt.Errorf("timeout")
}
say(fmt.Sprintf("Connecting to %v@%v", pipe.Username, pipe.Address))
pipe.say = say
return pipe, nil
}