..
  This file is part of Anastasis
  Copyright (C) 2019-2022 Anastasis SARL

  Anastasis is free software; you can redistribute it and/or modify it under the
  terms of the GNU Affero General Public License as published by the Free Software
  Foundation; either version 2.1, or (at your option) any later version.

  Anastasis is distributed in the hope that it will be useful, but WITHOUT ANY
  WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.

  You should have received a copy of the GNU Affero General Public License along with
  Anastasis; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>

  @author Christian Grothoff
  @author Dominik Meister
  @author Dennis Neufeld


========
REST API
========

.. _http-common:

-------------------------
HTTP Request and Response
-------------------------

Certain response formats are common for all requests. They are documented here
instead of with each individual request.  Furthermore, we note that clients may
theoretically fail to receive any response.  In this case, the client should
verify that the Internet connection is working properly, and then proceed to
handle the error as if an internal error (500) had been returned.

.. http:any:: /*


  **Request:**

  Unless specified otherwise, HTTP requests that carry a message body must
  have the content type ``application/json``.

  :reqheader Content-Type: application/json

  **Response:**

  :resheader Content-Type: application/json

  :http:statuscode:`200 Ok`:
    The request was successful.
  :http:statuscode:`400 Bad request`:
    One of the arguments to the request is missing or malformed.
  :http:statuscode:`500 Internal server error`:
    This always indicates some serious internal operational error of the Anastasis
    provider, such as a program bug, database problems, etc., and must not be used for
    client-side problems.  When facing an internal server error, clients should
    retry their request after some delay.  We recommended initially trying after
    1s, twice more at randomized times within 1 minute, then the user should be
    informed and another three retries should be scheduled within the next 24h.
    If the error persists, a report should ultimately be made to the auditor,
    although the auditor API for this is not yet specified.  However, as internal
    server errors are always reported to the exchange operator, a good operator
    should naturally be able to address them in a timely fashion, especially
    within 24h.

  Unless specified otherwise, all error status codes (4xx and 5xx) have a message
  body with an `ErrorDetail` JSON object.

  **Details:**

  .. ts:def:: ErrorDetail

    interface ErrorDetail {

      // Numeric error code unique to the condition, see ``gnu-taler-error-codes`` in GANA.
      // The other arguments are specific to the error value reported here.
      code: number;

      // Human-readable description of the error, i.e. "missing parameter", "commitment violation", ...
      // Should give a human-readable hint about the error's nature. Optional, may change without notice!
      hint?: string;

    }

-----------------------
Protocol Version Ranges
-----------------------

Anastasis services expose the range of API versions they support.  Clients in
turn have an API version range they support.  These version ranges are written
down in the `libtool version format
<https://www.gnu.org/software/libtool/manual/html_node/Libtool-versioning.html>`__.

A protocol version is a positive, non-zero integer.  A protocol version range consists of three components:

1. The ``current`` version.  This is the latest version of the protocol supported by the client or service.
2. The ``revision`` number.  This value should usually not be interpreted by the client/server, but serves
   purely as a comment.  Each time a service/client for a protocol is updated while supporting the same
   set of protocol versions, the revision should be increased.
   In rare cases, the revision number can be used to work around unintended breakage in deployed
   versions of a service.  This is discouraged and should only be used in exceptional situations.
3. The ``age`` number.  This non-zero integer identifies with how many previous protocol versions this
   implementation is compatible.  An ``age`` of 0 implies that the implementation only supports
   the ``current`` protocol version.  The ``age`` must be less or equal than the ``current`` protocol version.

To avoid confusion with semantic versions, the protocol version range is written down in the following format:

.. code:: none

  current[:revision[:age]]

The angle brackets mark optional components. If either ``revision`` or ``age`` are omitted, they default to 0.

Examples:

* "1" and "1" are compatible
* "1" and "2" are **incompatible**
* "2:0:1" and "1:0:0" are compatible
* "2:5:1" and "1:10:0" are compatible
* "4:0:1" and "2:0:0" are **incompatible**
* "4:0:1" and "3:0:0" are compatible

.. note::

  `Semantic versions <https://semver.org/>`__ are not a good tool for this job, as we concisely want to express
  that the client/server supports the last ``n`` versions of the protocol.
  Semantic versions don't support this, and semantic version ranges are too complex for this.

.. warning::

  A client doesn't have one single protocol version range.  Instead, it has
  a protocol version range for each type of service it talks to.

.. warning::

  For privacy reasons, the protocol version range of a client should not be
  sent to the service.  Instead, the client should just use the two version ranges
  to decide whether it will talk to the service.


.. _encodings-ref:

----------------
Common encodings
----------------

This section describes how certain types of values are represented throughout the API.

.. _base32:

Binary Data
^^^^^^^^^^^

.. ts:def:: foobase

  type Base32 = string;

Binary data is generally encoded using Crockford's variant of Base32
(http://www.crockford.com/wrmg/base32.html), except that "U" is not excluded
but also decodes to "V" to make OCR easy.  We will still simply use the JSON
type "base32" and the term "Crockford Base32" in the text to refer to the
resulting encoding.


Hash codes
^^^^^^^^^^
Hash codes are strings representing base32 encoding of the respective
hashed data. See `base32`_.

.. ts:def:: HashCode

  // 64-byte hash code.
  type HashCode = string;

.. ts:def:: ShortHashCode

  // 32-byte hash code.
  type ShortHashCode = string;



Large numbers
^^^^^^^^^^^^^

Large numbers such as 256 bit keys, are transmitted as other binary data in
Crockford Base32 encoding.


Timestamps
^^^^^^^^^^

Timestamps are represented by the following structure:

.. ts:def:: Timestamp

  interface Timestamp {
    // Milliseconds since epoch, or the special
    // value "never" to represent an event that will
    // never happen.
    t_ms: number | "never";
  }

.. ts:def:: RelativeTime

  interface Duration {
    // Duration in milliseconds or "forever"
    // to represent an infinite duration.
    d_ms: number | "forever";
  }


.. _public\ key:


Integers
^^^^^^^^

.. ts:def:: Integer

  // JavaScript numbers restricted to integers.
  type Integer = number;

Objects
^^^^^^^

.. ts:def:: Object

  // JavaScript objects, no further restrictions.
  type Object = object;

Keys
^^^^

.. ts:def:: EddsaPublicKey

   // EdDSA and ECDHE public keys always point on Curve25519
   // and represented  using the standard 256 bits Ed25519 compact format,
   // converted to Crockford `Base32`.
   type EddsaPublicKey = string;

.. ts:def:: EddsaPrivateKey

   // EdDSA and ECDHE public keys always point on Curve25519
   // and represented  using the standard 256 bits Ed25519 compact format,
   // converted to Crockford `Base32`.
   type EddsaPrivateKey = string;

.. ts:def:: ANASTASIS_PaymentSecretP

   // Random identifier used to later charge a payment.
   // Always 256 bits of binary data, converted to Crockford `Base32`.
   type EddsaPrivateKey = string;

.. _signature:

Signatures
^^^^^^^^^^


.. ts:def:: EddsaSignature

  // EdDSA signatures are transmitted as 64-bytes `base32`
  // binary-encoded objects with just the R and S values (base32_ binary-only).
  type EddsaSignature = string;

.. _amount:

Amounts
^^^^^^^

.. ts:def:: Amount

  type Amount = string;

Amounts of currency are serialized as a string of the format
``<Currency>:<DecimalAmount>``.  Taler treats monetary amounts as
fixed-precision numbers, with 8 decimal places.  Unlike floating point numbers,
this allows accurate representation of monetary amounts.

The following constrains apply for a valid amount:

1. The ``<Currency>`` part must be at most 11 characters long and may only consist
   of ASCII letters (``a-zA-Z``).
2. The integer part of ``<DecimalAmount>`` may be at most 2^52.
3. The fractional part of ``<DecimalAmount>`` may contain at most 8 decimal digits.

.. note::

  "EUR:1.50" and "EUR:10" are valid amounts.  These are all invalid amounts: "A:B:1.5", "EUR:4503599627370501.0", "EUR:1.", "EUR:.1".

An amount that is prefixed with a ``+`` or ``-`` character is also used in certain contexts.
When no sign is present, the amount is assumed to be positive.


Time
^^^^

In signed messages, time is represented using 64-bit big-endian values,
denoting microseconds since the UNIX Epoch.  ``UINT64_MAX`` represents "never".

.. sourcecode:: c

  struct GNUNET_TIME_Absolute {
    uint64_t timestamp_us;
  };
  struct GNUNET_TIME_AbsoluteNBO {
    uint64_t abs_value_us__;       // in network byte order
  };
  struct GNUNET_TIME_Timestamp {
    // must be round value (multiple of seconds)
    struct GNUNET_TIME_Absolute abs_time;
  };
  struct GNUNET_TIME_TimestampNBO {
    // must be round value (multiple of seconds)
    struct GNUNET_TIME_AbsoluteNBO abs_time;
  };

Cryptographic primitives
^^^^^^^^^^^^^^^^^^^^^^^^

All elliptic curve operations are on Curve25519.  Public and private keys are
thus 32 bytes, and signatures 64 bytes.  For hashing, including HKDFs, Taler
uses 512-bit hash codes (64 bytes).

.. sourcecode:: c

   struct GNUNET_HashCode {
     uint8_t hash[64];      // usually SHA-512
   };

.. _TALER_EcdhEphemeralPublicKeyP:
.. sourcecode:: c

   struct TALER_EcdhEphemeralPublicKeyP {
     uint8_t ecdh_pub[32];
   };

.. _ANASTASIS_TruthKeyP:
.. sourcecode:: c

   struct ANASTASIS_TruthKeyP {
     struct GNUNET_HashCode key;
   };

.. sourcecode:: c

   struct UUID {
     uint32_t value[4];
   };

.. _Signatures:

Signatures
^^^^^^^^^^
Any piece of signed data, complies to the abstract data structure given below.

.. sourcecode:: c

  struct Data {
    struct GNUNET_CRYPTO_EccSignaturePurpose purpose;
    type1_t payload1;
    type2_t payload2;
    ...
  };

  /*From gnunet_crypto_lib.h*/
  struct GNUNET_CRYPTO_EccSignaturePurpose {
    /**

    The following constraints apply for a valid amount:

     * This field is used to express the context in
     * which the signature is made, ensuring that a
     * signature cannot be lifted from one part of the protocol
     * to another. See `src/include/taler_signatures.h` within the
     * exchange's codebase (git://taler.net/exchange).
     */
    uint32_t purpose;
    /**
     * This field equals the number of bytes being signed,
     * namely 'sizeof (struct Data)'.
     */
    uint32_t size;
  };


