-
-
Notifications
You must be signed in to change notification settings - Fork 21
/
provisioning.go
552 lines (480 loc) · 15.2 KB
/
provisioning.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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
package main
import (
"bufio"
"context"
"encoding/json"
"errors"
"net"
"net/http"
_ "net/http/pprof"
"strings"
"time"
"github.com/gorilla/mux"
"github.com/gorilla/websocket"
log "maunium.net/go/maulogger/v2"
"maunium.net/go/mautrix"
"maunium.net/go/mautrix/bridge/bridgeconfig"
"maunium.net/go/mautrix/id"
"go.mau.fi/mautrix-discord/database"
"go.mau.fi/mautrix-discord/remoteauth"
)
const (
SecWebSocketProtocol = "com.gitlab.beeper.discord"
)
const (
ErrCodeNotConnected = "FI.MAU.DISCORD.NOT_CONNECTED"
ErrCodeAlreadyLoggedIn = "FI.MAU.DISCORD.ALREADY_LOGGED_IN"
ErrCodeAlreadyConnected = "FI.MAU.DISCORD.ALREADY_CONNECTED"
ErrCodeConnectFailed = "FI.MAU.DISCORD.CONNECT_FAILED"
ErrCodeDisconnectFailed = "FI.MAU.DISCORD.DISCONNECT_FAILED"
ErrCodeGuildBridgeFailed = "M_UNKNOWN"
ErrCodeGuildUnbridgeFailed = "M_UNKNOWN"
ErrCodeGuildNotBridged = "FI.MAU.DISCORD.GUILD_NOT_BRIDGED"
ErrCodeLoginPrepareFailed = "FI.MAU.DISCORD.LOGIN_PREPARE_FAILED"
ErrCodeLoginConnectionFailed = "FI.MAU.DISCORD.LOGIN_CONN_FAILED"
ErrCodeLoginFailed = "FI.MAU.DISCORD.LOGIN_FAILED"
ErrCodePostLoginConnFailed = "FI.MAU.DISCORD.POST_LOGIN_CONNECTION_FAILED"
)
type ProvisioningAPI struct {
bridge *DiscordBridge
log log.Logger
}
func newProvisioningAPI(br *DiscordBridge) *ProvisioningAPI {
p := &ProvisioningAPI{
bridge: br,
log: br.Log.Sub("Provisioning"),
}
prefix := br.Config.Bridge.Provisioning.Prefix
p.log.Debugln("Enabling provisioning API at", prefix)
r := br.AS.Router.PathPrefix(prefix).Subrouter()
r.Use(p.authMiddleware)
r.HandleFunc("/v1/disconnect", p.disconnect).Methods(http.MethodPost)
r.HandleFunc("/v1/ping", p.ping).Methods(http.MethodGet)
r.HandleFunc("/v1/login/qr", p.qrLogin).Methods(http.MethodGet)
r.HandleFunc("/v1/login/token", p.tokenLogin).Methods(http.MethodPost)
r.HandleFunc("/v1/logout", p.logout).Methods(http.MethodPost)
r.HandleFunc("/v1/reconnect", p.reconnect).Methods(http.MethodPost)
r.HandleFunc("/v1/guilds", p.guildsList).Methods(http.MethodGet)
r.HandleFunc("/v1/guilds/{guildID}", p.guildsBridge).Methods(http.MethodPost)
r.HandleFunc("/v1/guilds/{guildID}", p.guildsUnbridge).Methods(http.MethodDelete)
if p.bridge.Config.Bridge.Provisioning.DebugEndpoints {
p.log.Debugln("Enabling debug API at /debug")
r := p.bridge.AS.Router.PathPrefix("/debug").Subrouter()
r.Use(p.authMiddleware)
r.PathPrefix("/pprof").Handler(http.DefaultServeMux)
}
return p
}
func jsonResponse(w http.ResponseWriter, status int, response interface{}) {
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(response)
}
// Response structs
type Response struct {
Success bool `json:"success"`
Status string `json:"status"`
}
type Error struct {
Success bool `json:"success"`
Error string `json:"error"`
ErrCode string `json:"errcode"`
}
// Wrapped http.ResponseWriter to capture the status code
type responseWrap struct {
http.ResponseWriter
statusCode int
}
var _ http.Hijacker = (*responseWrap)(nil)
func (rw *responseWrap) WriteHeader(statusCode int) {
rw.ResponseWriter.WriteHeader(statusCode)
rw.statusCode = statusCode
}
func (rw *responseWrap) Hijack() (net.Conn, *bufio.ReadWriter, error) {
hijacker, ok := rw.ResponseWriter.(http.Hijacker)
if !ok {
return nil, nil, errors.New("response does not implement http.Hijacker")
}
return hijacker.Hijack()
}
// Middleware
func (p *ProvisioningAPI) authMiddleware(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
auth := r.Header.Get("Authorization")
// Special case the login endpoint to use the discord qrcode auth
if auth == "" && strings.HasSuffix(r.URL.Path, "/login") {
authParts := strings.Split(r.Header.Get("Sec-WebSocket-Protocol"), ",")
for _, part := range authParts {
part = strings.TrimSpace(part)
if strings.HasPrefix(part, SecWebSocketProtocol+"-") {
auth = part[len(SecWebSocketProtocol+"-"):]
break
}
}
} else if strings.HasPrefix(auth, "Bearer ") {
auth = auth[len("Bearer "):]
}
if auth != p.bridge.Config.Bridge.Provisioning.SharedSecret {
jsonResponse(w, http.StatusUnauthorized, map[string]interface{}{
"error": "Invalid auth token",
"errcode": mautrix.MUnknownToken.ErrCode,
})
return
}
userID := r.URL.Query().Get("user_id")
user := p.bridge.GetUserByMXID(id.UserID(userID))
start := time.Now()
wWrap := &responseWrap{w, 200}
h.ServeHTTP(wWrap, r.WithContext(context.WithValue(r.Context(), "user", user)))
duration := time.Now().Sub(start).Seconds()
p.log.Infofln("%s %s from %s took %.2f seconds and returned status %d", r.Method, r.URL.Path, user.MXID, duration, wWrap.statusCode)
})
}
// websocket upgrader
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
Subprotocols: []string{SecWebSocketProtocol},
}
// Handlers
func (p *ProvisioningAPI) disconnect(w http.ResponseWriter, r *http.Request) {
user := r.Context().Value("user").(*User)
if !user.Connected() {
jsonResponse(w, http.StatusConflict, Error{
Error: "You're not connected to discord",
ErrCode: ErrCodeNotConnected,
})
return
}
if err := user.Disconnect(); err != nil {
p.log.Errorfln("Failed to disconnect %s: %v", user.MXID, err)
jsonResponse(w, http.StatusInternalServerError, Error{
Error: "Failed to disconnect from discord",
ErrCode: ErrCodeDisconnectFailed,
})
} else {
jsonResponse(w, http.StatusOK, Response{
Success: true,
Status: "Disconnected from Discord",
})
}
}
type respPing struct {
Discord struct {
ID string `json:"id,omitempty"`
LoggedIn bool `json:"logged_in"`
Connected bool `json:"connected"`
Conn struct {
LastHeartbeatAck int64 `json:"last_heartbeat_ack,omitempty"`
LastHeartbeatSent int64 `json:"last_heartbeat_sent,omitempty"`
} `json:"conn"`
}
MXID id.UserID `json:"mxid"`
ManagementRoom id.RoomID `json:"management_room"`
}
func (p *ProvisioningAPI) ping(w http.ResponseWriter, r *http.Request) {
user := r.Context().Value("user").(*User)
resp := respPing{
MXID: user.MXID,
ManagementRoom: user.ManagementRoom,
}
resp.Discord.LoggedIn = user.IsLoggedIn()
resp.Discord.Connected = user.Connected()
resp.Discord.ID = user.DiscordID
if user.Session != nil {
resp.Discord.Conn.LastHeartbeatAck = user.Session.LastHeartbeatAck.UnixMilli()
resp.Discord.Conn.LastHeartbeatSent = user.Session.LastHeartbeatSent.UnixMilli()
}
jsonResponse(w, http.StatusOK, resp)
}
func (p *ProvisioningAPI) logout(w http.ResponseWriter, r *http.Request) {
user := r.Context().Value("user").(*User)
var msg string
if user.DiscordID != "" {
msg = "Logged out successfully."
} else {
msg = "User wasn't logged in."
}
user.Logout(false)
jsonResponse(w, http.StatusOK, Response{true, msg})
}
func (p *ProvisioningAPI) qrLogin(w http.ResponseWriter, r *http.Request) {
userID := r.URL.Query().Get("user_id")
user := p.bridge.GetUserByMXID(id.UserID(userID))
c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
p.log.Errorln("Failed to upgrade connection to websocket:", err)
return
}
log := p.log.Sub("QRLogin").Sub(user.MXID.String())
defer func() {
err := c.Close()
if err != nil {
log.Debugln("Error closing websocket:", err)
}
}()
go func() {
// Read everything so SetCloseHandler() works
for {
_, _, err := c.ReadMessage()
if err != nil {
break
}
}
}()
ctx, cancel := context.WithCancel(context.Background())
c.SetCloseHandler(func(code int, text string) error {
log.Debugfln("Login websocket closed (%d), cancelling login", code)
cancel()
return nil
})
if user.IsLoggedIn() {
_ = c.WriteJSON(Error{
Error: "You're already logged into Discord",
ErrCode: ErrCodeAlreadyLoggedIn,
})
return
}
client, err := remoteauth.New()
if err != nil {
log.Errorln("Failed to prepare login:", err)
_ = c.WriteJSON(Error{
Error: "Failed to prepare login",
ErrCode: ErrCodeLoginPrepareFailed,
})
return
}
qrChan := make(chan string)
doneChan := make(chan struct{})
log.Debugln("Started login via provisioning API")
err = client.Dial(ctx, qrChan, doneChan)
if err != nil {
log.Errorln("Failed to connect to Discord login websocket:", err)
close(qrChan)
close(doneChan)
_ = c.WriteJSON(Error{
Error: "Failed to connect to Discord login websocket",
ErrCode: ErrCodeLoginConnectionFailed,
})
return
}
for {
select {
case qrCode, ok := <-qrChan:
if !ok {
continue
}
err = c.WriteJSON(map[string]interface{}{
"code": qrCode,
"timeout": 120, // TODO: move this to the library or something
})
if err != nil {
log.Errorln("Failed to write QR code to websocket:", err)
}
case <-doneChan:
var discordUser remoteauth.User
discordUser, err = client.Result()
if err != nil {
log.Errorln("Discord login websocket returned error:", err)
_ = c.WriteJSON(Error{
Error: "Failed to log in",
ErrCode: ErrCodeLoginFailed,
})
return
}
log.Infofln("Logged in as %s#%s (%s)", discordUser.Username, discordUser.Discriminator, discordUser.UserID)
if err = user.Login(discordUser.Token); err != nil {
log.Errorln("Failed to connect after logging in:", err)
_ = c.WriteJSON(Error{
Error: "Failed to connect to Discord after logging in",
ErrCode: ErrCodePostLoginConnFailed,
})
return
}
err = c.WriteJSON(respLogin{
Success: true,
ID: user.DiscordID,
Username: discordUser.Username,
Discriminator: discordUser.Discriminator,
})
if err != nil {
log.Errorln("Failed to write login success to websocket:", err)
}
return
case <-ctx.Done():
return
}
}
}
type respLogin struct {
Success bool `json:"success"`
ID string `json:"id"`
Username string `json:"username"`
Discriminator string `json:"discriminator"`
}
type reqTokenLogin struct {
Token string `json:"token"`
}
func (p *ProvisioningAPI) tokenLogin(w http.ResponseWriter, r *http.Request) {
userID := r.URL.Query().Get("user_id")
user := p.bridge.GetUserByMXID(id.UserID(userID))
log := p.log.Sub("TokenLogin").Sub(user.MXID.String())
if user.IsLoggedIn() {
jsonResponse(w, http.StatusConflict, Error{
Error: "You're already logged into Discord",
ErrCode: ErrCodeAlreadyLoggedIn,
})
return
}
var body reqTokenLogin
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
log.Errorln("Failed to parse login request:", err)
jsonResponse(w, http.StatusBadRequest, Error{
Error: "Failed to parse request body",
ErrCode: mautrix.MBadJSON.ErrCode,
})
return
}
if err := user.Login(body.Token); err != nil {
log.Errorln("Failed to connect with provided token:", err)
jsonResponse(w, http.StatusUnauthorized, Error{
Error: "Failed to connect to Discord",
ErrCode: ErrCodePostLoginConnFailed,
})
return
}
log.Infoln("Successfully logged in")
jsonResponse(w, http.StatusOK, respLogin{
Success: true,
ID: user.DiscordID,
Username: user.Session.State.User.Username,
Discriminator: user.Session.State.User.Discriminator,
})
}
func (p *ProvisioningAPI) reconnect(w http.ResponseWriter, r *http.Request) {
user := r.Context().Value("user").(*User)
if user.Connected() {
jsonResponse(w, http.StatusConflict, Error{
Error: "You're already connected to discord",
ErrCode: ErrCodeAlreadyConnected,
})
return
}
if err := user.Connect(); err != nil {
jsonResponse(w, http.StatusInternalServerError, Error{
Error: "Failed to connect to discord",
ErrCode: ErrCodeConnectFailed,
})
} else {
jsonResponse(w, http.StatusOK, Response{
Success: true,
Status: "Connected to Discord",
})
}
}
type guildEntry struct {
ID string `json:"id"`
Name string `json:"name"`
AvatarURL id.ContentURI `json:"avatar_url"`
MXID id.RoomID `json:"mxid"`
AutoBridge bool `json:"auto_bridge_channels"`
BridgingMode string `json:"bridging_mode"`
}
type respGuildsList struct {
Guilds []guildEntry `json:"guilds"`
}
func (p *ProvisioningAPI) guildsList(w http.ResponseWriter, r *http.Request) {
user := r.Context().Value("user").(*User)
var resp respGuildsList
resp.Guilds = []guildEntry{}
for _, userGuild := range user.GetPortals() {
guild := p.bridge.GetGuildByID(userGuild.DiscordID, false)
if guild == nil {
continue
}
resp.Guilds = append(resp.Guilds, guildEntry{
ID: guild.ID,
Name: guild.PlainName,
AvatarURL: guild.AvatarURL,
MXID: guild.MXID,
AutoBridge: guild.BridgingMode == database.GuildBridgeEverything,
BridgingMode: guild.BridgingMode.String(),
})
}
jsonResponse(w, http.StatusOK, resp)
}
type reqBridgeGuild struct {
AutoCreateChannels bool `json:"auto_create_channels"`
}
type respBridgeGuild struct {
Success bool `json:"success"`
MXID id.RoomID `json:"mxid"`
}
func (p *ProvisioningAPI) guildsBridge(w http.ResponseWriter, r *http.Request) {
user := r.Context().Value("user").(*User)
guildID := mux.Vars(r)["guildID"]
var body reqBridgeGuild
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
p.log.Errorln("Failed to parse bridge request:", err)
jsonResponse(w, http.StatusBadRequest, Error{
Error: "Failed to parse request body",
ErrCode: mautrix.MBadJSON.ErrCode,
})
return
}
guild := user.bridge.GetGuildByID(guildID, false)
if guild == nil {
jsonResponse(w, http.StatusNotFound, Error{
Error: "Guild not found",
ErrCode: mautrix.MNotFound.ErrCode,
})
return
}
alreadyExists := guild.MXID == ""
if err := user.bridgeGuild(guildID, body.AutoCreateChannels); err != nil {
p.log.Errorfln("Error bridging %s: %v", guildID, err)
jsonResponse(w, http.StatusInternalServerError, Error{
Error: "Internal error while trying to bridge guild",
ErrCode: ErrCodeGuildBridgeFailed,
})
} else if alreadyExists {
jsonResponse(w, http.StatusOK, respBridgeGuild{
Success: true,
MXID: guild.MXID,
})
} else {
jsonResponse(w, http.StatusCreated, respBridgeGuild{
Success: true,
MXID: guild.MXID,
})
}
}
func (p *ProvisioningAPI) guildsUnbridge(w http.ResponseWriter, r *http.Request) {
guildID := mux.Vars(r)["guildID"]
user := r.Context().Value("user").(*User)
if user.PermissionLevel < bridgeconfig.PermissionLevelAdmin {
jsonResponse(w, http.StatusForbidden, Error{
Error: "Only bridge admins can unbridge guilds",
ErrCode: mautrix.MForbidden.ErrCode,
})
} else if guild := user.bridge.GetGuildByID(guildID, false); guild == nil {
jsonResponse(w, http.StatusNotFound, Error{
Error: "Guild not found",
ErrCode: mautrix.MNotFound.ErrCode,
})
} else if guild.BridgingMode == database.GuildBridgeNothing && guild.MXID == "" {
jsonResponse(w, http.StatusNotFound, Error{
Error: "That guild is not bridged",
ErrCode: ErrCodeGuildNotBridged,
})
} else if err := user.unbridgeGuild(guildID); err != nil {
p.log.Errorfln("Error unbridging %s: %v", guildID, err)
jsonResponse(w, http.StatusInternalServerError, Error{
Error: "Internal error while trying to unbridge guild",
ErrCode: ErrCodeGuildUnbridgeFailed,
})
} else {
w.WriteHeader(http.StatusNoContent)
}
}