Update gomatrixserverlib (#89)

This commit is contained in:
Mark Haines 2017-05-05 16:19:48 +01:00 committed by GitHub
parent a1ce351d36
commit 0309035aad
17 changed files with 1355 additions and 71 deletions

View file

@ -16,6 +16,7 @@
package gomatrixserverlib
import (
"bytes"
"crypto/tls"
"encoding/json"
"fmt"
@ -141,3 +142,81 @@ func (fc *Client) LookupUserInfo(matrixServer, token string) (u UserInfo, err er
return
}
// LookupServerKeys lookups up the keys for a matrix server from a matrix server.
// The first argument is the name of the matrix server to download the keys from.
// The second argument is a map from (server name, key ID) pairs to timestamps.
// The (server name, key ID) pair identifies the key to download.
// The timestamps tell the server when the keys need to be valid until.
// Perspective servers can use that timestamp to determine whether they can
// return a cached copy of the keys or whether they will need to retrieve a fresh
// copy of the keys.
// Returns the keys or an error if there was a problem talking to the server.
func (fc *Client) LookupServerKeys(
matrixServer string, keyRequests map[PublicKeyRequest]Timestamp,
) (map[PublicKeyRequest]ServerKeys, error) {
url := url.URL{
Scheme: "matrix",
Host: matrixServer,
Path: "/_matrix/key/v2/query",
}
// The request format is:
// { "server_keys": { "<server_name>": { "<key_id>": { "minimum_valid_until_ts": <ts> }}}
type keyreq struct {
MinimumValidUntilTS Timestamp `json:"minimum_valid_until_ts"`
}
request := struct {
ServerKeyMap map[string]map[KeyID]keyreq `json:"server_keys"`
}{map[string]map[KeyID]keyreq{}}
for k, ts := range keyRequests {
server := request.ServerKeyMap[k.ServerName]
if server == nil {
server = map[KeyID]keyreq{}
request.ServerKeyMap[k.ServerName] = server
}
server[k.KeyID] = keyreq{ts}
}
requestBytes, err := json.Marshal(request)
if err != nil {
return nil, err
}
response, err := fc.client.Post(url.String(), "application/json", bytes.NewBuffer(requestBytes))
if response != nil {
defer response.Body.Close()
}
if err != nil {
return nil, err
}
if response.StatusCode != 200 {
var errorOutput []byte
if errorOutput, err = ioutil.ReadAll(response.Body); err != nil {
return nil, err
}
return nil, fmt.Errorf("HTTP %d : %s", response.StatusCode, errorOutput)
}
var body struct {
ServerKeyList []ServerKeys `json:"server_keys"`
}
if err = json.NewDecoder(response.Body).Decode(&body); err != nil {
return nil, err
}
result := map[PublicKeyRequest]ServerKeys{}
for _, keys := range body.ServerKeyList {
keys.FromServer = matrixServer
// TODO: What happens if the same key ID appears in multiple responses?
// We should probably take the response with the highest valid_until_ts.
for keyID := range keys.VerifyKeys {
result[PublicKeyRequest{keys.ServerName, keyID}] = keys
}
for keyID := range keys.OldVerifyKeys {
result[PublicKeyRequest{keys.ServerName, keyID}] = keys
}
}
return result, nil
}