open Seppo_lib

(*
Peertube signature tests:
  https://github.com/Chocobozzz/PeerTube/blob/develop/server/tests/api/activitypub/helpers.ts
*)

(*
Keys from https://github.com/Chocobozzz/PeerTube/blob/develop/server/tests/fixtures/ap-json/peertube/keys.json
fixture from https://github.com/Chocobozzz/PeerTube/blob/develop/server/tests/fixtures/ap-json/mastodon/http-signature.json
Inbox https://github.com/Chocobozzz/PeerTube/blob/develop/server/tests/api/activitypub/helpers.ts#L151
*)
let test_signature () =
  Logr.info (fun m -> m "peertube.test.test_signature");
  let
    pk =
    Lwt.bind
      (As2.PubKeyPem.pk_from_pem ("data/peertube.priv.pem", "data/peertube.pub.pem"))
      (fun (_pub, pk) -> Lwt.return pk)
    |> Lwt_main.run
  and
    j = As2.json_from_file "data/peertube.json"
        |> Result.get_ok
  in
  let js k = Ezjsonm.find j [ "headers"; k ]
             |> Ezjsonm.get_string
  and _rt = ""
  and ho = "localhost"
  and da = "Mon, 22 Oct 2018 13:34:22 GMT"
  and di = "SHA-256=FEr5j2WSSfdEMcG3NTOXuGU0lUchfTJx4+BtUlWOwDk="
  and co = "application/activity+json"
  and si' =
    "oLKbgxdFXdXsHJ3x/UsG9Svu7oa8Dyqiy6Jif4wqNuhAqRVMRaG18f+dd2OcfFX3XRGF8p8flZkU6vvoEQBauTwGRGcgXAJuKC1zYIWGk+PeiW8lNUnE4qGapWcTiFnIo7FKauNdsgqg/tvgs1pQIdHkDDjZMI64twP7sTN/4vG1PCq+kyqi/DM+ORLi/W7vFuLVHt2Iz7ikfw/R3/mMtS4FwLops+tVYBQ2iQ9DVRhTwLKVbeL/LLVB/tdGzNZ4F4nImBAQQ9I7WpPM6J/k+cBmoEbrUKs8ptx9gbX3OSsl5wlvPVMNzU9F9yb2MrB/Y/J4qssKz+LbiaktKGj7OQ=="
  in
  let si =
    "keyId=\"http://localhost:3000/users/ronan2#main-key\",\
     algorithm=\"rsa-sha256\",\
     headers=\"(request-target) host date digest content-type\",\
     signature=\"" ^ si' ^ "\""
  and da',_,_ = Ptime.of_rfc3339 "2018-10-22T13:34:22+00:00" |> Result.get_ok in
  js "host" |> Assrt.equals_string __LOC__ ho;
  js "date" |> Assrt.equals_string __LOC__ da;
  js "digest" |> Assrt.equals_string __LOC__ di;
  js "content-type" |> Assrt.equals_string __LOC__ co;
  js "signature" |> Assrt.equals_string __LOC__ si;

  let open Cohttp in
  let h = Http.signed_headers
      (As2.PubKeyPem.sign pk)
      (Uri.of_string "http://localhost:3000/users/ronan2")
      da'
      di
      (Uri.of_string "http://localhost:3000/accounts/ronan/inbox")
  in
  Header.get h "signature"
  |> Option.get
  |> Assrt.equals_string ""
    ("keyId=\"http://localhost:3000/users/ronan2#main-key\",algorithm=\"rsa-sha256\",headers=\"(request-target)
host date digest content-type\",signature=\"" ^ si' ^ "\"")
  ;
  assert true

let () =
  Unix.chdir "../../../test/";
  test_signature () 
