/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "nsISupports.idl"

interface nsIArray;
interface nsIX509Cert;
interface nsIFile;
interface nsIInterfaceRequestor;
interface nsIZipReader;
interface nsIX509CertList;
interface nsIInputStream;

%{C++
#define NS_X509CERTDB_CONTRACTID "@mozilla.org/security/x509certdb;1"
%}

typedef uint32_t AppTrustedRoot;

[scriptable, function, uuid(fc2b60e5-9a07-47c2-a2cd-b83b68a660ac)]
interface nsIOpenSignedAppFileCallback : nsISupports
{
  void openSignedAppFileFinished(in nsresult rv,
                                 in nsIZipReader aZipReader,
                                 in nsIX509Cert aSignerCert);
};

[scriptable, function, uuid(d5f97827-622a-488f-be08-d850432ac8ec)]
interface nsIVerifySignedDirectoryCallback : nsISupports
{
  void verifySignedDirectoryFinished(in nsresult rv,
                                     in nsIX509Cert aSignerCert);
};

/**
 * Callback type for use with asyncVerifyCertAtTime.
 * If aPRErrorCode is PRErrorCodeSuccess (i.e. 0), aVerifiedChain represents the
 * verified certificate chain determined by asyncVerifyCertAtTime. aHasEVPolicy
 * represents whether or not the end-entity certificate verified as EV.
 * If aPRErrorCode is non-zero, it represents the error encountered during
 * verification. aVerifiedChain is null in that case and aHasEVPolicy has no
 * meaning.
 */
[scriptable, function, uuid(49e16fc8-efac-4f57-8361-956ef6b960a4)]
interface nsICertVerificationCallback : nsISupports {
  void verifyCertFinished(in int32_t aPRErrorCode,
                          in nsIX509CertList aVerifiedChain,
                          in bool aHasEVPolicy);
};

/**
 * This represents a service to access and manipulate
 * X.509 certificates stored in a database.
 */
[scriptable, uuid(5c16cd9b-5a73-47f1-ab0f-11ede7495cce)]
interface nsIX509CertDB : nsISupports {

  /**
   *  Constants that define which usages a certificate
   *  is trusted for.
   */
  const unsigned long UNTRUSTED       =      0;
  const unsigned long TRUSTED_SSL     = 1 << 0;
  const unsigned long TRUSTED_EMAIL   = 1 << 1;
  const unsigned long TRUSTED_OBJSIGN = 1 << 2;

  /**
   *  Will find a certificate based on its dbkey
   *  retrieved by getting the dbKey attribute of
   *  the certificate.
   *
   *  @param aDBkey Database internal key, as obtained using
   *                attribute dbkey in nsIX509Cert.
   */
  [must_use]
  nsIX509Cert findCertByDBKey(in ACString aDBkey);

  /**
   *  Find a certificate by email address.
   *
   *  @param aEmailAddress The email address to be used as the key
   *                       to find the certificate.
   *
   *  @return The matching certificate if found.
   */
  [must_use]
  nsIX509Cert findCertByEmailAddress(in ACString aEmailAddress);

  /**
   *  Use this to import a stream sent down as a mime type into
   *  the certificate database on the default token.
   *  The stream may consist of one or more certificates.
   *
   *  @param data The raw data to be imported
   *  @param length The length of the data to be imported
   *  @param type The type of the certificate, see constants in nsIX509Cert
   *  @param ctx A UI context.
   */
  void importCertificates([array, size_is(length)] in octet data,
                          in unsigned long length,
                          in unsigned long type,
                          in nsIInterfaceRequestor ctx);

  /**
   *  Import another person's email certificate into the database.
   *
   *  @param data The raw data to be imported
   *  @param length The length of the data to be imported
   *  @param ctx A UI context.
   */
  void importEmailCertificate([array, size_is(length)] in octet data,
                              in unsigned long length,
                              in nsIInterfaceRequestor ctx);

  /**
   *  Import a personal certificate into the database, assuming
   *  the database already contains the private key for this certificate.
   *
   *  @param data The raw data to be imported
   *  @param length The length of the data to be imported
   *  @param ctx A UI context.
   */
  void importUserCertificate([array, size_is(length)] in octet data,
                             in unsigned long length,
                             in nsIInterfaceRequestor ctx);

  /**
   *  Delete a certificate stored in the database.
   *
   *  @param aCert Delete this certificate.
   */
  void deleteCertificate(in nsIX509Cert aCert);

