/**
 * atk_unauthorized_access.spec.js
 *
 * Unauthorized access of different kind.
 */

/** ESLint directives */
/* eslint-disable import/first */

// Set up Playwright.
import { expect, test } from '@playwright/test'

import * as atkCommands from '../support/atk_commands'
// eslint-disable-next-line no-unused-vars
import * as atkUtilities from '../support/atk_utilities'

import playwrightConfig from '../../playwright.config'

// eslint-disable-next-line no-unused-vars
const baseUrl = playwrightConfig.use.baseURL

// Import ATK Configuration.
// eslint-disable-next-line no-unused-vars
import atkConfig from '../../playwright.atk.config'

// Standard accounts that use user accounts created
// by QA Accounts. QA Accounts are created when the QA
// Accounts module is enabled.
// eslint-disable-next-line no-unused-vars
import qaUserAccounts from '../data/qaUsers.json'

test.describe('Fed RAMP unauthorized access test', () => {
  //
  // Test unauthorized access to the resource not under the Drupal's control.
  // It will check authorization by the OS file permission.
  // Webserver process must run under the different user.
  // This test may not work under DDEV.
  //
  test('(ATK-PW-1230) Resource that isn\'t under the Drupal\'s control @ATK-PW-1230 @fedramp @unauthorized-access', async ({ request }) => {
    // Create a test file using a custom automated_testing_kit command.
    atkCommands.execDrush('file:create sites/default/files/test-content/test.txt --permissions 0600')

    // Access the test file via web.
    const response = await request.get(`${baseUrl}sites/default/files/test-content/test.txt`)
    expect(response.status()).toEqual(401)
  })

  //
  // List of URLs that should be unauthorized under anonymous user.
  //
  const ANONYMOUS_URL_LIST = ['admin', 'user/1']
  // eslint-disable-next-line no-restricted-syntax
  for (const url of ANONYMOUS_URL_LIST) {
    test(`(ATK-PW-1231) /${url} @ATK-PW-1231 @fedramp @unauthorized-access`, async ({ request }) => {
      // Access the list of resource via request.
      const response = await request.get(`${baseUrl}${url}`)
      expect(response.status()).toEqual(403)
    })
  }

  //
  // List of URLs that should be unauthorized under authenticated (not admin!) user.
  //
  const AUTHENTICATED_URL_LIST = ['admin', 'user/1']
  // eslint-disable-next-line no-restricted-syntax
  for (const url of AUTHENTICATED_URL_LIST) {
    const url1 = url
    test(`(ATK-PW-1234) /${url1} @ATK-PW-1234 @fedramp @unauthorized-access`, async ({ browser }) => {
      // Log in as authenticated user.
      const page = await atkCommands.getUserPage(browser, qaUserAccounts.authenticated)

      // Access the resource via page.
      let pageResponse
      page.on('response', (response) => {
        if (response.request().url().endsWith(url)) {
          pageResponse = response
        }
      })
      await page.goto(url1)
      expect(pageResponse.status()).toEqual(403)
    })
  }
})
