sign_json 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. #!/usr/bin/env python
  2. #
  3. # Copyright 2020 The Matrix.org Foundation C.I.C.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import argparse
  17. import json
  18. import sys
  19. from json import JSONDecodeError
  20. import yaml
  21. from signedjson.key import read_signing_keys
  22. from signedjson.sign import sign_json
  23. from synapse.util import json_encoder
  24. def main():
  25. parser = argparse.ArgumentParser(
  26. description="""Adds a signature to a JSON object.
  27. Example usage:
  28. $ scripts-dev/sign_json.py -N test -k localhost.signing.key "{}"
  29. {"signatures":{"test":{"ed25519:a_ZnZh":"LmPnml6iM0iR..."}}}
  30. """,
  31. formatter_class=argparse.RawDescriptionHelpFormatter,
  32. )
  33. parser.add_argument(
  34. "-N",
  35. "--server-name",
  36. help="Name to give as the local homeserver. If unspecified, will be "
  37. "read from the config file.",
  38. )
  39. parser.add_argument(
  40. "-k",
  41. "--signing-key-path",
  42. help="Path to the file containing the private ed25519 key to sign the "
  43. "request with.",
  44. )
  45. parser.add_argument(
  46. "-c",
  47. "--config",
  48. default="homeserver.yaml",
  49. help=(
  50. "Path to synapse config file, from which the server name and/or signing "
  51. "key path will be read. Ignored if --server-name and --signing-key-path "
  52. "are both given."
  53. ),
  54. )
  55. input_args = parser.add_mutually_exclusive_group()
  56. input_args.add_argument("input_data", nargs="?", help="Raw JSON to be signed.")
  57. input_args.add_argument(
  58. "-i",
  59. "--input",
  60. type=argparse.FileType("r"),
  61. default=sys.stdin,
  62. help=(
  63. "A file from which to read the JSON to be signed. If neither --input nor "
  64. "input_data are given, JSON will be read from stdin."
  65. ),
  66. )
  67. parser.add_argument(
  68. "-o",
  69. "--output",
  70. type=argparse.FileType("w"),
  71. default=sys.stdout,
  72. help="Where to write the signed JSON. Defaults to stdout.",
  73. )
  74. args = parser.parse_args()
  75. if not args.server_name or not args.signing_key_path:
  76. read_args_from_config(args)
  77. with open(args.signing_key_path) as f:
  78. key = read_signing_keys(f)[0]
  79. json_to_sign = args.input_data
  80. if json_to_sign is None:
  81. json_to_sign = args.input.read()
  82. try:
  83. obj = json.loads(json_to_sign)
  84. except JSONDecodeError as e:
  85. print("Unable to parse input as JSON: %s" % e, file=sys.stderr)
  86. sys.exit(1)
  87. if not isinstance(obj, dict):
  88. print("Input json was not an object", file=sys.stderr)
  89. sys.exit(1)
  90. sign_json(obj, args.server_name, key)
  91. for c in json_encoder.iterencode(obj):
  92. args.output.write(c)
  93. args.output.write("\n")
  94. def read_args_from_config(args: argparse.Namespace) -> None:
  95. with open(args.config, "r") as fh:
  96. config = yaml.safe_load(fh)
  97. if not args.server_name:
  98. args.server_name = config["server_name"]
  99. if not args.signing_key_path:
  100. args.signing_key_path = config["signing_key_path"]
  101. if __name__ == "__main__":
  102. main()