.. _salt:
.. _config:


-----------------------
Receiving Configuration
-----------------------

.. http:get:: /config

  Obtain the configuration details of the escrow provider.
  This specification corresponds to ``current`` protocol being version **2**.

  **Response:**

  Returns an `EscrowConfigurationResponse`_.


  .. _EscrowConfigurationResponse:
  .. ts:def:: EscrowConfigurationResponse

    interface EscrowConfigurationResponse {

      // Protocol identifier, clarifies that this is an Anastasis provider.
      name: "anastasis";

      // libtool-style representation of the Exchange protocol version, see
      // https://www.gnu.org/software/libtool/manual/html_node/Versioning.html#Versioning
      // The format is "current:revision:age".
      version: string;

      // Release version of the source code.
      // The format is MAJOR.MINOR.MICOR[-GITDATA]
      // and generally follows the "-v" option of the codebase.
      // Since **v2**.
      build_version: string;

      // URN of the implementation (needed to interpret 'revision' in version).
      // @since v0, may become mandatory in the future.
      implementation?: string;

      // Name of the business operating the service (for display to the user).
      business_name?: string;

      // Supported authorization methods.
      methods: AuthorizationMethodConfig[];

      // Maximum policy upload size supported.
      storage_limit_in_megabytes: number;

      // Payment required to maintain an account to store policy documents for a year.
      // Users can pay more, in which case the storage time will go up proportionally.
      annual_fee: Amount;

      // Payment required to upload truth.  To be paid per upload.
      truth_upload_fee: Amount;

      // Limit on the liability that the provider is offering with
      // respect to the services provided.
      liability_limit: Amount;

      // Salt value with 128 bits of entropy.
      // Different providers
      // will use different high-entropy salt values. The resulting
      // **provider salt** is then used in various operations to ensure
      // cryptographic operations differ by provider.  A provider must
      // never change its salt value.
      provider_salt: string;

    }

  .. _AuthorizationMethodConfig:
  .. ts:def:: AuthorizationMethodConfig

    interface AuthorizationMethodConfig {
      // Name of the authorization method.
      type: string;

      // Fee for accessing key share using this method.
      cost: Amount;

    }

