Debian Codegraph @

server/router.go

raw
1 package server
2
3 import (
4 "bytes"
5 "errors"
6 "fmt"
7 "io"
8 "net"
9 "net/http"
10 "net/url"
11 "strconv"
12 "strings"
13 "time"
14
15 "github.com/Masterminds/semver/v3"
16 "github.com/gin-gonic/gin"
17 "github.com/google/uuid"
18 "github.com/henrybear327/go-proton-api"
19 )
20
21 func initRouter(s *Server) {
22 s.r.Use(
23 s.requireValidAppVersion(),
24 s.setSessionCookie(),
25 s.applyStatusHooks(),
26 s.applyRateLimit(),
27 )
28
29 if core := s.r.Group("/core/v4"); core != nil {
30 // Domains routes don't need authentication.
31 if domains := core.Group("/domains"); domains != nil {
32 domains.GET("/available", s.handleGetDomainsAvailable())
33 }
34
35 // Reporting a bug is also possible without authentication.
36 if reports := core.Group("/reports"); reports != nil {
37 reports.POST("/bug", s.handlePostReportBug())
38 }
39
40 // These routes require auth.
41 if core := core.Group("", s.requireAuth()); core != nil {
42 if users := core.Group("/users"); users != nil {
43 users.GET("", s.handleGetUsers())
44 }
45
46 if addresses := core.Group("/addresses"); addresses != nil {
47 addresses.GET("", s.handleGetAddresses())
48 addresses.GET("/:addressID", s.handleGetAddress())
49 addresses.DELETE("/:addressID", s.handleDeleteAddress())
50 addresses.PUT("/:addressID/enable", s.handlePutAddressEnable())
51 addresses.PUT("/:addressID/disable", s.handlePutAddressDisable())
52 addresses.PUT("/order", s.handlePutAddressesOrder())
53 }
54
55 if labels := core.Group("/labels"); labels != nil {
56 labels.GET("", s.handleGetMailLabels())
57 labels.POST("", s.handlePostMailLabels())
58 labels.PUT("/:labelID", s.handlePutMailLabel())
59 labels.DELETE("/:labelID", s.handleDeleteMailLabel())
60 }
61
62 if keys := core.Group("/keys"); keys != nil {
63 keys.GET("", s.handleGetKeys())
64 keys.GET("/salts", s.handleGetKeySalts())
65 }
66
67 if events := core.Group("/events"); events != nil {
68 events.GET("/:eventID", s.handleGetEvents())
69 events.GET("/latest", s.handleGetEventsLatest())
70 }
71 if settings := core.Group("/settings"); settings != nil {
72 settings.GET("", s.handleGetUserSettings())
73 settings.PUT("/telemetry", s.handlePutUserSettingsTelemetry())
74 settings.PUT("/crashreports", s.handlePutUserSettingsCrashReports())
75 }
76 }
77 }
78
79 // All mail routes need authentication.
80 if mail := s.r.Group("/mail/v4", s.requireAuth()); mail != nil {
81 if settings := mail.Group("/settings"); settings != nil {
82 settings.GET("", s.handleGetMailSettings())
83 settings.PUT("/attachpublic", s.handlePutMailSettingsAttachPublicKey())
84 }
85
86 if messages := mail.Group("/messages"); messages != nil {
87 messages.GET("", s.handleGetMailMessages())
88 messages.POST("", s.handlePostMailMessages())
89 messages.GET("/ids", s.handleGetMailMessageIDs())
90 messages.GET("/:messageID", s.handleGetMailMessage())
91 messages.POST("/:messageID", s.handlePostMailMessage())
92 messages.PUT("/:messageID", s.handlePutMailMessage())
93 messages.PUT("/read", s.handlePutMailMessagesRead())
94 messages.PUT("/unread", s.handlePutMailMessagesUnread())
95 messages.PUT("/label", s.handlePutMailMessagesLabel())
96 messages.PUT("/unlabel", s.handlePutMailMessagesUnlabel())
97 messages.POST("/import", s.handlePutMailMessagesImport())
98 messages.PUT("/delete", s.handleDeleteMailMessages())
99 messages.GET("/count", s.handleMessageGroupCount())
100 }
101
102 if attachments := mail.Group("/attachments"); attachments != nil {
103 attachments.POST("", s.handlePostMailAttachments())
104 attachments.GET(":attachID", s.handleGetMailAttachment())
105 }
106 }
107
108 // All contacts routes need authentication.
109 if contacts := s.r.Group("/contacts/v4", s.requireAuth()); contacts != nil {
110 contacts.GET("/emails", s.handleGetContactsEmails())
111 }
112
113 // All data routes need authentication.
114 if data := s.r.Group("/data/v1", s.requireAuth()); data != nil {
115 if stats := data.Group("/stats"); stats != nil {
116 stats.POST("", s.handlePostDataStats())
117 stats.POST("/multiple", s.handlePostDataStatsMultiple())
118 }
119 }
120
121 // Top level auth routes don't need authentication.
122 if auth := s.r.Group("/auth/v4"); auth != nil {
123 auth.POST("", s.handlePostAuth())
124 auth.POST("/info", s.handlePostAuthInfo())
125 auth.POST("/refresh", s.handlePostAuthRefresh())
126
127 // These routes require auth.
128 if auth := auth.Group("", s.requireAuth()); auth != nil {
129 auth.DELETE("", s.handleDeleteAuth())
130
131 if sessions := auth.Group("/sessions"); sessions != nil {
132 sessions.GET("", s.handleGetAuthSessions())
133 sessions.DELETE("", s.handleDeleteAuthSessions())
134 sessions.DELETE("/:authUID", s.handleDeleteAuthSession())
135 }
136 }
137 }
138
139 // Test routes don't need authentication.
140 if tests := s.r.Group("/tests"); tests != nil {
141 tests.GET("/ping", s.handleGetPing())
142 }
143
144 // Quark routes don't need authentication.
145 if quark := s.r.Group("/internal/quark"); quark != nil {
146 quark.GET("/:command", s.handleQuarkCommand())
147 }
148
149 // Proxy any calls to the upstream server.
150 if proxy := s.r.Group("/proxy"); proxy != nil {
151 proxy.Any("/*path", s.handleProxy(proxy.BasePath()))
152 }
153 }
154
155 func (s *Server) requireValidAppVersion() gin.HandlerFunc {
156 return func(c *gin.Context) {
157 appVersion := c.Request.Header.Get("x-pm-appversion")
158
159 if appVersion == "" {
160 c.AbortWithStatusJSON(http.StatusBadRequest, proton.APIError{
161 Code: proton.AppVersionMissingCode,
162 Message: "Missing x-pm-appversion header",
163 })
164 } else if ok := s.validateAppVersion(appVersion); !ok {
165 c.AbortWithStatusJSON(http.StatusBadRequest, proton.APIError{
166 Code: proton.AppVersionBadCode,
167 Message: "This version of the app is no longer supported, please update to continue using the app",
168 })
169 }
170 }
171 }
172
173 func (s *Server) setSessionCookie() gin.HandlerFunc {
174 return func(c *gin.Context) {
175 url, err := url.Parse(s.s.URL)
176 if err != nil {
177 panic(err)
178 }
179
180 host, _, err := net.SplitHostPort(url.Host)
181 if err != nil {
182 panic(err)
183 }
184
185 if cookie, err := c.Request.Cookie("Session-Id"); errors.Is(err, http.ErrNoCookie) {
186 c.SetCookie("Session-Id", uuid.NewString(), int(90*24*time.Hour.Seconds()), "/", host, true, true)
187 } else {
188 c.SetCookie("Session-Id", cookie.Value, int(90*24*time.Hour.Seconds()), "/", host, true, true)
189 }
190 }
191 }
192
193 func (s *Server) applyStatusHooks() gin.HandlerFunc {
194 return func(c *gin.Context) {
195 s.statusHooksLock.RLock()
196 defer s.statusHooksLock.RUnlock()
197
198 for _, hook := range s.statusHooks {
199 if status, ok := hook(c.Request); ok {
200 c.AbortWithStatusJSON(status, proton.APIError{
201 Code: proton.InvalidValue,
202 Message: fmt.Sprintf("Request failed with status %d", status),
203 })
204
205 return
206 }
207 }
208 }
209 }
210
211 func (s *Server) applyRateLimit() gin.HandlerFunc {
212 return func(c *gin.Context) {
213 if s.rateLimit == nil {
214 return
215 }
216
217 if wait := s.rateLimit.exceeded(); wait > 0 {
218 c.Header("Retry-After", strconv.Itoa(int(wait.Seconds())))
219 c.AbortWithStatus(s.rateLimit.statusCode)
220 }
221 }
222 }
223
224 func (s *Server) logCalls() gin.HandlerFunc {
225 return func(c *gin.Context) {
226 start := time.Now()
227
228 req, err := io.ReadAll(c.Request.Body)
229 if err != nil {
230 panic(err)
231 } else {
232 c.Request.Body = io.NopCloser(bytes.NewReader(req))
233 }
234
235 res, err := newBodyWriter(c.Writer)
236 if err != nil {
237 panic(err)
238 } else {
239 c.Writer = res
240 }
241
242 c.Next()
243
244 s.callWatchersLock.RLock()
245 defer s.callWatchersLock.RUnlock()
246
247 for _, call := range s.callWatchers {
248 if call.isWatching(c.Request.URL.Path) {
249 call.publish(Call{
250 URL: c.Request.URL,
251 Method: c.Request.Method,
252 Status: c.Writer.Status(),
253
254 Time: start,
255 Duration: time.Since(start),
256
257 RequestHeader: c.Request.Header,
258 RequestBody: req,
259
260 ResponseHeader: c.Writer.Header(),
261 ResponseBody: res.bytes(),
262 })
263 }
264 }
265 }
266 }
267
268 func (s *Server) handleOffline() gin.HandlerFunc {
269 return func(c *gin.Context) {
270 if s.offline {
271 c.AbortWithStatus(http.StatusServiceUnavailable)
272 return
273 }
274 }
275 }
276
277 func (s *Server) requireAuth() gin.HandlerFunc {
278 return func(c *gin.Context) {
279 authUID := c.Request.Header.Get("x-pm-uid")
280 if authUID == "" {
281 c.AbortWithStatus(http.StatusUnauthorized)
282 return
283 }
284
285 auth := c.Request.Header.Get("Authorization")
286 if auth == "" {
287 c.AbortWithStatus(http.StatusUnauthorized)
288 return
289 }
290
291 userID, err := s.b.VerifyAuth(authUID, strings.Split(auth, " ")[1])
292 if err != nil {
293 c.AbortWithStatus(http.StatusUnauthorized)
294 return
295 }
296
297 c.Set("UserID", userID)
298
299 c.Set("AuthUID", authUID)
300 }
301 }
302
303 func (s *Server) validateAppVersion(appVersion string) bool {
304 if s.minAppVersion == nil {
305 return true
306 }
307
308 split := strings.Split(appVersion, "_")
309
310 if len(split) != 2 {
311 return false
312 }
313
314 version, err := semver.NewVersion(split[1])
315 if err != nil {
316 return false
317 }
318
319 if version.LessThan(s.minAppVersion) {
320 return false
321 }
322
323 return true
324 }
325
326 type bodyWriter struct {
327 gin.ResponseWriter
328 buf *bytes.Buffer
329 }
330
331 func newBodyWriter(w gin.ResponseWriter) (*bodyWriter, error) {
332 if w == nil {
333 return nil, errors.New("response writer is nil")
334 }
335
336 return &bodyWriter{
337 ResponseWriter: w,
338
339 buf: &bytes.Buffer{},
340 }, nil
341 }
342
343 func (w bodyWriter) Write(b []byte) (int, error) {
344 if n, err := w.buf.Write(b); err != nil {
345 return n, err
346 }
347
348 return w.ResponseWriter.Write(b)
349 }
350
351 func (w bodyWriter) bytes() []byte {
352 return w.buf.Bytes()
353 }