Cypress Testing: The Basics and a Quick Tutorial

What Is Cypress?

Cypress is an open source end-to-end testing framework that can help you unify web application testing. It works for all programming languages, platforms, and browsers. You can use Cypress for unit and integration testing. All tests are written in JavaScript and run in real browsers. 

Cypress provides an integrated development environment (IDE) that you can load in your browser. The framework employs an event-based architecture that connects with Google Chrome’s lifecycle events. It enables Chrome to wait for Ajax requests to complete without using a timeout or polling mechanism, leading to faster and more reliable tests.

Related content: Read our guide to mocha testing.

Key features of Cypress include:

  • Time travel
  • Live code reloading
  • Current and previous state diff-ing
  • Running tests in a browser or headless 
  • Screenshots and video recordings
  • Asynchronous testing
  • In-browser debugging

Cypress provides a CLI that you can use to test websites on various devices and browsers. The framework lets you use familiar debugging tools with Chrome and also install additional tools such as Redux Dev Tools and React Dev Tools. The goal is to enable you to run tests using the same stack you use for development. 

This is part of our series of articles about unit testing frameworks.

In this article:

Cypress Framework Architecture

Standard testing frameworks (e.g., Selenium) usually run outside the web browser to execute commands remotely across the network. The Cypress testing framework does the opposite – it runs in the same loop as the tested application.

A Node server process supports Cypress with constant communication and synchronization. The Node process and Cypress execute tasks for each other. Accessing the front and back end allows you to respond quickly to an application’s events. You can simultaneously perform high-privilege tasks outside the browser.

Cypress works at the network layer, reading and modifying web traffic as it flows. Therefore, Cypress can modify all incoming and outgoing browser traffic and change any code that might disrupt its capabilities, such as automating the browser. 

Cypress maintains control over the entire test automation process. It has a unique ability to understand events both within and outside the browser. Cypress can thus deliver consistent results – more so than other testing tools.

You install Cypress locally on a physical machine, allowing it to access the operating system to automate tasks. This setup enables Cypress to perform tasks like recording video content, taking snapshots, and executing network and file system operations. 

Cypress works within an application, providing native access to all components, including application instances, functions, timers, windows, documents, DOM elements, and service workers. You can access everything in a Cypress test. Cypress does not serialize objects or use an over-the-wire protocol to limit access. The test code has the same access as the application code. 

Related content: Read our guide to junit testing.

Cypress Testing Types

Choosing the type of test is one of the first considerations when building a testing suite. Cypress supports component and end-to-end tests. Each testing type has specific considerations and benefits depending on the test’s objectives. Usually, the application testing suite will contain both test types. 

End-to-End Tests

This technique fully tests applications from the back end to the web browser, covering third-party integrations. An end-to-end test aims to check how an application works as a whole. Cypress executes end-to-end testing using the same means users interact with an application, ensuring the test reflects the user experience. 

Developers, test engineers, and other team members can write these tests in Cypress using an API to simulate a real user’s behavior. End-to-end testing requires more complicated setup and maintenance than component testing.

Component Tests

Some development frameworks allow teams to break applications into components that team members write and test individually. Components are logical units ranging from small buttons to complex forms. They are easy to test because they are mountable, enabling testers to work with them separately from the rest of the application.

A component test focuses on a specific component’s functionality. Usually, developers write component tests when they build components – the test code resides with the component’s code. However, component testing does not accurately represent a component’s real-world performance – it doesn’t cover how the component interacts with other components or how the application functions overall. 

Quick Tutorial: Cypress Unit Testing Example

Here is a guide for creating Cypress component tests for React applications. Several frameworks are available to build React projects automatically (i.e., Vite, Create React App) – the following example uses Vite.

Use the following steps to create a project with Vite:

1. Use the scaffold command to create a project with the React template.

2. In the directory, run the npm install command.

3. Specify Cypress and launch the project.

Configure the Component Test

When Cypress runs for the first time for a given project, it prompts the user to set up end-to-end or component testing. Select the component testing option and continue through the wizard. The Cypress launchpad detects the framework and generates the required configuration information.

Image Source: Cypress

Once you’ve set up component testing, select and launch the preferred browser to open Cypress. 

Create a Component

Next, you’ll need components to test – you can start with a simple component with few dependencies. For an example of a simple React component, use a button without dependencies. Import the component from React.

Mount the Components

Most tests use a similar format regardless of the framework. To test a component, arrange the test by mounting your chosen component. You can import a mount function for every supported framework from the Cypress package: 

import { mount } from 'cypress/react'

Mount the imported component: 

import { mount } from 'cypress/react'
import Button from './Button'

describe('<Button>', () => {
  it('mounts', () => {
    mount(<Button />)
  })
})

You can add the mount function as a custom command to make it easier to use for all the component tests (the launchpad wizard normally configures this automatically). 

The component support file might look like this:

// cypress/support/component.js
import { mount } from 'cypress/react'

Cypress.Commands.add('mount', mount)

Next, remove the mount import to update the button component – use the cy.mount command. Create a project spec (Button.spec.jsx) and apply this script: 

import Button from './Button'

describe('<Button>', () => {
  it('mounts', () => {
    cy.mount(<Button />) /
  })
})

The test should now work. Open Cypress in your chosen browser and select Button.cy.jsx from your spec list. You should see the mounted button component in the test environment. If the test works in Cypress, it should also work in the real world because the test uses a real web browser. 

Security Unit Testing with Bright Security

Bright is a developer-first Dynamic Application Security Testing (DAST) scanner, the first of its kind to integrate into unit testing, revolutionizing the ability to shift security testing even further left. You can now start to test every component / function at the speed of unit tests, baking security testing across development and CI/CD pipelines to minimize security and technical debt, by scanning early and often, spearheaded by developers. With NO false positives, start trusting your scanner when testing your applications and APIs (REST, GraphQL), built for modern technologies and architectures. 

Unit Testing in Node.js: The Basics and a Quick Tutorial

What is Unit Testing in Node.js?

Node.js is a popular JavaScript library based on Chrome’s V8 JavaScript engine. It is used to develop server-side components of web applications.

Unit testing is a software testing method that tests individual units/components individually. A unit can be described as the smallest piece of code that can be tested in an application. Unit tests are typically performed by developers during the application development phase.