.. _terms:

--------------------------
Receiving Terms of Service
--------------------------

.. http:get:: /terms

  Obtain the terms of service provided by the escrow provider.

  **Response:**

  Returns the terms of service of the provider, in the best language
  and format available based on the client's request.

.. http:get:: /privacy

  Obtain the privacy policy of the service provided by the escrow provider.

  **Response:**

  Returns the privacy policy of the provider, in the best language
  and format available based on the client's request.


.. _manage-policy:


---------------
Managing policy
---------------

This API is used by the Anastasis client to deposit or request encrypted
recovery documents with the escrow provider.  Generally, a client will deposit
the same encrypted recovery document with each escrow provider, but provide
a different truth to each escrow provider.

Operations by the client are identified and authorized by ``$ACCOUNT_PUB``, which
should be kept secret from third parties. ``$ACCOUNT_PUB`` should be an account
public key using the Crockford base32-encoding.

In the following, UUID is always defined and used according to `RFC 4122`_.

.. _`RFC 4122`: https://tools.ietf.org/html/rfc4122

.. http:get:: /policy/$ACCOUNT_PUB/meta[?max_version=$NUMBER]

  Get meta data about a customer's encrypted recovery documents.
  If ``max_version`` is specified, only return results up to the
  given version number. The response may not contain meta data
  for all versions if there are way too many. In this case,
  ``max_version`` must be used to incrementally fetch more versions.

  **Response**:

  :http:statuscode:`200 OK`:
    The escrow provider responds with a RecoveryMetaSummary_ object.
  :http:statuscode:`400 Bad request`:
    The ``$ACCOUNT_PUB`` is not an EdDSA public key.
  :http:statuscode:`402 Payment Required`:
    The account's balance is too low for the specified operation.
    See the Taler payment protocol specification for how to pay.
  :http:statuscode:`404 Not found`:
    The requested resource was not found.

  **Details:**

  .. _RecoveryMetaSummary:
  .. ts:def:: RecoveryMetaSummary

    interface RecoveryMetaSummary {
      // Version numbers as a string (!) are used as keys.
      "$VERSION": MetaData;
    }

    interface MetaData {
      // The meta value can be NULL if the document
      // exists but no meta data was provided.
      meta: string;

      // Server-time indicative of when the recovery
      // document was uploaded.
      upload_time: Timestamp;
    }

  .. note::

    Both the version numbers used as keys and the ``upload_time`` are stated by
    the provider and are not covered by any signature.  See the warning under
    ``GET /policy/$ACCOUNT_PUB`` below before using either of them to decide
    which recovery document is the most recent one.

