aboutsummaryrefslogtreecommitdiff
path: root/serverkeyapi/internal/http.go
blob: 303275712020d916c400d10b359235f99e611e69 (plain)
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
package internal

import (
	"encoding/json"
	"net/http"

	"github.com/gorilla/mux"
	"github.com/matrix-org/dendrite/internal"
	"github.com/matrix-org/dendrite/serverkeyapi/api"
	"github.com/matrix-org/gomatrixserverlib"
	"github.com/matrix-org/util"
)

func (s *ServerKeyAPI) SetupHTTP(internalAPIMux *mux.Router) {
	internalAPIMux.Handle(api.ServerKeyQueryPublicKeyPath,
		internal.MakeInternalAPI("queryPublicKeys", func(req *http.Request) util.JSONResponse {
			result := map[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.PublicKeyLookupResult{}
			request := api.QueryPublicKeysRequest{}
			response := api.QueryPublicKeysResponse{}
			if err := json.NewDecoder(req.Body).Decode(&request); err != nil {
				return util.MessageResponse(http.StatusBadRequest, err.Error())
			}
			lookup := make(map[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.Timestamp)
			for req, timestamp := range request.Requests {
				if res, ok := s.ImmutableCache.GetServerKey(req); ok {
					result[req] = res
					continue
				}
				lookup[req] = timestamp
			}
			keys, err := s.FetchKeys(req.Context(), lookup)
			if err != nil {
				return util.ErrorResponse(err)
			}
			for req, res := range keys {
				result[req] = res
			}
			response.Results = result
			return util.JSONResponse{Code: http.StatusOK, JSON: &response}
		}),
	)
	internalAPIMux.Handle(api.ServerKeyInputPublicKeyPath,
		internal.MakeInternalAPI("inputPublicKeys", func(req *http.Request) util.JSONResponse {
			request := api.InputPublicKeysRequest{}
			response := api.InputPublicKeysResponse{}
			if err := json.NewDecoder(req.Body).Decode(&request); err != nil {
				return util.MessageResponse(http.StatusBadRequest, err.Error())
			}
			store := make(map[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.PublicKeyLookupResult)
			for req, res := range request.Keys {
				store[req] = res
				s.ImmutableCache.StoreServerKey(req, res)
			}
			if err := s.StoreKeys(req.Context(), store); err != nil {
				return util.ErrorResponse(err)
			}
			return util.JSONResponse{Code: http.StatusOK, JSON: &response}
		}),
	)
}