Thursday, November 18, 2021

Test your application using Cypress, GitHub, and Azure DevOps

 Summary: 

1. create project with product curd operations. 
2. write cypress tests to test fucntionality.
3. Execute tests locally .
4. Execute test using Azure dev ops.
5. Execute tests using Git Ations. 

Very interesting comparision of Azure devops and Git actionaa and writing simple tests using cypress.

Testing is a critical activity that allows development teams to get early feedback about the correctness of their code and eliminate more issues in the early stages of the development cycle. Today’s article will talk about front-end testing with Cypress and its integration with Azure DevOps and GitHub.

What is Cypress?

Cypress is a free, open-source testing tool that runs on a Node.js process and allows a developer to write performance End-to-end, Integration, and unit tests using Mocha’s syntax in JavaScript.

It has two main components that come default in its installation:

  • Cypress Test Runner: Runner that executes your actual test cases.
  • Dashboard: Service that tracks and provides insight about how your tests ran.

How it works?

When you run a test using Cypress test runner, a Node.js process starts and both your application and the test code are embedded into two different iFrames in a browser managed by Cypress. The test’s code communicates with a Node.js process via WebSockets and acts as a proxy by intercepting every HTTP request from the application and then allows Cypress to mock the responses quickly.

Process Explorer

The ability to mock responses isn’t the only benefit of this architecture. By running on along your application, Cypress can access each DOM (document object model) element, the window element, and even when your test needs to perform a command like ‘click a button’, will send the command to the DOM element by using a DOM event directly instead of relying on out-of-process communication with a WebDriver.

Folder structure

After adding a new project, Cypress will automatically create the following folder structure:

.
├── cypress
│ ├── fixtures
│ │ └── data.json
│ ├── integration
│ │ └── test.js
│ ├── plugins
│ │ └── index.js
│ └── support
│ ├── commands.js
│ └── index.js
└── cypress.json

Let’s take a minute to analyze each of them:

  • Fixtures: Store static data that your tests can use.
  • Integration: Contains all test files.
  • Plugins: Special file that executes before the project is loaded and before the browser launches. During your test, execution that modifies or extends Cypress’s internal behavior.
  • Support: This folder contains files with reusable behavior, like custom commands, that run before every spec file.
  • Cypress.json: This file allows you to modify the Cypress’ default behavior by supplying specific configurations like base URL, timeouts, etc.

Installation

If you are developing an application based on Node.js, you can easily add Cypress as a dependency to your package.json by executing the following command on our project root directory.

npm install cypress --save-dev

In case you are using Yarn as a package manager, the command is the following:

yarn add cypress --dev

If you don’t want to add any dependency to your project or your project is based on programming languages different from Node.js, for example, Python and Go; you can still enjoy the Cypress testing tool by running the Test Runner inside a Docker container while running the website on the host outside the container. After starting your application on the host machine, run the Docker image with the following parameters:

DISPLAY=$IP:0
docker run
-it \
-v $PWD:/e2e \
-w /e2e \
--entrypoint cypress \
cypress/included:3.2.0 open --project . \
--config baseUrl=http://host.docker.internal:2222

By doing so, the test runner will point back at the host machine, and you can test your application.

Setup you local environment

Before moving forward with its integration with Azure DevOps and GitHub, clone the repository from the following link.

I mainly use this repository for demo purposes. In its 0_Application folder, you can find a .NET 5 API developed using C# and a front-end application based on React.js.

.
├── 0. Application
│ ├── Training.API
│ │ ├── Controllers
│ ├── Training.Models
│ │ ├── Managers
│ │ ├── Store
│ └── Training.Web
│ ├── public
│ └── src
│ ├── components
│ ├── images
│ └── services
├── 1. Node.js and Docker
│ └── template
├── 2. k6 and testing
│ ├── Training.LoadTest
│ └── Training.Pipelines
└── 3. Unit testing
├── Training.Cypress
│ ├── fixtures
│ ├── integration
│ ├── plugins
│ └── support
└── Training.MSTest

Writing tests

First, you need to create the Cypress folder structure in your project.

.
└── cypress
└── integration

Inside the integration, the folder creates a new JavaScript file called products and paste the following code.