.. http:get:: /policy/$ACCOUNT_PUB[?version=$NUMBER]

  Get the customer's encrypted recovery document.  If ``version``
  is not specified, the server returns the latest available version.  If
  ``version`` is specified, returns the policy with the respective
  ``version``.  The response must begin with the nonce and
  an AES-GCM tag and continue with the ciphertext.  Once decrypted, the
  plaintext is expected to contain:

  * the escrow policy
  * the separately encrypted master public key

  Note that the key shares required to decrypt the master public key are
  not included, as for this the client needs to obtain authorization.
  The policy does provide sufficient information for the client to determine
  how to authorize requests for **truth**.

  The client MAY provide an ``If-None-Match`` header with an Etag.
  In that case, the server MUST additionally respond with an ``304`` status
  code in case the resource matches the provided Etag.

  **Response**:

  :http:statuscode:`200 OK`:
    The escrow provider responds with an EncryptedRecoveryDocument_ object.
  :http:statuscode:`304 Not modified`:
    The client requested the same resource it already knows.
  :http:statuscode:`400 Bad request`:
    The ``$ACCOUNT_PUB`` is not an EdDSA public key.
  :http:statuscode:`402 Payment Required`:
    The account's balance is too low for the specified operation.
    See the Taler payment protocol specification for how to pay.
  :http:statuscode:`404 Not found`:
    The requested resource was not found.

  *Anastasis-Version*: $NUMBER --- The server must return actual version of the encrypted recovery document via this header.
  If the client specified a version number in the header of the request, the server must return that version. If the client
  did not specify a version in the request, the server returns latest version of the EncryptedRecoveryDocument_.

  .. warning::

    The version number is **not** authenticated.  The ``Anastasis-Policy-Signature``
    of the upload covers the hash of the body and nothing else, so a provider can
    serve an older but perfectly well-signed recovery document while labelling it
    with any version number it likes, and it can withhold newer versions entirely.
    Clients MUST NOT treat the version --- or the ``upload_time`` reported by the
    ``/meta`` endpoint --- as a trustworthy statement about which document is the
    most recent one.  A client SHOULD still refuse a response whose version does
    not match the version it explicitly asked for, as that is a mismatch it can
    detect locally.

    This is an accepted limitation of the protocol, not an oversight: the version
    is assigned by the provider *after* the upload, so a client cannot sign a
    value it does not choose.  Version numbers are also assigned per provider, so
    the same document may well carry different version numbers at different
    providers.  A client that needs to determine which of several backups is the
    newest should place a timestamp, or a comparable ordering value, **inside**
    the recovery document, where it is covered by the account signature and can
    be compared across providers.

  *Etag*: Set by the server to the Base32-encoded SHA512 hash of the body. Used for caching and to prevent redundancies. The server MUST send the Etag if the status code is ``200 OK``.

  *If-None-Match*: If this is not the very first request of the client, this contains the Etag-value which the client has received before from the server.
  The client SHOULD send this header with every request (except for the first request) to avoid unnecessary downloads.


