This repository has been archived by the owner on Feb 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
create.go
210 lines (182 loc) · 6.17 KB
/
create.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
package handler
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"path"
"strconv"
"time"
"golang.org/x/net/context/ctxhttp"
"github.com/cloudradar-monitoring/plexus/api"
"github.com/cloudradar-monitoring/plexus/control"
"github.com/cloudradar-monitoring/plexus/token"
)
const (
defaultTimeout = 5 * time.Second
contentType = "application/json"
)
var (
ErrUnableToPair = errors.New("unable to pair")
ErrMissingSupporterInfo = errors.New("missing supporter info")
)
// CreateSession godoc
// @Summary Create a session.
// @Description Create a plexus session where meshagents can connect to.
// @Tags session
// @Accept application/x-www-form-urlencoded
// @Produce application/json
// @Param id formData string true "session id"
// @Param ttl formData int true "the time to live for the session"
// @Param username formData string true "the credentials to open the remote control interface & delete the session"
// @Param password formData string true "the credentials to open the remote control interface & delete the session"
// @Param supporter_name formData string true "the supporter name"
// @Param supporter_avatar formData string true "the supporter avatar"
// @Success 200 {object} api.Session
// @Failure 400 {object} api.Error
// @Failure 500 {object} api.Error
// @Failure 502 {object} api.Error
// @Router /session [post]
func (h *Handler) CreateSession(rw http.ResponseWriter, r *http.Request) {
if !h.auth(rw, r) {
return
}
id := r.FormValue("id")
ttlStr := r.FormValue("ttl")
user := r.FormValue("username")
pass := r.FormValue("password")
supName := r.FormValue("supporter_name")
supAvatar := r.FormValue("supporter_avatar")
ttl, err := strconv.ParseInt(ttlStr, 10, 64)
if err != nil {
api.WriteBadRequestJSON(rw, fmt.Sprintf("invalid ttl %s: %s", id, err))
return
}
if !h.sessionCredentials && (user != "" || pass != "") {
api.WriteBadRequestJSON(rw, "session credentials are not allowed")
return
}
h.lock.Lock()
defer h.lock.Unlock()
if _, ok := h.sessions[id]; ok {
api.WriteBadRequestJSON(rw, fmt.Sprintf("session with id %s does already exist", id))
return
}
mc, err := control.Connect(h.ccfg, h.log)
defer mc.Close()
if err != nil {
api.WriteBadGatewayJSON(rw, fmt.Sprintf("could not connect to mesh control: %s", err))
return
}
mesh, err := mc.CreateMesh(h.ccfg.MeshCentralGroupPrefix + "/" + id + "/" + token.New(5))
if err != nil {
api.WriteBadGatewayJSON(rw, fmt.Sprintf("could not create mesh: %s", err))
return
}
serverInfo, err := mc.ServerInfo()
if err != nil {
api.WriteBadGatewayJSON(rw, fmt.Sprintf("could not get server id: %s", err))
return
}
sessionToken := token.NewAuth()
session := &Session{
Token: sessionToken,
ID: id,
Username: user,
Password: pass,
ExpiresAt: time.Now().Add(time.Duration(ttl) * time.Second),
AgentConfig: api.AgentConfig{
MeshName: mesh.Name,
MeshIDHex: mesh.IDHex,
MeshID: mesh.ID,
ServerID: serverInfo.AgentHash,
MeshServer: fmt.Sprintf("wss://%s%s", r.Host, path.Join(h.prefix, "agent", fmt.Sprintf("%s:%s", id, sessionToken))),
MeshType: 2,
},
}
if h.pcfg.PairingURL != "" {
err = h.pcPair(r.Context(), r.Host, supName, supAvatar, session)
if err != nil {
if errors.Is(err, ErrMissingSupporterInfo) {
api.WriteJSONError(rw, http.StatusBadRequest, "You need to provide supporter_name and supporter_avatar for pairing")
return
}
api.WriteJSONError(rw, http.StatusBadGateway, fmt.Sprintf("Unable to create session, failed to pair: %s", err.Error()))
return
}
}
h.sessions[id] = session
go func() {
<-time.After(time.Duration(ttl) * time.Second)
h.lock.Lock()
defer h.lock.Unlock()
if s, ok := h.sessions[id]; ok {
h.log.Infof("Session %s expired", id)
err := h.deleteInternal(s)
if err != nil {
h.log.Errorf("Could not clean session %s: %s", id, err)
}
}
}()
rw.Header().Add("content-type", "application/json")
rw.WriteHeader(http.StatusCreated)
_ = json.NewEncoder(rw).Encode(&api.Session{
ID: id,
SessionURL: fmt.Sprintf("https://%s%s", r.Host, path.Join(h.prefix, "session", id)),
AgentMSH: fmt.Sprintf("https://%s%s", r.Host, path.Join(h.prefix, "config", fmt.Sprintf("%s:%s", id, sessionToken))),
PairingCode: session.PairingCode,
PairingURL: session.PairingURL,
AgentConfig: session.AgentConfig,
ExpiresAt: session.ExpiresAt,
})
}
type Request struct {
URL string `json:"url"`
}
type Response struct {
Success bool `json:"success"`
Code string `json:"code"`
PairingURL string `json:"pairing_url"`
RedirectURL string `json:"redirect_url"`
}
func (h *Handler) pcPair(ctx context.Context, host, supName, supAvatar string, session *Session) error {
h.log.Debugf("pairing to %s ...", h.pcfg.PairingURL)
if supName == "" || supAvatar == "" {
return ErrMissingSupporterInfo
}
jsonRequest, _ := json.Marshal(&Request{
URL: fmt.Sprintf("https://%s%s/pairing", host, h.prefix),
})
client := &http.Client{
Timeout: defaultTimeout,
}
response, err := ctxhttp.Post(ctx, client, h.pcfg.PairingURL, contentType, bytes.NewBuffer(jsonRequest))
if err != nil {
return fmt.Errorf("post failed: %w", err)
}
defer response.Body.Close()
jsonResponse, err := ioutil.ReadAll(response.Body)
if err != nil {
h.log.Errorf("pairing request failed: status(%d) response(%s)", response.StatusCode, string(jsonResponse))
return fmt.Errorf("reading body failed code(%d) error: %w", response.StatusCode, err)
}
if response.StatusCode != http.StatusOK {
h.log.Errorf("pairing request failed: status(%d) response(%s)", response.StatusCode, string(jsonResponse))
return fmt.Errorf("code(%d) error: %w", response.StatusCode, ErrUnableToPair)
}
resp := Response{}
err = json.Unmarshal(jsonResponse, &resp)
if err != nil {
h.log.Errorf("pairing request failed: status(%d) response(%s)", response.StatusCode, string(jsonResponse))
return fmt.Errorf("unmarshaling response failed code(%d) error: %w", response.StatusCode, err)
}
session.PairingCode = resp.Code
session.PairingURL = resp.PairingURL
session.SupporterName = supName
session.SupporterAvatar = supAvatar
h.log.Debugf("pairing succeeded code(%s)", resp.Code)
return nil
}