"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const tape_1 = __importDefault(require("tape-promise/tape"));
const uuid_1 = require("uuid");
const jose_1 = require("jose");
const public_api_1 = require("../../../main/typescript/public-api");
const public_api_2 = require("../../../main/typescript/public-api");
const cactus_common_1 = require("@hyperledger/cactus-common");
const cactus_core_api_1 = require("@hyperledger/cactus-core-api");
const authorization_protocol_1 = require("../../../main/typescript/config/authorization-protocol");
const testCase = "API server enforces authorization rules when configured";
const logLevel = "TRACE";
const log = cactus_common_1.LoggerProvider.getOrCreate({
    level: logLevel,
    label: __filename,
});
tape_1.default(testCase, async (t) => {
    try {
        const keyPair = await jose_1.JWK.generate("EC", "secp256k1", { use: "sig" }, true);
        const keyPairPem = keyPair.toPEM(true);
        const db = {
            cactusNode: [],
            consortium: [],
            consortiumMember: [],
            ledger: [],
            pluginInstance: [],
        };
        const jwtKeyPair = await jose_1.JWK.generate("RSA", 4096);
        const jwtPublicKey = jwtKeyPair.toPEM(false);
        const expressJwtOptions = {
            algorithms: ["RS256"],
            secret: jwtPublicKey,
            audience: uuid_1.v4(),
            issuer: uuid_1.v4(),
        };
        t.ok(expressJwtOptions, "Express JWT config truthy OK");
        const jwtPayload = { name: "Peter", location: "London" };
        const jwtSignOptions = {
            algorithm: "RS256",
            issuer: expressJwtOptions.issuer,
            audience: expressJwtOptions.audience,
        };
        const tokenGood = jose_1.JWT.sign(jwtPayload, jwtKeyPair, jwtSignOptions);
        // const tokenBad = JWT.sign(jwtPayload, jwtKeyPair);
        const authorizationConfig = {
            unprotectedEndpointExemptions: [],
            expressJwtOptions,
            socketIoJwtOptions: {
                secret: jwtPublicKey,
            },
        };
        const configService = new public_api_1.ConfigService();
        const apiSrvOpts = configService.newExampleConfig();
        apiSrvOpts.authorizationProtocol = authorization_protocol_1.AuthorizationProtocol.JSON_WEB_TOKEN;
        apiSrvOpts.authorizationConfigJson = authorizationConfig;
        apiSrvOpts.configFile = "";
        apiSrvOpts.apiCorsDomainCsv = "*";
        apiSrvOpts.apiPort = 0;
        apiSrvOpts.cockpitPort = 0;
        apiSrvOpts.apiTlsEnabled = false;
        apiSrvOpts.plugins = [
            {
                packageName: "@hyperledger/cactus-plugin-keychain-memory",
                type: cactus_core_api_1.PluginImportType.Local,
                options: {
                    instanceId: uuid_1.v4(),
                    keychainId: uuid_1.v4(),
                    logLevel,
                },
            },
            {
                packageName: "@hyperledger/cactus-plugin-consortium-manual",
                type: cactus_core_api_1.PluginImportType.Local,
                options: {
                    instanceId: uuid_1.v4(),
                    keyPairPem: keyPairPem,
                    consortiumDatabase: db,
                },
            },
        ];
        const config = configService.newExampleConfigConvict(apiSrvOpts);
        const apiServer = new public_api_1.ApiServer({
            config: config.getProperties(),
        });
        tape_1.default.onFinish(async () => await apiServer.shutdown());
        const startResponse = apiServer.start();
        await t.doesNotReject(startResponse, "failed to start API server with dynamic plugin imports configured for it...");
        t.ok(startResponse, "startResponse truthy OK");
        const addressInfoApi = (await startResponse).addressInfoApi;
        const protocol = apiSrvOpts.apiTlsEnabled ? "https" : "http";
        const { address, port } = addressInfoApi;
        const apiHost = `${protocol}://${address}:${port}`;
        const baseOptions = { headers: { Authorization: `Bearer ${tokenGood}` } };
        const conf = new cactus_core_api_1.Configuration({ basePath: apiHost, baseOptions });
        const apiClient = new public_api_2.DefaultApi(conf);
        const resHc = await apiClient.getHealthCheck();
        t.ok(resHc, "healthcheck response truthy OK");
        t.equal(resHc.status, 200, "healthcheck response status === 200 OK");
        t.equal(typeof resHc.data, "object", "typeof resHc.data is 'object' OK");
        t.ok(resHc.data.createdAt, "resHc.data.createdAt truthy OK");
        t.ok(resHc.data.memoryUsage, "resHc.data.memoryUsage truthy OK");
        t.ok(resHc.data.memoryUsage.rss, "resHc.data.memoryUsage.rss truthy OK");
        t.ok(resHc.data.success, "resHc.data.success truthy OK");
        t.true(public_api_1.isHealthcheckResponse(resHc.data), "isHealthcheckResponse OK");
        t.end();
    }
    catch (ex) {
        log.error(ex);
        t.fail("Exception thrown during test execution, see above for details!");
        throw ex;
    }
});
//# sourceMappingURL=data:application/json;base64, 