To do unit testing in Node.js, you will typically use a JavaScript unit testing framework. Common frameworks include Mocha, Jest, Jasmine, and Cypress. We’ll show how to do Node.js unit testing in Jest.

Related content: Read our guide to unit testing in Javascript

In this article:

Why Is Unit Testing Important?

In Node.js, like in other programming languages, unit tests can help you ensure that your program works as expected, identify bugs early in the development process, and improve the stability of your software. Good testing ensures your program meets user requirements and maintains high code quality as development progresses.

A major benefit of unit tests is that they can help you catch regressions. A regression is a new change to the codebase that causes problems with pre-existing code or functionality. Without unit tests, to catch regressions you would have to comprehensively test the entire application every time it changes, which is very difficult to do. A comprehensive set of unit tests, run  automatically every time your codebase changes, is highly effective at catching regressions.

How to Choose a Node.js Testing Framework

There are many JavaScript testing frameworks. Here are a few things you should look when evaluating a Node.js testing framework for your project:

  • Setup time—the framework should require minimal effort to get your tests up and running.
  • Support—the framework should have comprehensive documentation and an active community to support you if there are issues.
  • Feature set—ensure the framework has advanced unit testing features such as mocking/stubbing, matchers (functions that test the relation between objects), and spiers (which gather execution information unavailable to the test code).
  • Performance—unit tests need to run fast, otherwise they will interrupt your development process and reduce productivity. Ensure your framework can run your unit tests quickly.
  • Reporting—the framework should have reporting of test coverage and execution results. If your organization needs customized reporting, check if the framework provides it.
  • Integration—test libraries should be easy to integrate into your continuous integration (CI) process. Preferably, your CI system should support the framework out of the box.

Related content: Read our guide to unit testing frameworks

Quick Tutorial: Node.js Unit Testing with Jest

Jest is a popular framework for unit-testing Node.js applications. It’s popular for its testing functionality that uses parallelism techniques for improved performance. Additionally, it gives an output that shows the piece of code causing failed tests.

Jest requires no configuration except for its installation. Once installed, you can start writing tests and testing your Node.js applications immediately.

Creating a Demo Node.js Application

To create a demo Node.js application for testing:

  1. Use the following commands to create and start a directory for a demo Node.js application.

    mkdir string-multiplier
    cd string-multiplier
    npm -y
  1. Add the following code to a file called index.js in the root folder. 

const http = require('http')
const query_string = require('querystring')
const multiplication = require('./multiplication')