.. http:post:: /policy/$ACCOUNT_PUB

  Upload a new version of the customer's encrypted recovery document.
  While the document's structure is described in JSON below, the upload
  should just be the bytestream of the raw data (i.e. 32-byte nonce followed
  by 16-byte tag followed by the encrypted document).
  If the request has been seen before, the server should do nothing, and otherwise store the new version.
  The body must begin with a nonce, an AES-GCM tag and continue with the ciphertext.  The format
  is the same as specified for the response of the GET method. The
  Anastasis server cannot fully validate the format, but MAY impose
  minimum and maximum size limits.

  **Request**:

  :query storage_duration=YEARS:
     For how many years from now would the client like us to
     store the recovery document? Defaults to 0 (that is, do
     not extend / prolong existing storage contract).
     The server will respond with a ``402 Payment required``, but only
     if the rest of the request is well-formed (account
     signature must match).  Clients that do not actually
     intend to make a new upload but that only want to pay
     may attempt to upload the latest backup again, as this
     option will be checked before the ``304 Not modified``
     case.
  :query timeout_ms=NUMBER: *Optional.*  If specified, the Anastasis server will
    wait up to ``timeout_ms`` milliseconds for completion of the payment before
    sending the HTTP response.  A client must never rely on this behavior, as the
    backend may return a response immediately. If a ``timeout_ms`` is not given, the Anastasis server may apply a default timeout (usually 30s) when talking to the merchant backend.

  *If-None-Match*: This header MUST be present and set to the SHA512 hash (Etag) of the body by the client.
  The client SHOULD also set the ``Expect: 100-Continue`` header and wait for ``100 continue``
  before uploading the body.  The server MUST
  use the Etag to check whether it already knows the encrypted recovery document that is about to be uploaded.
  The server MUST refuse the upload with a ``304`` status code if the Etag matches
  the latest version already known to the server.

  *Anastasis-Policy-Meta-Data*: Encrypted meta data to be stored by the server and returned with the respective endpoint to provide an overview of the available policies. Encrypted using a random nonce and a key derived from the user ID using the salt "rmd". The plaintext metadata must consist of the policy hash (for deduplication) and the (human readable) secret name.

  *Anastasis-Policy-Signature*: The client must provide Base-32 encoded EdDSA signature over hash of body with ``$ACCOUNT_PRIV``, affirming desire to upload an encrypted recovery document.

  *Payment-Identifier*: Base-32 encoded 32-byte payment identifier that was included in a previous payment (see ``402`` status code). Used to allow the server to check that the client paid for the upload (to protect the server against DoS attacks) and that the client knows a real secret of financial value (as the **kdf_id** might be known to an attacker). If this header is missing in the client's request (or the associated payment has exceeded the upload limit), the server must return a ``402`` response.  When making payments, the server must include a fresh, randomly-generated payment-identifier in the payment request.  If a payment identifier is given, the Anastasis backend may block for the payment to be confirmed by Taler as specified by the ``timeout_ms`` argument.

  **Response**:

  :http:statuscode:`204 No content`:
    The encrypted recovery document was accepted and stored.  ``Anastasis-Version``
    indicates what version was assigned to this encrypted recovery document upload by the server.
    ``Anastasis-Policy-Expiration`` indicates the time until the server promises to store the policy,
    in seconds since epoch.
  :http:statuscode:`304 Not modified`:
    The same encrypted recovery document was previously accepted and stored.  ``Anastasis-Version`` header
    indicates what version was previously assigned to this encrypted recovery document.
  :http:statuscode:`400 Bad request`:
    The ``$ACCOUNT_PUB`` is not an EdDSA public key or mandatory headers are missing.
    The response body MUST elaborate on the error using a Taler error code in the typical JSON encoding.
  :http:statuscode:`402 Payment required`:
    The account's balance is too low for the specified operation.
    See the Taler payment protocol specification for how to pay.
    The response body MAY provide alternative means for payment.
  :http:statuscode:`403 Forbidden`:
    The required account signature was invalid.  The response body may elaborate on the error.
  :http:statuscode:`413 Request entity too large`:
    The upload is too large *or* too small. The response body may elaborate on the error.

  **Details:**

  .. _EncryptedRecoveryDocument:
  .. ts:def:: EncryptedRecoveryDocument

    interface EncryptedRecoveryDocument {
      // Nonce used to compute the (iv,key) pair for encryption of the
      // encrypted_compressed_recovery_document.
      nonce: [32]; //bytearray

      // Authentication tag.
      aes_gcm_tag: [16]; //bytearray

      // Variable-size encrypted recovery document. After decryption,
      // this contains a gzip compressed JSON-encoded `RecoveryDocument`.
      // The salt of the HKDF for this encryption must include the
      // string "erd".
      encrypted_compressed_recovery_document: []; //bytearray of undefined length

    }

  .. _RecoveryDocument:
  .. ts:def:: RecoveryDocument

    interface RecoveryDocument {
      // Human-readable name of the secret
      secret_name?: string;

      // Encrypted core secret.
      encrypted_core_secret: string; // bytearray of undefined length

      // List of escrow providers and selected authentication method.
      escrow_methods: EscrowMethod[];

      // List of possible decryption policies.
      policies: DecryptionPolicy[];

    }

  .. _EscrowMethod:
  .. ts:def:: EscrowMethod

    interface EscrowMethod {
      // URL of the escrow provider (including possibly this Anastasis server).
      url : string;

      // Type of the escrow method (e.g. security question, SMS etc.).
      escrow_type: string;

      // UUID of the escrow method (see /truth/ API below).
      uuid: string;

      // Key used to encrypt the `Truth` this `EscrowMethod` is related to.
      // Client has to provide this key to the server when using ``/truth/``.
      truth_key: [32]; //bytearray

      // Salt used to hash the security answer if appliccable.
      question_salt: [32]; //bytearray

      // Salt from the provider to derive the user ID
      // at this provider.
      provider_salt: [32]; //bytearray

      // The instructions to give to the user (i.e. the security question
      // if this is challenge-response).
      // (Q: as string in base32 encoding?)
      // (Q: what is the mime-type of this value?)
      //
      // The plaintext challenge is not revealed to the
      // Anastasis server.
      instructions: string;

    }

  .. _DecryptionPolicy:
  .. ts:def:: DecryptionPolicy

    interface DecryptionPolicy {
      // Salt included to encrypt master key share when
      // using this decryption policy.
      master_salt: [32]; //bytearray

      // Master key, AES-encrypted with key derived from
      // salt and keyshares revealed by the following list of
      // escrow methods identified by UUID.
      master_key: [32]; //bytearray

      // List of escrow methods identified by their UUID.
      uuids: string[];

    }

