├── .dockerignore ├── .eslintrc ├── .github └── dependabot.yml ├── .gitignore ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── Dockerfile ├── LICENSE.txt ├── README.md ├── build.sh ├── configUtils.sh ├── configuration-default ├── .gitignore ├── certificates │ ├── README.md │ └── internal_ca │ │ ├── README.md │ │ └── USERTrust_RSA_Certification_Authority.crt └── config.yml ├── default.env ├── diagram.png ├── nyc.config.js ├── reporter_config.json ├── runAll.sh ├── runQVS.sh ├── samples └── simple-signing-service │ ├── .gitignore │ ├── Dockerfile │ ├── README.md │ ├── build.sh │ ├── package.json │ ├── prepareCerts.sh │ ├── runSSS.sh │ ├── simple-signing-service.js │ ├── swagger.js │ └── swagger.json ├── security.md ├── src ├── bootstrap.js ├── clients │ ├── crlAccessLayer │ │ └── CRLClient.js │ ├── pcsAccessLayer │ │ └── PCSClient.js │ └── vcsAccessLayer │ │ └── VCSClient.js ├── common │ ├── RestClient.js │ ├── config.js │ ├── detailedErrorString.js │ ├── errorHandler.js │ ├── getCACertificatesSync.js │ ├── httpStatusCodes.js │ ├── logger.js │ ├── nodeRequestHandler.js │ ├── readFileSafely.js │ ├── requestHandler.js │ ├── requestLogFormatter.js │ ├── restClientErrors.js │ └── tlsType.js ├── configLoader.js ├── fips │ └── openssl.cnf ├── handlers │ ├── certificateChainParser.js │ ├── health.js │ └── verifyAttestationEvidence.js ├── healthChecker.js ├── jsDoc │ └── types.js ├── koa │ ├── commonDataValidator.js │ ├── errors.js │ ├── init │ │ └── serverInit.js │ ├── koaHealthCache.js │ ├── koaHealthRouter.js │ ├── maxClientsHandler.js │ ├── middleware │ │ ├── bodyParser.js │ │ ├── configureCtxLoggerAndLogResponse.js │ │ ├── errorHandler.js │ │ ├── rawBodyParser.js │ │ ├── requestBodyLogger.js │ │ ├── requestControl.js │ │ ├── requestId.js │ │ └── responseHandler.js │ └── response.js ├── logger.js ├── package.json ├── qvl │ ├── BaseWorker.cpp │ ├── BaseWorker.h │ ├── CMakeLists.txt │ ├── GetCertificationDataWorker.cpp │ ├── GetCertificationDataWorker.h │ ├── GetCrlDistributionPointWorker.cpp │ ├── GetCrlDistributionPointWorker.h │ ├── GetPckCertificateDataWorker.cpp │ ├── GetPckCertificateDataWorker.h │ ├── VerifyQuoteErrorSource.h │ ├── VerifyQuoteWorker.cpp │ ├── VerifyQuoteWorker.h │ ├── VersionWorker.cpp │ ├── VersionWorker.h │ ├── index.js │ ├── main.cpp │ ├── status.js │ └── verifyQuoteErrorSource.js ├── routes │ ├── health.js │ ├── index.js │ └── v1 │ │ └── verifyAttestationEvidence.js ├── server.js └── util │ ├── buffer.js │ ├── clone.js │ ├── jsonUtils.js │ ├── onelinerFormat.js │ ├── random.js │ └── responseUtils.js ├── swagger.json └── test ├── bootstrapTest.js ├── clients ├── CRLClientTest.js ├── PCSClientTest.js └── VCSClientTest.js ├── common ├── RestClientTest.js ├── configTest.js ├── getCACertificatesSyncTest.js ├── nodeRequestHandlerTest.js ├── readFileSafelyTest.js ├── requestHandlerTest.js ├── requestLogFormatterTest.js └── restClientErrorsTest.js ├── configLoaderTest.js ├── handlers ├── certificateChainParserTest.js ├── healthTest.js └── verifyAttestationEvidenceTest.js ├── healthCheckerTest.js ├── jsDoc └── typesTest.js ├── koa ├── errorTest.js ├── init │ ├── serverInitTest.js │ └── serverTerminationTest.js ├── koaHealthCacheTest.js ├── koaHealthRouterTest.js ├── maxClientsHandlerTest.js ├── middleware │ ├── bodyParserTest.js │ ├── configureCtxLoggerAndLogResponseTest.js │ ├── errorHandlerTest.js │ ├── rawBodyParserTest.js │ ├── requestBodyLoggerTest.js │ ├── requestControlTest.js │ ├── requestIdTest.js │ └── responseHandlerTest.js ├── mocks │ └── loggerMock.js └── responseTest.js ├── loggerTest.js ├── mocks └── helpers.js ├── package.json ├── qvl └── qvlTest.js ├── routes ├── KoaRouterMock.js ├── healthTest.js ├── routesTest.js └── verifyAttestationEvidenceTest.js ├── serverTest.js └── swagger.js /.dockerignore: -------------------------------------------------------------------------------- 1 | # 1. Ignore everything 2 | * 3 | 4 | # 2. Add files and directories that should be included 5 | !configuration-default 6 | !src 7 | !test 8 | !build/qvls 9 | !Dockerfile 10 | !nyc.config.js 11 | !.eslintrc 12 | !reporter_config.json 13 | 14 | # 3. Ignore unnecessary files inside allowed directories 15 | src/node_modules 16 | test/node_modules 17 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: "npm" 4 | directory: "src" 5 | schedule: 6 | interval: "daily" 7 | versioning-strategy: increase 8 | - package-ecosystem: "npm" 9 | directory: "test" 10 | schedule: 11 | interval: "daily" 12 | versioning-strategy: increase -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | build 2 | native 3 | src/qvl/cmake-* 4 | src/node_modules 5 | test/node_modules 6 | test/.nyc_output -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | ### License 4 | 5 | is licensed under the terms in [LICENSE]. By contributing to the project, you agree to the license and copyright terms therein and release your contribution under these terms. 6 | 7 | ### Sign your work 8 | 9 | Please use the sign-off line at the end of the patch. Your signature certifies that you wrote the patch or otherwise have the right to pass it on as an open-source patch. The rules are pretty simple: if you can certify 10 | the below (from [developercertificate.org](http://developercertificate.org/)): 11 | 12 | ``` 13 | Developer Certificate of Origin 14 | Version 1.1 15 | 16 | Copyright (C) 2004, 2006 The Linux Foundation and its contributors. 17 | 660 York Street, Suite 102, 18 | San Francisco, CA 94110 USA 19 | 20 | Everyone is permitted to copy and distribute verbatim copies of this 21 | license document, but changing it is not allowed. 22 | 23 | Developer's Certificate of Origin 1.1 24 | 25 | By making a contribution to this project, I certify that: 26 | 27 | (a) The contribution was created in whole or in part by me and I 28 | have the right to submit it under the open source license 29 | indicated in the file; or 30 | 31 | (b) The contribution is based upon previous work that, to the best 32 | of my knowledge, is covered under an appropriate open source 33 | license and I have the right under that license to submit that 34 | work with modifications, whether created in whole or in part 35 | by me, under the same open source license (unless I am 36 | permitted to submit under a different license), as indicated 37 | in the file; or 38 | 39 | (c) The contribution was provided directly to me by some other 40 | person who certified (a), (b) or (c) and I have not modified 41 | it. 42 | 43 | (d) I understand and agree that this project and the contribution 44 | are public and that a record of the contribution (including all 45 | personal information I submit with it, including my sign-off) is 46 | maintained indefinitely and may be redistributed consistent with 47 | this project or the open source license(s) involved. 48 | ``` 49 | 50 | Then you just add a line to every git commit message: 51 | 52 | Signed-off-by: Joe Smith 53 | 54 | Use your real name (sorry, no pseudonyms or anonymous contributions.) 55 | 56 | If you set your `user.name` and `user.email` git configs, you can sign your 57 | commit automatically with `git commit -s`. 58 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | BSD 3-Clause License 2 | 3 | Copyright (C) 2011-2024 Intel Corporation. All rights reserved. 4 | 5 | Redistribution and use in source and binary forms, with or without 6 | modification, are permitted provided that the following conditions 7 | are met: 8 | 9 | * Redistributions of source code must retain the above copyright 10 | notice, this list of conditions and the following disclaimer. 11 | * Redistributions in binary form must reproduce the above copyright 12 | notice, this list of conditions and the following disclaimer in 13 | the documentation and/or other materials provided with the 14 | distribution. 15 | * Neither the name of Intel Corporation nor the names of its 16 | contributors may be used to endorse or promote products derived 17 | from this software without specific prior written permission. 18 | 19 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 20 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 21 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 22 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 23 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 24 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 25 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 26 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 27 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 28 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 29 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 30 | 31 | 32 | ============================================================== 33 | 34 | SPDX-License-Identifier: BSD-3-Clause 35 | -------------------------------------------------------------------------------- /build.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # 4 | # Copyright (c) 2022, Intel Corporation 5 | # SPDX-License-Identifier: BSD-3-Clause 6 | # 7 | # Redistribution and use in source and binary forms, with or without 8 | # modification, are permitted provided that the following conditions are met: 9 | # 10 | # * Redistributions of source code must retain the above copyright notice, 11 | # this list of conditions and the following disclaimer. 12 | # * Redistributions in binary form must reproduce the above copyright notice, 13 | # this list of conditions and the following disclaimer in the documentation 14 | # and/or other materials provided with the distribution. 15 | # * Neither the name of Intel Corporation nor the names of its contributors 16 | # may be used to endorse or promote products derived from this software 17 | # without specific prior written permission. 18 | # 19 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 20 | # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 21 | # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 22 | # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 23 | # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 24 | # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 25 | # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 26 | # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 27 | # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 28 | # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 29 | # POSSIBILITY OF SUCH DAMAGE. 30 | # 31 | 32 | function fail { 33 | printf '%s\n' "$1" >&2 ## Send message to stderr. 34 | exit "${2-1}" ## Return a code specified by $2, or 1 by default. 35 | } 36 | 37 | # Get absolute path to the script itself 38 | SCRIPT_DIR="$(cd "$(dirname "$0")" || exit 1; pwd)" 39 | 40 | DEBUG=false 41 | OPTS=$(getopt -o "d" -l "debug" -n "$0" -- "$@") 42 | if [ $? != 0 ] ; then 43 | fail "Failed parsing args usage: build.sh [-d|--debug] [qvlPath]" 44 | fi 45 | eval set -- ${OPTS} 46 | while : 47 | do 48 | case $1 in 49 | -d | --debug) DEBUG=true; shift ;; 50 | --) shift; break ;; 51 | esac 52 | done 53 | 54 | # Check if QVL path has been provided 55 | QVL_PATH_ARG=$1 56 | if [ -z "$QVL_PATH_ARG" ] 57 | then 58 | QVL_PATH="$(cd "$(dirname "$SCRIPT_DIR"/../QVL/Src)" || exit 2; pwd)/Src" 59 | else 60 | QVL_PATH="$(cd "$(dirname "$QVL_PATH_ARG")" || exit 2; pwd)/$(basename "$QVL_PATH_ARG")" 61 | fi 62 | 63 | echo "QVL_PATH=$QVL_PATH" 64 | cd "$QVL_PATH" || fail "Failed to access QVL path" 2 65 | 66 | # Check if QVL_PATH contains absolute path 67 | case $QVL_PATH in 68 | /*) ;; 69 | *) fail "Absolute path to QVL sources should be provided" 3 ;; 70 | esac 71 | 72 | # Create local copy of QVL sources for Docker context 73 | copyQvlSources() { 74 | mkdir -p "$SCRIPT_DIR/build" 75 | cp -R "$QVL_PATH" "$SCRIPT_DIR/build/qvls" 76 | rm -rf "$SCRIPT_DIR/build/qvls/Build" "$SCRIPT_DIR"/build/qvls/cmake-build* 77 | } 78 | 79 | if ! copyQvlSources "$@"; then 80 | fail "Error when copying QVL" 5 81 | fi 82 | 83 | # Build Docker Image 84 | function buildDocker() { 85 | docker build --target artifacts --output="$SCRIPT_DIR" "$SCRIPT_DIR" 86 | if [ "$DEBUG" = true ]; then 87 | docker build --target debug-artifacts --output="$SCRIPT_DIR" "$SCRIPT_DIR" 88 | fi 89 | docker build --target app "$SCRIPT_DIR" -t qvs 90 | } 91 | 92 | if ! buildDocker; then 93 | fail "Error when building Docker image" 7 94 | fi 95 | 96 | pushd ${SCRIPT_DIR}/samples/simple-signing-service || fail "Failed to access SSS dir" 4 97 | ./build.sh 98 | popd || fail "Failed leave SSS dir" 5 99 | 100 | echo "Build - Done" 101 | -------------------------------------------------------------------------------- /configuration-default/.gitignore: -------------------------------------------------------------------------------- 1 | certificates/*.pem 2 | certificates/internal_ca/*.pem 3 | -------------------------------------------------------------------------------- /configuration-default/certificates/README.md: -------------------------------------------------------------------------------- 1 | # Quote Verification Service certificates configuration 2 | This guide describes how to create certificates required by the service. 3 | 4 | ## Prerequisite 5 | 6 | - Install [OpenSSL](https://www.openssl.org/ "OpenSSL") (tested with version 1.1.0g) 7 | - SSS MTLS client certificate has been [created](../../samples/simple-signing-service/README.md#configure-key-pairs). 8 | 9 | ## Configure Key Pairs 10 | Let’s create a key and self-signed cert for HTTPS enabling: 11 | 12 | ``` 13 | (cd internal_ca; openssl genrsa -out qvs-key.pem) 14 | (cd internal_ca; openssl req -new -key qvs-key.pem -out csr.pem) 15 | (cd internal_ca; openssl x509 -req -days 9999 -in csr.pem -signkey qvs-key.pem -out qvs-cert.pem) 16 | (cd internal_ca; rm csr.pem) 17 | ``` 18 | 19 | Copy or mount created files to Docker container and provide paths in the following environment variables: 20 | 21 | * QVS_SERVICE_CERT_FILE 22 | * QVS_SERVICE_KEY_FILE 23 | 24 | Then set QVS_SERVICE_TLS_SERVER_TYPE environment variable to TLS to enable HTTPS. 25 | 26 | ### Configure MTLS with SSS 27 | 28 | Generate a second pair for MTLS connection between components: 29 | 30 | ``` 31 | (cd internal_ca; openssl genrsa -out qvs-to-sss-client-key.pem) 32 | (cd internal_ca; openssl req -new -key qvs-to-sss-client-key.pem -out csr.pem) 33 | (cd internal_ca; openssl x509 -req -days 9999 -in csr.pem -signkey qvs-to-sss-client-key.pem -out qvs-to-sss-client-cert.pem) 34 | (cd internal_ca; rm csr.pem) 35 | ``` 36 | 37 | 38 | Make sure SSS(VCS) certificate is trusted for QVS: 39 | ``` 40 | cp ../../samples/simple-signing-service/certificates/cert.pem ./internal_ca/ 41 | ``` 42 | Make sure QVS certificate is trusted for SSS: 43 | ``` 44 | cp internal_ca/qvs-to-sss-client-cert.pem ../../samples/simple-signing-service/ 45 | ``` 46 | 47 | Make sure [../config.yml](../config.yml) contains certificate paths and client server name: 48 | ``` 49 | service: 50 | certFile: '${QVS_SERVICE_CERT_FILE:certificates/internal_ca/qvs-cert.pem}' 51 | keyFile: '${QVS_SERVICE_KEY_FILE:certificates/internal_ca/qvs-key.pem}' 52 | tlsServerType: '${QVS_SERVICE_TLS_SERVER_TYPE:TLS}' 53 | ... 54 | vcsClient: 55 | host: '${QVS_VCS_CLIENT_HOST:localhost}' 56 | port: '${QVS_VCS_CLIENT_PORT:8797}' 57 | certFile: '${QVS_VCS_CLIENT_CERT_FILE:certificates/internal_ca/qvs-to-sss-client-cert.pem}' 58 | keyFile: '${QVS_VCS_CLIENT_KEY_FILE:certificates/internal_ca/qvs-to-sss-client-key.pem}' 59 | servername: '${QVS_VCS_CLIENT_SERVERNAME:}' 60 | ``` 61 | 62 | Copy or mount created files to Docker container and provide paths in the following environment variables: 63 | 64 | * QVS_VCS_CLIENT_CERT_FILE 65 | * QVS_VCS_CLIENT_KEY_FILE 66 | 67 | Provide host and port of VCS (e.g. simple-signing-service) in the following environment variables: 68 | 69 | * QVS_VCS_CLIENT_HOST 70 | * QVS_VCS_CLIENT_PORT 71 | -------------------------------------------------------------------------------- /configuration-default/certificates/internal_ca/README.md: -------------------------------------------------------------------------------- 1 | Your custom trusted CA certificates should be here -------------------------------------------------------------------------------- /configuration-default/certificates/internal_ca/USERTrust_RSA_Certification_Authority.crt: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIIF3jCCA8agAwIBAgIQAf1tMPyjylGoG7xkDjUDLTANBgkqhkiG9w0BAQwFADCB 3 | iDELMAkGA1UEBhMCVVMxEzARBgNVBAgTCk5ldyBKZXJzZXkxFDASBgNVBAcTC0pl 4 | cnNleSBDaXR5MR4wHAYDVQQKExVUaGUgVVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNV 5 | BAMTJVVTRVJUcnVzdCBSU0EgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMTAw 6 | MjAxMDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCBiDELMAkGA1UEBhMCVVMxEzARBgNV 7 | BAgTCk5ldyBKZXJzZXkxFDASBgNVBAcTC0plcnNleSBDaXR5MR4wHAYDVQQKExVU 8 | aGUgVVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNVBAMTJVVTRVJUcnVzdCBSU0EgQ2Vy 9 | dGlmaWNhdGlvbiBBdXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIK 10 | AoICAQCAEmUXNg7D2wiz0KxXDXbtzSfTTK1Qg2HiqiBNCS1kCdzOiZ/MPans9s/B 11 | 3PHTsdZ7NygRK0faOca8Ohm0X6a9fZ2jY0K2dvKpOyuR+OJv0OwWIJAJPuLodMkY 12 | tJHUYmTbf6MG8YgYapAiPLz+E/CHFHv25B+O1ORRxhFnRghRy4YUVD+8M/5+bJz/ 13 | Fp0YvVGONaanZshyZ9shZrHUm3gDwFA66Mzw3LyeTP6vBZY1H1dat//O+T23LLb2 14 | VN3I5xI6Ta5MirdcmrS3ID3KfyI0rn47aGYBROcBTkZTmzNg95S+UzeQc0PzMsNT 15 | 79uq/nROacdrjGCT3sTHDN/hMq7MkztReJVni+49Vv4M0GkPGw/zJSZrM233bkf6 16 | c0Plfg6lZrEpfDKEY1WJxA3Bk1QwGROs0303p+tdOmw1XNtB1xLaqUkL39iAigmT 17 | Yo61Zs8liM2EuLE/pDkP2QKe6xJMlXzzawWpXhaDzLhn4ugTncxbgtNMs+1b/97l 18 | c6wjOy0AvzVVdAlJ2ElYGn+SNuZRkg7zJn0cTRe8yexDJtC/QV9AqURE9JnnV4ee 19 | UB9XVKg+/XRjL7FQZQnmWEIuQxpMtPAlR1n6BB6T1CZGSlCBst6+eLf8ZxXhyVeE 20 | Hg9j1uliutZfVS7qXMYoCAQlObgOK6nyTJccBz8NUvXt7y+CDwIDAQABo0IwQDAd 21 | BgNVHQ4EFgQUU3m/WqorSs9UgOHYm8Cd8rIDZsswDgYDVR0PAQH/BAQDAgEGMA8G 22 | A1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEMBQADggIBAFzUfA3P9wF9QZllDHPF 23 | Up/L+M+ZBn8b2kMVn54CVVeWFPFSPCeHlCjtHzoBN6J2/FNQwISbxmtOuowhT6KO 24 | VWKR82kV2LyI48SqC/3vqOlLVSoGIG1VeCkZ7l8wXEskEVX/JJpuXior7gtNn3/3 25 | ATiUFJVDBwn7YKnuHKsSjKCaXqeYalltiz8I+8jRRa8YFWSQEg9zKC7F4iRO/Fjs 26 | 8PRF/iKz6y+O0tlFYQXBl2+odnKPi4w2r78NBc5xjeambx9spnFixdjQg3IM8WcR 27 | iQycE0xyNN+81XHfqnHd4blsjDwSXWXavVcStkNr/+XeTWYRUc+ZruwXtuhxkYze 28 | Sf7dNXGiFSeUHM9h4ya7b6NnJSFd5t0dCy5oGzuCr+yDZ4XUmFF0sbmZgIn/f3gZ 29 | XHlKYC6SQK5MNyosycdiyA5d9zZbyuAlJQG03RoHnHcAP9Dc1ew91Pq7P8yF1m9/ 30 | qS3fuQL39ZeatTXaw2ewh0qpKJ4jjv9cJ2vhsE/zB+4ALtRZh8tSQZXq9EfX7mRB 31 | VXyNWQKV3WKdwrnuWih0hKWbt5DHDAff9Yk2dDLWKMGwsAvgnEzDHNb842m1R0aB 32 | L6KCq9NjRHDEjf8tM7qtj3u1cIiuPhnPQCjY/MiQu12ZIvVS5ljFH4gxQ+6IHdfG 33 | jjxDah2nGN59PRbxYvnKkKj9 34 | -----END CERTIFICATE----- 35 | -------------------------------------------------------------------------------- /default.env: -------------------------------------------------------------------------------- 1 | QVS_SERVICE_CERT_FILE=certificates/qvs-cert.pem 2 | QVS_SERVICE_KEY_FILE=certificates/qvs-key.pem 3 | QVS_SERVICE_TLS_SERVER_TYPE=TLS 4 | QVS_VCS_CLIENT_HOST=localhost 5 | QVS_VCS_CLIENT_PORT=8797 6 | QVS_VCS_CLIENT_CERT_FILE=certificates/qvs-to-sss-client-cert.pem 7 | QVS_VCS_CLIENT_KEY_FILE=certificates/qvs-to-sss-client-key.pem 8 | QVS_ATTESTATION_REPORT_SIGNING_CERTIFICATE=SIGNING_KEY_CERTIFCATE_URL_ENCODED 9 | QVS_VCS_CLIENT_SERVERNAME=localhost 10 | -------------------------------------------------------------------------------- /diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/intel/SGX-TDX-DCAP-QuoteVerificationService/32ebde6972922efb3083fcdd7d15adef1b4e1b1d/diagram.png -------------------------------------------------------------------------------- /nyc.config.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2024 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 'use strict'; 32 | 33 | const requiredCoverage = 88; 34 | const singleUTTimeout = 2500; 35 | const nycReportDir = '../build/code-coverage-report'; 36 | 37 | module.exports = { 38 | 'all': true, 39 | 'cwd': '../src', 40 | 'reporter': ['text', 'lcov', 'json'], 41 | 'report-dir': `${nycReportDir}/`, 42 | 'temp-dir': `${nycReportDir}/.nyc_tempAndCache`, 43 | 'cache-dir': `${nycReportDir}/.nyc_tempAndCache`, 44 | 'check-coverage': true, 45 | 'statements': requiredCoverage, 46 | 'branches': requiredCoverage, 47 | 'functions': requiredCoverage, 48 | 'lines': requiredCoverage, 49 | 'timeout': singleUTTimeout 50 | }; 51 | -------------------------------------------------------------------------------- /reporter_config.json: -------------------------------------------------------------------------------- 1 | { 2 | "reporterEnabled": "spec, mocha-junit-reporter", 3 | "mochaJunitReporterReporterOptions": { 4 | "mochaFile": "../build/test-reports/tests-results.xml" 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /runAll.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # 4 | # Copyright (c) 2023, Intel Corporation 5 | # SPDX-License-Identifier: BSD-3-Clause 6 | # 7 | # Redistribution and use in source and binary forms, with or without 8 | # modification, are permitted provided that the following conditions are met: 9 | # 10 | # * Redistributions of source code must retain the above copyright notice, 11 | # this list of conditions and the following disclaimer. 12 | # * Redistributions in binary form must reproduce the above copyright notice, 13 | # this list of conditions and the following disclaimer in the documentation 14 | # and/or other materials provided with the distribution. 15 | # * Neither the name of Intel Corporation nor the names of its contributors 16 | # may be used to endorse or promote products derived from this software 17 | # without specific prior written permission. 18 | # 19 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 20 | # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 21 | # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 22 | # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 23 | # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 24 | # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 25 | # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 26 | # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 27 | # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 28 | # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 29 | # POSSIBILITY OF SUCH DAMAGE. 30 | # 31 | # Get absolute path to the script itself 32 | QVS_DIR="$(cd "$(dirname "$0")" || exit 1; pwd)" 33 | 34 | source ${QVS_DIR}/configUtils.sh 35 | 36 | # Prepare QVS certs 37 | pushd ${QVS_DIR}/configuration-default/certificates || fail "Failed to access QVS certificates dir" 2 38 | prepareSelfSignedCert "qvs-" '/C=US/O=Example/CN=QVS HTTPS' 39 | prepareSelfSignedCert "qvs-to-sss-client-" '/C=US/O=Example/CN=QVS to SSS MTLS' 40 | popd || fail "Failed leave QVS certificates dir" 3 41 | 42 | # Prepare SSS certs and run docker 43 | pushd ${QVS_DIR}/samples/simple-signing-service/ || fail "Failed to access SSS dir" 4 44 | ./prepareCerts.sh 45 | ./runSSS.sh 46 | popd || fail "Failed leave SSS dir" 5 47 | 48 | #Run QVS Container 49 | ./runQVS.sh 50 | 51 | echo "RunAll - Done." 52 | 53 | -------------------------------------------------------------------------------- /runQVS.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # 4 | # Copyright (c) 2023, Intel Corporation 5 | # SPDX-License-Identifier: BSD-3-Clause 6 | # 7 | # Redistribution and use in source and binary forms, with or without 8 | # modification, are permitted provided that the following conditions are met: 9 | # 10 | # * Redistributions of source code must retain the above copyright notice, 11 | # this list of conditions and the following disclaimer. 12 | # * Redistributions in binary form must reproduce the above copyright notice, 13 | # this list of conditions and the following disclaimer in the documentation 14 | # and/or other materials provided with the distribution. 15 | # * Neither the name of Intel Corporation nor the names of its contributors 16 | # may be used to endorse or promote products derived from this software 17 | # without specific prior written permission. 18 | # 19 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 20 | # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 21 | # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 22 | # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 23 | # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 24 | # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 25 | # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 26 | # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 27 | # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 28 | # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 29 | # POSSIBILITY OF SUCH DAMAGE. 30 | # 31 | # Get absolute path to the script itself 32 | QVS_DIR="$(cd "$(dirname "$0")" || exit 1; pwd)" 33 | 34 | source ${QVS_DIR}/configUtils.sh 35 | 36 | docker run --name qvs --network host -v ${QVS_DIR}/configuration-default/certificates:/QVS/configuration-default/certificates --env-file ${QVS_DIR}/default.env --rm qvs:latest & 37 | 38 | echo 'Veryfying QVS HTTPS endpoint...' 39 | waitForHttpsServiceToStart 8799 40 | 41 | -------------------------------------------------------------------------------- /samples/simple-signing-service/.gitignore: -------------------------------------------------------------------------------- 1 | certificates 2 | node_modules -------------------------------------------------------------------------------- /samples/simple-signing-service/Dockerfile: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright (c) 2023, Intel Corporation 3 | # SPDX-License-Identifier: BSD-3-Clause 4 | # 5 | # Redistribution and use in source and binary forms, with or without 6 | # modification, are permitted provided that the following conditions are met: 7 | # 8 | # * Redistributions of source code must retain the above copyright notice, 9 | # this list of conditions and the following disclaimer. 10 | # * Redistributions in binary form must reproduce the above copyright notice, 11 | # this list of conditions and the following disclaimer in the documentation 12 | # and/or other materials provided with the distribution. 13 | # * Neither the name of Intel Corporation nor the names of its contributors 14 | # may be used to endorse or promote products derived from this software 15 | # without specific prior written permission. 16 | # 17 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 18 | # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 19 | # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 20 | # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 21 | # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 22 | # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 23 | # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 24 | # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 25 | # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 26 | # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 27 | # POSSIBILITY OF SUCH DAMAGE. 28 | # 29 | 30 | FROM node:lts-slim 31 | 32 | LABEL description="Simple Signing Service" 33 | 34 | # Update the OS and install required dependencies 35 | RUN apt-get update && \ 36 | DEBIAN_FRONTEND=noninteractive apt-get upgrade --assume-yes -o Dpkg::Options::="--force-confold" && \ 37 | DEBIAN_FRONTEND=noninteractive apt-get install --assume-yes --no-install-recommends ca-certificates=\* openssl=\* && \ 38 | rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* 39 | 40 | # Add SSS 41 | ENV NODE_ENV=production 42 | RUN mkdir /SSS 43 | COPY --chown=node:node package.json simple-signing-service.js swagger.js swagger.json /SSS/ 44 | 45 | WORKDIR /SSS 46 | RUN npm install 47 | 48 | # Remove Node package managers and its dependencies and clear apt cache 49 | RUN rm -rf /usr/local/lib/node_modules/ \ 50 | && rm -rf /usr/local/bin/npm \ 51 | && rm -rf /usr/local/bin/npx \ 52 | && rm -rf /opt \ 53 | && rm -rf /var/cache/apt/archives 54 | 55 | USER node 56 | 57 | ENTRYPOINT ["node", "/SSS/simple-signing-service.js"] 58 | -------------------------------------------------------------------------------- /samples/simple-signing-service/README.md: -------------------------------------------------------------------------------- 1 | # Simple Signing Service Example 2 | 3 | DO NOT USE THIS IN PRODUCTION. 4 | 5 | ## Prerequisite 6 | 7 | Non-SGX platform is sufficient, tested with Ubuntu 18.04 and Ubuntu 20.04 8 | 9 | For easier setup use docker, however it can be run manually without containers. 10 | 11 | ## Quick Setup 12 | With self-signed certs, scripts and docker image 13 | 14 | Requirements: 15 | - [Docker](https://www.docker.com/) (tested with version 20.10.11) 16 | - ```$ curl -fsSL https://get.docker.com -o get-docker.sh``` 17 | - ```$ sudo sh ./get-docker.sh``` 18 | 19 | ### Building and Starting Service 20 | ```bash 21 | # Build sss:latest docker image 22 | ./build.sh 23 | 24 | # Create self-signed certs 25 | ./prepareCerts.sh 26 | 27 | # Run SSS 28 | ./runSSS.sh 29 | ``` 30 | Healthcheck is performed automatically to ensure SSS is operable. 31 | 32 | ## Manual Setup 33 | Requirements: 34 | - [Node.js](https://nodejs.org/en/) (tested with version 16.13.1) 35 | - [OpenSSL](https://www.openssl.org/ "OpenSSL") (tested with version 1.1.0g) 36 | 37 | ## Configure Key Pairs 38 | In order to use the service, we need to generate 2 key pairs and corresponding self-signed certificates: one for HTTPS, second for signing Attestation Report. 39 | 40 | First, let’s create a key and self-signed cert for HTTPS enabling: 41 | 42 | ``` 43 | openssl genrsa -out key.pem 44 | openssl req -new -key key.pem -out csr.pem 45 | openssl x509 -req -days 9999 -in csr.pem -signkey key.pem -out cert.pem 46 | rm csr.pem 47 | ``` 48 | 49 | Finally, let’s create a key and self-signed cert for signing Attestation Report: 50 | 51 | ``` 52 | openssl genrsa -out sign-key.pem 3072 53 | openssl req -new -key sign-key.pem -out csr.pem 54 | openssl x509 -req -days 9999 -in csr.pem -signkey sign-key.pem -out sign-cert.pem 55 | rm csr.pem 56 | ``` 57 | 58 | ## Communication with Quote Verification Service 59 | 60 | Sample simple-signing-service is configured by default to support MTLS. 61 | 62 | To allow requests from Quote Verification Service, QVS client certificate has to be added to SSS's trusted CA. It's configured by [QVS_VCS_CLIENT_CERT_FILE](../../README.md#service-configuration) configuration variable. 63 | 64 | To do so, please [create QVS Client certificate](../../configuration-default/certificates/README.md#configure-mtls-with-sss). Expected result is that qvs-to-sss-client-cert.pem copy is located in SSS's directory. 65 | 66 | 67 | 68 | ## Building and Starting Service Manually 69 | 70 | Build simple-signing-service: 71 | 72 | ```npm install``` 73 | 74 | and start: 75 | 76 | ```npm start``` or ```node simple-signing-service.js``` 77 | 78 | This service will run with two ports enabled: 79 | 80 | ``` 81 | Server Started: https://localhost:8797 82 | Server Started: http://localhost:8796 83 | ``` 84 | ## Healtcheck 85 | In order to use HTTPS (default port: 8797) please create qvs-to-sss-client key and cert first, 86 | following: [../../configuration-default/certificates/README.md](../../configuration-default/certificates/README.md) 87 | 88 | ``` 89 | curl http://localhost:8796/health 90 | curl --cacert ../../configuration-default/certificates/internal_ca/sss-mtls-cert.pem --key ../../configuration-default/certificates/qvs-to-sss-client-key.pem --cert ../../configuration-default/certificates/qvs-to-sss-client-cert.pem https://localhost:8797/health 91 | ``` 92 | 93 | ## Configuration for Quote Verification Service 94 | 95 | Read the log and get information from the line below: 96 | 97 | ``` 98 | Signing Certificate in URL encoded: 99 | ``` 100 | 101 | That will be required to start Quote Verification Service. 102 | -------------------------------------------------------------------------------- /samples/simple-signing-service/build.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # 4 | # Copyright (c) 2023, Intel Corporation 5 | # SPDX-License-Identifier: BSD-3-Clause 6 | # 7 | # Redistribution and use in source and binary forms, with or without 8 | # modification, are permitted provided that the following conditions are met: 9 | # 10 | # * Redistributions of source code must retain the above copyright notice, 11 | # this list of conditions and the following disclaimer. 12 | # * Redistributions in binary form must reproduce the above copyright notice, 13 | # this list of conditions and the following disclaimer in the documentation 14 | # and/or other materials provided with the distribution. 15 | # * Neither the name of Intel Corporation nor the names of its contributors 16 | # may be used to endorse or promote products derived from this software 17 | # without specific prior written permission. 18 | # 19 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 20 | # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 21 | # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 22 | # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 23 | # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 24 | # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 25 | # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 26 | # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 27 | # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 28 | # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 29 | # POSSIBILITY OF SUCH DAMAGE. 30 | # 31 | # Get absolute path to the script itself 32 | SSS_DIR="$(cd "$(dirname "$0")" || exit 1; pwd)" 33 | echo 'Building SSS docker image...' 34 | docker build "$SSS_DIR" -t sss 35 | 36 | -------------------------------------------------------------------------------- /samples/simple-signing-service/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "simple-signing-service", 3 | "version": "0.0.1", 4 | "description": "DO NOT USE IN PRODUCTION. This simple service demonstrates Verification Crypto Service concept.", 5 | "main": "simple-signing-service.js", 6 | "scripts": { 7 | "start": "node simple-signing-service.js", 8 | "swagger": "node swagger.js" 9 | }, 10 | "dependencies": { 11 | "koa": "^2.13.4", 12 | "koa-router": "^12.0.0", 13 | "koa-body": "^5.0.0" 14 | }, 15 | "devDependencies": { 16 | "swagger-autogen": "^2.23.1" 17 | }, 18 | "keywords": [], 19 | "author": "", 20 | "license": "ISC" 21 | } 22 | -------------------------------------------------------------------------------- /samples/simple-signing-service/prepareCerts.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # 4 | # Copyright (c) 2023, Intel Corporation 5 | # SPDX-License-Identifier: BSD-3-Clause 6 | # 7 | # Redistribution and use in source and binary forms, with or without 8 | # modification, are permitted provided that the following conditions are met: 9 | # 10 | # * Redistributions of source code must retain the above copyright notice, 11 | # this list of conditions and the following disclaimer. 12 | # * Redistributions in binary form must reproduce the above copyright notice, 13 | # this list of conditions and the following disclaimer in the documentation 14 | # and/or other materials provided with the distribution. 15 | # * Neither the name of Intel Corporation nor the names of its contributors 16 | # may be used to endorse or promote products derived from this software 17 | # without specific prior written permission. 18 | # 19 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 20 | # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 21 | # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 22 | # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 23 | # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 24 | # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 25 | # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 26 | # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 27 | # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 28 | # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 29 | # POSSIBILITY OF SUCH DAMAGE. 30 | # 31 | 32 | source ../../configUtils.sh 33 | 34 | # Imports QVS MTLS certificate to SSS ./certificates 35 | # Context: Requires being in SSS certificates dir 36 | function ImportQVSCertificate() { 37 | ImportCertificate "../../../configuration-default/certificates/qvs-to-sss-client-cert.pem" "." 38 | } 39 | 40 | # Exports provided MTLS certificate to QVS internal-ca 41 | # Context: Requires being in SSS certificates dir 42 | function ExportSSSCertificate() { 43 | ImportCertificate "./sss-mtls-cert.pem" "../../../configuration-default/certificates/internal_ca" 44 | } 45 | 46 | # Prepare SSS certs 47 | mkdir -p certificates 48 | pushd certificates || fail "Failed to access SSS certificates dir" 4 49 | prepareSelfSignedCert "sss-mtls-" '/C=US/O=Example/CN=localhost' 50 | prepareSelfSignedCert "sign-" '/C=US/CN=Sample signing key/O=Example' 51 | 52 | #Exchange SSS and QVS MTLS certs 53 | ImportQVSCertificate 54 | ExportSSSCertificate 55 | popd || fail "Failed leave SSS certificates dir" 5 56 | 57 | -------------------------------------------------------------------------------- /samples/simple-signing-service/runSSS.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # 4 | # Copyright (c) 2023, Intel Corporation 5 | # SPDX-License-Identifier: BSD-3-Clause 6 | # 7 | # Redistribution and use in source and binary forms, with or without 8 | # modification, are permitted provided that the following conditions are met: 9 | # 10 | # * Redistributions of source code must retain the above copyright notice, 11 | # this list of conditions and the following disclaimer. 12 | # * Redistributions in binary form must reproduce the above copyright notice, 13 | # this list of conditions and the following disclaimer in the documentation 14 | # and/or other materials provided with the distribution. 15 | # * Neither the name of Intel Corporation nor the names of its contributors 16 | # may be used to endorse or promote products derived from this software 17 | # without specific prior written permission. 18 | # 19 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 20 | # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 21 | # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 22 | # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 23 | # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 24 | # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 25 | # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 26 | # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 27 | # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 28 | # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 29 | # POSSIBILITY OF SUCH DAMAGE. 30 | # 31 | # Get absolute path to the script itself 32 | SSS_DIR="$(cd "$(dirname "$0")" || exit 1; pwd)" 33 | QVS_CERT_DIR="${SSS_DIR}/../../configuration-default/certificates" 34 | 35 | source ${SSS_DIR}/../../configUtils.sh 36 | echo 'Starting SSS...' 37 | docker run --name vcs-sss -p 8797:8797 -p 8796:8796 -v ${SSS_DIR}/certificates:/SSS/certificates --rm sss & 38 | 39 | echo 'Veryfying SSS HTTP endpoint...' 40 | waitForHttpServiceToStart 8796 41 | echo 'Veryfying SSS MTLS endpoint...' 42 | retryHealthCheack "curl --cacert ${QVS_CERT_DIR}/internal_ca/sss-mtls-cert.pem --key ${QVS_CERT_DIR}/qvs-to-sss-client-key.pem --cert ${QVS_CERT_DIR}/qvs-to-sss-client-cert.pem https://localhost:8797/health" 43 | 44 | -------------------------------------------------------------------------------- /samples/simple-signing-service/swagger.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 'use strict'; 32 | 33 | const swaggerAutogen = require('swagger-autogen')(); 34 | 35 | const outputFile = './swagger.json'; 36 | const endpointsFiles = ['./simple-signing-service.js']; 37 | 38 | const doc = { 39 | info: { 40 | version: '1.0.0', 41 | title: 'Simple Signing Service', 42 | description: 'Documentation automatically generated from comments in SSS code' 43 | }, 44 | host: 'localhost:8797', 45 | basePath: '/', 46 | schemes: ['https'], 47 | consumes: ['application/json'], 48 | produces: ['application/json'], 49 | definitions: { 50 | PositiveHealthReport: { 51 | status: 'OK', 52 | version: '1.0.0', 53 | lastChecked: '2023-03-07T10:30:29.282Z' 54 | }, 55 | NegativeHealthReport: { 56 | status: 'FAILED', 57 | version: '1.0.0', 58 | lastChecked: '2023-03-07T10:30:29.282Z' 59 | }, 60 | SignatureResponse: { 61 | signature: 'M5iPd/7XrQlhweDBzKzou8kIamLAfDR/Hc1bC8RCEtxpDLlRhRWjxlUNpIwcDoxvRSt7fMQujO4JPaTV9+bTW3b74rhSmkiuTdxMnF7eYZl29cge6OFCpyz9M/c4U61IlYE8yAFoaSrbd0zHH0jUx//AzsD1Iw03P8YL2G/rUbBAtOGpZUF7hRmHDVGqGhjN6n0HIX4yMZ8CHQQTTziJokn+HSIN8tDQWV5DVFfCLFmUQ5Fyf3UIh07FmX+3HDukR/601FvbBvoaw3ERTjtLH30d+3Px/EVq8ZwRy6SCE9+3MJpIXFZttL4wO45mNEiHNdMPnBTBPJylN2a5mkz1Ww==' 62 | } 63 | } 64 | }; 65 | 66 | swaggerAutogen(outputFile, endpointsFiles, doc); 67 | -------------------------------------------------------------------------------- /samples/simple-signing-service/swagger.json: -------------------------------------------------------------------------------- 1 | { 2 | "swagger": "2.0", 3 | "info": { 4 | "version": "1.0.0", 5 | "title": "Simple Signing Service", 6 | "description": "Documentation automatically generated from comments in SSS code" 7 | }, 8 | "host": "localhost:8797", 9 | "basePath": "/", 10 | "schemes": [ 11 | "https" 12 | ], 13 | "consumes": [ 14 | "application/json" 15 | ], 16 | "produces": [ 17 | "application/json" 18 | ], 19 | "paths": { 20 | "/health": { 21 | "get": { 22 | "description": "Checks health and version of the service", 23 | "produces": [ 24 | "application/json" 25 | ], 26 | "responses": { 27 | "200": { 28 | "schema": { 29 | "$ref": "#/definitions/PositiveHealthReport" 30 | }, 31 | "description": "Health report" 32 | }, 33 | "503": { 34 | "schema": { 35 | "$ref": "#/definitions/NegativeHealthReport" 36 | }, 37 | "description": "Health report" 38 | } 39 | } 40 | } 41 | }, 42 | "/sign/attestation-verification-report": { 43 | "post": { 44 | "description": "Prepare a signature of received body", 45 | "consumes": [ 46 | "application/json" 47 | ], 48 | "produces": [ 49 | "application/json" 50 | ], 51 | "parameters": [ 52 | { 53 | "name": "payload", 54 | "in": "body", 55 | "description": "Attestation Verification Report to be signed", 56 | "schema": { 57 | "type": "object", 58 | "properties": {} 59 | } 60 | } 61 | ], 62 | "responses": { 63 | "200": { 64 | "schema": { 65 | "$ref": "#/definitions/SignatureResponse" 66 | }, 67 | "description": "Signature of the request body" 68 | } 69 | } 70 | } 71 | } 72 | }, 73 | "definitions": { 74 | "PositiveHealthReport": { 75 | "type": "object", 76 | "properties": { 77 | "status": { 78 | "type": "string", 79 | "example": "OK" 80 | }, 81 | "version": { 82 | "type": "string", 83 | "example": "1.0.0" 84 | }, 85 | "lastChecked": { 86 | "type": "string", 87 | "example": "2023-03-07T10:30:29.282Z" 88 | } 89 | } 90 | }, 91 | "NegativeHealthReport": { 92 | "type": "object", 93 | "properties": { 94 | "status": { 95 | "type": "string", 96 | "example": "FAILED" 97 | }, 98 | "version": { 99 | "type": "string", 100 | "example": "1.0.0" 101 | }, 102 | "lastChecked": { 103 | "type": "string", 104 | "example": "2023-03-07T10:30:29.282Z" 105 | } 106 | } 107 | }, 108 | "SignatureResponse": { 109 | "type": "object", 110 | "properties": { 111 | "signature": { 112 | "type": "string", 113 | "example": "M5iPd/7XrQlhweDBzKzou8kIamLAfDR/Hc1bC8RCEtxpDLlRhRWjxlUNpIwcDoxvRSt7fMQujO4JPaTV9+bTW3b74rhSmkiuTdxMnF7eYZl29cge6OFCpyz9M/c4U61IlYE8yAFoaSrbd0zHH0jUx//AzsD1Iw03P8YL2G/rUbBAtOGpZUF7hRmHDVGqGhjN6n0HIX4yMZ8CHQQTTziJokn+HSIN8tDQWV5DVFfCLFmUQ5Fyf3UIh07FmX+3HDukR/601FvbBvoaw3ERTjtLH30d+3Px/EVq8ZwRy6SCE9+3MJpIXFZttL4wO45mNEiHNdMPnBTBPJylN2a5mkz1Ww==" 114 | } 115 | } 116 | } 117 | } 118 | } -------------------------------------------------------------------------------- /security.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | Intel is committed to rapidly addressing security vulnerabilities affecting our customers and providing clear guidance on the solution, impact, severity and mitigation. 3 | 4 | ## Reporting a Vulnerability 5 | Please report any security vulnerabilities in this project utilizing the guidelines [here](https://www.intel.com/content/www/us/en/security-center/vulnerability-handling-guidelines.html). 6 | -------------------------------------------------------------------------------- /src/bootstrap.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 32 | 'use strict'; 33 | 34 | const path = require('path'); 35 | const process = require('process'); 36 | const genericLogger = require('./common/logger').genericLogger; 37 | 38 | module.exports = (async function bootstrap() { 39 | try { 40 | await require('./configLoader').init(path.join(__dirname, '../configuration-default/')); 41 | } 42 | catch (e) { 43 | genericLogger.error('During loading config and parsing templates occurred an', e); 44 | /*eslint no-process-exit: 0 */ 45 | return process.exit(1); 46 | } 47 | return require('./server'); // async function (use with await or return) 48 | }()); 49 | -------------------------------------------------------------------------------- /src/clients/vcsAccessLayer/VCSClient.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 32 | 'use strict'; 33 | 34 | const config = require('../../configLoader').getConfig(); 35 | const RestClient = require('../../common/RestClient'); 36 | 37 | const client = new RestClient( 38 | config.vcsClient.tlsClientType, 39 | config.vcsClient.host, 40 | config.vcsClient.port, 41 | config.vcsClient.retries, 42 | config.vcsClient.initialInterval, 43 | config.vcsClient.factor, 44 | config.vcsClient.certFile, 45 | config.vcsClient.keyFile, 46 | config.vcsClient.caCertDirectories, 47 | config.vcsClient.proxy, 48 | config.vcsClient.servername); 49 | 50 | /** 51 | * @typedef {import('../../jsDoc/types').Logger} Logger 52 | */ 53 | 54 | /** 55 | * Signs the attestation verification report 56 | * @param {{}} body - attestation verification report to be signed 57 | * @param {string} requestId 58 | * @param {Logger} logger 59 | * @returns {Promise<{ 60 | * status: number, 61 | * body: { 62 | * signature: string 63 | * }, 64 | * headers: Object. 65 | * }|Error>} 66 | */ 67 | async function signVerificationReport(body, requestId, logger) { 68 | const path = '/sign/attestation-verification-report'; 69 | 70 | let response; 71 | try { 72 | response = await client.postRequestPromised(requestId, logger, body, path); 73 | } 74 | catch (error) { 75 | response = error; 76 | } 77 | 78 | return response; 79 | } 80 | 81 | /** 82 | * Retrieves health status of component and its dependencies 83 | * @param {Logger} logger 84 | * @param {Object.} headers 85 | * @returns {status: number, body: JSON, headers: Object.} 86 | */ 87 | function getHealth(logger, headers) { 88 | return client.health(logger, headers); 89 | } 90 | 91 | module.exports = { 92 | getHealth, 93 | signVerificationReport 94 | }; 95 | -------------------------------------------------------------------------------- /src/common/detailedErrorString.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 32 | 'use strict'; 33 | 34 | const { serializeError } = require('serialize-error'); 35 | const onelinerFormat = require('../util/onelinerFormat'); 36 | 37 | function detailedErrorString(e) { 38 | const errorJson = serializeError(e); 39 | return onelinerFormat(JSON.stringify(errorJson)); 40 | } 41 | 42 | module.exports = detailedErrorString; 43 | -------------------------------------------------------------------------------- /src/common/errorHandler.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 32 | 'use strict'; 33 | 34 | /** 35 | * Returns error stack trace depending on if it's multiline 36 | * 37 | * @param {Error} error 38 | * @param {boolean} isMultiline 39 | * 40 | * @returns {string} 41 | */ 42 | function errorStackTraceHandler(error, isMultiline) { 43 | if (error) { 44 | if (isMultiline) { 45 | const errorStack = String(error.stack); 46 | return errorStack; 47 | } 48 | else { 49 | const errorStack = String(error.stack).replace(/\n/gi, ' | '); 50 | return errorStack; 51 | } 52 | } 53 | else { 54 | return ''; 55 | } 56 | } 57 | 58 | module.exports = { errorStackTraceHandler }; 59 | -------------------------------------------------------------------------------- /src/common/getCACertificatesSync.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 32 | 'use strict'; 33 | 34 | const fs = require('fs'); 35 | const path = require('path'); 36 | const logger = require('../common/logger').genericLogger; 37 | 38 | module.exports = (caCertDirectories) => { 39 | let CACertsFiles = []; 40 | 41 | if (caCertDirectories) { 42 | CACertsFiles = caCertDirectories 43 | .map(dir => 44 | fs.readdirSync(dir) 45 | .map(caFile => path.join(dir, caFile)) 46 | .filter(path => fs.statSync(path).isDirectory()) 47 | .map(subdir => 48 | fs.readdirSync(subdir) 49 | .map(caFile => path.join(subdir, caFile)) 50 | .filter(path => fs.statSync(path).isFile()) 51 | ) 52 | .reduce((all, inDir) => all.concat(inDir), []) 53 | .concat(fs.readdirSync(dir) 54 | .map(caFile => path.join(dir, caFile)) 55 | .filter(path => fs.statSync(path).isFile())) 56 | ) 57 | .reduce((all, inDir) => all.concat(inDir), CACertsFiles); 58 | } 59 | logger.info('Read ' + CACertsFiles.length + ' certificates from ' + caCertDirectories); 60 | return CACertsFiles; 61 | }; 62 | -------------------------------------------------------------------------------- /src/common/httpStatusCodes.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 32 | 'use strict'; 33 | 34 | const httpStatusCodes = { 35 | // 2xx 36 | SUCCESS: 200, 37 | CREATED: 201, 38 | 39 | // 3xx 40 | 41 | // 4xx 42 | BAD_REQUEST: 400, 43 | UNAUTHORIZED: 401, 44 | NOT_FOUND: 404, 45 | METHOD_NOT_ALLOWED: 405, 46 | 47 | // 5xx 48 | INTERNAL_SERVER_ERROR: 500, 49 | SERVICE_UNAVAILABLE: 503 50 | }; 51 | 52 | module.exports = httpStatusCodes; 53 | -------------------------------------------------------------------------------- /src/common/nodeRequestHandler.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 32 | 'use strict'; 33 | 34 | const axios = require('axios'); 35 | 36 | /** 37 | * IntelliJ IDEA has long lasting bugs: 38 | * https://youtrack.jetbrains.com/issue/WEB-31971 39 | * https://youtrack.jetbrains.com/issue/WEB-52385 40 | * JSDoc import works for example in Visual Studio Code. 41 | * 42 | * @typedef {import('../jsDoc/types').KoaResponse} KoaResponse 43 | * @typedef {import('../jsDoc/types').Logger} Logger 44 | */ 45 | 46 | /** 47 | * Create result 48 | * 49 | * @param {number} statusCode 50 | * @param {Object} headers 51 | * @param {Object} body 52 | * 53 | * @returns {{headers, body, statusCode}} 54 | */ 55 | function createResult(statusCode, headers, body) { 56 | return { statusCode, headers, body }; 57 | } 58 | 59 | /** 60 | * @typedef {Object} NodeRequestOptions 61 | * @property {?Object} httpAgent 62 | * @property {?Object} httpsAgent 63 | * @property {number} timeout 64 | * @property {string} method 65 | * @property {string} url 66 | * @property {Object} headers 67 | */ 68 | 69 | const limit10MB = 1024 * 1024 * 10; // 10 MB 70 | 71 | /** 72 | * Create node request 73 | * @param {NodeRequestOptions} options 74 | * @param {string} body 75 | * @param {boolean=} isResponseBinary - default false 76 | */ 77 | async function nodeRequest(options, body, isResponseBinary = false) { 78 | const axiosOptions = { 79 | ...options, 80 | maxContentLength: limit10MB, 81 | maxBodyLength: limit10MB, 82 | responseType: isResponseBinary ? 'arraybuffer' : 'json', 83 | }; 84 | if (body) { 85 | axiosOptions.data = body; 86 | } 87 | try { 88 | const response = await axios(axiosOptions); 89 | return createResult(response.status, response.headers, response.data); 90 | } 91 | catch (error) { 92 | const response = error.response; 93 | if (response) { 94 | return createResult(response.status, response.headers, response.data); 95 | } 96 | throw error; 97 | } 98 | } 99 | 100 | module.exports = nodeRequest; 101 | -------------------------------------------------------------------------------- /src/common/readFileSafely.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 32 | 'use strict'; 33 | 34 | const fs = require('fs'); 35 | const os = require('os'); 36 | const path = require('path'); 37 | 38 | const Buffer = require('../util/buffer'); 39 | const logger = require('./logger').genericLogger; 40 | 41 | function getRealPathFromFileDescriptor(fd) { 42 | return fs.readlinkSync('/proc/self/fd/' + fd); 43 | } 44 | 45 | /** 46 | * Reads file using file descriptor, blocking changes in the meantime 47 | * In case filePath is a symlink, it checks where it directs and if target path is in allowed location 48 | * inside user home directory or allowed mount point 49 | * 50 | * @param {string} filePath - path to file to read 51 | * @param {string} encoding - default is 'utf8' 52 | * @returns {string} file content 53 | */ 54 | function readFileSafely(filePath, encoding = 'utf8') { 55 | const absolutePath = path.resolve(filePath); 56 | const allowedLocations = [ 57 | os.homedir() + path.sep, // user home directory 58 | ]; 59 | const fd = fs.openSync(absolutePath); 60 | let content = ''; 61 | try { 62 | const link = getRealPathFromFileDescriptor(fd); 63 | logger.trace('Loading file from: ' + absolutePath); 64 | if (absolutePath !== link) { 65 | logger.debug('Loading file from symlink: ' + absolutePath + ' which directs to: ' + link); 66 | const locationAllowed = allowedLocations.some((prefix) => link.startsWith(prefix)); 67 | if (!locationAllowed) { 68 | throw new Error('Loading link which directs outside of provided locations: ' + JSON.stringify(allowedLocations) + ' is forbidden!'); 69 | } 70 | } 71 | 72 | const stat = fs.fstatSync(fd); 73 | if (stat.isDirectory()) { 74 | throw new Error(`Expected path to a file, not a directory. Are you sure path "${filePath}" is correct?`); 75 | } 76 | const buff = Buffer.alloc(stat.size); 77 | fs.readSync(fd, buff, 0, buff.length); 78 | content = buff.toString(encoding); 79 | } 80 | catch (err) { 81 | logger.error('Problem loading file: ' + err); 82 | throw err; 83 | } 84 | finally { 85 | try { 86 | fs.closeSync(fd); 87 | } 88 | catch (err) { 89 | logger.error('Problem closing file ' + fd + ': ' + err); 90 | } 91 | } 92 | return content; 93 | } 94 | 95 | module.exports = readFileSafely; 96 | -------------------------------------------------------------------------------- /src/common/restClientErrors.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 32 | 'use strict'; 33 | 34 | class RuntimeError extends Error { 35 | constructor(message, details = {}) { 36 | super(message); 37 | this.details = details; 38 | } 39 | } 40 | 41 | class HttpNoRetryError extends Error { 42 | constructor(message, status, body, headers) { 43 | super(message); 44 | 45 | this.body = {}; 46 | this.status = status; 47 | this.headers = {}; 48 | 49 | if (body) { 50 | this.body = body; 51 | } 52 | 53 | if (headers) { 54 | this.headers = headers; 55 | } 56 | } 57 | } 58 | 59 | class HttpError extends Error { 60 | constructor(message, status, body, headers) { 61 | super(message); 62 | 63 | this.body = {}; 64 | this.status = status; 65 | this.headers = {}; 66 | 67 | if (body) { 68 | this.body = body; 69 | } 70 | 71 | if (headers) { 72 | this.headers = headers; 73 | } 74 | } 75 | } 76 | 77 | module.exports = { 78 | HttpError, 79 | RuntimeError, 80 | HttpNoRetryError 81 | }; 82 | -------------------------------------------------------------------------------- /src/common/tlsType.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 32 | 'use strict'; 33 | 34 | const MTLS = 'MTLS'; 35 | const TLS = 'TLS'; 36 | const None = 'None'; 37 | 38 | const CIPHERS = 39 | 'TLS_AES_256_GCM_SHA384:' + 40 | 'TLS_AES_128_GCM_SHA256:' + 41 | 'TLS_AES_128_CCM_SHA256: ' + 42 | 'DHE-PSK-AES256-GCM-SHA384:' + 43 | 'ECDHE-ECDSA-CHACHA20-POLY1305:' + 44 | 'ECDHE-ECDSA-AES256-GCM-SHA384:' + 45 | 'TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:' + 46 | 'TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:' + 47 | 'TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:' + 48 | 'ECDHE-PSK-CHACHA20-POLY1305:' + 49 | 'DHE-PSK-CHACHA20-POLY1305:' + 50 | 'DHE-DSS-AES256-GCM-SHA384:' + 51 | 'DHE-DSS-AES128-GCM-SHA256:' + 52 | 'DHE-PSK-AES128-GCM-SHA256:' + 53 | 'ECDHE-ECDSA-AES128-GCM-SHA256'; 54 | const MIN_SECURE_PROTOCOL = 'TLSv1.2'; 55 | const MAX_SECURE_PROTOCOL = 'TLSv1.3'; 56 | 57 | module.exports = { 58 | MTLS, 59 | TLS, 60 | None, 61 | CIPHERS, 62 | MIN_SECURE_PROTOCOL, 63 | MAX_SECURE_PROTOCOL, 64 | }; 65 | -------------------------------------------------------------------------------- /src/configLoader.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 32 | 'use strict'; 33 | 34 | const config = require('./common/config'); 35 | const ConfigLoader = config.ConfigLoader; 36 | const _ = require('lodash'); 37 | 38 | class QVSConfig extends config.BaseRestService { 39 | 40 | constructor(configJson) { 41 | 42 | super(configJson); 43 | this.validate(configJson, { 44 | required: ['service', 'pcsClient', 'crlClient', 'healthCheck', 'logger', 'cache', 'target'], 45 | properties: { 46 | crlClient: { 47 | required: ['retries', 'initialInterval', 'factor'], 48 | properties: { 49 | retries: { 50 | type: 'number' 51 | }, 52 | initialInterval: { 53 | type: 'number' 54 | }, 55 | factor: { 56 | type: 'number' 57 | } 58 | } 59 | }, 60 | target: { 61 | required: ['attestationReportSigningCaCertificate', 'attestationReportSigningCertificate', 'trustedRootPublicKey'], 62 | attestationReportSigningCaCertificate: { 63 | type: 'string' 64 | }, 65 | attestationReportSigningCertificate: { 66 | type: 'string' 67 | }, 68 | trustedRootPublicKey: { 69 | type: 'string' 70 | } 71 | } 72 | 73 | } 74 | }); 75 | 76 | this.pcsClient = new config.RestClient(configJson.pcsClient); 77 | if (configJson.vcsClient) { 78 | this.vcsClient = new config.RestClient(configJson.vcsClient); 79 | } 80 | this.crlClient = new config.BaseRestClient(configJson.crlClient); 81 | 82 | this.healthCheck = _.extend({}, configJson.healthCheck); 83 | this.logger = _.extend({}, configJson.logger); 84 | this.cache = new config.Cache(configJson.cache); 85 | this.target = configJson.target; 86 | } 87 | } 88 | 89 | const loader = new ConfigLoader(QVSConfig); 90 | 91 | module.exports = loader; 92 | -------------------------------------------------------------------------------- /src/fips/openssl.cnf: -------------------------------------------------------------------------------- 1 | nodejs_conf = nodejs_init 2 | 3 | .include /QVS/src/fips/fipsmodule.cnf 4 | 5 | [nodejs_init] 6 | providers = provider_sect 7 | 8 | [provider_sect] 9 | default = default_sect 10 | # The fips section name should match the section name inside the 11 | # included fipsmodule.cnf. 12 | fips = fips_sect 13 | 14 | [default_sect] 15 | activate = 1 16 | -------------------------------------------------------------------------------- /src/handlers/health.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 32 | 'use strict'; 33 | 34 | const healthChecker = require('../healthChecker'); 35 | 36 | module.exports = { 37 | checkHealth: async(ctx) => { 38 | await healthChecker.handleRequest(ctx); 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /src/healthChecker.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 32 | 'use strict'; 33 | 34 | const HealthCache = require('./koa/koaHealthCache'); 35 | const detailedErrorString = require('./common/detailedErrorString'); 36 | const config = require('./configLoader').getConfig(); 37 | const logger = require('./logger')(config); 38 | const { version } = require('./package.json'); 39 | const vcsHealth = require('./clients/vcsAccessLayer/VCSClient').getHealth; 40 | const errorHandler = require('./common/errorHandler'); 41 | const qvl = require('./qvl'); 42 | 43 | // initialize from configuration 44 | const koaHealthCache = new HealthCache({ 45 | frequencyMS: config.healthCheck.intervalMs, 46 | validityMS: config.healthCheck.freshnessMs, 47 | version, 48 | logger 49 | }); 50 | 51 | async function handleHealthConditionCallback(svcClientHealth, logger, reqId, callback) { 52 | try { // All exceptions have to be handled inside because function is executed without await in common code 53 | const response = await svcClientHealth(logger, { 'Request-ID': reqId }); 54 | return callback(null, response.body); 55 | } 56 | catch (err) { 57 | logger.error(`Request health ended with an error: ${detailedErrorString(err)}`); 58 | return callback(null, err.body); 59 | } 60 | } 61 | 62 | koaHealthCache.addComponentHealthCondition('VerificationCryptoService', async(logger, reqId, callback) => { 63 | return handleHealthConditionCallback(vcsHealth, logger, reqId, callback); 64 | }); 65 | 66 | koaHealthCache.addComponentHealthCondition('QuoteVerificationLibrary', async(logger, reqId, callback) => { 67 | try { // All exceptions have to be handled inside because function is executed without await in common code 68 | const response = await qvl.getVersion(reqId, logger); 69 | return callback(null, response.body); 70 | } 71 | catch (err) { 72 | logger.error(errorHandler.errorStackTraceHandler(err, logger.isMultiline), 'Request health ended with an error.'); 73 | return callback(null, err.body); 74 | } 75 | }); 76 | 77 | koaHealthCache.addComponentHealthCondition('this', async(logger, reqId, callback) => { 78 | callback(null, { 79 | status: koaHealthCache.status.OK, 80 | version 81 | }); 82 | }); 83 | 84 | 85 | module.exports = koaHealthCache; 86 | -------------------------------------------------------------------------------- /src/koa/commonDataValidator.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 32 | 'use strict'; 33 | 34 | const _ = require('lodash'); 35 | const validator = require('validator'); 36 | 37 | /** 38 | * IntelliJ IDEA has long lasting bugs: 39 | * https://youtrack.jetbrains.com/issue/WEB-31971 40 | * https://youtrack.jetbrains.com/issue/WEB-52385 41 | * JSDoc import works for example in Visual Studio Code. 42 | * 43 | * @typedef {import('../jsDoc/types').Logger} Logger 44 | */ 45 | 46 | /** 47 | * Validates hex string 48 | * 49 | * @param {string} name 50 | * @param {string} hexstring 51 | * @param {number} expectedLength 52 | * @param {Logger} log logger instance 53 | * 54 | * @return {boolean} 55 | */ 56 | function validateHexstring(name, hexstring, expectedLength, log) { 57 | if (!isHexString(name, hexstring, log)) { 58 | return false; 59 | } 60 | if (hexstring.length !== expectedLength) { 61 | log.error(`Parameter ${name}(${hexstring}) has invalid length: expected: ${expectedLength}, but found ${hexstring.length}.`); 62 | return false; 63 | } 64 | return true; 65 | } 66 | 67 | /** 68 | * Checks if value is hexstring 69 | * 70 | * @param {string} name 71 | * @param {string} hexstring 72 | * @param {Logger} log 73 | * 74 | * @return {boolean} 75 | */ 76 | function isHexString(name, hexstring, log) { 77 | if (!_.isString(hexstring)) { 78 | log.error(`Parameter ${name}(${hexstring}) is not a string.`); 79 | return false; 80 | } 81 | if (!validator.isHexadecimal(hexstring)) { 82 | log.error(`Parameter ${name}(${hexstring}) is not a valid hexstring.`); 83 | return false; 84 | } 85 | 86 | return true; 87 | } 88 | 89 | module.exports = { 90 | validateHexstring, 91 | isHexString, 92 | }; 93 | -------------------------------------------------------------------------------- /src/koa/errors.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 32 | 'use strict'; 33 | 34 | class SgxError extends Error { 35 | constructor(message) { 36 | super(message); 37 | this.name = this.constructor.name; 38 | } 39 | } 40 | 41 | class TcbOutOfDate extends SgxError {} 42 | class FmspNotFound extends SgxError {} 43 | class DeviceKeyNotFound extends SgxError {} 44 | class PpidNotFound extends SgxError {} 45 | class EventDataNotFound extends SgxError {} 46 | class EnclaveTcbNotFound extends SgxError {} 47 | class EnclaveIdentityNotFound extends SgxError {} 48 | class InvalidPlatformManifest extends SgxError {} 49 | class IncompatiblePackage extends SgxError {} 50 | class PackageNotFound extends SgxError {} 51 | class InvalidOrRevokedPackage extends SgxError {} 52 | class InvalidRegistrationServer extends SgxError {} 53 | class InvalidRequestSyntax extends SgxError {} 54 | 55 | class InternalError extends SgxError { 56 | constructor(message, cause) { 57 | super(message); 58 | this.cause = () => cause; 59 | } 60 | } 61 | 62 | class InternalErrorWithNoRetryStatus extends SgxError { 63 | constructor(body) { 64 | super(undefined); 65 | this.body = body; 66 | } 67 | } 68 | 69 | module.exports = { 70 | InternalError, 71 | InternalErrorWithNoRetryStatus, 72 | TcbOutOfDate, 73 | PpidNotFound, 74 | DeviceKeyNotFound, 75 | FmspNotFound, 76 | EnclaveTcbNotFound, 77 | EnclaveIdentityNotFound, 78 | EventDataNotFound, 79 | InvalidPlatformManifest, 80 | IncompatiblePackage, 81 | PackageNotFound, 82 | InvalidOrRevokedPackage, 83 | InvalidRegistrationServer, 84 | InvalidRequestSyntax 85 | }; 86 | -------------------------------------------------------------------------------- /src/koa/koaHealthRouter.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 32 | 'use strict'; 33 | 34 | const Router = require('koa-router'); 35 | 36 | /** 37 | * IntelliJ IDEA has long lasting bugs: 38 | * https://youtrack.jetbrains.com/issue/WEB-31971 39 | * https://youtrack.jetbrains.com/issue/WEB-52385 40 | * JSDoc import works for example in Visual Studio Code. 41 | * 42 | * @typedef {import('../jsDoc/types').KoaRouter} KoaRouter 43 | */ 44 | 45 | /** 46 | * Creates new router as its instances are mutable and should be used only once 47 | * 48 | * @param {function} healthHandler - handler for health router 49 | * @param {string} urlPrefix - optional url prefix, '/' as default 50 | * 51 | * @returns {KoaRouter} 52 | */ 53 | function createHealthRouter(healthHandler, urlPrefix = '/') { 54 | const router = new Router(); 55 | if (urlPrefix === '/') { 56 | router.get('/', healthHandler); 57 | router.get('/:component', healthHandler); 58 | } 59 | else { 60 | router.get(urlPrefix, healthHandler); 61 | router.get(`${urlPrefix}/:component`, healthHandler); 62 | } 63 | return router; 64 | } 65 | 66 | module.exports = { 67 | createHealthRouter 68 | }; 69 | -------------------------------------------------------------------------------- /src/koa/maxClientsHandler.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 32 | 'use strict'; 33 | 34 | const random = require('./../util/random'); 35 | const { 36 | STATUS_SERVICE_UNAVAILABLE 37 | } = require('./response').STATUSES; 38 | 39 | global.currentClients = 0; 40 | 41 | function decreaseCurrentClients(log, serviceName, taskType, taskID) { 42 | global.currentClients--; 43 | log.info('Decreasing number of clients. Current number: %s', global.currentClients); 44 | log.trace('STOP task_type: %s.%s task_id: %s', serviceName, taskType, taskID); 45 | } 46 | 47 | function handleServiceBusy(ctx) { 48 | ctx.status = STATUS_SERVICE_UNAVAILABLE.httpCode; 49 | ctx.body = { code: 'KO.', message: 'Server too busy.' }; 50 | } 51 | 52 | module.exports.createRequestManager = (serviceName, maxClients) => { 53 | return { 54 | manageRequest(taskType, action) { 55 | return async(ctx, next) => { 56 | const taskID = random.uuid(); 57 | if (global.currentClients + 1 <= maxClients) { 58 | global.currentClients++; 59 | ctx.log.info('Increasing number of clients. Current number: %s', global.currentClients); 60 | ctx.log.trace('START task_type: %s.%s task_id: %s', serviceName, taskType, taskID); 61 | 62 | const log = ctx.log; //ctx is cleared after finish/close 63 | ctx.res.on('finish', () => { 64 | decreaseCurrentClients(log, serviceName, taskType, taskID); 65 | }); 66 | ctx.res.on('close', () => { 67 | if (!ctx.res.writableFinished) { 68 | log.error('res.end() was not called. Something bad has happened.'); 69 | // ctx.res.finished = true; 70 | decreaseCurrentClients(log, serviceName, taskType, taskID); 71 | } 72 | }); 73 | return action(ctx, next); 74 | } 75 | else { 76 | ctx.log.info('Too many requests'); 77 | ctx.log.trace('Discarding task_type: %s task_id: %s', taskType, taskID); 78 | handleServiceBusy(ctx); 79 | } 80 | }; 81 | } 82 | }; 83 | }; 84 | -------------------------------------------------------------------------------- /src/koa/middleware/bodyParser.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 32 | 'use strict'; 33 | 34 | const bodyParser = require('koa-bodyparser'); 35 | 36 | /** 37 | * Configures and returns bodyParser 38 | * 39 | * @param {Object} config - service configuration 40 | * 41 | * @returns {function} bodyParser middleware 42 | */ 43 | function getConfiguredBodyParser(config) { 44 | const bodyParserOpts = { 45 | enableTypes: ['json', 'text', 'form'] 46 | }; 47 | if (config && config.service && config.service.bodySizeLimits) { 48 | bodyParserOpts.jsonLimit = config.service.bodySizeLimits.json; // default is 1mb 49 | bodyParserOpts.textLimit = config.service.bodySizeLimits.text; // default is 1mb 50 | bodyParserOpts.formLimit = config.service.bodySizeLimits.form; // default is 56kb 51 | } 52 | return bodyParser(bodyParserOpts); 53 | } 54 | 55 | module.exports = { 56 | getConfiguredBodyParser 57 | }; 58 | -------------------------------------------------------------------------------- /src/koa/middleware/configureCtxLoggerAndLogResponse.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 32 | 'use strict'; 33 | 34 | 35 | const { ERROR, WARN, INFO } = require('log4js').levels; 36 | 37 | const { formatResponseMessage } = require('../../common/requestLogFormatter'); 38 | const { STATUS_INTERNAL_ERROR, STATUS_BAD_REQUEST } = require('../response').STATUSES; 39 | 40 | function getLevel(status) { 41 | if (status >= STATUS_INTERNAL_ERROR.httpCode) { 42 | return ERROR.levelStr.toLowerCase(); 43 | } 44 | if (status >= STATUS_BAD_REQUEST.httpCode) { 45 | return WARN.levelStr.toLowerCase(); 46 | } 47 | return INFO.levelStr.toLowerCase(); 48 | } 49 | 50 | module.exports = (logger) => { 51 | return async(ctx, next) => { 52 | const t = Date.now(); 53 | ctx.log = logger; 54 | ctx.res.on('finish', () => { 55 | const dt = Date.now() - t; 56 | const messages = formatResponseMessage( 57 | ctx.request.method, ctx.request.originalUrl, ctx.status, ctx.response.headers, ctx.response.body, dt 58 | ); 59 | messages.forEach(msg => ctx.log[getLevel(ctx.status)](msg)); 60 | }); 61 | 62 | return next(); 63 | }; 64 | }; 65 | -------------------------------------------------------------------------------- /src/koa/middleware/errorHandler.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 32 | 'use strict'; 33 | 34 | /** 35 | * Handles errors thrown during request processing 36 | * 37 | * Removes charset from Content-Type response header 38 | * Logs an error and can hide detailed error message from client 39 | * 40 | * @param sendBodyOnErrors if body should be send with error responses 41 | */ 42 | 43 | function errorHandler(sendBodyOnErrors) { 44 | return async(ctx, next) => { 45 | try { 46 | await next(); 47 | removeCharsetFromContentTypeHeader(ctx); 48 | if (((ctx.status === 400 || ctx.status === 403 || ctx.status === 404 || ctx.status === 500 || ctx.status === 503) && !ctx.body) || 49 | (ctx.status > 400 && ctx.status !== 403 && ctx.status !== 404 && ctx.status !== 500 && ctx.status !== 503)) { 50 | ctx.throw(ctx.status); 51 | } 52 | } 53 | catch (err) { 54 | // HTTP errors won't be additionally logged 55 | const status = err.status || err.statusCode; 56 | if (!status) { 57 | ctx.log.error(err); 58 | } 59 | ctx.status = status || 500; 60 | // Bad Request HTTP error is the only one which gives more information to the user 61 | // Top level services should not return body on all errors 62 | if (status !== 400 || !sendBodyOnErrors) { 63 | ctx.body = ''; 64 | } 65 | else { 66 | ctx.body = { status: err.message }; 67 | removeCharsetFromContentTypeHeader(ctx); 68 | } 69 | } 70 | removeContentTypeWhenEmptyBody(ctx); 71 | }; 72 | } 73 | 74 | function removeCharsetFromContentTypeHeader(ctx) { 75 | let contentType = ctx.response.get('Content-Type'); 76 | if (contentType) { 77 | contentType = contentType.replace('; charset=utf-8', ''); 78 | ctx.set('Content-Type', contentType); 79 | } 80 | } 81 | 82 | function removeContentTypeWhenEmptyBody(ctx) { 83 | if (!ctx.body) { 84 | ctx.type = undefined; 85 | } 86 | } 87 | 88 | module.exports = { 89 | withBodyOnError: errorHandler(true), 90 | withNoBodyOnError: errorHandler(false) 91 | }; 92 | -------------------------------------------------------------------------------- /src/koa/middleware/rawBodyParser.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 32 | 'use strict'; 33 | 34 | const getRawBody = require('raw-body'); 35 | const PassThrough = require('stream').PassThrough; 36 | 37 | /** 38 | * Configures and returns bodyParser 39 | * @param {Object} config - service configuration 40 | * @returns {function} rawBodyParser middleware 41 | */ 42 | function getConfiguredRawBodyParser(config) { 43 | return async(ctx, next) => { 44 | try { 45 | /* 46 | Observed behaviour: 47 | 0. keep-alive must be enabled 48 | 1. client sends too long request 49 | 2. server's middleware pareses the stream and throws error 50 | 3. koa catches the error, returns response 51 | 4. koa kills socket w/o informing the client 52 | 5. client sends an another request and receives 'socket hung' error 53 | 54 | Wrap the stream in another stream to prevent koa noticing an error. 55 | If there is no error, connection remains alive. 56 | */ 57 | const wrappedStream = ctx.request.req.on('error', ctx.onerror).pipe(new PassThrough()); 58 | ctx.request.body = await getRawBody(wrappedStream, { 59 | length: ctx.request.headers['content-length'], 60 | limit: config.service.bodySizeLimits.blob 61 | }); 62 | await next(); 63 | } 64 | catch (err) { 65 | ctx.log.error(err); 66 | ctx.throw(err.statusCode ? err.statusCode : 500); 67 | } 68 | }; 69 | } 70 | 71 | module.exports = { 72 | getConfiguredRawBodyParser 73 | }; 74 | -------------------------------------------------------------------------------- /src/koa/middleware/requestBodyLogger.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 32 | 'use strict'; 33 | 34 | const requestLogFormatter = require('../../common/requestLogFormatter'); 35 | 36 | module.exports = async(ctx, next) => { 37 | // Body has to be logged after parsing and accepting 38 | // It make sense to print request headers before, as they show the reason of return of 413 http code if it happens 39 | const msg = requestLogFormatter.formatRequestBodyMessage(ctx.request.body); 40 | if (msg) { 41 | ctx.log.info(msg); 42 | } 43 | 44 | return next(); 45 | }; 46 | -------------------------------------------------------------------------------- /src/koa/middleware/requestControl.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 32 | 'use strict'; 33 | 34 | /** 35 | * Request control 36 | * @param {Object} opts 37 | * @return {function} returns middleware 38 | */ 39 | function requestControl(opts) { 40 | const options = opts || {}; 41 | const allowedMethods = options.allowedMethods || ['PUT', 'GET', 'POST', 'DELETE']; // this is just to filter out HEAD, CONNECT, TRACE, etc. methods 42 | const contentType = options.contentType || 'application/json'; // it should be configured per endpoint, I will leave this logic as it was until it bites us 43 | 44 | return async(ctx, next) => { 45 | const path = ctx.path; 46 | const method = ctx.req.method; 47 | const router = ctx.app.middleware.find(x => x.name === 'dispatch').router; // pull out router from the request context 48 | const matched = router.match(path, method); 49 | 50 | const allowed = {}; 51 | for (let i = 0; i < matched.path.length; i++) { 52 | const route = matched.path[i]; 53 | for (let j = 0; j < route.methods.length; j++) { 54 | const method = route.methods[j]; 55 | if (allowedMethods.includes(method)) { 56 | allowed[method] = method; 57 | } 58 | } 59 | } 60 | const allowedArr = Object.keys(allowed); // allowedArr is almost copy pasted from koa-router's allowedMethods method 61 | 62 | if (matched.path.length === 0 || allowedArr.length === 0) { 63 | ctx.log.warn(`Path: ${path} is not allowed.`); 64 | ctx.throw(404); 65 | } 66 | 67 | if (!allowedArr.includes(method) || !matched.route) { 68 | ctx.log.warn(`Method: ${method} is not allowed.`); 69 | ctx.set('Allow', allowedArr.join(', ')); 70 | ctx.throw(405); 71 | } 72 | 73 | if (method === 'GET') { 74 | // If there is no request body, null is returned. If there is no content type, 75 | // or the match fails false is returned. Otherwise, it returns the matching content-type. 76 | if (ctx.is('*/*') !== null) { 77 | ctx.log.warn('Incoming request has not empty body for GET method. Return 415 Unsupported Media Type.'); 78 | ctx.throw(415); 79 | } 80 | return next(); 81 | } 82 | 83 | if (contentType !== 'None' && !ctx.is(contentType)) { 84 | ctx.log.warn(`Only ${contentType} content type is supported. Return 415 Unsupported Media Type.`); 85 | ctx.throw(415); 86 | } 87 | return next(); 88 | }; 89 | } 90 | 91 | module.exports = { 92 | requestControl 93 | }; 94 | -------------------------------------------------------------------------------- /src/koa/middleware/requestId.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 32 | 'use strict'; 33 | 34 | const { Buffer } = require('node:buffer'); 35 | const { WARN, INFO, DEBUG } = require('log4js').levels; 36 | const uuidGen = require('uuid-random'); 37 | const validators = require('../commonDataValidator'); 38 | const requestLogFormatter = require('../../common/requestLogFormatter'); 39 | 40 | async function generateReqId() { 41 | return Buffer.from(uuidGen.bin()).toString('hex'); 42 | } 43 | 44 | module.exports = (serverLevel) => { 45 | return async function requestId(ctx, next) { 46 | let msg = ''; 47 | let logLevel = INFO.levelStr.toLowerCase(); 48 | const incomingReqIDHeader = ctx.req.headers['request-id']; 49 | // Set correct reqId 50 | if (incomingReqIDHeader) { 51 | if (serverLevel.isTopLevel) { 52 | ctx.reqId = ctx.request.reqId = await generateReqId(); 53 | msg = `Received own Request-ID header: [${incomingReqIDHeader}]. New Request-ID is: [${ctx.reqId}]`; 54 | } 55 | else if (!validators.validateHexstring('Request-ID', incomingReqIDHeader, 32, ctx.log)) { 56 | ctx.reqId = ctx.request.reqId = await generateReqId(); 57 | msg = `Received own Request-ID header: [${incomingReqIDHeader}] has incorrect format (must be 32-sign hexadecimal). New Request-ID is: [${ctx.reqId}]`; 58 | logLevel = WARN.levelStr.toLowerCase(); 59 | } 60 | else { 61 | ctx.reqId = ctx.request.reqId = incomingReqIDHeader; 62 | msg = `Using received Request-ID: [${ctx.reqId}]`; 63 | logLevel = DEBUG.levelStr.toLowerCase(); 64 | } 65 | } 66 | else { 67 | ctx.reqId = ctx.request.reqId = await generateReqId(); 68 | msg = `No Request-ID header. New Request-ID is: [${ctx.reqId}]`; 69 | logLevel = DEBUG.levelStr.toLowerCase(); 70 | } 71 | 72 | ctx.log = ctx.log.scoped(ctx.reqId); 73 | ctx.log[logLevel](msg); 74 | 75 | ctx.log.info(requestLogFormatter.formatRequestMessageWithoutBody( 76 | ctx.request.method, ctx.request.originalUrl, ctx.request.headers 77 | )); 78 | 79 | // Add response header with Request-ID 80 | ctx.set('Request-ID', ctx.reqId); 81 | return next(); 82 | }; 83 | }; 84 | -------------------------------------------------------------------------------- /src/logger.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 32 | 'use strict'; 33 | 34 | const logger = require('./common/logger'); 35 | const qvl = require('./qvl'); 36 | const path = require('node:path'); 37 | 38 | module.exports = (config) => { 39 | const loggerConfig = config.logger; 40 | 41 | const fileNameParsed = path.parse(loggerConfig.fileName); 42 | const qvlLogFileName = path.format({ 43 | dir: fileNameParsed.dir, 44 | name: fileNameParsed.name + '-qvl', 45 | ext: fileNameParsed.ext 46 | }); 47 | 48 | qvl.loggerSetup(loggerConfig.category, loggerConfig.levelConsole.toUpperCase(), loggerConfig.levelFile.toUpperCase(), 49 | qvlLogFileName, '[%Y-%m-%dT%H:%M:%S.%eZ] [%l] [%n %@] [pid:%P]%r %v'); 50 | 51 | return logger.createLogger(loggerConfig.category, loggerConfig.fileName, loggerConfig.levelFile, 52 | loggerConfig.levelConsole, loggerConfig.isMultilineLogEnabled); 53 | }; 54 | -------------------------------------------------------------------------------- /src/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "quoteverificationservice", 3 | "scripts": { 4 | "install": "cmake-js build -d qvl/ -O qvl/cmake-build-release", 5 | "install-debug": "cmake-js build -d qvl/ -O qvl/cmake-build-release --debug", 6 | "swagger": "node swagger.js" 7 | }, 8 | "version": "1.0.0", 9 | "license": "SEE LICENSE IN RESPECTIVE FILES", 10 | "main": "bootstrap.js", 11 | "dependencies": { 12 | "axios": "^1.6.8", 13 | "bluebird": "^3.7.2", 14 | "fast-url-parser": "^1.1.3", 15 | "https-proxy-agent": "^5.0.1", 16 | "js-yaml": "^4.1.0", 17 | "koa": "^2.14.2", 18 | "koa-bodyparser": "^4.4.1", 19 | "koa-router": "^12.0.1", 20 | "lodash": "^4.17.21", 21 | "log4js": "^6.9.1", 22 | "moment": "^2.29.4", 23 | "node-addon-api": "^6.1.0", 24 | "node-cache": "^5.1.2", 25 | "raw-body": "^2.5.2", 26 | "retry": "^0.13.1", 27 | "safe-buffer": "^5.2.1", 28 | "serialize-error": "^8.1.0", 29 | "uuid-random": "^1.3.2", 30 | "validator": "^13.9.0", 31 | "z-schema": "^6.0.1" 32 | }, 33 | "devDependencies": { 34 | "cmake-js": "^7.2.1" 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/qvl/BaseWorker.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 32 | #include "BaseWorker.h" 33 | #include 34 | 35 | namespace intel::sgx::dcap::qvlwrapper { 36 | void BaseWorker::Execute() 37 | { 38 | sgxAttestationLoggerSetCustomField("reqId", requestId.c_str()); 39 | Run(); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/qvl/BaseWorker.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 32 | #ifndef QUOTEVERIFICATIONLIBRARYWRAPPER_BASEWORKER_H 33 | #define QUOTEVERIFICATIONLIBRARYWRAPPER_BASEWORKER_H 34 | 35 | #include 36 | #include // std::move 37 | 38 | namespace intel::sgx::dcap::qvlwrapper { 39 | class BaseWorker : public Napi::AsyncWorker{ 40 | public: 41 | BaseWorker(Napi::Env &env, Napi::Promise::Deferred &promise, std::string requestId) 42 | : Napi::AsyncWorker(env), promise(promise), requestId(std::move(requestId)) {} 43 | 44 | ~BaseWorker() override = default; 45 | 46 | void Execute() override; 47 | 48 | virtual void Run() = 0; 49 | 50 | protected: 51 | std::string requestId; 52 | Napi::Promise::Deferred promise; 53 | }; 54 | } 55 | 56 | 57 | #endif //QUOTEVERIFICATIONLIBRARYWRAPPER_BASEWORKER_H 58 | -------------------------------------------------------------------------------- /src/qvl/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright (c) 2022, Intel Corporation 3 | # SPDX-License-Identifier: BSD-3-Clause 4 | # 5 | # Redistribution and use in source and binary forms, with or without 6 | # modification, are permitted provided that the following conditions are met: 7 | # 8 | # * Redistributions of source code must retain the above copyright notice, 9 | # this list of conditions and the following disclaimer. 10 | # * Redistributions in binary form must reproduce the above copyright notice, 11 | # this list of conditions and the following disclaimer in the documentation 12 | # and/or other materials provided with the distribution. 13 | # * Neither the name of Intel Corporation nor the names of its contributors 14 | # may be used to endorse or promote products derived from this software 15 | # without specific prior written permission. 16 | # 17 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 18 | # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 19 | # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 20 | # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 21 | # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 22 | # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 23 | # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 24 | # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 25 | # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 26 | # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 27 | # POSSIBILITY OF SUCH DAMAGE. 28 | # 29 | 30 | cmake_minimum_required(VERSION 3.18) 31 | #Consider building from sources by including cmake from QVL 32 | #set(QVL_SRC ${CMAKE_CURRENT_LIST_DIR}/../../../../QVL/QVL/Src/CMakeLists.txt) 33 | #include(${QVL_SRC}) 34 | 35 | project (QuoteVerificationLibraryWrapper) 36 | 37 | if(NOT DEFINED QVL_PATH) 38 | message(FATAL_ERROR "You must provide QVL_PATH") 39 | endif() 40 | message(STATUS "QVL_PATH set to ${QVL_PATH}") 41 | 42 | set(CMAKE_DEBUG_POSTFIX d) 43 | 44 | if(CMAKE_BUILD_TYPE STREQUAL "Debug") 45 | set(QVL_LIB_NAME "QuoteVerificationStaticd") 46 | set(ATTESTATIONPARSERS_LIB_NAME "AttestationParsersStaticd") 47 | set(ATTESTATIONCOMMONS_LIB_NAME "AttestationCommonsStaticd") 48 | else() 49 | set(QVL_LIB_NAME "QuoteVerificationStatic") 50 | set(ATTESTATIONPARSERS_LIB_NAME "AttestationParsersStatic") 51 | set(ATTESTATIONCOMMONS_LIB_NAME "AttestationCommonsStatic") 52 | endif() 53 | message(STATUS "QVL_LIB_NAME set to ${QVL_LIB_NAME}") 54 | message(STATUS "ATTESTATIONPARSERS_LIB_NAME set to ${ATTESTATIONPARSERS_LIB_NAME}") 55 | 56 | 57 | find_library(QVL NAMES ${QVL_LIB_NAME} PATHS ${QVL_PATH}/lib) 58 | find_library(AttestationParsers NAMES ${ATTESTATIONPARSERS_LIB_NAME} PATHS ${QVL_PATH}/lib) 59 | find_library(AttestationCommons NAMES ${ATTESTATIONCOMMONS_LIB_NAME} PATHS ${QVL_PATH}/lib) 60 | 61 | file(GLOB SOURCE_FILES *.cpp *.h) 62 | add_library(${PROJECT_NAME} SHARED ${SOURCE_FILES} ${CMAKE_JS_SRC}) 63 | 64 | set_property(TARGET ${PROJECT_NAME} PROPERTY CXX_STANDARD 17) 65 | set_target_properties(${PROJECT_NAME} PROPERTIES PREFIX "" SUFFIX ".node") 66 | 67 | execute_process(COMMAND node -p "require('node-addon-api').include" 68 | WORKING_DIRECTORY ${CMAKE_SOURCE_DIR} 69 | OUTPUT_VARIABLE NODE_ADDON_API_DIR 70 | ) 71 | string(REPLACE "\n" "" NODE_ADDON_API_DIR ${NODE_ADDON_API_DIR}) 72 | string(REPLACE "\"" "" NODE_ADDON_API_DIR ${NODE_ADDON_API_DIR}) 73 | 74 | if(NOT DEFINED CMAKE_JS_INC) 75 | message(FATAL_ERROR "You must provide CMAKE_JS_INC") 76 | endif() 77 | message(STATUS "CMAKE_JS_INC set to ${CMAKE_JS_INC}") 78 | 79 | target_include_directories(${PROJECT_NAME} 80 | PRIVATE ${NODE_ADDON_API_DIR} 81 | PRIVATE ${CMAKE_JS_INC} 82 | PRIVATE ${QVL_PATH}/include) 83 | 84 | target_link_libraries(${PROJECT_NAME} ${CMAKE_JS_LIB} ${QVL} ${AttestationParsers} ${AttestationCommons}) 85 | -------------------------------------------------------------------------------- /src/qvl/GetCertificationDataWorker.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 32 | #include "GetCertificationDataWorker.h" 33 | 34 | 35 | namespace intel::sgx::dcap::qvlwrapper { 36 | void GetCertificationDataWorker::Run() { 37 | qvlStatus = sgxAttestationGetQECertificationDataSize(quote, quoteSize, &qeCertificationDataSize); 38 | if (qvlStatus != STATUS_OK) { 39 | SetError("sgxAttestationGetQECertificationDataSize failed"); 40 | return; 41 | } 42 | 43 | qeCertificationData = new uint8_t[qeCertificationDataSize]; 44 | 45 | qvlStatus = sgxAttestationGetQECertificationData(quote, quoteSize, qeCertificationDataSize, 46 | qeCertificationData, 47 | &qeCertificationDataType); 48 | 49 | if (qvlStatus != STATUS_OK) { 50 | SetError("sgxAttestationGetQECertificationData failed"); 51 | return; 52 | } 53 | } 54 | 55 | void GetCertificationDataWorker::OnOK() { 56 | auto returnObj = Napi::Object::New(Env()); 57 | returnObj.Set("type", qeCertificationDataType); 58 | returnObj.Set("data",Napi::Buffer::Copy(Env(), qeCertificationData, qeCertificationDataSize)); 59 | promise.Resolve(returnObj); 60 | 61 | delete qeCertificationData; 62 | } 63 | 64 | void GetCertificationDataWorker::OnError(const Napi::Error &e) { 65 | auto returnObj = Napi::Object::New(Env()); 66 | returnObj.Set("status", (int) qvlStatus); 67 | returnObj.Set("error", e.Message()); 68 | promise.Reject(returnObj); 69 | 70 | delete qeCertificationData; 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/qvl/GetCertificationDataWorker.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 32 | #ifndef QUOTEVERIFICATIONLIBRARYWRAPPER_GETCERTIFICATIONDATAWORKER_H 33 | #define QUOTEVERIFICATIONLIBRARYWRAPPER_GETCERTIFICATIONDATAWORKER_H 34 | 35 | #include 36 | 37 | #include 38 | #include "BaseWorker.h" 39 | 40 | namespace intel::sgx::dcap::qvlwrapper { 41 | class GetCertificationDataWorker : public BaseWorker { 42 | public: 43 | GetCertificationDataWorker(Napi::Env &env, Napi::Promise::Deferred &promise, const std::string& requestId, 44 | uint8_t *quote, uint32_t quoteSize) 45 | : BaseWorker(env, promise, requestId), quote(quote), quoteSize(quoteSize) {} 46 | 47 | ~GetCertificationDataWorker() override = default; 48 | 49 | void Run() override; 50 | 51 | void OnOK() override; 52 | 53 | void OnError(const Napi::Error &e) override ; 54 | 55 | private: 56 | uint8_t *quote = nullptr; 57 | uint32_t quoteSize = 0; 58 | uint16_t qeCertificationDataType{}; 59 | uint8_t *qeCertificationData{}; 60 | uint32_t qeCertificationDataSize{}; 61 | Status qvlStatus = STATUS_OK; 62 | }; 63 | } 64 | #endif //QUOTEVERIFICATIONLIBRARYWRAPPER_GETCERTIFICATIONDATAWORKER_H 65 | -------------------------------------------------------------------------------- /src/qvl/GetCrlDistributionPointWorker.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 32 | #include 33 | #include "GetCrlDistributionPointWorker.h" 34 | 35 | namespace intel::sgx::dcap::qvlwrapper { 36 | using namespace intel::sgx::dcap::parser; 37 | 38 | void GetCrlDistributionPointWorker::Run() { 39 | try { 40 | auto certificate = x509::Certificate::parse(pemCertificate); 41 | crlDistributionPoint = certificate.getCrlDistributionPoint(); 42 | } 43 | catch (std::exception& e) { 44 | std::string msg = "Error getting CRL distribution point: "; 45 | msg.append(e.what()); 46 | SetError(msg); 47 | return; 48 | } 49 | } 50 | 51 | void GetCrlDistributionPointWorker::OnOK() { 52 | auto napiValue = Napi::String::New(Env(), crlDistributionPoint); 53 | promise.Resolve(napiValue); 54 | } 55 | 56 | void GetCrlDistributionPointWorker::OnError(const Napi::Error &e) { 57 | auto returnObj = Napi::Object::New(Env()); 58 | returnObj.Set("error", e.Message()); 59 | promise.Reject(returnObj); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/qvl/GetCrlDistributionPointWorker.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 32 | #ifndef QUOTEVERIFICATIONLIBRARYWRAPPER_GETCRLDISTRIBUTIONPOINT_H 33 | #define QUOTEVERIFICATIONLIBRARYWRAPPER_GETCRLDISTRIBUTIONPOINT_H 34 | 35 | #include 36 | 37 | #include // std::move 38 | #include "BaseWorker.h" 39 | 40 | namespace intel::sgx::dcap::qvlwrapper { 41 | class GetCrlDistributionPointWorker : public BaseWorker{ 42 | public: 43 | GetCrlDistributionPointWorker(Napi::Env &env, Napi::Promise::Deferred &promise, const std::string& requestId, 44 | std::string pemCertificate) 45 | : BaseWorker(env, promise, requestId), pemCertificate(std::move(pemCertificate)) {} 46 | 47 | ~GetCrlDistributionPointWorker() override = default; 48 | 49 | void Run() override; 50 | 51 | void OnOK() override; 52 | 53 | void OnError(const Napi::Error &e) override; 54 | 55 | private: 56 | const std::string pemCertificate; 57 | std::string crlDistributionPoint; 58 | }; 59 | } 60 | 61 | #endif //QUOTEVERIFICATIONLIBRARYWRAPPER_GETCRLDISTRIBUTIONPOINT_H 62 | -------------------------------------------------------------------------------- /src/qvl/GetPckCertificateDataWorker.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 32 | #ifndef QUOTEVERIFICATIONLIBRARYWRAPPER_GetPckCertificateDataWORKER_H 33 | #define QUOTEVERIFICATIONLIBRARYWRAPPER_GetPckCertificateDataWORKER_H 34 | 35 | #include 36 | #include "BaseWorker.h" 37 | #include 38 | #include // std::move 39 | 40 | namespace intel::sgx::dcap::qvlwrapper { 41 | 42 | class GetPckCertificateDataWorker : public BaseWorker { 43 | public: 44 | GetPckCertificateDataWorker(Napi::Env &env, Napi::Promise::Deferred &promise, const std::string& requestId, 45 | std::string pemCertificate) 46 | : BaseWorker(env, promise, requestId), pemCertificate(std::move(pemCertificate)) {} 47 | 48 | ~GetPckCertificateDataWorker() override = default; 49 | 50 | void Run() override; 51 | 52 | void OnOK() override; 53 | 54 | void OnError(const Napi::Error &e) override; 55 | 56 | private: 57 | const std::string pemCertificate; // input 58 | std::vector fmspc{}; // output 59 | dcap::parser::x509::SgxType sgxType{}; // output 60 | bool dynamicPlatform{}; // output 61 | bool cachedKeys{}; // output 62 | bool smtEnabled{}; // output 63 | std::vector cpusvn{}; // output 64 | std::uint32_t pcesvn{}; // output 65 | }; 66 | 67 | } 68 | #endif //QUOTEVERIFICATIONLIBRARYWRAPPER_GetPckCertificateDataWORKER_H 69 | -------------------------------------------------------------------------------- /src/qvl/VerifyQuoteErrorSource.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 32 | namespace intel::sgx::dcap::qvlwrapper { 33 | 34 | enum VerifyQuoteErrorSource 35 | { 36 | VERIFY_PCK_CERTIFICATE, 37 | VERIFY_TCB_INFO, 38 | VERIFY_ENCLAVE_IDENTITY, 39 | VERIFY_QUOTE 40 | }; 41 | } 42 | -------------------------------------------------------------------------------- /src/qvl/VerifyQuoteWorker.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 32 | #include "VerifyQuoteWorker.h" 33 | 34 | namespace intel::sgx::dcap::qvlwrapper { 35 | void VerifyQuoteWorker::Run() { 36 | auto pckCertChain = pckCertIssuerCertChain + pckCert; 37 | const char *crls[] = {rootCaCrl.c_str(), pckCrl.c_str()}; 38 | 39 | qvlStatus = sgxAttestationVerifyPCKCertificate(pckCertChain.c_str(), crls, trustedRootCaPem.c_str(), nullptr); 40 | if (qvlStatus != STATUS_OK) { 41 | errorSource = VERIFY_PCK_CERTIFICATE; 42 | SetError("PCK certificate verification failed"); 43 | return; 44 | } 45 | 46 | qvlStatus = sgxAttestationVerifyTCBInfo(tcbInfo.c_str(), tcbInfoIssuerCertChain.c_str(), rootCaCrl.c_str(), 47 | tcbInfoSigningChainTrustedRoot.c_str(), nullptr); 48 | if (qvlStatus != STATUS_OK) { 49 | errorSource = VERIFY_TCB_INFO; 50 | SetError("TCB info verification failed"); 51 | return; 52 | } 53 | 54 | qvlStatus = sgxAttestationVerifyEnclaveIdentity(qeIdentity.c_str(), tcbInfoIssuerCertChain.c_str(), 55 | rootCaCrl.c_str(), tcbInfoSigningChainTrustedRoot.c_str(), nullptr); 56 | if (qvlStatus != STATUS_OK) { 57 | errorSource = VERIFY_ENCLAVE_IDENTITY; 58 | SetError("Enclave identity verification failed"); 59 | return; 60 | } 61 | 62 | qvlStatus = sgxAttestationVerifyQuote(quote, quoteSize, pckCert.c_str(), pckCrl.c_str(), tcbInfo.c_str(), 63 | qeIdentity.c_str()); 64 | if (qvlStatus != STATUS_OK) { 65 | errorSource = VERIFY_QUOTE; 66 | SetError("Quote verification failed"); 67 | return; 68 | } 69 | } 70 | 71 | void VerifyQuoteWorker::OnOK() { 72 | auto returnObj = Napi::Object::New(Env()); 73 | returnObj.Set("status", static_cast(qvlStatus)); 74 | promise.Resolve(returnObj); 75 | } 76 | 77 | void VerifyQuoteWorker::OnError(const Napi::Error &e) { 78 | auto returnObj = Napi::Object::New(Env()); 79 | returnObj.Set("status", static_cast(qvlStatus)); 80 | returnObj.Set("errorSource", static_cast(errorSource)); 81 | returnObj.Set("error", e.Message()); 82 | promise.Resolve(returnObj); 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/qvl/VerifyQuoteWorker.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 32 | #ifndef QUOTEVERIFICATIONLIBRARYWRAPPER_VERIFYQUOTEQORKER_H 33 | #define QUOTEVERIFICATIONLIBRARYWRAPPER_VERIFYQUOTEQORKER_H 34 | 35 | #include 36 | #include 37 | #include "BaseWorker.h" 38 | #include "VerifyQuoteErrorSource.h" 39 | 40 | namespace intel::sgx::dcap::qvlwrapper { 41 | 42 | class VerifyQuoteWorker : public BaseWorker { 43 | public: 44 | VerifyQuoteWorker(Napi::Env &env, Napi::Promise::Deferred &promise, const std::string& requestId, 45 | uint8_t *quote, 46 | size_t quoteSize, 47 | std::string pckCert, 48 | std::string tcbInfo, 49 | std::string qeIdentity, 50 | std::string pckCertIssuerCertChain, 51 | std::string tcbInfoIssuerCertChain, 52 | std::string pckCrl, 53 | std::string rootCaCrl, 54 | std::string trustedRootCaPem, 55 | std::string tcbInfoSigningChainTrustedRoot) 56 | : BaseWorker(env, promise, requestId), 57 | quote(quote), 58 | quoteSize(quoteSize), 59 | pckCert(std::move(pckCert)), 60 | tcbInfo(std::move(tcbInfo)), 61 | qeIdentity(std::move(qeIdentity)), 62 | pckCertIssuerCertChain(std::move(pckCertIssuerCertChain)), 63 | tcbInfoIssuerCertChain(std::move(tcbInfoIssuerCertChain)), 64 | pckCrl(std::move(pckCrl)), 65 | rootCaCrl(std::move(rootCaCrl)), 66 | trustedRootCaPem(std::move(trustedRootCaPem)), 67 | tcbInfoSigningChainTrustedRoot(std::move(tcbInfoSigningChainTrustedRoot)) {} 68 | 69 | ~VerifyQuoteWorker() override = default; 70 | 71 | void Run() override; 72 | 73 | void OnOK() override; 74 | 75 | void OnError(const Napi::Error &e) override ; 76 | 77 | private: 78 | uint8_t *quote = nullptr; 79 | size_t quoteSize = 0; 80 | std::string pckCert; 81 | std::string tcbInfo; 82 | std::string qeIdentity; 83 | std::string pckCertIssuerCertChain; 84 | std::string tcbInfoIssuerCertChain; 85 | std::string pckCrl; 86 | std::string rootCaCrl; 87 | std::string trustedRootCaPem; 88 | std::string tcbInfoSigningChainTrustedRoot; 89 | 90 | Status qvlStatus = STATUS_OK; 91 | VerifyQuoteErrorSource errorSource{}; 92 | }; 93 | 94 | } 95 | #endif //QUOTEVERIFICATIONLIBRARYWRAPPER_VERIFYQUOTEQORKER_H 96 | -------------------------------------------------------------------------------- /src/qvl/VersionWorker.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 32 | #include "VersionWorker.h" 33 | 34 | namespace intel::sgx::dcap::qvlwrapper { 35 | void VersionWorker::Run() { 36 | size_t bufSize = 10; 37 | auto version = std::make_unique(bufSize); 38 | sgxEnclaveAttestationGetVersion(version.get(), bufSize); 39 | result = std::string(version.get()); 40 | } 41 | 42 | void VersionWorker::OnOK() { 43 | auto returnObj = Napi::Object::New(Env()); 44 | returnObj.Set("result", result); 45 | promise.Resolve(returnObj); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/qvl/VersionWorker.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 32 | #ifndef QUOTEVERIFICATIONLIBRARYWRAPPER_VERSIONWORKER_H 33 | #define QUOTEVERIFICATIONLIBRARYWRAPPER_VERSIONWORKER_H 34 | 35 | #include 36 | #include 37 | #include 38 | #include "BaseWorker.h" 39 | 40 | namespace intel::sgx::dcap::qvlwrapper { 41 | class VersionWorker : public BaseWorker { 42 | public: 43 | VersionWorker(Napi::Env &env, Napi::Promise::Deferred &promise, const std::string& requestId) 44 | : BaseWorker(env, promise, requestId) {} 45 | 46 | ~VersionWorker() override = default; 47 | 48 | void Run() override; 49 | void OnOK() override; 50 | 51 | private: 52 | std::string result = "NA"; 53 | }; 54 | 55 | } 56 | #endif //QUOTEVERIFICATIONLIBRARYWRAPPER_VERSIONWORKER_H 57 | -------------------------------------------------------------------------------- /src/qvl/verifyQuoteErrorSource.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 32 | 'use strict'; 33 | 34 | 35 | /** 36 | * These statuses are taken from file VerifyQuoteErrorSource.h in wrapper and should be kept in sync with it 37 | * @readonly 38 | * @enum {number} 39 | */ 40 | module.exports = { 41 | VERIFY_PCK_CERTIFICATE: 0, 42 | VERIFY_TCB_INFO: 1, 43 | VERIFY_ENCLAVE_IDENTITY: 2, 44 | VERIFY_QUOTE: 3 45 | }; 46 | -------------------------------------------------------------------------------- /src/routes/health.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 32 | 'use strict'; 33 | 34 | const { createHealthRouter } = require('../koa/koaHealthRouter'); 35 | const healthHandler = require('../handlers/health'); 36 | 37 | function createRouter(urlPrefix) { 38 | return createHealthRouter(healthHandler.checkHealth, urlPrefix); 39 | } 40 | 41 | module.exports = { 42 | createRouter 43 | }; 44 | -------------------------------------------------------------------------------- /src/routes/index.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 32 | 'use strict'; 33 | 34 | const Router = require('koa-router'); 35 | 36 | /* Place to import all nested routers below */ 37 | const healthRouter = require('./health').createRouter(); 38 | const verifyAttestationEvidenceRouter = require('./v1/verifyAttestationEvidence').createRouter(); 39 | 40 | /* Place to compose service API below */ 41 | const apiRouter = new Router(); 42 | 43 | /* 44 | #swagger.start 45 | #swagger.path = '/health' 46 | #swagger.method = 'get' 47 | #swagger.description = 'Checks communication with dependent services' 48 | #swagger.produces = ["application/json"] 49 | #swagger.responses[200] = { 50 | schema: { 51 | '$ref': '#/definitions/PositiveHealthReport' 52 | }, 53 | description: 'Health report', 54 | headers: { 55 | 'Request-ID': { 56 | description: 'Request ID', 57 | type: 'string' 58 | } 59 | } 60 | } 61 | #swagger.responses[503] = { 62 | schema: { 63 | '$ref': '#/definitions/NegativeHealthReport' 64 | }, 65 | description: 'Health report', 66 | headers: { 67 | 'Request-ID': { 68 | description: 'Request ID', 69 | type: 'string' 70 | } 71 | } 72 | } 73 | #swagger.end 74 | */ 75 | apiRouter.use('/health', healthRouter.routes(), healthRouter.allowedMethods()); 76 | 77 | apiRouter.use('/attestation/sgx/dcap/v1/report', verifyAttestationEvidenceRouter.routes(), verifyAttestationEvidenceRouter.allowedMethods()); 78 | 79 | 80 | module.exports = apiRouter; 81 | -------------------------------------------------------------------------------- /src/routes/v1/verifyAttestationEvidence.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 32 | 'use strict'; 33 | 34 | const Router = require('koa-router'); 35 | 36 | const { verifyAttestationEvidence } = require('../../handlers/verifyAttestationEvidence'); 37 | 38 | /** 39 | * @typedef Router 40 | * @type {object} 41 | * @property {function} routes 42 | * @property {function} allowedMethods 43 | */ 44 | 45 | /** 46 | * Creates new router 47 | * @returns {Router} 48 | */ 49 | function createRouter() { 50 | const router = new Router(); 51 | router.post('/', verifyAttestationEvidence); 52 | return router; 53 | } 54 | 55 | module.exports = { 56 | createRouter 57 | }; 58 | -------------------------------------------------------------------------------- /src/server.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 32 | 'use strict'; 33 | 34 | const process = require('process'); 35 | 36 | const config = require('./configLoader').getConfig(); 37 | const logger = require('./logger')(config); 38 | 39 | const HealthCache = require('./healthChecker'); 40 | const router = require('./routes'); 41 | 42 | const ServerInit = require('./koa/init/serverInit'); 43 | const { getConfiguredBodyParser } = require('./koa/middleware/bodyParser'); 44 | const requestId = require('./koa/middleware/requestId'); 45 | const errorHandler = require('./koa/middleware/errorHandler').withNoBodyOnError; 46 | const { requestControl } = require('./koa/middleware/requestControl'); 47 | 48 | const options = { 49 | serverName: 'QVS', 50 | logger, 51 | middlewares: [ 52 | errorHandler, 53 | requestId({ isTopLevel: true }), 54 | requestControl(), 55 | getConfiguredBodyParser(config) 56 | ], 57 | serviceConfig: config.service 58 | }; 59 | 60 | const init = new ServerInit(options); 61 | 62 | process.on('unhandledRejection', (result, error) => { 63 | logger.error('Unhandled Rejection occured:', result, 'Error:', error); 64 | }); 65 | 66 | module.exports = (async function initialize() { 67 | try { 68 | if (config.service.tlsServerType === 'None') { 69 | await init.startHTTPServer(config.service.port, router); 70 | } 71 | else { 72 | await init.startHTTPSServer(config.service.port, router); 73 | } 74 | HealthCache.run(); 75 | } 76 | catch (e) { 77 | logger.error('Error occurred during server initialization:', e); 78 | /*eslint no-process-exit: 0 */ 79 | process.exit(1); 80 | } 81 | }()); 82 | -------------------------------------------------------------------------------- /src/util/buffer.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 32 | 'use strict'; 33 | 34 | const Buffer = require('safe-buffer').Buffer; 35 | 36 | Buffer.prototype.toJSON = function toJSON() { return { type: 'Buffer', data: this.toString('hex').toUpperCase() }; }; 37 | 38 | module.exports = Buffer; 39 | -------------------------------------------------------------------------------- /src/util/clone.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 32 | 'use strict'; 33 | 34 | /** 35 | * Returns a clone of an object 36 | * 37 | * @param {Object} input 38 | * 39 | * @return {Object} 40 | */ 41 | function clone(input) { 42 | return JSON.parse(JSON.stringify(input)); 43 | } 44 | 45 | module.exports = clone; 46 | -------------------------------------------------------------------------------- /src/util/jsonUtils.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 32 | 'use strict'; 33 | 34 | const _ = require('lodash'); 35 | 36 | module.exports.parse = (data) => { 37 | if (_.isEmpty(data)) { 38 | return undefined; 39 | } 40 | else if (_.isObject(data)) { 41 | return data; 42 | } 43 | try { 44 | return JSON.parse(data); 45 | } 46 | catch (e) { 47 | throw new Error('Input data must be in JSON string format', e); 48 | } 49 | }; 50 | -------------------------------------------------------------------------------- /src/util/onelinerFormat.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 32 | 'use strict'; 33 | 34 | const LINE_SEPARATOR = ' | '; 35 | 36 | function onelinerFormat(message) { 37 | return message.replace(/[\r\n]+/gm, LINE_SEPARATOR); 38 | } 39 | 40 | module.exports = onelinerFormat; 41 | -------------------------------------------------------------------------------- /src/util/random.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 32 | 'use strict'; 33 | 34 | const { Buffer } = require('node:buffer'); 35 | const uuidGen = require('uuid-random'); 36 | 37 | module.exports.uuid = () => { 38 | return Buffer.from(uuidGen.bin()).toString('hex'); 39 | }; 40 | -------------------------------------------------------------------------------- /src/util/responseUtils.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 32 | 'use strict'; 33 | 34 | /** 35 | * IntelliJ IDEA has long lasting bugs: 36 | * https://youtrack.jetbrains.com/issue/WEB-31971 37 | * https://youtrack.jetbrains.com/issue/WEB-52385 38 | * JSDoc import works for example in Visual Studio Code. 39 | * 40 | * @typedef {import('../jsDoc/types').KoaResponse} KoaResponse 41 | */ 42 | 43 | class ResponseUtils { 44 | 45 | /** 46 | * Get status code safely 47 | * @param {KoaResponse} response 48 | * @returns {number} 49 | */ 50 | getStatusCodeSafely(response) { 51 | if (response && response.statusCode) { 52 | return response.statusCode; 53 | } 54 | } 55 | 56 | /** 57 | * check if status code does not exist 58 | * @param {KoaResponse} response 59 | * @returns {boolean} 60 | */ 61 | statusCodeNotExists(response) { 62 | return !this.getStatusCodeSafely(response); 63 | } 64 | } 65 | 66 | module.exports = new ResponseUtils(); 67 | -------------------------------------------------------------------------------- /test/bootstrapTest.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 32 | 'use strict'; 33 | 34 | const proxyquire = require('proxyquire').noCallThru().noPreserveCache(); 35 | const sinon = require('sinon'); 36 | const assert = require('assert'); 37 | const helpers = require('./mocks/helpers'); 38 | 39 | class TestContext { 40 | constructor() { 41 | this.process = { 42 | exit: sinon.stub() 43 | }; 44 | this.path = { 45 | join: sinon.stub().returns('/path') 46 | }; 47 | this.commonLogger = { 48 | genericLogger: { 49 | error: sinon.stub() 50 | } 51 | }; 52 | this.server = 'server'; 53 | } 54 | 55 | async getTarget(initStub) { 56 | return proxyquire('../src/bootstrap', { 57 | './common/logger': this.commonLogger, 58 | 'path': this.path, 59 | 'process': this.process, 60 | './configLoader': { 61 | init: initStub 62 | }, 63 | './server': this.server, 64 | }); 65 | } 66 | } 67 | 68 | describe('bootstrapTest', () => { 69 | 70 | describe('positive', () => { 71 | it('config processed, server run', async() => { 72 | // GIVEN 73 | const c = new TestContext(); 74 | const init = sinon.stub().resolves(); 75 | // WHEN 76 | const run = await c.getTarget(init); 77 | // THEN 78 | assert(init.calledOnce); 79 | assert.strictEqual(run, c.server); 80 | }); 81 | 82 | 83 | }); 84 | 85 | describe('negative', () => { 86 | it('error processing config', async() => { 87 | // GIVEN 88 | const c = new TestContext(); 89 | const init = sinon.stub().rejects(new Error('Error processing config')); 90 | // WHEN 91 | const run = await c.getTarget(init); 92 | // THEN 93 | assert(init.calledOnce); 94 | assert(c.commonLogger.genericLogger.error.calledOnce); 95 | assert.strictEqual(c.commonLogger.genericLogger.error.args[0][0], 96 | 'During loading config and parsing templates occurred an'); 97 | helpers.assertMockFirstCalledWithArgs(c.process.exit, 1); 98 | assert.strictEqual(run, undefined); 99 | }); 100 | }); 101 | }); 102 | -------------------------------------------------------------------------------- /test/handlers/healthTest.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 32 | 'use strict'; 33 | 34 | const proxyquire = require('proxyquire').noCallThru().noPreserveCache(); 35 | const sinon = require('sinon'); 36 | const assert = require('assert'); 37 | 38 | class TestContext { 39 | constructor() { 40 | this.healthCache = { 41 | handleRequest: sinon.stub() 42 | }; 43 | } 44 | 45 | async getTarget() { 46 | return proxyquire('../../src/handlers/health', { 47 | '../healthChecker': this.healthCache 48 | }); 49 | } 50 | } 51 | 52 | describe('health handler tests', () => { 53 | it('check health', async() => { 54 | // GIVEN 55 | const c = new TestContext(); 56 | // WHEN 57 | const target = await c.getTarget(); 58 | await target.checkHealth({}); 59 | // THEN 60 | assert(c.healthCache.handleRequest.calledOnce); 61 | }); 62 | }); 63 | -------------------------------------------------------------------------------- /test/jsDoc/typesTest.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 32 | 'use strict'; 33 | 34 | const proxyquire = require('proxyquire').noCallThru().noPreserveCache(); 35 | const assert = require('assert'); 36 | 37 | class TestContext { 38 | 39 | async getTarget() { 40 | return proxyquire('../../src/jsDoc/types', {}); 41 | } 42 | 43 | } 44 | 45 | describe('include JSDoc - no other functionality exported', () => { 46 | it('types', async() => { 47 | // GIVEN 48 | const c = new TestContext(); 49 | // WHEN 50 | const target = await c.getTarget(); 51 | 52 | // THEN 53 | assert.deepStrictEqual(target, {}); 54 | }); 55 | }); 56 | -------------------------------------------------------------------------------- /test/koa/koaHealthRouterTest.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 32 | 'use strict'; 33 | 34 | const proxyquire = require('proxyquire').noCallThru().noPreserveCache(); 35 | const sinon = require('sinon'); 36 | const assert = require('chai').assert; 37 | 38 | const { assertMockCalledOnceWithArgs } = require('../mocks/helpers'); 39 | 40 | class RouterStub { 41 | constructor() { 42 | this.get = sinon.spy(); 43 | } 44 | } 45 | 46 | class TestContext { 47 | constructor() { 48 | this.healthHandler = sinon.stub(); 49 | } 50 | 51 | getTarget() { 52 | return proxyquire('../../src/koa/koaHealthRouter', { 53 | 'koa-router': RouterStub 54 | }); 55 | } 56 | } 57 | 58 | describe('koa health cache router', () => { 59 | it('should return router with prefix', async() => { 60 | const c = new TestContext(); 61 | const target = c.getTarget(); 62 | const router = target.createHealthRouter(c.healthHandler, '/test'); 63 | assert.instanceOf(router, RouterStub); 64 | assertMockCalledOnceWithArgs(router.get, '/test/:component', c.healthHandler); 65 | assertMockCalledOnceWithArgs(router.get, '/test', c.healthHandler); 66 | }); 67 | 68 | it('should return router with default prefix', async() => { 69 | const c = new TestContext(); 70 | const target = c.getTarget(); 71 | const router = target.createHealthRouter(c.healthHandler); 72 | assert.instanceOf(router, RouterStub); 73 | assertMockCalledOnceWithArgs(router.get, '/:component', c.healthHandler); 74 | assertMockCalledOnceWithArgs(router.get, '/', c.healthHandler); 75 | }); 76 | }); 77 | -------------------------------------------------------------------------------- /test/koa/middleware/bodyParserTest.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 32 | 'use strict'; 33 | 34 | const sinon = require('sinon'); 35 | const proxyquire = require('proxyquire'); 36 | 37 | const assertMockFirstCalledWithArgs = require('../../mocks/helpers').assertMockFirstCalledWithArgs; 38 | 39 | class TestContext { 40 | constructor() { 41 | this.koaBodyParser = sinon.stub(); 42 | } 43 | 44 | getTarget() { 45 | return proxyquire('../../../src/koa/middleware/bodyParser', { 46 | 'koa-bodyparser': this.koaBodyParser 47 | }); 48 | } 49 | } 50 | 51 | describe('body parser middleware tests', () => { 52 | 53 | it('default limits', async() => { 54 | // GIVEN 55 | const c = new TestContext(); 56 | const getConfiguredBodyParser = c.getTarget().getConfiguredBodyParser; 57 | // WHEN 58 | getConfiguredBodyParser(); 59 | // THEN 60 | assertMockFirstCalledWithArgs(c.koaBodyParser, { enableTypes: ['json', 'text', 'form'] }); 61 | }); 62 | 63 | it('specific limits', async() => { 64 | // GIVEN 65 | const c = new TestContext(); 66 | const getConfiguredBodyParser = c.getTarget().getConfiguredBodyParser; 67 | const bodySizeLimits = { 68 | json: '192mb', 69 | text: '192mb', 70 | form: '64kb' 71 | }; 72 | // WHEN 73 | getConfiguredBodyParser({ 74 | service: { bodySizeLimits } 75 | }); 76 | // THEN 77 | assertMockFirstCalledWithArgs(c.koaBodyParser, { 78 | enableTypes: ['json', 'text', 'form'], 79 | jsonLimit: bodySizeLimits.json, 80 | textLimit: bodySizeLimits.text, 81 | formLimit: bodySizeLimits.form 82 | }); 83 | }); 84 | 85 | }); 86 | -------------------------------------------------------------------------------- /test/koa/middleware/requestBodyLoggerTest.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 32 | 'use strict'; 33 | 34 | const proxyquire = require('proxyquire').noCallThru().noPreserveCache(); 35 | const sinon = require('sinon'); 36 | const assert = require('assert'); 37 | 38 | const assertMockFirstCalledWithArgs = require('../../mocks/helpers').assertMockFirstCalledWithArgs; 39 | 40 | class TestContext { 41 | constructor() { 42 | this.ctx = { 43 | log: { 44 | info: sinon.stub() 45 | }, 46 | request: { 47 | body: 'requestBody' 48 | } 49 | }; 50 | this.next = sinon.stub(); 51 | } 52 | 53 | getTarget() { 54 | return proxyquire('../../../src/koa/middleware/requestBodyLogger', {}); 55 | } 56 | } 57 | 58 | describe('requestBodyLoggerTest', () => { 59 | describe('Body printed', () => { 60 | it('text', async() => { 61 | // GIVEN 62 | const c = new TestContext(); 63 | // WHEN 64 | await c.getTarget()(c.ctx, c.next); 65 | // THEN 66 | assertMockFirstCalledWithArgs(c.ctx.log.info, ' [body=\'requestBody\']'); 67 | assert(c.next.calledOnce); 68 | }); 69 | 70 | it('json', async() => { 71 | // GIVEN 72 | const c = new TestContext(); 73 | c.ctx.request.body = { key: 'value' }; 74 | // WHEN 75 | await c.getTarget()(c.ctx, c.next); 76 | // THEN 77 | assertMockFirstCalledWithArgs(c.ctx.log.info, ' [body={"key":"value"}]'); 78 | assert(c.next.calledOnce); 79 | }); 80 | }); 81 | 82 | describe('Empty body', () => { 83 | it('no logs', async() => { 84 | // GIVEN 85 | const c = new TestContext(); 86 | c.ctx.request.body = undefined; 87 | // WHEN 88 | await c.getTarget()(c.ctx, c.next); 89 | // THEN 90 | assert(c.ctx.log.info.notCalled); 91 | assert(c.next.calledOnce); 92 | }); 93 | }); 94 | }); 95 | -------------------------------------------------------------------------------- /test/koa/mocks/loggerMock.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 32 | 'use strict'; 33 | 34 | const sinon = require('sinon'); 35 | 36 | /** 37 | * Create mocked logger object; to be used in UTs only 38 | * @return Object - mocked logger object 39 | * @exports 40 | */ 41 | function createLoggerMock() { 42 | const logger = {}; 43 | logger.warn = sinon.spy(); 44 | logger.debug = sinon.spy(); 45 | logger.info = sinon.spy(); 46 | logger.error = sinon.spy(); 47 | return logger; 48 | } 49 | 50 | module.exports.create = createLoggerMock; 51 | -------------------------------------------------------------------------------- /test/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "quoteverificationservice-test", 3 | "scripts": { 4 | "test": "nyc mocha './' --recursive --exclude 'node_modules/**/*' --exclude '?/**/*' --exclude 'build/**/*' --reporter 'node_modules/mocha-multi-reporters/index.js' --reporter-options 'configFile=../reporter_config.json'", 5 | "lint-fix": "eslint --config ../.eslintrc --fix ..", 6 | "lint": "eslint --config ../.eslintrc --format stylish --quiet ..", 7 | "lint-report": "eslint --config ../.eslintrc --format checkstyle --output-file ../build/eslint_report.xml .." 8 | }, 9 | "version": "1.0.0", 10 | "license": "SEE LICENSE IN RESPECTIVE FILES", 11 | "main": "bootstrap.js", 12 | "dependencies": { 13 | "axios": "^1.6.8", 14 | "bluebird": "^3.7.2", 15 | "fast-url-parser": "^1.1.3", 16 | "https-proxy-agent": "^5.0.1", 17 | "js-yaml": "^4.1.0", 18 | "koa": "^2.14.2", 19 | "koa-bodyparser": "^4.4.1", 20 | "koa-router": "^12.0.1", 21 | "lodash": "^4.17.21", 22 | "log4js": "^6.9.1", 23 | "moment": "^2.29.4", 24 | "node-addon-api": "^6.1.0", 25 | "node-cache": "^5.1.2", 26 | "raw-body": "^2.5.2", 27 | "retry": "^0.13.1", 28 | "safe-buffer": "^5.2.1", 29 | "serialize-error": "^8.1.0", 30 | "uuid-random": "^1.3.2", 31 | "validator": "^13.9.0", 32 | "z-schema": "^6.0.1" 33 | }, 34 | "devDependencies": { 35 | "chai": "^4.3.7", 36 | "cmake-js": "^7.2.1", 37 | "eslint": "^8.39.0", 38 | "mocha": "^10.2.0", 39 | "mocha-junit-reporter": "^2.2.0", 40 | "mocha-multi-reporters": "^1.5.1", 41 | "nyc": "^15.1.0", 42 | "proxyquire": "^2.1.3", 43 | "sinon": "^15.0.4", 44 | "swagger-autogen": "^2.23.1" 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /test/routes/KoaRouterMock.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 32 | 'use strict'; 33 | 34 | module.exports = (use, routes, get, post) => function KoaRouterMock() { 35 | this.use = use; 36 | this.routes = routes; 37 | this.get = get; 38 | this.post = post; 39 | }; 40 | -------------------------------------------------------------------------------- /test/routes/healthTest.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 32 | 'use strict'; 33 | 34 | const proxyquire = require('proxyquire').noCallThru().noPreserveCache(); 35 | const sinon = require('sinon'); 36 | const assert = require('assert'); 37 | 38 | class TestContext { 39 | constructor() { 40 | this.checkHealth = sinon.stub(); 41 | } 42 | 43 | getTarget() { 44 | return proxyquire('../../src/routes/health', { 45 | '../handlers/health': { 46 | checkHealth: this.checkHealth 47 | } 48 | }); 49 | } 50 | } 51 | 52 | describe('health router', () => { 53 | it('should return router with prefix', async() => { 54 | const c = new TestContext(); 55 | const target = c.getTarget(); 56 | const router = target.createRouter('/test'); 57 | assert.equal(router.stack[1].path, '/test/:component', c.checkHealth); 58 | assert.equal(router.stack[1].stack[0], c.checkHealth); 59 | assert.equal(router.stack[0].path, '/test'); 60 | assert.equal(router.stack[0].stack[0], c.checkHealth); 61 | }); 62 | 63 | it('should return router', async() => { 64 | const c = new TestContext(); 65 | const target = c.getTarget(); 66 | const router = target.createRouter(); 67 | assert.equal(router.stack[1].path, '/:component', c.checkHealth); 68 | assert.equal(router.stack[1].stack[0], c.checkHealth); 69 | assert.equal(router.stack[0].path, '/'); 70 | assert.equal(router.stack[0].stack[0], c.checkHealth); 71 | }); 72 | }); 73 | -------------------------------------------------------------------------------- /test/routes/routesTest.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 32 | 'use strict'; 33 | 34 | const proxyquire = require('proxyquire').noCallThru().noPreserveCache(); 35 | const sinon = require('sinon'); 36 | const assert = require('chai').assert; 37 | 38 | const createKoaRouterMock = require('./KoaRouterMock'); 39 | const assertMockCalledOnceWithArgs = require('../mocks/helpers').assertMockCalledOnceWithArgs; 40 | 41 | 42 | class TestContext { 43 | constructor() { 44 | this.koaRouter = { 45 | use: sinon.spy(), 46 | routes: sinon.spy() 47 | }; 48 | 49 | this.routes = 'routes'; 50 | this.allowedMethods = 'allowedMethods'; 51 | 52 | this.routerMock = { 53 | createRouter: sinon.stub().returns({ 54 | routes: sinon.stub().returns(this.routes), 55 | allowedMethods: sinon.stub().returns(this.allowedMethods) 56 | }) 57 | }; 58 | } 59 | 60 | async getTarget() { 61 | const self = this; 62 | return proxyquire('../../src/routes', { 63 | 'koa-router': createKoaRouterMock(self.koaRouter.use, self.koaRouter.routes), 64 | './health': this.routerMock, 65 | './v1/verifyAttestationEvidence': this.routerMock 66 | }); 67 | } 68 | } 69 | 70 | describe('routesTest', () => { 71 | 72 | it('should create router', async() => { 73 | // GIVEN 74 | const c = new TestContext(); 75 | 76 | // WHEN 77 | await c.getTarget(); 78 | 79 | // THEN 80 | assert.strictEqual(c.koaRouter.use.callCount, 2); 81 | assertMockCalledOnceWithArgs(c.koaRouter.use, '/health', c.routes, c.allowedMethods); 82 | assertMockCalledOnceWithArgs(c.koaRouter.use, '/attestation/sgx/dcap/v1/report', c.routes, c.allowedMethods); 83 | }); 84 | 85 | }); 86 | -------------------------------------------------------------------------------- /test/routes/verifyAttestationEvidenceTest.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in 12 | * the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Intel Corporation nor the names of its 15 | * contributors may be used to endorse or promote products derived 16 | * from this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | */ 31 | 32 | 'use strict'; 33 | 34 | const proxyquire = require('proxyquire').noCallThru().noPreserveCache(); 35 | const sinon = require('sinon'); 36 | const createKoaRouterMock = require('./KoaRouterMock'); 37 | 38 | const assertMockCalledOnceWithArgs = require('../mocks/helpers').assertMockCalledOnceWithArgs; 39 | 40 | class TestContext { 41 | constructor() { 42 | this.koaRouter = { 43 | use: sinon.spy(), 44 | routes: sinon.spy(), 45 | get: sinon.spy(), 46 | post: sinon.spy() 47 | }; 48 | this.verifyAttestationEvidenceHandler = { 49 | verifyAttestationEvidence: sinon.stub() 50 | }; 51 | } 52 | 53 | async getTarget() { 54 | const self = this; 55 | return proxyquire('../../src/routes/v1/verifyAttestationEvidence', { 56 | '../../handlers/verifyAttestationEvidence': this.verifyAttestationEvidenceHandler, 57 | 'koa-router': 58 | createKoaRouterMock( 59 | self.koaRouter.use, 60 | self.koaRouter.routes, 61 | self.koaRouter.get, 62 | self.koaRouter.post 63 | ) 64 | }); 65 | } 66 | } 67 | 68 | describe('verify attestation evidence routes', () => { 69 | 70 | it('should create router', async() => { 71 | // GIVEN 72 | const c = new TestContext(); 73 | const target = await c.getTarget(); 74 | // WHEN 75 | await target.createRouter(); 76 | // THEN 77 | assertMockCalledOnceWithArgs(c.koaRouter.post, '/', c.verifyAttestationEvidenceHandler.verifyAttestationEvidence); 78 | }); 79 | 80 | }); 81 | --------------------------------------------------------------------------------