Module: Async::Matrix::ApplicationService::Server::Grape

Defined in:
lib/async/matrix/application_service/server.rb

Overview

The Matrix Application Service wire protocol, as an includable concern. Mixing it into a Grape::API defines these routes (all under /_matrix/app/v1), reading its collaborators from Grape configuration:

configuration[:hs_token]    — homeserver token (authentication)
configuration[:dispatcher]  — Dispatcher receiving transactions
configuration[:thirdparty]  — optional third-party lookup handler
configuration[:client]      — optional Client (exposed to endpoints)

Routes:

PUT  transactions/{txnId}        — receive events (authenticated)
POST ping                        — healthcheck (unauthenticated)
GET  users/{userId}              — user existence query (authenticated)
GET  rooms/{roomAlias}           — room alias query (authenticated)
GET  thirdparty/protocol/{proto} — protocol metadata (authenticated)
GET  thirdparty/location         — location lookup (authenticated)
GET  thirdparty/location/{proto} — reverse location lookup (authenticated)
GET  thirdparty/user             — user lookup (authenticated)
GET  thirdparty/user/{proto}     — reverse user lookup (authenticated)

Third-party queries delegate to configuration, a duck type:

protocol(name)           -> Hash | nil   (nil ⇒ 404 M_NOT_FOUND)
locations(proto, params) -> Array        (default [])
users(proto, params)     -> Array        (default [])

Class Method Summary collapse

Class Method Details

.included(base) ⇒ Object



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
# File 'lib/async/matrix/application_service/server.rb', line 79

def self.included(base)
  base.class_eval do
    format :json
    content_type :json, "application/json"
    default_format :json

    helpers do
      def hs_token
        configuration[:hs_token]
      end

      def dispatcher
        configuration[:dispatcher]
      end

      def thirdparty
        configuration[:thirdparty]
      end

      def client
        configuration[:client]
      end

      # Homeserver token from the Authorization header (Bearer scheme)
      # or the legacy access_token query parameter.
      def request_token
        auth = headers["Authorization"]
        if auth&.start_with?("Bearer ")
          auth.delete_prefix("Bearer ")
        else
          params[:access_token]
        end
      end

      def authenticate!
        token = request_token
        unless token && secure_compare(token, hs_token.to_s)
          error!({errcode: "M_FORBIDDEN"}, 403)
        end
      end

      def secure_compare(a, b)
        return false unless a.bytesize == b.bytesize

        l = a.unpack("C*")
        r = b.unpack("C*")
        result = 0
        l.each_with_index { |byte, i| result |= byte ^ r[i] }
        result.zero?
      end

      # Raw JSON body, parsed here (rather than via Grape's param
      # coercion) so malformed input yields the Matrix M_BAD_JSON.
      def json_body
        raw = request.body.read
        request.body.rewind if request.body.respond_to?(:rewind)
        return {} if raw.nil? || raw.empty?

        JSON.parse(raw)
      rescue JSON::ParserError => e
        Console.error(self) { "Bad JSON in request: #{e.message}" }
        error!({errcode: "M_BAD_JSON"}, 400)
      end
    end

    # --- Healthcheck (unauthenticated) -----------------------------

    post "/_matrix/app/v1/ping" do
      status 200
      {}
    end

    # --- Authenticated homeserver-facing routes --------------------

    namespace "/_matrix/app/v1" do
      before { authenticate! }

      put "transactions/:txn_id" do
        body = json_body
        Console.info(self) do
          events = body["events"] || []
          "Transaction #{params[:txn_id]}: #{events.size} event(s)"
        end
        dispatcher.receive_transaction(params[:txn_id], body)
        {}
      end

      get "users/:user_id", requirements: {user_id: %r{[^/]+}} do
        {}
      end

      get "rooms/:room_alias", requirements: {room_alias: %r{[^/]+}} do
        error!({errcode: "M_NOT_FOUND"}, 404)
      end

      # --- Third-party protocol lookups ---

      get "thirdparty/protocol/:protocol" do
        result = thirdparty&.protocol(params[:protocol])
        error!({errcode: "M_NOT_FOUND"}, 404) unless result

        result
      end

      get "thirdparty/location" do
        thirdparty&.locations(nil, params) || []
      end

      get "thirdparty/location/:protocol" do
        thirdparty&.locations(params[:protocol], params) || []
      end

      get "thirdparty/user" do
        thirdparty&.users(nil, params) || []
      end

      get "thirdparty/user/:protocol" do
        thirdparty&.users(params[:protocol], params) || []
      end
    end
  end
end