Category

React

Challenges and Best Practices of Docker s Container security

In the recent years massive adoption rates of dockers have made the security an important point to consider for firms which are using these containers for the development and production of different things.Containers are complex when compared to virtual machines or other deployed technologies. The process to secure docker containers are also very complex.

We will take a view of docker security container and explain the reason behind the complexity of docker container. We will discuss the default environments for better security and practices to monitor containers for security.

Following is the complete guide for container security:

Challenges faced by dockers container security:

Many organisations used virtual machines or bare-metal servers before Docker to host applications. These technologies are quite simple when seen from a security perspective. When hardening your development and monitoring for security relevant events you need to focus on just two layers. As APIs, overlay networks or complex software defined storage configuration are not a major part of virtual machine or bare metal developments so you do not have to worry about these.

A typical Docker environment has many moving parts hence its security is much more complicated. Those moving parts include:

  • Probably you have multiple Docker container images and individual micro services will be hosted by each one of your containers. Also probably multiple intances of each imagine will be running at a time. Proper security and monitoring will be required for these intances and images.
  • To keep the containers and its host safe, the Docker daemon need to be secured.
  • Bare metal or virtual machine might be the host server.
  • Another layer to secure is service like ECS if you use it to host your containers.
  • Communication between containers is facilitated by APIs and Overlay networks.
  • Other storage system that exists externally from your containers is Data volume.

And if you are thinking that learning to secure Docker is tough because dockers security is undoubtely much more complex than any other security system.

Best practices of Docker container security:

Luckily we can overcome the challenges. this article is not a tiring guide to security of docker but you can use this official Docker documentation),as a reference. Below are some best practices:

#1 setting of reference quotes

One easy thing in docker is configuring of resource quotas. Resource quotas helps us to limit the memory amount and resources of cpu which is consumed by the container.

This is helpful for many reasons. It helps to keep the environment of docker efficient and saves one container from mixing with other system resources. It also increases the security by saving the container from using large space or resources so that it gets prevented from any harmful activity.

Resources quotas are easily set by use of commands. View this Docker documentation.

#2 Root should not be run

We all know the feeling when we are tired and dont want to get entangled in problems related to permission setting to get an application work properly so running in root is the only option left so you dont worry about issues related to permission restrictions.

if you are a beginner it is sometimes okay to use Docker testing environment but there is no reason good enough to let a Docker container run with roof permissions in production.

Because Docker doesn’t run containers as root by default so this is an easy docker security to be followed. So you don’t have to make amendments to prevent running as a root by default in a default configuration. letting a container as a root is a temptation that needs to be resisted as it is more convenient in some situations.

If you use kubernetes to orchestrate your containers for added Docker security, you can explicitly prevent containers from starting as root. We can use MustRunAsNonRoot directive in a pod security policy.

#3 Secure container registeries

Docker is powerful because of the container registeries.It makes it easy to set central repositories which helps us in downloading the container images.

Using the container registries is a security risk if one does not know the evaluation of the security constraints.We can use Docker Trusted Registry  which can be installed in the firewalls to eradicate the risk of viruses.

The registry can be accessed from the back of firewalls and we can limit the unknown access of uploading and downloading images from our registry. Using role based access can control explicitly of unknown users or access.It is nice to leave our registry open to others but it is useful only if it stops the access of viruses and harmful things.

#4 Use of trusted and secure images

We should be sure that the the images or  container images  we use are from a trusted source. This is obvious but there are many platforms from where we can download images and they might not be trusted or verified.

One should consider not using public container registries or try to use official trusted repositories, like the ones on Docker Hub.

One can use image scanning tools which help to identify harmful sources . Mostupper level containerhave embedded scanning tools. The ones like Clair.

#5 Identify the source of your code

Docker images contain some original code and packages from upstream sources. sometimes the image downloaded can come from a trusted registry, the image can have packages from untrusted sources. these unknown packages can be made up of code taken from multiple outside sources.

That is why analysis tools are important. Downloading the sources of the Docker images and scanning the code origin we can know if any of the code is from unknown sources.

#6 network security and API

As we have seen above Docker containers depend on APIs and networks for communication. It is important to make sure that your APIs and network architectures are secure and monitoring the APIs and network activity for any unusual activity must also be checked.

As APIs and networks are not a part of Docker and are resources of Dockers so steps for securing APIs and networks are not included in this article. But it is important to check the security of the sources.

In Conclusion

Docker is a complex concept and having no simple trick for maintaining Docker container security. But one has to think carefully about steps to secure your Docker containers, and strengthen your container environment at many levels. This is the only way to ensure that you can have all the benefits of Docker containers without having major security issues.

Using Jest for Unit Testing of Gatsby, Typescript and React Testing Library