  /**
   *  Modify the trust that is stored and associated to a certificate within
   *  a database. Separate trust is stored for
   *  One call manipulates the trust for one trust type only.
   *  See the trust type constants defined within this interface.
   *
   *  @param cert Change the stored trust of this certificate.
   *  @param type The type of the certificate. See nsIX509Cert.
   *  @param trust A bitmask. The new trust for the possible usages.
   *               See the trust constants defined within this interface.
   */
  [must_use]
  void setCertTrust(in nsIX509Cert cert,
                    in unsigned long type,
                    in unsigned long trust);

  /**
   * @param cert        The certificate for which to modify trust.
   * @param trustString decoded by CERT_DecodeTrustString. 3 comma separated
   *                    characters, indicating SSL, Email, and Obj signing
   *                    trust.
   */
  [must_use]
  void setCertTrustFromString(in nsIX509Cert cert, in ACString trustString);

  /**
   *  Query whether a certificate is trusted for a particular use.
   *
   *  @param cert Obtain the stored trust of this certificate.
   *  @param certType The type of the certificate. See nsIX509Cert.
   *  @param trustType A single bit from the usages constants defined
   *                   within this interface.
   *
   *  @return Returns true if the certificate is trusted for the given use.
   */
  [must_use]
  boolean isCertTrusted(in nsIX509Cert cert,
                        in unsigned long certType,
                        in unsigned long trustType);

  /**
   *  Import certificate(s) from file
   *
   *  @param aFile Identifies a file that contains the certificate
   *               to be imported.
   *  @param aType Describes the type of certificate that is going to
   *               be imported. See type constants in nsIX509Cert.
   */
  [must_use]
  void importCertsFromFile(in nsIFile aFile,
                           in unsigned long aType);

  /**
   *  Import a PKCS#12 file containing cert(s) and key(s) into the database.
   *
   *  @param aFile Identifies a file that contains the data to be imported.
   */
  [must_use]
  void importPKCS12File(in nsIFile aFile);

  /**
   *  Export a set of certs and keys from the database to a PKCS#12 file.
   *
   *  @param aFile Identifies a file that will be filled with the data to be
   *               exported.
   *  @param count The number of certificates to be exported.
   *  @param aCerts The array of all certificates to be exported.
   */
  [must_use]
  void exportPKCS12File(in nsIFile aFile,
                        in unsigned long count,
                        [array, size_is(count)] in nsIX509Cert aCerts);

  /*
   *  Decode a raw data presentation and instantiate an object in memory.
   *
   *  @param base64 The raw representation of a certificate,
   *                encoded as Base 64.
   *  @return The new certificate object.
   */
  [must_use]
  nsIX509Cert constructX509FromBase64(in ACString base64);

  /*
   *  Decode a raw data presentation and instantiate an object in memory.
   *
   *  @param certDER The raw representation of a certificate,
   *                 encoded as raw DER.
   *  @return The new certificate object.
   */
  [must_use]
  nsIX509Cert constructX509(in ACString certDER);

  /**
   *  Verifies the signature on the given JAR file to verify that it has a
   *  valid signature.  To be considered valid, there must be exactly one
   *  signature on the JAR file and that signature must have signed every
   *  entry. Further, the signature must come from a certificate that
   *  is trusted for code signing.
   *
   *  On success, NS_OK, a nsIZipReader, and the trusted certificate that
   *  signed the JAR are returned.
   *
   *  On failure, an error code is returned.
   *
   *  This method returns a nsIZipReader, instead of taking an nsIZipReader
   *  as input, to encourage users of the API to verify the signature as the
   *  first step in opening the JAR.
   */
  // 1 used to be AppMarketplaceProdPublicRoot.
  // 2 used to be AppMarketplaceProdReviewersRoot.
  // 3 used to be AppMarketplaceDevPublicRoot.
  // 4 used to be AppMarketplaceDevReviewersRoot.
  // 5 used to be AppMarketplaceStageRoot.
  const AppTrustedRoot AppXPCShellRoot = 6;
  const AppTrustedRoot AddonsPublicRoot = 7;
  const AppTrustedRoot AddonsStageRoot = 8;
  const AppTrustedRoot PrivilegedPackageRoot = 9;
  /*
   * If DeveloperImportedRoot is set as trusted root, a CA from local file
   * system will be imported. Only used when preference
   * "network.http.packaged-apps-developer-mode" is set.
   * The path of the CA is specified by preference
   * "network.http.packaged-apps-developer-trusted-root".
   */
  const AppTrustedRoot DeveloperImportedRoot = 10;
  [must_use]
  void openSignedAppFileAsync(in AppTrustedRoot trustedRoot,
                              in nsIFile aJarFile,
                              in nsIOpenSignedAppFileCallback callback);