const demo_server = http.createServer(function(request, response) {
  console.dir(request.param)
  if (request.method == 'POST') {
    console.log('POST')
    var request_body = ''
    request.on('data', function(data) {
      request_body += data
    })

    request.on('end', function() {
      const post_request = query_string.parse(request_body)
      const input_numbers = post_request.numbers
     const product = multiplication.multiply(input_numbers)
      response.writeHead(200, {'Content-Type': 'text/html'})
      response.end('Result: ' + product)
    })
  } else {
    var html = `
            &lt;html&gt;
                &lt;body&gt;
                    &lt;form method="post" action="http://localhost:3000"&gt;Numbers: 
                        &lt;input type="text" name="numbers" /&gt;
                        &lt;input type="submit" value="Multiply" /&gt;
                    &lt;/form&gt;
                &lt;/body&gt;
            &lt;/html&gt;`
    response.writeHead(200, {'Content-Type': 'text/html'}
    response.end(html)
  }
})

const port = 3000
const host = '127.0.0.1'
demo_server.listen(port, host
console.log(`Listening at http://${host}:${port}`)

This Node.js application will display a form and ask for numbers as input. Next, it will forward the input string it receives to the multiplication function. The application displays the product of comma-separated numbers when the user presses Multiply. Run the following command and go to the address it returns as output to see the HTML page working.

node index.js

  1. This tutorial will test a simple multiplication function. Create a file called multiplication.js and add the function shown below.

    function multiply(numbers) {
        return numbers
            .split(',')
            .map(x =&gt; parseInt(x))
            .reduce((a, b) =&gt; a * b)
    }

exports.multiply = multiply;

  1. Create a package.json file for this Node.js application and add the following specifications.

    {
    "name": "string-multiplier",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
    "test": "echo "Error: no tests or frameworks specified" &amp;&amp; exit 1"
    },
    "keywords": [],
    "author": "",
    "license": "ISC"
    }

Installing the Jest Framework

To download and install Jest:

  1. Navigate to the root directory of your project through the terminal.
  1. Install Jest by running the following command. The --save-dev flag installs all the needed dependencies and the framework itself.

    npm install jest --save-dev
  2. Go to the package.json file also present in the root directory. Replace the line with "test:" with the following code.

    "test": "jest"

Now, npm will run the Jest unit tests whenever you want to test your Node.js application. 

Writing and Running Tests for Node.js Application

To create unit tests for a Node.js application:

  1. Create a separate file for your tests in the project’s folder. A unit test for the multiplication function from the demo Node.js application looks like as shown below. This code is in a file called multiplication.test.js.

    const multiplication = require('./multiplication)

test('string with a single number should result in the number itself', () => {
    expect(multiplication.multiply('1')).toBe(1);
  });

test('string with two numbers should result in the product of the numbers', () => {
    expect(multiplication.multiply('5,5')).toBe(25);
  });

This code is in a file called multiplication.test.js. Here, the code first imports the module it will test. Then, it describes the test by providing a helpful string. Finally, it specifies what inputs to pass and the expected outcome that will determine a successful or failed test.

  1. Navigate to the terminal and use any of the two following commands to run the test:
    • npm test
    • jest

Learn more in our detailed guide to vue unit testing.

Security Unit Testing with Bright Security 

Bright is a developer-first Dynamic Application Security Testing (DAST) scanner, the first of its kind to integrate into unit testing, letting you shift security testing even further left. 

You can now start to test every component / function at the speed of unit tests, baking security testing across development and CI/CD pipelines to minimize security and technical debt, by scanning early and often, spearheaded by developers. 

With NO false positives, start trusting your scanner when testing your applications and APIs (SOAP, REST, GraphQL), built for modern technologies and architectures. 
Sign up now for a free account or read our docs to learn more.

OWASP Top 10 API Security Threats

What Is the Open Web Application Security Project (OWASP)?

The Open Web Application Security Project (OWASP) is a non-profit foundation by a global community dedicated to providing free application security resources. OWASP offers guidance on developing and maintaining secure software applications. The goal is to educate software architects, developers, and business owners about security risks. 

OWASP supports open source as well commercial security products. Its website offers a place for security experts and IT professionals to learn about application security and get actionable advice for securing their applications. 

OWASP publishes the widely known Top 10 Web Application Security Risks, which is updated every few years as new risks emerge and listed risks change. The list includes the most dangerous web application security risks and offers recommendations for mitigating them. OWASP also has two similar lists for APIs and mobile applications.

This is part of an extensive series of guides about application security.

In this article:

How Can OWASP Help Your Security Efforts?
– Key OWASP Projects
– OWASP Top 10 Series
– OWASP Cheat Sheet Series
– OWASP ZAP
– OWASP Dependency-Check
– OWASP Juice Shop
– OWASP SAMM
– OWASP Top 10 Web Application Security Risks
– Broken Access Controls
– Cryptography Failures
– Injection Vulnerabilities
– Design Flaws
– Security Misconfigurations
– Outdated and Vulnerable Components
– Authentication Issues
– Integrity Vulnerabilities
– Security Monitoring and Logging Failures
– SSRF Vulnerabilities
OWASP Top 10 API Security Threats
– Object-Level Authorization Failures
– User Authentication Failures
– Data Exposures
– Insufficient Resources and Rate-Limiting
– Function-Level Authorization Failures
– Mass Assignment
– Security Misconfigurations
– Injection Vulnerabilities
– Asset Mismanagement
– Insufficient Monitoring and Logging
– OWASP Top 10 Mobile Security Risks
– Misuse of Platforms
– Insecurely Stored Data
– Communication Flaws
– Authentication Failures
– Cryptography Flaws
– Authorization Failures
– Client-Side Code Quality Issues
– Tampering Risks
– Reverse Engineering Vulnerabilities
– Redundant Functionality

How Can OWASP Help Your Security Efforts?

OWASP strives to educate all stakeholders involved in the software development lifecycle, including architects, developers, designers, managers, and business owners. The goal is to inform stakeholders about the importance of web security and the consequences of poor security practices. 

Security knowledge base

OWASP offers an online wiki supported by almost two decades of research and backed by leading security experts. OWASP’s ethical hackers gathered vulnerabilities from thousands of applications and hundreds of organizations. They leverage the information to share knowledge of vulnerabilities, threats, and key strategies for implementing countermeasures. 

Examples of risks and attacks

OWASP provides code examples and sample applications intentionally riddled with security flaws to help developers train to avoid known pitfalls. The community-backed resources can help organizations mitigate risk, conduct threat modeling, and perform architectural threat analysis. 

OWASP compliance

Software development teams can adopt OWASP compliance as part of the software development lifecycle and use the information to create risk management policies that improve credibility. OWASP offers code review guides and frameworks that provide documentation for penetration testing best practices, helping teams measure risk relative to specific environments. 

Conforming to OWASP standards and making development more security-conscious helps teams and organizations better mitigate vulnerabilities and improve the overall quality of applications.

Related content: Read our guide to OWASP certification (coming soon)

Key OWASP Projects

The OWASP foundation helps aspiring open source projects improve software security. The foundation is a well-known and credible entity within the security community, offering funding and project summits for qualifying programs. The community holds conferences and local chapters that connect projects with users.

OWASP projects are open source and built by the community of volunteers. Project leaders are in charge of defining their project’s roadmap, vision and tasks, promoting the project, and building the team. OWASP currently supports over 100 active projects, with new applications submitted weekly.

OWASP projects give members the opportunity to test ideas and theories while getting professional advice and support from the OWASP community. Each project has a web page, Slack Channel, and mailing list. Most projects also maintain their content in OWASP’s GitHub organization.

OWASP Top 10 Series

The OWASP Top 10 list explains the most critical web application vulnerabilities. Data analysts determine eight of these threats, and an industry survey helps decide the last two threats. When it was first created, the list was perceived as an awareness document. 

However, the list is now considered an industry standard for training, testing, and development. It is also referenced in several compliance regulations, including The Payment Card Industry Data Security Standard (PCI DSS).

The importance of the OWASP Top 10 list

A web application vulnerability is a security weakness in software designed to run on a web browser. The ability to run on web browsers makes applications highly accessible but also makes them a target for attackers. 

Web applications can include many security vulnerabilities—there are hundreds of application security vulnerabilities, including misconfigurations and flawed code. It is inadvisable to think a web application does not have a vulnerability of some kind.

The OWASP top 10 list provides organizations and development teams with a way to prioritize mitigation. Once these vulnerabilities are detected, organizations can immediately work on remediating these issues before, during, and after development.

OWASP Cheat Sheet Series

The OWASP Cheat Sheet Series provides a set of simple guides for application developers and security defenders. Instead of focusing on detailed yet impractical best practices, these guides offer good practices that most developers can implement.

Related content: Read our guide to OWASP cheat sheets (coming soon)

OWASP ZAP

Zed Attack Proxy (ZAP) is an OWASP open source penetration testing tool. It is flexible and extensible, designed especially to help test web applications. ZAP works as a Man-in-the-Middle (MitM) proxy, standing between a tester’s browser and the tested web application. 

OWASP ZAP can intercept and inspect the messages sent between the browser and tested web application, modify these contents when needed, and forward the packets to the destination. You can use it as a standalone application or as a daemon process.

Related content: Learn more in our detailed guide to OWASP ZAP (coming soon)

OWASP Dependency-Check

Dependency-Check is OWASP’s software composition analysis (SCA) tool. It attempts to identify publicly disclosed vulnerabilities within your project’s dependencies. It tries to determine if a common platform enumeration (CPE) identifier exists for each dependency. If OWASP Dependency-Check finds a CPE identifier, it generates a report that links to all relevant CVE entries.

Related content: Learn more in our detailed guide to OWASP Dependency Check (coming soon)

OWASP Juice Shop

OWASP Juice Shop is a web application made intentionally vulnerable for security training purposes. It is written in JavaScript and filled with many hacking challenges of varying difficulty levels created for user exploitation. It helps users start learning about web application security.

You can use OWASP Juice Shop for security training, Capture the Flag (CTFs), as a guinea pig for security tools, and awareness demos. It encompasses vulnerabilities from the OWASP Top 10 list as well as many other security flaws from real-world applications.

eb application security.

Related content: Learn more in our detailed guide to OWASP Juice Shop (coming soon)

OWASP SAMM

The Software Assurance Maturity Model (SAMM) is a software security compliance model developed by OWASP and sponsored by industry organizations. OWASP SAMM aims to provide a measurable and effective way to analyze and improve the software security posture of organizations of all types and sizes. 

This self-assessment model can help raise awareness and inform organizations on how to securely design, develop, and deploy software. Organizations that implement and strictly adhere to the model can increase their confidence, knowing they are prepared to handle source code threats.

Related content: Learn more in our detailed guide to OWASP SAMM (coming soon)

OWASP Top 10 Web Application Security Risks

Below we present a brief overview of the top 10 risks and how to prevent them. 

Learn more about these risks in our detailed guide to the OWASP Top 10.

Broken Access Controls

All sensitive information must be available to a limited set of users based on their access permissions. Broken access controls allow unauthorized users to access data without the required permissions.

To ensure proper access controls:

  • Establish a secure application development lifecycle with strong security and privacy controls.
  • Leverage secure designs and pre-built components.
  • Implement threat modeling.
  • Embed security controls in user stories.
  • Apply plausibility checks across the application.
  • Keep the application tiers separate.

Cryptography Failures

Cryptographic vulnerabilities result from improper encryption and decryption methods, including using obsolete ciphers and misapplying protocols. 

To ensure strong cryptography to protect data:

  • Disable autocomplete and caching on data collection forms.
  • Minimize the data surface.
  • Encrypt data at rest and in transit.
  • Implement up-to-date encryption.
  • Use adaptive hashing functions to save passwords.

Injection Vulnerabilities

Attackers exploit these vulnerabilities to inject malicious commands into applications. SQL injection is the most common injection attack. To mitigate injection attacks: 

  • Authenticate all data from untrusted sources, including end-users. 
  • Separate data and commands to prevent applications from executing supplied data as commands. 
  • Use parameterized SQL queries. 
  • Use a secure API instead of an interpreter. 
  • Use intrusion detection and server-side validation to identify suspicious behavior.

Design Flaws

Design flaws affect insecure applications that lack threat modeling and secure design practices. Insecure design often fails to profile business risks and determine the required security level. 

To ensure secure design:

  • Establish a secure application development lifecycle with strong security and privacy controls.
  • Leverage secure designs and pre-built components.
  • Implement threat modeling.
  • Embed security controls in user stories.
  • Apply plausibility checks across the application.
  • Keep the application tiers separate.

Security Misconfigurations

Issues with an application’s security configurations can enable attacks. For instance, applications that don’t filter packets properly may allow attackers to use default credentials. 

To prevent security misconfigurations:

  • Implement repeatable hardening processes with identical configurations across all environments.
  • Avoid incorporating unnecessary features or components and delete unused objects.
  • Incorporate configuration reviews and updates into the patch management process.
  • Segment the application’s architecture to contain threats.
  • Automate verification processes to evaluate configurations.

Outdated and Vulnerable Components

Unsupported and out-of-date software and components with known vulnerabilities allow attackers to compromise applications. 

To keep applications free of vulnerable components: 

  • Regularly test and scan components for vulnerabilities.
  • Maintain inventory of all components and dependencies.
  • Eliminate redundant components, features, and dependencies. 
  • Only use components from trusted sources (i.e., signed packages). 
  • Monitor components and libraries to identify unmaintained and unpatched objects.

Authentication Issues

Authentication vulnerabilities include weak identification and authentication measures, allowing attackers to stuff credentials or break through with brute force. 

To prevent authentication vulnerabilities:

  • Use multi-factor authentication.
  • Close expired and inactive sessions.
  • Use robust passwords and avoid default credentials.
  • Monitor all login attempts.
  • Leverage a session manager to secure user sessions.

Integrity Vulnerabilities

Maintaining data and software integrity is essential for securing applications. Failure to verify integrity can result in exploits. One such vulnerability is insecure deserialization, where the application fails to deserialize vulnerable external objects, allowing attackers to manipulate the data received at the back end.

To ensure integrity:

  • Verify the source of data and software using digital signatures. 
  • Ensure dependencies and libraries only consume trusted repositories.
  • Review configuration and code changes to prevent malicious configurations and code from reaching the software pipeline.
  • Segregate and securely configure the CI/CD pipeline.

Security Monitoring and Logging Failures

These failures include detection and response errors. Monitoring and logging are essential for detecting breaches, ensuring visibility, and allowing security and IT teams to respond. 

To ensure proper monitoring and logging:

  • Log all validation failures with the relevant context information for forensic analysis. 
  • Use an easy-to-consume log format.
  • Encode all log data correctly to mitigate injection attacks. 
  • Keep audit trails for all high-value transactions.

SSRF Vulnerabilities

Server-side request forgery (SSRF) is a security vulnerability allowing attackers to induce server-side applications to send malicious HTTP requests to a chosen domain. It arises when applications don’t validate user-supplied data. Attackers often use SSRF to bypass firewalls and other access controls.

To prevent SSRF:

  • Segment the functionality of sensitive resources to minimize the impact of SSRF attacks.
  • Use policies that deny access by default or block non-essential traffic.
  • Sanitize and validate user-supplied data.
  • Use allow lists to restrict access. 
  • Avoid sending raw responses to the client.
  • Disable HTTP redirection.

OWASP Top 10 API Security Threats

OWASP published the API Security Top 10 to inform organizations about security issues affecting APIs. Below we present a brief overview of the top 10 API risks. 

Learn more about these risks in our detailed guide to the OWASP API Top 10.

Object-Level Authorization Failures

APIs often expose endpoints handling object identifiers, widening the attack surface. Object-level authorization should apply to all functions that access data sources using user input.

To prevent broken object-level authorization:

  • Implement a system to detect and remediate broken object-level authorization.
  • Use strong authorization mechanisms. 
  • Use API gateways.  
  • Use threat modeling to evaluate authorization policies.

User Authentication Failures

Attackers often exploit incorrectly implemented authentication mechanisms to steal tokens and impersonate users. 

To protect user authentication:

  • Use multi-factor authentication to verify user identity.  
  • Block access after several login attempts.  
  • Secure user credentials.  
  • Use robust API keys.
  • Apply the ASVS requirements to the authentication system.

Data Exposures

Developers often expose too much data, assuming the client will filter the data before presenting it to users. 

To prevent data exposure:

  • Use a proactive, shift-left security approach to build secure APIs.
  • Don’t rely on clients to filter data.  
  • Minimize back end responses. 

Insufficient Resources and Rate-Limiting

APIs often fail to impose restrictions on resource requests, enabling DoS and brute force attacks. 

To mitigate these flaws:

  • Evaluate the API design and ensure it has the proper rate-limiting controls. 
  • Refer to OWASP’s Automated Threat Handbook to understand the bots consuming your computing resources.

Function-Level Authorization Failures

An overly complex access control system increases the risk of policy misconfigurations and authorization failures. Attackers exploit these flaws to access user resources and admin functions.

To prevent broken function-level authorization:

  • Ensure the access control policies are clear, outlining who can access what. 
  • Ensure everyone knows their responsibilities. 
  • Audit the access control system regularly. 

Mass Assignment

Mass assignment often results from unfiltered, client-supplied data bound to data models. Attackers can guess object properties or read documentation to edit properties. 

To prevent mass assignment:

  • Use penetration tests to identify vulnerabilities. 
  • Don’t directly map client data to internal variables.
  • Use an allow list for object properties. 

Security Misconfigurations

Security misconfigurations often result from default or incomplete configurations. 

To prevent security misconfigurations:

  • Periodically audit the system for misconfigurations.
  • Avoiding relying on defaults. 
  • Use scanning and testing tools to check the application stack. 
  • Don’t include sensitive information in error messages. 

Injection Vulnerabilities

These vulnerabilities include SQL, NoSQL, and command injection flaws. Attackers send malicious data to an interpreter that executes unauthorized commands or exposes sensitive data.

To prevent injection attacks:

  • Validate inputs using an allow list.
  • Process incoming API requests with parameterized interfaces. 
  • Restrict record returns by reviewing the filtering logic.

Asset Mismanagement

APIs often expose more endpoint devices than web apps, so it’s essential to maintain proper documentation.

To ensure proper asset management:

  • Maintain an inventory of all APIs.
  • Review all APIs for security. 
  • Standardize API functions.
  • Prioritize APIs according to risk level.

Insufficient Monitoring and Logging 

Combined with incident response, monitoring and logging allow organizations to detect and block attackers. Without proper monitoring, attackers can persist, causing damage undetected.

To ensure sufficient monitoring and logging:

  • Use a standard logging format for all APIs.
  • Monitor every API endpoint throughout its lifecycle. 

OWASP Top 10 Mobile Security Risks

Below we present a brief overview of the top 10 risks facing mobile applications. 

Learn more about these risks in our detailed guide to the OWASP Mobile Top 10.

Misuse of Platforms

Misusing the Android or iOS platform is the greatest security vulnerability for mobile devices. Apps can unintentionally misuse platforms. 

To address this vulnerability:

  • Follow the platform’s security guidelines. 
  • Utilize the server-side security features available.
  • Use secure configurations and coding practices. 
  • Harden the server-side. 
  • Limit data transmission between applications.
  • Limit file access permissions.
  • Encrypted stored data.

Insecurely Stored Data 

Insecure data storage allows attackers to exploit stolen mobile devices and steal sensitive information. Sometimes, it is unavoidable to have applications store sensitive data, but it is essential to ensure this data is not accessible to unauthorized users. Encryption alone is not always enough.

To secure stored data:

  • Encrypt all data.
  • Use authorization and authentication mechanisms for accessing mobile apps.
  • Restrict mobile app access to stored files.
  • Use secure coding practices.

Communication Flaws

Insecure communication allows attackers to intercept data as it traverses the Internet. 

To ensure secure communication:

  • Use SSL/TLS certificates.
  • Avoid untrusted and unsigned certificates.
  • Use strong encryption protocols. 
  • Send sensitive data to the back end. 
  • Avoid sending session IDs with SSL tokens.
  • Protect transmission channels with SSL/TLS. 

Authentication Failures

Mobile devices often allow users to log in with default credentials when they fail to recognize users correctly, allowing malicious actors to bypass authentication measures. 

To ensure secure authentication:

  • Use the right authentication mechanisms and security protocols.
  • Deploy authentication on the server-side. 
  • Avoid storing credentials on mobile devices.
  • Encrypt local storage with strong keys.
  • Avoid “remember me” options.
  • Provide warnings when users opt for “remember me” options.
  • Use device-based authentication to prevent users from accessing data from other devices.
  • Implement binary attack protections.

Cryptography Flaws

Attackers exploit cryptography flaws to access sensitive data. It is usually easy to exploit weak encryption mechanisms on mobile devices.

To ensure sufficient cryptography:

  • Don’t store data on mobile devices.
  • Use robust cryptography algorithms. 

Authorization Failures

Attackers exploit insufficient authorization measures and IDOR vulnerabilities to access sensitive data and escalate privileges. If an app’s authorization is incomplete, it might grant user permissions without sufficient verification.

To prevent insecure authorization:

  • Avoid granting roles and permissions via mobile devices.
  • Verify each identity independently through the back end code.

Client-Side Code Quality Issues

Poor coding practices can result in poor and inconsistent code quality. While client code issues are harder for attackers to detect, they pose a significant risk if discovered. 

To protect client code quality:

  • Implement safe and consistent coding practices.
  • Use static code analysis.
  • Refrain from simple logic.
  • Integrate with reliable libraries.
  • List all third-party libraries to patch and update components.
  • Use automated tools to test memory leaks and buffer overflow.
  • Flag permissions on the content provider to block unauthorized access.

Tampering Risks

Counterfeit mobile apps with tampered code are often available on app stores. For instance, attackers may modify an application’s binary to install a backdoor. 

To address code tampering risks:

  • Look for test keys, known APKs, and OTA certificates.
  • Check if the build is official using the build.prop element. 
  • Look for SU binaries and try to use direct SU commands. 
  • Test-run the SU command to check the current user ID.
  • Allow the mobile app to identify and react to code integration.
  • Use anti-tampering techniques like validation, code hardening, checksum, and digital signatures.

Reverse Engineering Vulnerabilities

Attackers often reverse engineer and decompile applications to analyze code and insert malicious functionality. Reverse engineering allows attackers to understand how an app works and exploit its weaknesses. 

To minimize reverse engineering: 

  • Check if an attacker can decompile the application using debugging tools. 
  • Use robust obfuscation, including for metadata. 
  • Build the app with C or C++ to secure runtime changes.
  • Segment the source code to control the app’s code flow.
  • Use binary packaging to prevent decompilation.
  • Implement anti-debugging mechanisms. 

Redundant Functionality

Hackers can exploit many applications with redundant functionality to reach the back end. Some functions allow users to execute a privileged action anonymously.

To address this vulnerability:

  • Manually review the code before releasing it to production. 
  • Analyze API endpoints and check logs and files to verify that attackers cannot exploit hidden functionality. 
  • Check app configurations for hidden switches.
  • Verify that API endpoints and log statements are not publicly available.
  • Check if the log contains information about privileged accounts or back end processes.

Preventing OWASP Vulnerabilities with Bright Security

Bright Security is a developer-first Dynamic Application Security Testing (DAST) scanner that can test your applications and APIs (SOAP, REST, GraphQL), enabling you to bake security testing into your development and CI/CD pipelines. 

Detect the OWASP Top 10 for web applications and APIs, MITRE 25 and more, including Business Logic Vulnerabilities. You can easily reduce your security and technical debt by scanning early and often, on every build, to be secure by design. 

With NO false positives, there is no need for manual validation of security findings, removing costly and time consuming human bottlenecks that cripple your rapid releases and drain your security team’s limited resources. 

See Additional Guides on Key Application Security Topics

Together with our content partners, we have authored in-depth guides on several other topics that can also be useful as you explore the world of application security.

Application Migration

Authored by Faddom

API Security Testing

Authored by Pynt

API Security

Authored by Pynt

Security is Everybody’s Job — Part 6 — The Second Way

The Second Way of DevOps is fast feedback. In security, when we see this we should all be thinking the same thing: Pushing Left. We want to start security at the beginning of the system development life cycle (SDLC) and ensure we are there (providing feedback, support and solutions) the whole way through!

Pushing Left, Tanya' Favorite Thing
Pushing Left, Tanya’s Favorite Thing

Fast feedback loops means getting important information to the right people, quickly and regularly. One of the main reasons that Waterfall projects failed in the past was the lack of timely feedback; no one wants to find out twelve months after they made a mistake, when it’s too late to fix it.

The goal of security activities in a DevOps environment must be to shorten and amplify feedback loops so security flaws (design issues) and bugs (code issues) are fixed as early as possible, when it’s faster, cheaper and easier to do a better job. These DevOps people are really onto something!

– Me

Let’s go over several ideas of how to achieve this.

Activities to create fast feedback loops.

  • Automate as much as humanly possible. Inside or outside the pipeline, automation is key.
  • Whenever possible integrate your tools with the Dev and Ops team’s tools. For instance, have the issues found by your IAST tool  turned into tickets in the developer’s bug tracking system, automagically.
  • When you have a Pentest done, check all your other apps for the things found in the report, then add create unit tests to look for these things and prevent them from coming back.
  • Rename insecure functions or libraries as “insecure” with a wrapper, so programmers see immediately that there is an issue.
  • Add security sprints to your project schedule (to fix all security bugs in backlog).
  • Asking the Dev and Ops what they are concerned about (in relation to security), so you can fix any problems the security team might be causing them.
  • Add important security tests that are quick and accurate to the pipeline. For instance, scan for secrets in the code that is being checked in. That is an important test!
  • If an important security tests fail in the pipeline, the continuous integration server must break the build. Just like quality tests. This is loud feedback.
  • Create a second pipeline that doesn’t release any code, but runs all the long and slow security tests, then have the security team review the results after and turn the important things into tickets for the Devs.
  • Tune all security tools as much as possible and validate all results so that the feedback you are giving is *accurate*. There is no point of sending lots of feedback if half of it is wrong.
  • Work with developers to create negative unit tests (sometimes known as abuse tests). Create copies of regular unit tests, rename them with “Abuse” at the end, then add malicious payloads and ensure that your app fails gracefully and handles bad input well.
  • Have reports from your security tools automatically send their results to a vulnerability management tool such as Defect Dojo or Thread Fix to keep metrics and use them to improve all of your work. You need feedback too.

Be creative. Any way that you can get feedback faster to other teams is a huge win for your team too!

Security is Everybody’s Job — Part 5 — The First Way

The First Way of DevOps

The first “Way” of DevOps is emphasizing the efficiency of the entire system. Many of us tend to focus only on our part of a giant system, and get bogged down improving only our own contributions to the larger process. It’s rare that we stand back, look at the entire thing, and realize that if we helped another team or changed something small within our part, that it could improve other areas for the better. The first way of DevOps is about looking at the entire system, and making sure the entire thing is as efficient as possible. #speed

The First Way of DevOps - Efficiency
The First Way of DevOps – Efficiency

When we worked in Waterfall development environments security often acted as a gate. You had to jump through their hoops, then you were let through, and you could push your code to prod. Awesome, right? Not really. It was slow. Security activities took FOREVER. And things got missed. It was rigid and unpleasant and didn’t result in reliably secure software.

It may seem obvious to new developers that security should not slow down the SDLC, but I assure you, this concept is very, very new. When I was a software developer I referred to the security team as “Those who say no”, and I found almost all of my interactions with them left me frustrated and without helpful answers.

When we (security practitioners) think about The First Way, we must figure out how to get our work done, without slowing down all the other teams. They won’t wait for us, and we can’t set up gates. We have to learn to work the way they do; FAST.

Below I will offer suggestions for how we can work together with the dev and ops teams to ensure we get our mandate done, within the DevOps workflows and processes.

Tools:

First of all, we need to use modern tooling that is made for DevOps pipelines if we are going to put anything into the CI/CD pipeline. Never take an old tool and toss it in there; no DevOps team is going to wait 5 hours for your SAST tool to run. Tune your tools and ensure you select tools that are made for pipelines if that is how you are going to use them. Whenever possible, only run your tools on the ‘delta’ (the code changed in that release, not the entire code base).

Tool Selection:

When selecting tools, remember that not every tool needs to be put in the pipeline. In fact, having tools that are out-of-band, but located on the ‘left’ of the SDLC, can offer even more value and save time. Examples:

  • Create automated security unit tests using Bright’s SecTester for java script, to be run before you run the CI/CD
  • Package management tools that only serve packages that are not known to be insecure (pre-approved by a security research team)
  • Creating your own custom security unit tests, which are often run before the code arrives in the pipeline (for instance, write input validation tests that ensures your code properly handles input taken from the XSS Filter Evasion Cheat Sheet)
  • Adding security tooling to the check-in process, such as secret scans (don’t even let them check it in if it looks like there’s a secret in the code)
  • Run a DAST such a Bright against your web server or within your CI/CD, after you’ve configured it to run quickly
  • Scanning your code repository for known-insecure components. It’s just sitting there, why not use it?

Bugs:

This also means that security bugs should be placed in the same bug tracker or ticketing system that the developers and ops teams are using. They shouldn’t check two systems, that is not efficient.

Finding Vulnerabilities:

If at all possible, we should be providing and/or approving tools that assist in finding vulnerabilities in written code (both the code your team wrote, and the code from dependencies) and running code. This could be SAST + SCA + DAST, or it could be SCA + IAST (run during unit testing, QA and in prod). It could also mean manual secure code review plus a PenTest the week before going live (this is the least-efficient of the three options presented here).

Templates and Code Reuse:

If it makes sense, create templates and provide secure code samples, there’s no need to reinvent the wheel. Also, enable the developers and ops teams to scan their own code by providing tools for them (and training on how to use them safely and effectively).

Think Outside The Box

We (security) can no longer be a bottleneck, we must work to enable them to get their jobs done securely, in anyway we can. Examine your processes to ensure they are efficient; create a second asynchronous (which does not release to prod) pipeline to automate your longer tests; write your own tools if you absolutely have to. The sky is the limit.

Part 6 of this series is available here.

Security is Everybody’s Job — Part 4 — What is DevSecOps?

In this post we will explore The 3 Ways of DevOps. But first, a definition from a friend.

DevSecOps is Application Security, adjusted for a DevOps environment.

Imran A Mohammed

DevSecOps is the security activities that application security professionals perform, in order to ensure the systems created by DevOps practices are secure. It’s the same thing we (AppSec professionals) have always done, with a new twist. Thanks Imran!

Refresher on The Three Ways:

  1. Emphasize the efficiency of the entire system, not just your part.
  2. Fast feedback loops.
  3. Continuous learning, risk taking and experimentation (failing fast). Taking time to improve your daily work.

Let’s dig in, shall we?

1. Emphasize the efficiency of the entire system, not just one part.

This means that Security CANNOT slow down or stop the entire pipeline (break the build/block a release), unless it’s a true emergency. This means Security learning to sprint, just like Ops and Dev are doing. It means focusing on improving ALL value streams, and sharing how securing the final product offers value to all the other steams. It means fitting security activities into the Dev and Ops processes, and making sure we are fast.

2. Fast feedback loops.

Fast feedback loops = “Pushing Left” (in application security)

Pushing or shifting “left” means starting security earlier in the System Development Life Cycle (SDLC). We want security activities to happen sooner in order to provide feedback earlier, which means this goal is 100% inline with that we want. The goal of security activities must be to shorten and amplify feedback loops so security flaws (design/architecture issues) and bugs (code/implementation issues) are fixed as early as possible, when it’s faster, cheaper and easier to do a better job.

3. Continuous learning, risk taking and experimentation

For most security teams this means serious culture change; my favorite thing! InfoSec really needs some culture change if we are going to do DevOps well. In fact, all of IT does (including Dev and Ops) if we want to make security everybody’s job.

Part of The Third Way:

  • Allocating time for the improvement of daily work
  • Creating rituals that reward the team for taking risks: celebrate successes
  • Introducing faults into the system to increase resilience: red team exercises

We are going to delve deep into each of the three ways over the next several articles, exploring several ways that we can weave security through the DevOps processes to ensure we are creating more secure software, without breaking the flow.

If you are itching for more, but can’t wait until the next post, watch this video by Tanya Janca. She will explain this and much more in her talk ‘Security Learns To Sprint’.

If you’re willing to learn more, don’t forget to check out part 5.

Security is Everybody’s Job — Part 3 — What IS DevOps?

What IS DevOps?

There are many definitions of DevOps, too many, some might say. Some people say it’s “People, Processes, and Products”, and that sounds great, but I don’t know what I’m supposed to do with that. When I did waterfall I also had people, processes, and products, and that was not great. I thought DevOps was supposed to be a huge improvement?

I’ve heard other people say that it’s paying one person to do two jobs (Dev and Ops), which can’t be right… Can it? I’ve also been told once by a CEO that their product was “made out of DevOps”, as though it was a substance. I decided not to work there, but that’s another story. Let’s look at some better sources.

Wikipedia says:

DevOps is a set of practices that combines software development and information-technology operations which aims to shorten the systems development life cycle and provide continuous delivery with high software quality.

But what are the practices? Why are we aiming to shorten the SDLC? Are we making smaller software? What is ‘continuous delivery’?

To get to the bottom of it I decided to read The DevOps Handbook. 
Then I knew what DevOps was, and I knew how to do it. As an added bonus, I 
discovered that I LOVED DevOps.

According to the DevOps Handbook, DevOps has three goals.

Improved deployment frequency; Shortened lead time between fixes;

Awesome! This means if a security bug is found it can be fixed extremely quickly. I like this.

Lower failure rate of new releases and faster recovery time;

Meaning better availability, which is a key security concern with any application (CIA). Lower failures mean things are available more often (the ‘A’ in CIA), and that’s definitely in the security wheelhouse. So far, so good.

Faster time to market; meaning the business gets what they want.

Sometimes we forget that the entire purpose of every security team is to enable the business to get the job done securely. And if we are doing DevSecOps, getting them products that are more secure, faster, is a win for everyone. Again, a big checkmark for security.

Great! Now I think the DevOps people want the same things that I, as a security person, want. Excellent! Now: How do I *DO* DevOps?

That is where The Three Ways of DevOps comes in.

  1. Emphasize the efficiency of the entire system, not just one part.
  2. Fast feedback loops.
  3. Continuous learning, risk-taking and experimentation (failing fast)

In the next post we will talk more in detail about The 3 Ways (and how security fits in perfectly).

Security is Everybody’s Job — Part 2 — What is Application Security?

Application Security is every action you take towards ensuring the software that you (or someone else) create is secure.

Tanya Janca

This can mean a formal secure code review, hiring someone to come in and perform a penetration test, or updating your framework because you heard it has a serious security flaw. It doesn’t need to be extremely formal, it just needs to have the goal of ensuring your systems are more secure.

Now that we know AppSec is, why is it important?

For starters, insecure software is (unfortunately), the #1 cause of data breaches (according to the Verizon Breach Reports, 2016, 2017, 2018 and 2019). This is not a list that anyone wants to be #1 on. According to the reports, insecure software causes 30–40% of breaches, year after year, yet 30–40% of the security budget at most organizations is certainly not being spent on AppSec. This is one part of the problem.

The graph above is from the Verizon Breach Report 2017. Hats off to Verizon for creating and freely sharing such a helpful report, year after year.

If the problem is that insecure software causes breaches, and one of the causes is that security budgets don’t appear to prioritize software, what are some of the other root causes of this issue?

For starters, universities, colleges, and programming bootcamps are not teaching the students how to ensure that they are creating secure software. Imagine electricians whet to trade school, but they didn’t teach them safety? They twist two cables together and then just push them into the wall, unaware that they need two more layers of safety (electrical tape, and then a marrett). This is what we are doing with our software developers, we teach them from their very first lesson how to make insecure code.

Hello (insecure) World

Lesson #1 for every bootcamp or programming course: Hello World.
Step 1) Output “Hello World” to screen
Step 2) Output “What is your name?” to screen

