"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const test_1 = require("@playwright/test");
const _8_10_1 = require("../../fixtures/8.10");
const UtilitiesPage_1 = require("../../pages/8.10/UtilitiesPage");
const _setup_1 = require("../../test-setup.js");
const apiHelpers_1 = require("../../utils/apiHelpers");
const users_1 = require("../../utils/users");
const urlHelpers_1 = require("../../utils/urlHelpers");
const testUser = (0, users_1.getTestUser)('twentySecondUser');
// This suite covers the manual scenario: create a new API client via UI,
// copy the API URL from the credentials, and verify that the cluster's V2
// API endpoints require authentication.
//
// V2 endpoints (/v2/process-definitions/search, /v2/user-tasks/search, ...)
// are served by the Zeebe REST API exposed at ZEEBE_REST_ADDRESS in the
// client credentials — NOT by the Operate URL (the Operate URL is the SPA
// frontend and returns 200 + HTML for unknown paths, so a previous version
// of this spec that POSTed V2 paths to it always saw 200/HTML and never
// the auth response under test).
_8_10_1.test.describe.configure({ mode: 'parallel' });
_8_10_1.test.describe('Cluster V2 API requires authentication @tasklistV2', () => {
    let clientName;
    const clusterName = 'Test Cluster';
    _8_10_1.test.beforeEach(async ({ page, loginPage }, testInfo) => {
        await (0, UtilitiesPage_1.loginWithRetry)(page, loginPage, testUser, (testInfo.workerIndex + 1) * 1000);
    });
    _8_10_1.test.afterEach(async ({ page, homePage, clusterPage, clusterDetailsPage }, testInfo) => {
        await (0, _setup_1.captureScreenshot)(page, testInfo);
        await (0, _setup_1.captureFailureVideo)(page, testInfo);
        if (clientName) {
            await homePage.clickClusters();
            await clusterPage.clickClusterLink(clusterName);
            await clusterDetailsPage.clickAPITab();
            await clusterDetailsPage.deleteAPIClientsIfExist(clientName);
        }
    });
    (0, _8_10_1.test)('check that request POST /v2/process-definitions/search returns 401 without credentials', async ({ homePage, clusterPage, clusterDetailsPage, request, }) => {
        clientName = `cluster-deny-${await (0, _setup_1.generateRandomStringAsync)(5)}`;
        let zeebeRestUrl = '';
        await _8_10_1.test.step('Add API Client and capture Zeebe REST URL', async () => {
            await homePage.clickClusters();
            await clusterPage.clickClusterLink(clusterName);
            await clusterDetailsPage.clickAPITab();
            const variables = await clusterDetailsPage.createAPIClientAndReturnVariables(clientName, true);
            zeebeRestUrl = variables.zeebeUrl;
            (0, test_1.expect)(zeebeRestUrl).toMatch(/^https?:\/\//);
            await clusterDetailsPage.clickCloseModalButton();
            await (0, test_1.expect)(clusterDetailsPage.clientsList.filter({ hasText: clientName })).toBeVisible({ timeout: 6000 });
        });
        await _8_10_1.test.step('POST search endpoint without auth should be rejected', async () => {
            const sanitizedUrl = (0, urlHelpers_1.sanitizeUrl)(zeebeRestUrl);
            const response = await request.post(`${sanitizedUrl}/v2/process-definitions/search`, {
                data: { filter: {}, page: { limit: 10 } },
            });
            (0, test_1.expect)(response.status()).toBe(401);
        });
    });
    (0, _8_10_1.test)('check that request POST /v2/process-definitions/search returns 200 with valid credentials', async ({ homePage, clusterPage, clusterDetailsPage, request, }) => {
        clientName = `cluster-allow-${await (0, _setup_1.generateRandomStringAsync)(5)}`;
        let zeebeRestUrl = '';
        await _8_10_1.test.step('Add API Client and capture Zeebe REST URL', async () => {
            await homePage.clickClusters();
            await clusterPage.clickClusterLink(clusterName);
            await clusterDetailsPage.clickAPITab();
            const variables = await clusterDetailsPage.createAPIClientAndReturnVariables(clientName, true);
            zeebeRestUrl = variables.zeebeUrl;
            (0, test_1.expect)(zeebeRestUrl).toMatch(/^https?:\/\//);
            await clusterDetailsPage.clickCloseModalButton();
            await (0, test_1.expect)(clusterDetailsPage.clientsList.filter({ hasText: clientName })).toBeVisible({ timeout: 6000 });
        });
        await _8_10_1.test.step('POST search endpoint with valid Zeebe bearer token returns 200 or is routed', async () => {
            const validToken = await (0, apiHelpers_1.authSaasAPI)();
            const sanitizedUrl = (0, urlHelpers_1.sanitizeUrl)(zeebeRestUrl);
            const response = await request.post(`${sanitizedUrl}/v2/process-definitions/search`, {
                headers: {
                    Authorization: validToken,
                    'Content-Type': 'application/json',
                },
                data: { filter: {}, page: { limit: 10 } },
            });
            (0, test_1.expect)([200, 400, 405]).toContain(response.status());
            if (response.status() === 200) {
                const body = await response.json();
                (0, test_1.expect)(body).toHaveProperty('items');
            }
        });
    });
    (0, _8_10_1.test)('check that POST /v2/user-tasks/search returns 401 without credentials', async ({ homePage, clusterPage, clusterDetailsPage, request, }) => {
        clientName = `tasklist-deny-${await (0, _setup_1.generateRandomStringAsync)(5)}`;
        let zeebeRestUrl = '';
        await _8_10_1.test.step('Add API Client and capture Zeebe REST URL', async () => {
            await homePage.clickClusters();
            await clusterPage.clickClusterLink(clusterName);
            await clusterDetailsPage.clickAPITab();
            const variables = await clusterDetailsPage.createAPIClientAndReturnVariables(clientName, true);
            zeebeRestUrl = variables.zeebeUrl;
            (0, test_1.expect)(zeebeRestUrl).toMatch(/^https?:\/\//);
            await clusterDetailsPage.clickCloseModalButton();
            await (0, test_1.expect)(clusterDetailsPage.clientsList.filter({ hasText: clientName })).toBeVisible({ timeout: 6000 });
        });
        await _8_10_1.test.step('POST /v2/user-tasks/search without auth returns 401', async () => {
            const sanitizedUrl = (0, urlHelpers_1.sanitizeUrl)(zeebeRestUrl);
            const response = await request.post(`${sanitizedUrl}/v2/user-tasks/search`, {
                data: { filter: {}, page: { limit: 10 } },
            });
            (0, test_1.expect)(response.status()).toBe(401);
        });
    });
    (0, _8_10_1.test)('check that POST /v2/process-definitions/search with wrong-audience token returns 401', async ({ homePage, clusterPage, clusterDetailsPage, request, }) => {
        clientName = `cluster-wrong-aud-${await (0, _setup_1.generateRandomStringAsync)(5)}`;
        let zeebeRestUrl = '';
        await _8_10_1.test.step('Add API Client and capture Zeebe REST URL', async () => {
            await homePage.clickClusters();
            await clusterPage.clickClusterLink(clusterName);
            await clusterDetailsPage.clickAPITab();
            const variables = await clusterDetailsPage.createAPIClientAndReturnVariables(clientName, true);
            zeebeRestUrl = variables.zeebeUrl;
            (0, test_1.expect)(zeebeRestUrl).toMatch(/^https?:\/\//);
            await clusterDetailsPage.clickCloseModalButton();
            await (0, test_1.expect)(clusterDetailsPage.clientsList.filter({ hasText: clientName })).toBeVisible({ timeout: 6000 });
        });
        await _8_10_1.test.step('Token scoped for Optimize audience rejected by Zeebe REST endpoint', async () => {
            const optimizeToken = await (0, apiHelpers_1.authSaasAPI)(process.env.OPTIMIZE_API_TOKEN_AUDIENCE);
            const sanitizedUrl = (0, urlHelpers_1.sanitizeUrl)(zeebeRestUrl);
            const response = await request.post(`${sanitizedUrl}/v2/process-definitions/search`, {
                headers: {
                    Authorization: optimizeToken,
                    'Content-Type': 'application/json',
                },
                data: { filter: {}, page: { limit: 10 } },
            });
            (0, test_1.expect)([401, 403]).toContain(response.status());
        });
    });
});