  /**
   *  Verifies the signature on a directory representing an unpacked signed
   *  JAR file. To be considered valid, there must be exactly one signature
   *  on the directory structure and that signature must have signed every
   *  entry. Further, the signature must come from a certificate that
   *  is trusted for code signing.
   *
   *  On success NS_OK and the trusted certificate that signed the
   *  unpacked JAR are returned.
   *
   *  On failure, an error code is returned.
   */
  [must_use]
  void verifySignedDirectoryAsync(in AppTrustedRoot trustedRoot,
                                  in nsIFile aUnpackedDir,
                                  in nsIVerifySignedDirectoryCallback callback);

  /*
   * Add a cert to a cert DB from a binary string.
   *
   * @param certDER The raw DER encoding of a certificate.
   * @param trust String describing the trust settings to assign the
   *              certificate. Decoded by CERT_DecodeTrustString. Consists of 3
   *              comma separated sets of characters, indicating SSL, Email, and
   *              Object signing trust.
   * @return nsIX509Cert the resulting certificate
   */
  [must_use]
  nsIX509Cert addCert(in ACString certDER, in ACString trust);

  // Flags for verifyCertNow (these must match the values in CertVerifier.cpp):
  // Prevent network traffic. Doesn't work with classic verification.
  const uint32_t FLAG_LOCAL_ONLY = 1 << 0;
  // Do not fall back to DV verification after attempting EV validation.
  // Actually does prevent network traffic, but can cause a valid EV
  // certificate to not be considered valid.
  const uint32_t FLAG_MUST_BE_EV = 1 << 1;

  /** Warning: This interface is inteded to use only for testing only as:
   *    1. It can create IO on the main thread.
   *    2. It is in constant change, so in/out can change at any release.
   *
   *  Obtain the verification result for a cert given a particular usage.
   *  On success, the call returns 0, the chain built during verification,
   *  and whether the cert is good for EV usage.
   *  On failure, the call returns the PRErrorCode for the verification failure
   *
   *  @param aCert Obtain the stored trust of this certificate
   *  @param aUsage a integer representing the usage from NSS
   *  @param aFlags flags as described above
   *  @param aHostname the (optional) hostname to verify for
   *  @param aTime the time at which to verify, in seconds since the epoch
   *  @param aVerifiedChain chain of verification up to the root if success
   *  @param aHasEVPolicy bool that signified that the cert was an EV cert
   *  @return 0 if success or the value or the error code for the verification
   *          failure
   */
  [must_use]
  int32_t /*PRErrorCode*/
    verifyCertAtTime(in nsIX509Cert aCert,
                     in int64_t /*SECCertificateUsage*/ aUsage,
                     in uint32_t aFlags,
                     in ACString aHostname,
                     in uint64_t aTime,
                     out nsIX509CertList aVerifiedChain,
                     out bool aHasEVPolicy);
  [must_use]
  int32_t /*PRErrorCode*/
    verifyCertNow(in nsIX509Cert aCert,
                  in int64_t /*SECCertificateUsage*/ aUsage,
                  in uint32_t aFlags,
                  in ACString aHostname,
                  out nsIX509CertList aVerifiedChain,
                  out bool aHasEVPolicy);

  /**
   * Similar to the above, but asynchronous. As a result, use of this API is not
   * limited to tests.
   */
  [must_use]
  void asyncVerifyCertAtTime(in nsIX509Cert aCert,
                             in int64_t /*SECCertificateUsage*/ aUsage,
                             in uint32_t aFlags,
                             in ACString aHostname,
                             in uint64_t aTime,
                             in nsICertVerificationCallback aCallback);

  // Clears the OCSP cache for the current certificate verification
  // implementation.
  [must_use]
  void clearOCSPCache();

  /*
   * Add a cert to a cert DB from a base64 encoded string.
   *
   * @param base64 The raw representation of a certificate, encoded as Base 64.
   * @param trust String describing the trust settings to assign the
   *              certificate. Decoded by CERT_DecodeTrustString. Consists of 3
   *              comma separated sets of characters, indicating SSL, Email, and
   *              Object signing trust.
   * @return nsIX509Cert the resulting certificate
   */
  [must_use]
  nsIX509Cert addCertFromBase64(in ACString base64, in ACString trust);

  /*
   * Get all the known certs in the database
   */
  [must_use]
  nsIX509CertList getCerts();

  /*
   * Get a list of imported enterprise root certificates (currently only
   * implemented on Windows).
   */
  [must_use]
  nsIX509CertList getEnterpriseRoots();
};