Step 3) Read the user’s input into a variable (note: we skip teaching input validation)
Step 4) Output the user’s input to the screen with a hello message (note: we skip output encoding)

The above lesson teaches new programmers the best possible recipe for including reflected Cross Site Scripting (XSS) in their application. As far as I know there is not a follow up lesson provided on how ensure the code is secure.

“Hello World” is the most-taught lesson for starting a new programming language, I’m sure you’ve seen it everywhere. More like “Hello Insecure World”.

Although there has been some headway in universities and colleges recently, most of them barely scratch the surface in regards to application security.

So that’s reason #2. Let’s move onto reason #3.

Another issue that contributes to this problem is that security training for developers is costly. While this is true for all types of professional training, security training is significantly more expensive then other forms of technical training. A single course at the SANS institute (a well-respected training establishment that specializes in all things cyber), could cost an attendee as much as $5000-$7000 USD, for one week of training. There are other less-pricy options, such as taking a course when attending a conference, which usually range from $2000-$5000, however, those are of varying quality, and there is no standardized curriculum, making them a bit of a gamble. I’ve taken several trainings when attending various conferences over the years, and I’d say about 1/2 were good.

There are much cheaper alternatives to the options above (such as the courses from We Hack Purple and other training providers), and they are of very varying quality levels. I’ve seen both good free courses and some where I wish I could have my time back they were so bad. Most of them do not provide a curriculum to follow either, meaning it is often unclear to the student which other courses they should take in order to get the specific job they want. It is very easy to waste quite a bit of time and money; I know, that is how I started my AppSec career… Although I was quite lucky to have two professional mentors guiding me, which made it a lot easier. Not everyone has a mentor.