describe('Testing Product CRUD operations', () => {
beforeEach(() => {
cy.visit('http://localhost:3000/products')
})
it('Adds a new product', () => {
// Browse to add product
cy.get('nav a').eq(1).click()
cy.get('.dropdown-menu.show a').eq(1).click()
// Add product
cy.get('input[name="name"]').type('Test 01')
cy.get('input[name="price"]').type('10')
cy.get('button[type=submit]').click()
// Check that there are at least one element
cy.get('nav a').eq(1).click()
cy.get('.dropdown-menu.show a').eq(0).click()
cy.get('table[data-element-id="products"] tbody tr').should('have.length', 1)
})
it('Delete a product', () => {
cy.get('nav a').eq(1).click()
cy.get('.dropdown-menu.show a').eq(0).click()
cy.get('table[data-element-id="products"] tbody tr button').eq(0).contains('Delete').click()
cy.get('table[data-element-id="products"] tbody tr').should('have.length', 0)
})
})

This integration test is composed of two steps. Before starting the execution of each test, the test runner will browse to the URL http://localhost:3000/products. Then it will sequentially execute the listed commands. In the first step, it browses the add product page by clicking on the relative link on the navbar, then it will fill the input, and finally will submit the form. The test will finish with the assertion that the products table will contain exactly one element. Instead, the second step will simply click on the first button that has Delete as text and check that the list is empty.

Cypress test runner execution

Integration with Azure DevOps

It is time to create your build pipeline.

  • From the dashboard, select Pipelines.
  • Click the New pipeline button.
Create build pipeline
  • Select GitHub and the repository where the source code resides.
  • First, instruct the service to trigger the pipeline when there are changes in the path Training/0_Application/Training.Web of the main branch.
