/
provisioning.go
296 lines (241 loc) · 7.52 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
// mautrix-slack - A Matrix-Slack puppeting bridge.
// Copyright (C) 2022 Tulir Asokan
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package main
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/gorilla/websocket"
log "maunium.net/go/maulogger/v2"
"maunium.net/go/mautrix/bridge/status"
"maunium.net/go/mautrix/id"
)
const (
SecWebSocketProtocol = "com.gitlab.beeper.slack"
)
type ProvisioningAPI struct {
bridge *SlackBridge
log log.Logger
}
func newProvisioningAPI(br *SlackBridge) *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/ping", p.ping).Methods(http.MethodGet)
r.HandleFunc("/v1/login", p.login).Methods(http.MethodPost)
r.HandleFunc("/v1/logout", p.logout).Methods(http.MethodPost)
p.bridge.AS.Router.HandleFunc("/_matrix/app/com.beeper.asmux/ping", p.BridgeStatePing).Methods(http.MethodPost)
p.bridge.AS.Router.HandleFunc("/_matrix/app/com.beeper.bridge_state", p.BridgeStatePing).Methods(http.MethodPost)
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
auth = strings.TrimPrefix(auth, "Bearer ")
if auth != p.bridge.Config.Bridge.Provisioning.SharedSecret {
jsonResponse(w, http.StatusForbidden, map[string]interface{}{
"error": "Invalid auth token",
"errcode": "M_FORBIDDEN",
})
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.Since(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) ping(w http.ResponseWriter, r *http.Request) {
user := r.Context().Value("user").(*User)
puppets := []interface{}{}
for _, team := range user.GetLoggedInTeams() {
puppets = append(puppets, map[string]interface{}{
"puppetId": team.Key.String(),
"puppetMxid": user.MXID,
"userId": team.Key.SlackID,
"data": map[string]interface{}{
"team": map[string]string{
"id": team.Key.TeamID,
"name": team.TeamName,
},
"self": map[string]string{
"id": team.Key.String(),
"name": team.SlackEmail,
},
},
})
}
user.Lock()
resp := map[string]interface{}{
"puppets": puppets,
"management_room": user.ManagementRoom,
"mxid": user.MXID,
}
user.Unlock()
jsonResponse(w, http.StatusOK, resp)
}
func (p *ProvisioningAPI) logout(w http.ResponseWriter, r *http.Request) {
userID := r.URL.Query().Get("user_id")
user := p.bridge.GetUserByMXID(id.UserID(userID))
slackTeamID := strings.Split(r.URL.Query().Get("slack_team_id"), "-")[0] // in case some client sends userTeam instead of team ID
userTeam := user.GetUserTeam(slackTeamID)
if userTeam == nil || !userTeam.IsLoggedIn() {
jsonResponse(w, http.StatusNotFound, Error{
Error: "Not logged in",
ErrCode: "Not logged in",
})
return
}
err := user.LogoutUserTeam(userTeam)
if err != nil {
user.log.Warnln("Error while logging out:", err)
jsonResponse(w, http.StatusInternalServerError, Error{
Error: fmt.Sprintf("Unknown error while logging out: %v", err),
ErrCode: err.Error(),
})
return
}
jsonResponse(w, http.StatusOK, Response{true, "Logged out successfully."})
}
func (p *ProvisioningAPI) login(w http.ResponseWriter, r *http.Request) {
userID := r.URL.Query().Get("user_id")
user := p.bridge.GetUserByMXID(id.UserID(userID))
var data struct {
Token string
Cookietoken string
}
err := json.NewDecoder(r.Body).Decode(&data)
if err != nil {
jsonResponse(w, http.StatusBadRequest, Error{
Error: "Invalid JSON",
ErrCode: "Invalid JSON",
})
return
}
if data.Token == "" {
jsonResponse(w, http.StatusBadRequest, Error{
Error: "Missing field token",
ErrCode: "Missing field token",
})
return
}
if data.Cookietoken == "" {
jsonResponse(w, http.StatusBadRequest, Error{
Error: "Missing field cookietoken",
ErrCode: "Missing field cookietoken",
})
return
}
cookieToken, _ := url.PathUnescape(data.Cookietoken)
info, err := user.TokenLogin(data.Token, cookieToken)
if err != nil {
jsonResponse(w, http.StatusNotAcceptable, Error{
Error: fmt.Sprintf("Slack login error: %s", err),
ErrCode: err.Error(),
})
return
}
jsonResponse(w, http.StatusCreated,
map[string]interface{}{
"success": true,
"teamid": info.TeamID,
"userid": info.UserID,
})
}
func (p *ProvisioningAPI) BridgeStatePing(w http.ResponseWriter, r *http.Request) {
if !p.bridge.AS.CheckServerToken(w, r) {
return
}
userID := r.URL.Query().Get("user_id")
user := p.bridge.GetUserByMXID(id.UserID(userID))
var global status.BridgeState
global.StateEvent = status.StateRunning
global = global.Fill(nil)
resp := status.GlobalBridgeState{
BridgeState: global,
RemoteStates: map[string]status.BridgeState{},
}
userTeams := user.GetLoggedInTeams()
for _, userTeam := range userTeams {
var remote status.BridgeState
if userTeam.IsLoggedIn() {
remote.StateEvent = status.StateConnected
} else {
remote.StateEvent = status.StateLoggedOut
}
remote = remote.Fill(userTeam)
resp.RemoteStates[remote.RemoteID] = remote
}
user.log.Debugfln("Responding bridge state in bridge status endpoint: %+v", resp)
jsonResponse(w, http.StatusOK, &resp)
}