.. _Truth:

--------------
Managing truth
--------------

Truth always consists of an encrypted key share and encrypted
authentication data.  The key share and the authentication data
are encrypted using different keys. Additionally, truth includes
the name of the authentication method, the mime-type of the
authentication data, and an expiration time in
cleartext.

This API is used by the Anastasis client to deposit **truth** or request a (encrypted) **key share** with
the escrow provider.

An **escrow method** specifies an Anastasis provider and how the user should
authorize themself.  The **truth** API allows the user to provide the
(encrypted) key share to the respective escrow provider, as well as auxiliary
data required for such a respective escrow method.

An Anastasis-server may store truth for free for a certain time period, or
charge per truth operation using GNU Taler.

.. http:post:: /truth/$UUID

  **Request:**

  Upload a `TruthUploadRequest`-Object according to the policy the client created before (see `RecoveryDocument`_).
  If request has been seen before, the server should do nothing, and otherwise store the new object.


  :query timeout_ms=NUMBER: *Optional.*  If specified, the Anastasis server will
    wait up to ``timeout_ms`` milliseconds for completion of the payment before
    sending the HTTP response.  A client must never rely on this behavior, as the
    backend may return a response immediately.

  **Response:**

  :http:statuscode:`204 No content`:
    Truth stored successfully.
  :http:statuscode:`304 Not modified`:
    The same truth was previously accepted and stored under this UUID.  The
    Anastasis server must still update the expiration time for the truth when returning
    this response code.
  :http:statuscode:`402 Payment required`:
    This server requires payment to store truth per item.
    See the Taler payment protocol specification for how to pay.
    The response body MAY provide alternative means for payment.
  :http:statuscode:`409 Conflict`:
    The server already has some truth stored under this UUID. The client should check that it
    is generating UUIDs with enough entropy.
  :http:statuscode:`412 Precondition failed`:
    The selected authentication method is not supported on this provider.


  **Details:**

  .. _TruthUploadRequest:
  .. ts:def:: TruthUploadRequest

    interface TruthUploadRequest {
      // Contains the information of an interface `EncryptedKeyShare`, but simply
      // as one binary block (in Crockford Base32 encoding for JSON).
      key_share_data: []; //bytearray

      // Key share method, i.e. "security question", "SMS", "e-mail", ...
      type: string;

      // Variable-size truth. After decryption,
      // this contains the ground truth, i.e. H(challenge answer),
      // phone number, e-mail address, picture, fingerprint, ...
      // **base32 encoded**.
      //
      // The nonce of the HKDF for this encryption must include the
      // string "ECT".
      encrypted_truth: []; //bytearray

      // MIME type of truth, i.e. text/ascii, image/jpeg, etc.
      truth_mime?: string;

      // For how many years from now would the client like us to
      // store the truth?
      storage_duration_years: number;

    }


  .. http:post:: /truth/$UUID/solve

  Solve the challenge and get the stored encrypted key share.
  Also, the user has to provide the correct *truth_encryption_key* with the request (see below).
  The encrypted key share is returned simply as a byte array and not in JSON format.

  **Request**:

   Upload a `TruthSolutionRequest`_-Object.

   :query timeout_ms=NUMBER: *Optional.*  If specified, the Anastasis server will
    wait up to ``timeout_ms`` milliseconds for completion of the payment or the
    challenge before sending the HTTP response.  A client must never rely on this
    behavior, as the backend may return a response immediately.

  **Response**:

  :http:statuscode:`200 OK`:
    `EncryptedKeyShare`_ is returned in body (in binary).
  :http:statuscode:`402 Payment required`:
    The service requires payment for access to truth.
    See the Taler payment protocol specification for how to pay.
    The response body MAY provide alternative means for payment.
  :http:statuscode:`403 Forbidden`:
    The ``$H_RESPONSE`` provided is not a good response to the challenge associated
    with the UUID, or at least the answer is not valid yet.  A generic
    response is provided with an error code.
  :http:statuscode:`404 Not found`:
    The server does not know any truth under the given UUID.
  :http:statuscode:`429 Too Many Requests`:
    The client exceeded the number of allowed attempts at providing
    a valid response for the given time interval.
    The response format is given by `RateLimitedMessage`_.
  :http:statuscode:`503 Service Unavailable`:
    Server is out of Service.

  **Details:**

  .. _TruthSolutionRequest:
  .. ts:def:: TruthSolutionRequest

    interface TruthSolutionRequest {

       // Hash over the response that solves the challenge
       // issued for this truth.  This can be the
       // hash of the security question (as specified before by the client
       // within the `TruthUploadRequest` (see ``encrypted_truth``)), or the hash of the
       // PIN code sent via SMS, E-mail or postal communication channels.
       // Only when ``$H_RESPONSE`` is correct, the server responds with the encrypted key share.
       h_response: HashCode;

       // Key that was used to encrypt the **truth** (see encrypted_truth within `TruthUploadRequest`)
       // and which has to provided by the user. The key is stored with
       // the according `EscrowMethod`. The server needs this key to get the
       // info out of `TruthUploadRequest` to verify the ``$H_RESPONSE``.
       truth_decryption_key: ANASTASIS_TruthKeyP;

       // Reference to a payment made by the client to
       // pay for this request. Optional.
       payment_secret?: ANASTASIS_PaymentSecretP;
    }


  .. _EncryptedKeyShare:
  .. ts:def:: EncryptedKeyShare

    interface EncryptedKeyShare {
      // Nonce used to compute the decryption (iv,key) pair.
      nonce_i: [32]; //bytearray

      // Authentication tag.
      aes_gcm_tag_i: [16]; //bytearray

      // Encrypted key-share in base32 encoding.
      // After decryption, this yields a `KeyShare`.  Note that
      // the `KeyShare` MUST be encoded as a fixed-size binary
      // block (instead of in JSON encoding).
      //
      // HKDF for the key generation must include the
      // string "eks" as salt.
      // Depending on the method,
      // the HKDF may additionally include
      // bits from the response (i.e. some hash over the
      // answer to the security question).
      encrypted_key_share_i: [32]; //bytearray

    }

  .. _KeyShare:
  .. ts:def:: KeyShare

    interface KeyShare {
      // Key material to derive the key to decrypt the master key.
      key_share: [32]; //bytearray
    }


  .. _RateLimitedMessage:
  .. ts:def:: RateLimitedMessage

    interface RateLimitedMessage {

      // Taler error code, TALER_EC_ANASTASIS_TRUTH_RATE_LIMITED.
      code: number;

      // How many attempts are allowed per challenge?
      request_limit: number;

      // At what frequency are new challenges issued?
      request_frequency: RelativeTime;

      // The error message.
      hint: string;

    }


  .. http:post:: /truth/$UUID/challenge

  NEW API (#7064):

  Initiate process to solve challenge associated with the given truth object.

  **Request**:

   Upload a `TruthChallengeRequest`_-Object.

  **Response**:

  :http:statuscode:`200 Ok`:
    The escrow provider will respond out-of-band (i.e. SMS).
    The body may contain human- or machine-readable instructions on next steps.
    In case the response is in JSON, the format is given
    by `ChallengeInstructionMessage`_.
  :http:statuscode:`402 Payment required`:
    The service requires payment to issue a challenge.
    See the Taler payment protocol specification for how to pay.
    The response body MAY provide alternative means for payment.
  :http:statuscode:`403 Forbidden`:
    This type of truth does not permit requests to trigger a challenge.
    This is the case for security questions and TOTP methods.
  :http:statuscode:`404 Not found`:
    The server does not know any truth under the given UUID.
  :http:statuscode:`424 Failed Dependency`:
    The decrypted ``truth`` does not match the expectations of the authentication
    backend, i.e. a phone number for sending an SMS is not a number, or
    an e-mail address for sending an E-mail is not a valid e-mail address.
  :http:statuscode:`503 Service Unavailable`:
    Server is out of Service.

  **Details:**

  .. _TruthChallengeRequest:
  .. ts:def:: TruthChallengeRequest

    interface TruthChallengeRequest {

       // Key that was used to encrypt the **truth** (see encrypted_truth within `TruthUploadRequest`)
       // and which has to provided by the user. The key is stored with
       // the according `EscrowMethod`. The server needs this key to get the
       // info out of `TruthUploadRequest` to verify the ``$H__RESPONSE``.
       truth_decryption_key: ANASTASIS_TruthKeyP;

       // Reference to a payment made by the client to
       // pay for this request. Optional.
       payment_secret?: ANASTASIS_PaymentSecretP;
    }


  .. _ChallengeInstructionMessage:
  .. ts:def:: ChallengeInstructionMessage

    type ChallengeInstructionMessage =
      | FileChallengeInstructionMessage
      | IbanChallengeInstructionMessage
      | PinChallengeInstructionMessage;

  .. _IbanChallengeInstructionMessage:
  .. ts:def:: IbanChallengeInstructionMessage

    interface IbanChallengeInstructionMessage {

      // What kind of challenge is this?
      method: "IBAN_WIRE";

      // How much should be wired?
      amount: Amount;

      // What is the target IBAN?
      credit_iban: string;

      // What is the receiver name?
      business_name: string;

      // What is the expected wire transfer subject?
      wire_transfer_subject: string;

      // What is the numeric code (also part of the
      // wire transfer subject) to be hashed when
      // solving the challenge?
      answer_code: number;

      // Hint about the origin account that must be used.
      debit_account_hint: string;

    }

  .. _PinChallengeInstructionMessage:
  .. ts:def:: PinChallengeInstructionMessage

    interface PinChallengeInstructionMessage {

      // What kind of challenge is this?
      method: "TAN_SENT";

      // Where was the PIN code sent? Note that this
      // address will most likely have been obscured
      // to improve privacy.
      tan_address_hint: string;

    }

  .. _FileChallengeInstructionMessage:
  .. ts:def:: FileChallengeInstructionMessage

    interface FileChallengeInstructionMessage {

      // What kind of challenge is this?
      method: "FILE_WRITTEN";

      // Name of the file where the PIN code was written.
      filename: string;

    }