trigger:
branches:
include:
- main
paths:
include:
- Training/0_Application/Training.Web/*
variables:
- name: projectPath
value: './0_Application/Training.Web/'
  • Install NodeJS and the dependencies needed to run the application.
- task: NodeTool@0
displayName: 'Use Node 12.x'
inputs:
versionSpec: 12.x
- script: |
yarn install --verbose
workingDirectory: ${{variables.projectPath}}
displayName: 'Install project dependencies'

- script: |
yarn build
workingDirectory: ${{variables.projectPath}}
displayName: 'Build application'
  • Then, run the process in the background by using the command (Yarn run start&).
- script: |
(yarn run start&)
workingDirectory: ${{variables.projectPath}}
displayName: 'Start application'
  • Finally, run the integration tests and publish the results.
- script: |
./node_modules/.bin/cypress run --browser chrome
workingDirectory: ${{variables.projectPath}}
displayName: 'Run cypress tests'
- task: PublishTestResults@2
displayName: 'Publish test results'
inputs:
testResultsFormat: 'JUnit'
testResultsFiles: '*.xml'
searchFolder: '$(System.DefaultWorkingDirectory)/cypress/reports/junit'
mergeTestResults: true
testRunTitle: 'Cypress tests'

The final YAML script will look similar to this:

trigger:
branches:
include:
- main
paths:
include:
- Training/0_Application/Training.Web/*
variables:
- name: projectPath
value: './0_Application/Training.Web/'
steps:
- task: NodeTool@0
displayName: 'Use Node 12.x'
inputs:
versionSpec: 12.x
- script: |
yarn install --verbose
workingDirectory: ${{variables.projectPath}}
displayName: 'Install project dependencies'

- script: |
yarn build
workingDirectory: ${{variables.projectPath}}
displayName: 'Build application'
- script: |
(yarn run start&)
workingDirectory: ${{variables.projectPath}}
displayName: 'Start application'
- script: |
./node_modules/.bin/cypress run --browser chrome
workingDirectory: ${{variables.projectPath}}
displayName: 'Run cypress tests'
continueOnError: true
- task: PublishTestResults@2
displayName: 'Publish test results'
inputs:
testResultsFormat: 'JUnit'
testResultsFiles: '*.xml'
searchFolder: '$(System.DefaultWorkingDirectory)/cypress/reports/junit'
mergeTestResults: true
testRunTitle: 'Cypress tests'

It’s now time to push your change to your repository and run the pipeline.

Execution using Azure DevOps

Integration with GitHub Actions

First, you need to create a new GitHub Action in your repository.

  • Browse to GitHub, log in with your account and select your repository.
  • From the navigation bar, select Actions.
  • Click the New Workflow button.
GitHub Actions
  • GitHub will then propose many templates, but in our case, we need to start from scratch. For this reason, click the link set up a workflow yourself.
Setup a workflow from scratch
  • First, you need to specify what will trigger your action. In this case, I want to trigger the action every time there is a change in the directory 0_Application/Training.Web/ of the main branch.
on:
push:
paths:
- 0_Application/Training.Web/**
branches:
- main
  • To make the workflow easier to manage, I will set an environment variable with the location of my application.
env:
WORKING_DIRECTORY: './0_Application/Training.Web/'
  • It’s now time to create the core of your workflow, the jobs that the agent will execute. Because the cypress task only runs on Linux, you need to instruct GitHub to use an agent installed on an Ubuntu machine.
jobs:
build:
runs-on: ubuntu-latest
  • Then, you can move forward by checking out your source code and installing Node.js and all of the dependencies specified in your package.json.
- uses: actions/checkout@v2

- name: Set up Node.js version
uses: actions/setup-node@v1
with:
node-version: '14.x'

- name: yarn install, build, and test
run: |
yarn install
yarn build
working-directory: ${{ env.WORKING_DIRECTORY }}
  • It’s now time to perform some testing. To do so, I’m going to use different cypress-io/github-action@v2 actions for each browser.

Important: Because my application’s package.json is in a subfolder of the repository, I needed to add the parameter working-directory in each of my cypress-io/github-action@v2 task.

- name: Cypress run on chrome
uses: cypress-io/github-action@v2
with:
browser: chrome
start: yarn start
wait-on: 'http://localhost:3000'
working-directory: ${{ env.WORKING_DIRECTORY }}

- name: Cypress run on firefox
uses: cypress-io/github-action@v2
with:
browser: firefox
start: yarn start
wait-on: 'http://localhost:3000'
working-directory: ${{ env.WORKING_DIRECTORY }}

- name: Cypress run on edge
uses: cypress-io/github-action@v2
with:
browser: edge
start: yarn start
wait-on: 'http://localhost:3000'
working-directory: ${{ env.WORKING_DIRECTORY }}

The final YAML script will look similar to this:

name: Cypress testing
on:
push:
paths:
- 0_Application/Training.Web/**
branches:
- main
env:
WORKING_DIRECTORY: './0_Application/Training.Web/'
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2

- name: Set up Node.js version
uses: actions/setup-node@v1
with:
node-version: '14.x'

- name: yarn install, build, and test
run: |
yarn install
yarn build
working-directory: ${{ env.WORKING_DIRECTORY }}

- name: Cypress run on chrome
uses: cypress-io/github-action@v2
with:
browser: chrome
start: yarn start
wait-on: 'http://localhost:3000'
working-directory: ${{ env.WORKING_DIRECTORY }}

- name: Cypress run on firefox
uses: cypress-io/github-action@v2
with:
browser: firefox
start: yarn start
wait-on: 'http://localhost:3000'
working-directory: ${{ env.WORKING_DIRECTORY }}

- name: Cypress run on edge
uses: cypress-io/github-action@v2
with:
browser: edge
start: yarn start
wait-on: 'http://localhost:3000'
working-directory: ${{ env.WORKING_DIRECTORY }}

It’s now time to push your change to your repository and start the workflow.

Execution using GitHub Action

After completing each step of your test, you will be able to see the execution time (in case it succeeds), the exception (in case it fails), and a summary at the end of both of the tests and GitHub Action.

Test succeeded
Test failed
Summary at the end of the GitHub Action

References:

Friday, September 3, 2021

Cloud security test cases - part 1

 

Overview of Security

This report presents suggested best practices and techniques that an organization should acknowledge when building a full-fledged cloud strategy. This article covers the leading cloud providers Security Checklist.

AWS Security Checklist

  • Permit CloudTrail logging across all Amazon Web Services.
  • Set on CloudTrail log file validation.
  • Permit CloudTrail multi-region logging.
  • Combine CloudTrail with CloudWatch.
  • Permit access logging for CloudTrail S3 buckets.
  • Permit access logging for Elastic Load Balancer (ELB).
  • Permit Redshift audit logging.
  • Permit Virtual Private Cloud (VPC) flow logging.
  • Multifactor authentication (MFA) is required to delete CloudTrail buckets.
  • Set on multifactor authentication for the “root” account.
  • Set on multifactor authentication for IAM users.
  • Permit IAM users for multi-mode access.
  • Link IAM policies to groups or roles.
  • Regularly rotate IAM access keys, and standardize on the selected number of days.
  • strict password policy must be set up
  • Set the password termination session to 90 days
  • Expired SSL/TLS certificates should not be used
  • User HTTPS for CloudFront distributions.
  • Limit access to CloudTrail bucket.
  • Encrypt the CloudTrail log files at rest.
  • Elastic Block Store (EBS) database must be encrypted
  • Provision access to resources using IAM roles.
  • Using root user accounts should be avoided
  • SSL secure ciphers must be applied while connecting between the client and ELB.
  • SSL secure versions must be used while connecting between ELB and Client.
  • Use a standard naming (tagging) convention for EC2.
  • Encrypt Amazon’s Relational Database Service (RDS).
  • Access keys should not be used with root accounts.
  • Use secure CloudFront SSL versions.
  • Permit the require_ssl parameter in all Redshift clusters.
  • Periodically rotate SSH keys
  • Number of discrete security groups should be minimized
  • Reduce the number of IAM groups.
  • Terminate available access keys.
  • Disable access for unused or inactive IAM users.
  • Remove unused IAM access keys.
  • Delete unused SSH Public Keys.
  • Limit access to Amazon Machine Images (AMIs).
  • Limit access to EC2 security groups.
  • Limit access to RDS instances.
  • Limit access to Redshift clusters.
  • Limit access to outbound access.
  • Disallow unrestricted ingress access on different ports.
  • Limit access to well-known ports such as CIFS, FTP, ICMP, SMTP, SSH, Remote desktop.
  • Involve IT security throughout the development process.
  • Limited privileges should be granted as possible for application users.
  • Encrypt highly sensitive data such as personally identifiable information (PII) or protected health information (PHI)

Azure Security Checklist

  • Ensure that multi factor authentication is enabled for all users
  • Ensure that there are no guest users.
  • Use Role-Based Access Control to manage access to resources.
  • Ensure that ‘enable users to memorize multi factor authentication on devices they trust’ is disabled.
  • Ensure that ‘number of processes required to reset’ is set to 2.
  • Assure that ‘number of days before users are asked to re-confirm their authentication report’ is not set to 0.
  • Assure that ‘caution users on password resets’ is set to yes.
  • Ensure that ‘notify all admins when other admins reset their password?’ is set to yes
  • Ensure that ‘users can comply with apps obtaining company data on their account’ is set to none.
  • Guarantee that ‘users can add gallery apps to their Entrance Panel’ is set to no.
  • Ensure that ‘users can disclose applications’ is fixed to no.
  • Guarantee that ‘guest users agreements are limited’ is set to yes.
  • Ensure that ‘members can request’ is set to no.
  • Guarantee that ‘guests can invite’ is set to no.
  • Ensure that entrance to the Azure AD administration portal should be limited
  • Ensure that ‘users can create security associations’ is set to none.
  • Ensure that ‘self-service group administration enabled’ is established to no.
  • Ensure that ‘users who can handle security groups’ is set to none.
  • Ensure that ‘users can create Office 365 groups’ is set to no.
  • Ensure that ‘users who can manage Office 365 groups’ is set to none.
  • Ensure that ‘require multifactor auth to join devices’ is set to yes
  • Ensure that ‘secure transfer required’ is arranged to enable.
  • Ensure that ‘storage service encryption’ is set to enabled
  • On SQL servers, ensure that ‘auditing’ is set to on.
  • On SQL servers, ensure that ‘auditing type’ is set to blob
  • On SQL servers, ensure that ‘threat detection’ is set to on.
  • On SQL servers, ensure that ‘threat detection types’ is set to all.
  • On SQL servers, ensure that ‘send alerts to’ is set.
  • On SQL servers, ensure that ‘email service and co-administrators’ is enabled.
  • On SQL servers, ensure that firewall rules are set as appropriate.
  • Disable RDP access on network security groups from the internet
  • Disable SSH access on network security groups from the internet.

Google Security Checklist

  • Require 2-Step Verification for admin accounts
  • Enforce 2-Step Verification for users
  • Don’t use a super admin account for daily activities
  • Don’t remain signed in to an idle super admin account
  • Set up admin email alerts
  • Review the admin audit log
  • Add recovery options to admin accounts
  • Enroll a spare security key
  • Save the backup codes
  • Use unique passwords
  • Prevent password reuse with password alert
  • Regularly review activity reports and alerts
  • Know and approve which third-party can access G Suite core services
  • Create a Whitelist of trusted apps
  • Limit external calendar sharing
  • Set up underlying Chrome OS and Chrome Browser policy
  • Warn the users when chatting outside their domain
  • Don’t automatically share the contact information
  • Validate email with SPF, DKIM, and DMARC
  • Disable the “Do not require sender authentication” setting for spam policies.
  • Prevent automatic forwarding the incoming mail
  • Enable comprehensive mail storage
  • Enable additional attachment protection
  • Enable enhanced pre-delivery message scanning
  • Enable additional attachment protection
  • Limit group creation to admins
  • Set up the private access to groups
  • Enforce mobile password requirements (reduce risk if the device is lost)
  • Encrypt data on mobile devices
  • Enable mobile inactivity reports
  • Disable location history
  • Disable access to offline docs
  • Do not permit users to establish add-ons for Docs from the add-on store

Free hosting web sites and features -2024

  Interesting  summary about hosting and their offers. I still host my web site https://talash.azurewebsites.net with zero cost on Azure as ...