The task to set up Jest and React Testing library for TDD using Gatsby is an easy one.Its tricky as i planned to use Typescripts in my test.

Firstly , i installed jestbabel-jest and babel-preset-gatsby ensuring the presence of babel preset(s) which can be used internally for Gatsby site.

npm install –save-dev jest babel-jest babel-preset-gatsby identity-obj-proxy tslint-react @types/jest

Configure Jest for checking its working with Gatsby

As Gatsby has its own babel configuration so we have to manually tell jest to use babel-jest. the gatsby website tells to create  jest.config.js file. look at the code below

jest.config.js

const path = require(“path”)

module.exports = {
setupFilesAfterEnv: [
path.resolve(dirname, “./jest-configs/setup-test-env.js”) ], transform: { // “^.+\.(tsx?|jsx?)$”: “ts-jest”, “\.svg”: “/jest-configs/__mocks/svgTransform.js” ,
“^.+\.(tsx?|jsx?)$”: <rootDir>/jest-configs/jest-preprocess.js,
},
moduleNameMapper: {
// “\.svg”: ./jest-configs/__mocks__/file-mocks.js,
“\.svg”: <rootDir>/jest-configs/__mocks__/svgTransform.js,
“typeface-“: “identity-obj-proxy”, “.+\.(css|styl|less|sass|scss)$”: identity-obj-proxy, “.+\.(jpg|jpeg|png|gif|eot|otf|webp|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$”: <rootDir>/jest-configs/__mocks__/file-mocks.js, }, testPathIgnorePatterns: [node_modules, .cache, public], transformIgnorePatterns: [node_modules/(?!(gatsby)/), \\.svg], globals: { PATH_PREFIX: “, }, testRegex: “(/tests/.|\.(test|spec))\.(ts|tsx)$”,
moduleFileExtensions: [
“ts”,
“tsx”,
“js”
],
collectCoverage: false,
coverageReporters: [
“lcov”,
“text”,
“html”
]
}

svgTransform.js

module.exports = {
process() {
return ‘module.exports = {};’;
},
getCacheKey() {
// The output is always the same.
return ‘svgTransform’;
},
};

The function of transform option is to tell Jest that all ts, tsx, js or jsx files should be transformed using a jest-preprocess.js file.

jest-configs/jest-preprocess.js

const babelOptions = {
presets: [
‘@babel/preset-react’,
‘babel-preset-gatsby’,
“@babel/preset-typescript”
],
};

module.exports = require(“babel jest”).createTransformer(babelOptions)

some code should also be put in setup-test-env.js .
The Jest Configuration docs explains the setupFilesAfterEnv: .... configuration option.

A list of direction or path to modules which run some code to configure or set up the testing framework before each test.

jest-configs/setup-test-env.js

import “@testing-library/jest-dom/extend-expect”

That should have Jest properly configured. Now, I’ll install the testing library and jest-dom as dev-dependencies with npm.

npm install –save-dev @testing-library/react @testing-library/jest-dom

Now run npx jestand now our code is good to go

SO NOW WE ARE GOOD TO GO

Now i will write my first test and run it. I like TDD because it is fast. We can write test before writing code. A test should fail at the beginning Read this up.
Now i will create a folder named __tests__ in my root folder of project. Then i will create a file named  test.spec.tsx and paste this code in it.

tests/test.spec.tsx

import React from "react"
import { render } from "@testing-library/react"

// You have to write data-testid
const Title = () => <h1 data-testid="hero-title">Gatsby is awesome!</h1>

test("Displays the correct title", () => {
  const { getByTestId } = render(<Title />)
  // Assertion
  expect(getByTestId("hero-title")).toHaveTextContent("Gatsby is awesome!")
  // --> Test will pass
})

Run commands like Yarn or npm install if you get errors like.

Cannot find module 'react' from 'test.spec.tsx'
    > 1 | import React from "react"

YAAYYY WE ACCOMPLISHED UNIT TESTING WITH TYPESCRIPT AND GATSBY AND JEST AND REACT TESTING LIBRARY

I am very happy with this . I will just start out Typescript with React so this was a great deal of learning for me. I’ll put up more post about writing real code using TDD. stay tuned

Mobile Applications architecture -React Native VS Native

Having an iOS and android background i struggled working with react native. i had no experience of working in this environment before and i worked with mobile development previously. i shifted to this new environment to develop the mindset of tech skills as a web developer. i was still understanding the mobile ecosystems rules like low memory usage and having battery of users, UI and others.

After passing the boundary of JavaScript learning norms, the new pattern of React, and what React Native includes , i next made a move to understand the structuring of app. My aim was to understand the path that is needed to be followed in order to structure the apps. My goal was to have knowledge for native development, and compare the tech worlds.

Native World

Nowadays, for many people with native background , its not difficult for them to decide the architecture of their app. these people have set some good options like MVP, MVVM and VIPER (mostly iOS). These people have the following goals in their mind:

  • unrelating the supply from business logics
  • developing testable applications
  • structuring of the app in modules for defining responsibilities

There was no right way decided by google or apple for many years, but 2 years ago google described their take at Google I/O and published a detailed blog ( detailed blog post) about structuring of app according to them and added extensive frameworks to android to support them .

The logic behind this step was to separate screens into their native components, with UI, business logics, networks and storage, all in their own entities. Look at the following diagram:

React Native

Most decisions related to architecture comes from FED world as ract native is based on react. It can be difficult for the react native developers initially as the ecosystem is different and decomposed between the different solutions.

After viewing the architecture we come to know that the web is mostly aligned with Flux. The main goal behind this was to develop one directional and predictable flow of data for your app, so it gets easy to understand and debug.

Redux is the best known implementation of flux despite many other implementations .

the application state is kept in Playstore or other stores and any change in store changes the parts of app. Look at the picture below:

Image for post

the components separate the actions, actions in return do something and update the store which changes the components in a good way. In above diagram differences and similarities can be seen.

let us view the differences and understand their existence and process parallel to them. I use android most of the time but in iOS the fragments can be switched to view controller and have feels like home.

Smart Components = Fragments

As in react native we speak about screens and in react we speak in terms of components. These components are the building units of all screens. A screen has many components and most of them are dumb , some are smart and are connected with the store or query needed by the data.

Some screens have smart components and access their own store with their business logics. for :

Image for post

This example describes the addition of task screen in the to do list of the application. It contains many smart components like pick location which has its own state or store, user interface states and business logic storage and server API. This helps to develop each part even when there are different teams and have screen which is a dumb container.

Native equivalent:

The notion of composing your screen into different separate components is also present. Each smart component can be its own part in native. The screen is result of combination of several small components , each of them having its own logic and interactive environment. The logics or the states are taken out of different components, which takes us to the next step.

Actions + Store = ViewModel

This part of component is in charge of all the states of the components and logics related to business and presentation. Its the most important part as it helps in the implementation process. This is the main heart of the application.

By using Redux , we can dispatch the actions and have to wait till any change in store and we check the changes if they are appropriate or not. In each action we can request any network, ask queries related to storage and upgrade the stores. The object named store is global and not attached to any other component life-cycle.

Native Counterpart:

Actions are similar to calling methods in appropriate view models. Store state is in the view model . Any change in the state disturbs the UI and gives benefits of reactivity.

Frameworks like RXjava and RXswift makes reactivity very simple.

Some differences noted are listed below:

The state is private in ViewModel in native, while in Redux the store is global. It has an advantage that when one component can effect another component the UI remains consistent.

Some disadvantages include the leakage of state to other components due to which it can be misused and rely on inside details that should be kept hidden . Also when one component is to be shown on the screen more than once , so updating that store can have issues and screens effect each other causing difficulty in debugging errors . To remove such issues we should decide what must be kept in the store an what not.

Remote Server

No difference.

Async Storage ≠ Relational DB

Now here lies big differences.

In react we have to use key/value storage , in native we use relational DB solutions. Both approaches have their own advantages and disadvantages so people with DB background find it difficult to work with key/value storages and its hard for them in schema portion.

Summary

We can see that initially it seems like recat native was different from native development, but after viewing we came to know that many ideas are similar with small chnages.

While comparing the architectural patterns its seen that in the android trends and is called MVI which aims to bring the flux pattern to native development.

Also Redux is the most used library and most used state management , although there are others like Mobx which brings MVC back to the web.

For mobile developers with native knowledge should take start from react native path, as both have similar goals mainly SOLID principles of software engineering.

Implementation might have some differences ; some are more functional or reactive, some with boilerplate, but mainly they have same goals.

Remote React App Developer- Best And Most Underrated Pattern Design

<Modal showCloseButton>
	<title>Modal title</title>
	<contents>Modal body text goes here.</contents>
	<dismissButton onClick={close}>Close</dismissButton>
	<actionButton> onClick={save}>Save</actionButton>
</Modal> 

The times are near when we would like to pass props and would want to control the behavior of child elements. For example, in the picture given below, you can see there are different elements:

  • A title section that is written at the top.
  • A cross button to close the action present at the top right corner.
  • A content area where you can write some text.
  • A button to save the changes, “Save changes”.
  • A dismiss button to close it, “Close”.

Now, if we want to reuse the Modal properly, we must modify the modal and its elements. This means that users will get control over things such as the content which is displayed, the dispatched events, the style of the content, and all other elements of the Modal that will be under the control of the user. Users can select a naïve solution for the acceptance of proposed for each element like they are:

<Modal
  showCloseButton
  showDismissButton
  showActionButton
  title="Modal title"
  contents="Modal body text goes here."
  dismissButtonText="Close"
  actionButtonText="Save changes"
  handleDismiss={close}
  handleAction={save}
/>

The problem with this kind of approach is that it spams the mechanism of propos, and this makes the whole component look less readable and more inflated. While on the one hand, it is less attractive, at the other end, it limits the amount of propos that users can pass to child elements. This method also prevents users from having complete control over the elements. However, you can solve this problem through another way by providing generic props objects where every prop object is representing a different element:

<Modal
  showCloseButton
  title="Modal title"
  contents="Modal body text goes here."
  dismissButtonProps={{
    text: 'Close',
    handler: close,
  }}
  actionButtonProps={{
    text: 'Save changes',
    handler: save,
  }}
/>

However, this solution works fine, but it does not solve the issue of spam, and you are completely abusing the syntactic sugar that JSX provides you in this way. You are obligated to use JSONs style attributes instead of using the HTML style attribute assignments (attr= “value”).

Using Bootstrap for the rescue

They take a very shrewd approach in Bootstrap, and that is instead of defining props all over the places, they gave us the capability to manipulate the Modal’s children directly. Now, we can achieve this intended functionality by using the dedicated components that Bootstrap was aiming for:

<Modal.Dialog>
  <Modal. Header closeButton>
    <Modal.Title>Modal title</Modal.Title>
  </Modal.Header>

  <Modal.Body>
    <p>Modal body text goes here.</p>
  </Modal.Body>

  <Modal.Footer>
    <Button variant="secondary" onClick={close}>
      Close
    </Button>
    <Button variant="primary" onClick={save}>
      Save changes
    </Button>
  </Modal.Footer>
</Modal.Dialog>

As you can see, the progress is there, and things are getting better, but we can take it to the next level. 

Although things are very declarative and clear and we can stay here, but we are still obligated to compose an entire modal to the next level. But this would mean that we would not be able to use the Modal’s children to cover up the missing pieces, as we implemented the part of the logic before. Normally, it is not like that we have to write the Modal’s content from scratch.

Moreover, you can use it as a template for your use in future cases. However, there is no filter or restriction on the children’s input, and you can use it the way you want. But normally, we would like it if the user uses only a few limited elements so that he does not mess up the things, and if that is the case, we must see what could be the right approach to follow it.

Introducing the design pattern that contains everything

Now, if we see our last progress and calculate what we gathered so far, the new pattern should have the following attributes:

  • Has complete control over child elements using props.children.
  • Has a template already in place for the user.
  • No spamming of the mechanism of props.
  • Has restrictions on the input.

Well, this sounds good and promising so let’s take a look at an example and we will be using the Bootstrap Modal component it as an anchor:

const ModalFromTheFuture = ({ showCloseButton, children }) => {
  const childProps = useChildProps(props.children, [
    'title',
    'contents'
    'dismissButton',
    'actionButton',
  ]);

  return (
    <Modal.Dialog>
      <Modal.Header closeButton={showCloseButton}>
        {childProps.title && <Modal.Title {...childProps.title} />}
      </Modal.Header>

      <Modal.Body>
        {childProps.contents && <p {...childProps.contents} />}
      </Modal.Body>

      <Modal.Footer>
        {childProps.actionButton && <Button {...childProps.actionButton} variant="secondary" />}
        {childProps.dismissButton && <Button {...childProps.dismissButton} variant="primary" />}
      </Modal.Footer>
    </Modal.Dialog>
  );
};

Now you can clearly view that the new modal component uses a hook known as “useChildProps(). Moreover, this hook will basically flatten nested propos by going through the ‘props.children’.  Furthermore, when it will come to make sure that right names are addressed, this method will validate them against a provided white list.

const useChildProps = (children, whitelist) => {
  return useMemo(() =>
    [].concat(children).reduce(
      (childProps, child) => {
        if (whitelist && !whitelist.includes(child.type)) {
          throw Error(`element <${child.type}> is not supported`);
        }

        childProps[child.type] = child.props;

        return childProps;
      },
      [children]
    )
  );
};
<ModalFromTheFuture showCloseButton>
  <title>Modal title</title>
  <contents>Modal body text goes here.</contents>
  <dismissButton onClick={close}>Close</dismissButton>
  <actionButton onClick={save}>Save changes</actionButton>
</ModalFromTheFuture>

However, we know it will cause confusion with native HTML tag names, but this can be said about any other React component being used by other users or us. But if you see the changing trends, such as the introduction of component-based user-interface, for example, Angular, Vue, React, or other web components, so new tag names are not rare now. Therefore, you should go for the new design and must not stay afraid of getting hands on it.

If you need to hire Remote React App Developer then you can contact me.