Another cause (#4) of insecure software is that the security team is usually grossly outnumbered. According to several sources there is usually 100 software developers for every 10 operations employees for every single (1) security professional.

Let me repeat that. There are 100/10/1, Dev/Ops/Sec. With numbers like that you can’t work harder, you have to work smarter. Which is where we are going with this series.

Now we know the problem and several of the causes, what can we do about it? The short answer is DevSecOps, and the long answer is ‘read the rest of the blog series’.

For now though, let’s define DevSecOps, before we dive into what DevOps is, The Three Ways, and so much more, in the next article.

DevSecOps: performing AppSec, adjusted for a DevOps Environment. The same goals, but with different tactics and strategies to get us there. Changing the way we do things, so that we weave ourselves into the DevOps culture and processes.

Looking for more content? Part 3 is out and you can check it out here.

Security is Everybody’s Job — Part 1 — DevSecOps

This is the first in a many-part blog series on the topic of DevSecOps. Throughout the series we will discuss weaving security through DevOps in effective and efficient ways. We will also discuss the ideas that security is everybody’s job, it is everyone’s duty to perform their jobs in the most secure way they know how, and that it is the security team’s responsibility to enable everyone else in their organization to get their jobs done, securely. We will define DevOps, ‘The Three Ways’, AppSec and DevSecOps. We will get in deep on the many strategies we can adjust security activities for DevOps environments, while still reaching our goals of ensuring that we reliably create and release secure software.

In summary; We will discuss how to make security a part of our daily work. 
It cannot be added later or after, it needs to be a part of everything.

But let’s not get ahead of ourselves, I have many more posts planned where I will attempt to sway your opinion my way.

Tanya Janca, also known as SheHacksPurple, presenting her ideas in Sydney Australia, 2019. Artwork by the talented Ashley Willis.

Before we get too deep into anything I’d like to dispel some myths. Look at the image below. This is how *some* security professionals see DevOps.

Slide credit: Pete Cheslock

This slide’s author, Pete Cheslock, is highly intelligent and experienced, this mention is not meant to insult him in any way. The slide is social commentary, it is not literal. That said, many people I’ve met truly feel this way; that DevOps engineers are running around making security messes where ever go, and that we (security professionals) are left to clean up the mess. I disagree with that opinion.

Luckily for me, my introduction to DevOps was at DevSecCon, where they introduced me to this image. Below you can see the security team teaching, providing tooling and enabling the magical DevOps unicorns in doing their jobs, securely. This is how I view DevOps; the security team enabling everyone, working within the confines of the processes and systems that all the other teams use.

Slide Credit: Francois Raynaud & DevSecCon

This series will be loosely based off a conference talk which I have delivered at countless events, all over the planet, ‘Security is Everybody’s Job’. You can watch the video here.

Part 2 of this article is available here.