Thursday, May 12, 2022

Setup username-token authentication for Gradle

 

What is github authentication?


Well as it sounds, github authentication is used for accessing github resources(repositories/registries). 

Also github offering various kind of authentication methods to authenticate a resource. You have to use one of them in most cases and unless the resources is not public.

Let’s have a look on authentication methods in github.
  • username - password authentication
  • ssh authentication
  • Token authentication 
  • SSO authentication

why we need token authentication for github?


So as we discussed there are few authentication methods in github. But, why we need token authentication with gradle?

The simplest answer is to access to github registry packages

In gradle, it is not supported to ssh or sso authentication. So we have to choose user-pass authentication or token authentication,
Under the best practices and security reasons best option is using token authentication.

Setting up Token authentication in github and gradle


Github:
  1. Verify your email address, if it hasn't been verified yet.
  2. In the upper-right corner of any page, click your profile photo, then click Settings.
  1. In the left sidebar, click Developer settings.

  1. Click Generate new token.
  1. Give your token a descriptive name.
  2. Select the scopes, or permissions, you'd like to grant this token. To use your token to access repositories from the command line, select repo.
  1. Click Generate token.
Setting up github token with gradle

To use github token in gradle you need to add it to gradle global properties

The global properties file should be located in your home directory:
  • On Windows: C:\Users\<you>\.gradle\gradle.properties
  • On Mac/Linux: /Users/<you>/.gradle/gradle.properties

Replace youre username and Token.

USERNAME="Your username"
TOKEN="Your password"


Now try to build your favorite gradle project.


AWS Firewall Manager

 

AWS Firewall Manager is a security management service which allows you to centrally configure and manage firewall rules across your accounts and applications in AWS Organizations. As new applications are created, Firewall Manager makes it easy to bring new applications and resources into compliance by enforcing a common set of security rules. Now you have a single service to build firewall rules, create security policies, and enforce them in a consistent, hierarchical manner across your entire infrastructure, from a central administrator account.
Using AWS Firewall Manager, you can easily roll out AWS WAF rules for your Application Load Balancers, API Gateways, and Amazon CloudFront distributions. You can create AWS Shield Advanced protections for your Application Load Balancers, ELB Classic Load Balancers, Elastic IP Addresses and CloudFront distributions. You can also configure new Amazon Virtual Private Cloud (VPC) security groups and audit any existing VPC security groups for your Amazon EC2, Application Load Balancer (ALB) and ENI resource types. You can deploy AWS Network Firewalls across accounts and VPCs in your organization. Finally, with AWS Firewall Manager, you can also associate your VPCs with Amazon Route 53 Resolvers DNS Firewall rules.


Benefits


Firewall Manager provides these benefits:
  • Helps to protect resources across accounts
  • Helps to protect all resources of a particular type, such as all Amazon CloudFront distributions
  • Helps to protect all resources with specific tags
  • Automatically adds protection to resources that are added to your account
  • Allows you to subscribe all member accounts in an AWS Organizations organization to AWS Shield Advanced, and automatically subscribes new in-scope accounts that join the organization
  • Allows you to apply security group rules to all member accounts or specific subsets of accounts in an AWS Organizations organization, and automatically applies the rules to new in-scope accounts that join the organization
  • Lets you use your own rules, or purchase managed rules from AWS Marketplace
Firewall Manager is particularly useful when you want to protect your entire organization rather than a small number of specific accounts and resources, or if you frequently add new resources that you want to protect. Firewall Manager also provides centralized monitoring of DDoS attacks across your organization.

AWS Firewall Manager handles five types of protection policies - AWS WAF, AWS Shield Advanced, Amazon VPC security groups, AWS Network Firewall, and Amazon Route 53 Resolver DNS Firewall. AWS Firewall Manager protection policies are priced with a monthly fee per region (prorated hourly).


For AWS Network Firewall protection policies, AWS Firewall Manager has these main pricing components:
  • AWS Firewall Manager protection policy - Monthly fee per Region.
  • AWS Network Firewall endpoints - Those created by Firewall Manager will be charged based on current pricing. For more details, see AWS Network Firewall pricing.
  • AWS Config Rules - Those rules created by Firewall Manager to monitor changes in resource configurations are charged based on current pricing. For more details, see AWS Config pricing.
You only pay for what you use, as you use it; there are no minimum fees and no upfront commitments


For AWS WAF protection policies, AWS Firewall Manager has these main pricing components:
  • AWS Firewall Manager protection policy - Monthly fee per Region.
  • AWS WAF WebACLs or Rules - Those created by Firewall Manager will be charged based on current pricing. For more details, see AWS WAF pricing.
  • AWS Config Rules - Those rules created by Firewall Manager to monitor changes in resource configurations are charged based on current pricing. For more details, see AWS Config pricing.
If you are an AWS Shield Advanced customer:
For AWS Shield Advanced customers, AWS Firewall Manager protection policy is included at no additional charge. Shield Advanced customers will be charged for the AWS Config rules created to monitor any changes in resource configurations. For more details, check the AWS Shield pricing and AWS Config pricing.

AWS Shield protection policies can be created using AWS Firewall Manager only for Shield Advanced users. The price is included in the AWS Shield Advanced subscription at no additional cost. In addition, the pricing components are as follows:
• AWS Shield Advanced Data Transfer Out Usage Fees: For more details, see AWS Shield pricing
• AWS Config Rules - Those rules created by Firewall Manager to monitor changes in resource configurations are charged based on current pricing. For more details, see AWS Config pricing


For Amazon VPC security group protection policies, AWS Firewall Manager has these main pricing components:
• AWS Firewall Manager protection policy - Monthly fee per Region.
• AWS Config Rules - Those rules created by Firewall Manager to monitor changes in resource configurations are charged based on current pricing. For more details, see AWS Config pricing.
You only pay for what you use, as you use it; there are no minimum fees and no upfront commitments.

For Amazon Route 53 Resolver DNS Firewall protection policies, AWS Firewall Manager has these main pricing components:
  • AWS Firewall Manager protection policy - Monthly fee per Region.
  • Route 53 Resolver DNS Firewall charges- Rule groups created by Firewall Manager will be charged based on current pricing. For more details, see Route 53 Resolver DNS Firewall pricing.
  • AWS Config Rules - Those rules created by Firewall Manager to monitor changes in resource configurations are charged based on current pricing. For more details, see AWS Config pricing.
You only pay for what you use, as you use it; there are no minimum fees and no upfront commitments.


AWS Firewall Manager pricing for customers


AWS Network Firewall protection policy

All public regions


AWS WAF protection policy

All public regions
$100.00 per policy per Region
Global (Amazon CloudFront locations)
$100.00 per policy per Region


AWS Shield Advanced protection policy

All public regions
Included for Shield Advanced customers. No charge per policy per Region
Global (Amazon CloudFront locations)
Included for Shield Advanced customers. No charge per policy per Region
  • AWS WAF WebACLs or Rules created by Firewall Manager - Included. No additional charge.
  • AWS Config rules created by Firewall Manager - See AWS Config pricing
  • AWS Shield Advanced - See AWS Shield pricing


Amazon VPC security group protection policy

All public regions


Amazon Route 53 Resolver DNS Firewall protection policy

All public regions


AWS Firewall Manager prerequisites


This topic shows you how to get ready to administer AWS Firewall Manager. You use one Firewall Manager administrator account to manage all Firewall Manager security policies for your organization in AWS Organizations. Except where noted, perform the prerequisite steps using the account that you will use as the Firewall Manager administrator.
Before you use Firewall Manager for the first time, perform the following steps in sequence.
Topics
After you follow these steps, you can configure Firewall Manager to begin protecting your resources. For more information, see Getting started with AWS Firewall Manager AWS WAF policies.

Step 1: Join and configure AWS Organizations


To use Firewall Manager, your account must be a member of the organization in the AWS Organizations service where you want to use your Firewall Manager policies.
Note
For information about Organizations, see AWS Organizations User Guide.

To establish the required AWS Organizations membership and configuration
  1. Choose an account to use as the Firewall Manager administrator for the organization in Organizations.
  2. If your chosen account isn't already a member of the organization, have it join. Follow the guidance at Inviting an AWS account to join your organization.
  3. AWS Organizations has two available feature sets: consolidated billing features and all features. To use Firewall Manager, your organization must be enabled for all features. If your organization is configured only for consolidated billing, follow the guidance at Enabling All Features in Your Organization.

Step 2: Set the AWS Firewall Manager administrator account


This procedure uses the account and organization that you chose and configured in the preceding step.
When you set the Firewall Manager administrator account, Firewall Manager automatically sets it as the AWS Organizations Delegated Administrator for Firewall Manager. This allows Firewall Manager to access information about the organizational units (OUs). You can use OUs to specify the scope of your Firewall Manager policies. For more information about setting policy scope, see the guidance for the individual policy types under Creating an AWS Firewall Manager policy. For more information about Organizations and management accounts, see Managing the AWS Accounts in Your Organization.
To set the Firewall Manager administrator account
  1. Sign in to the AWS Management Console using an existing AWS Organizations management account. You can sign in using the account's root user (not recommended) or another IAM user or IAM role within the account that has equivalent permissions.
  2. Open the Firewall Manager console at https://console.aws.amazon.com/wafv2/fmsv2
.
Choose Get started.
Type the ID of the account that you've chosen to use as the Firewall Manager administrator.
Note
This account is given permission to create and manage Firewall Manager policies across all accounts within your organization.
Choose Set administrator.

Step 3: Enable AWS Config


To use Firewall Manager, you must enable AWS Config.
Note
You incur charges for your AWS Config settings, according to AWS Config pricing. For more information, see Getting Started with AWS Config.
To enable AWS Config for Firewall Manager
  1. Enable AWS Config for each of your AWS Organizations member accounts, including the Firewall Manager administrator account. For more information, see Getting Started with AWS Config.
  2. Enable AWS Config for each AWS Region that contains the resources that you want to protect. You can enable AWS Config manually, or you can use the AWS CloudFormation template "Enable AWS Config" at AWS CloudFormation StackSets Sample Templates.
  3. If you don't want to enable AWS Config for all resources, then you must enable the following according to the type of Firewall Manager policies that you use:
    • WAF policy – Enable Config for the resource types CloudFront Distribution, Application Load Balancer (choose ElasticLoadBalancingV2 from the list), API Gateway, WAF WebACL, WAF Regional WebACL, and WAFv2 WebACL. To enable AWS Config to protect a CloudFront distribution, you must be in the US East (N. Virginia) Region. Other Regions don't have CloudFront as an option.
    • Shield policy – Enable Config for the resource types Shield Protection, ShieldRegional Protection, Application Load Balancer, EC2 EIP, WAF WebACL, WAF Regional WebACL, and WAFv2 WebACL.
    • Security group policy – Enable Config for the resource types EC2 SecurityGroup, EC2 Instance, and EC2 NetworkInterface.
    • Network Firewall policy – Enable Config for the resource types NetworkFirewall FirewallPolicy, NetworkFirewall RuleGroup, EC2 VPC, EC2 InternetGateway, EC2 RouteTable, and EC2 Subnet.
    • DNS Firewall policy – Enable Config for the resource types DNSFirewall RuleGroup and EC2 VPC.


Step 4: For Network Firewall and DNS Firewall policies, enable resource sharing


To manage Firewall Manager Network Firewall and DNS Firewall policies, you must enable sharing with AWS Organizations in AWS Resource Access Manager. This allows Firewall Manager to deploy protections across your accounts when you create these policy types.
To enable sharing with AWS Organizations in AWS Resource Access Manager
If you run into problems with resource sharing, see the guidance at Resource sharing for Network Firewall and DNS Firewall policies.

Step 5: To use AWS Firewall Manager in Regions that are disabled by default


To use Firewall Manager in a Region that's disabled by default, you must enable the Region for both the management account of your AWS organization and the Firewall Manager administrator account.
For information about Regions that are disabled by default and how to enable them, see Managing AWS Regions in the AWS General Reference.
To enable a disabled Region
  • For both the Organizations management account and the Firewall Manager administrator account, follow the guidance at Enabling a Region in the AWS General Reference.


Managing the AWS Firewall Manager administrator


You use your Firewall Manager administrator account to manage your Firewall Manager policies. When you set the Firewall Manager administrator account, Firewall Manager automatically sets it as the AWS Organizations Delegated Administrator for Firewall Manager. This allows Firewall Manager to access information about the organizational units (OUs) that you use to specify the scope of your Firewall Manager policies. For more information about Organizations and management accounts, see Managing the AWS Accounts in Your Organization.
To begin using Firewall Manager, you set up your Firewall Manager administrator account and perform other required steps. To do this, follow the guidance under AWS Firewall Manager prerequisites.
This topic provides information and guidance for managing your existing administrator account.
Required settings for the Firewall Manager administrator
The Firewall Manager administrator account must have the following settings:
  • It must be a member of the organization in AWS Organizations where you want to apply your Firewall Manager policies.
  • It must be designated as the Firewall Manager administrator by the Organizations management account for the organization.


Monitoring Spring Boot Application With Micrometer, Prometheus And Grafana Using Custom Metrics


We initialized the project using spring-boot-starter-actuator which already exposes production-ready endpoints.
If we start our application we can see that some endpoints like health and info are already exposed to the /actuator endpoint per default.
Triggering the /actuator/health endpoint gives us a metric if the service is up and running:
▶ http GET "http://localhost:8080/actuator/health"
HTTP/1.1 200
Connection: keep-alive
Content-Type: application/vnd.spring-boot.actuator.v3+json
Date: Wed, 21 Oct 2020 18:11:35 GMT
Keep-Alive: timeout=60
Transfer-Encoding: chunked

{
    "status": "UP"
}
Spring Boot Actuator can be integrated into Spring Boot Admin which provides a visual admin interface for your application. But this approach is not very popular and has some limitations. Therefore, we use Prometheus instead of Spring Boot Actuator and Grafana instead of Spring Boot Admin to have a more popular and framework/language-independent solution.
This solution approach needs vendor-neutral metrics and Micrometer is a popular tool for this use case.

Micrometer

  • Micrometer provides a simple facade over the instrumentation clients for the most popular monitoring systems, allowing you to instrument your JVM-based application code without vendor lock-in. Think SLF4J, but for metrics.
Micrometer is an open-source project and provides a metric facade that exposes metric data in a vendor-neutral format that a monitoring system can understand. These monitoring systems are supported:
  • AppOptics
  • Azure Monitor
  • Netflix Atlas
  • CloudWatch
  • Datadog
  • Dynatrace
  • Elastic
  • Ganglia
  • Graphite
  • Humio
  • Influx/Telegraf
  • JMX
  • KairosDB
  • New Relic
  • Prometheus
  • SignalFx
  • Google Stackdriver
  • StatsD
  • Wavefront
Micrometer is not part of the Spring ecosystem and needs to be added as a dependency. In our demo application, this was already done in the Spring Initializr configuration.
Next step is to expose the Prometheus metrics in application.properties:
management.endpoints.web.exposure.include=prometheus,health,info,metric
Now we can trigger this endpoint and see the Prometheus metrics:


Custom Metrics
We can also define some custom metrics, which I will demonstrate in this section. The demo contains a Scheduler class which periodically runs the included schedulingTask method.
To be able to send custom metrics we need to import MeterRegistry from the Micrometer library and inject it into our class. For more detail please check the official documentation.
It is possible to instantiate these types of meters from MeterRegistry:
  • Counter: reports merely a count over a specified property of an application
  • Gauge: shows the current value of a meter
  • Timers: measures latencies or frequency of events
  • DistributionSummary: provides distribution of events and a simple summary
I implemented a counter and a gauge for demonstration purposes:
@Component
public class Scheduler {

  private final AtomicInteger testGauge;
  private final Counter testCounter;

  public Scheduler(MeterRegistry meterRegistry) {
    // Counter vs. gauge, summary vs. histogram
    // https://prometheus.io/docs/practices/instrumentation/#counter-vs-gauge-summary-vs-histogram
    testGauge = meterRegistry.gauge("custom_gauge", new AtomicInteger(0));
    testCounter = meterRegistry.counter("custom_counter");
  }

  @Scheduled(fixedRateString = "1000", initialDelayString = "0")
  public void schedulingTask() {
    testGauge.set(Scheduler.getRandomNumberInRange(0, 100));

    testCounter.increment();
  }

  private static int getRandomNumberInRange(int min, int max) {
    if (min >= max) {
      throw new IllegalArgumentException("max must be greater than min");
    }

    Random r = new Random();
    return r.nextInt((max - min) + 1) + min;
  }
}
If we run the application we can see that our custom metrics are exposed via the actuatuor/prometheus endpoint:
  ▶ http GET "http://localhost:8080/actuator/prometheus" | grep custom
# HELP custom_gauge
# TYPE custom_gauge gauge
custom_gauge 29.0
# HELP custom_counter_total
# TYPE custom_counter_total counter
custom_counter_total 722.0
As we now have the metrics available in a format that Prometheus can understand, we will look at how to set up Prometheus.

Prometheus

Prometheus stores our metric data in time series in memory by periodically pulling it via HTTP. The data can be visualized by a console template language, a built-in expression browser, or by integrating Grafana (which we will do after setting up Prometheus).
In this demo, we will run Prometheus locally in a Docker container and we, therefore, need some configurations in a prometheus.yml file that you can place anywhere on your hard drive:
global:
    scrape_interval: 10s # How frequently to scrape targets by default
  
scrape_configs:
    - job_name: 'spring_micrometer'         # The job name is assigned to scraped metrics by default.
      metrics_path: '/actuator/prometheus'  # The HTTP resource path on which to fetch metrics from targets.
      scrape_interval: 5s                   # How frequently to scrape targets from this job.
      static_configs:                       # A static_config allows specifying a list of targets and a common label set for them
        - targets: ['192.168.178.22:8080']
All available configuration options can be seen in the official documentation.
As we want to run Prometheus in a Docker container we need to tell Prometheus our IP address instead of localhost in static_configs -> targets. Instead of localhost:8080 we are using 192.168.178.22:8080 where 192.168.178.22 is my IP address at the moment. To get your system IP you can use ifconfig or ipconfig in your terminal depending on your operating system.
Now we are ready to run Prometheus:
docker run -d -p 9090:9090 -v <path-to-your-prometheus.yml>:/etc/prometheus/prometheus.yml prom/prometheus
<path-to-your-prometheus.yml> should be the path where you placed the prometheus.yml configuration file described above.
Finally, we can open the Prometheus on http://localhost:9090 in the web browser and search for our custom metric named custom_gauge:
Prometheus Graph
To check that Prometheus is correctly listening to our locally running Spring Boot application we can navigate to Status -> Targets in the top main navigation bar:
Prometheus Targets
Prometheus provides a query language PromQL, check the official documentation for more details.

Grafana

The included Prometheus browser graph is nice for basic visualization of our metrics but we will use Grafana instead. Grafana provides a rich UI where you create, explore and share dashboards that contain multiple graphs.
Grafana can pull data from various data sources like Prometheus, Elasticsearch, InfluxDB, etc. It also allows you to set rule-based alerts, which then can notify you over Slack, Email, Hipchat, and similar.
We start Grafana also locally in a Docker container:
docker run -d -p 3000:3000 grafana/grafana
Opening http://localhost:3000 in a browser should now show the following login page:
Grafana Login
You can log in using the default username admin and the default password admin. After login, you should change these default passwords by visiting http://localhost:3000/profile/password.
The first step is to add our local Prometheus as our data source:
Grafana Add Datasource
Grafana Select Prometheus
Grafana Prometheus Config
Community Dashboard
The first dashboard we want to add is a community dashboard. As we are using a Spring Boot application we choose the popular JVM dashboard:
Grafana Import JVM Dashboard
After loading the URL we can see the imported dashboard:
Grafana Imported JVM Dashboard
Custom Metric Dashboard
Finally, we want to create a new dashboard where we show our custom metrics. The first step is to create a new dashboard:
Grafana Imported JVM Dashboard
Now we see a new dashboard where we can create a new panel:
Grafana New Dashboard Panel
In the first panel we add a visualization for our custom_gauge metric. I use the Stat visualization as it shows the current value and a simple graph:
Grafana Stat Gauge Vizualization
Additionally, a new panel for the custom_counter metric is added to our dashboard:
Grafana Graph Counter Vizualization
In the end, the dashboard looks like this:
Grafana Custom Dashboard

Conclusion 

It is important to monitor an application’s metrics and health which helps us to improve performance, manage the app in a better way and notice unoptimized behavior. Monitoring each service is important to be able to maintain a system that consists of many microservices.
In this article, I showed how a Spring Boot web application can be monitored using Micrometer which exposes metrics from our application, Prometheus which stores the metric data and Grafana to visualize the data in graphs.

Also, Since the this architecture use pull-based metric system we don’t need to define any endpoints from the application side and it is more effective to use with containerized, replica environments as well.

Update openSSL to latest 1.1.1 version (1.1.1w)

  By the time(2024) one our system use this old OpenSSL version 1.1.1g and we are going to update it to latest version of 1.1.1 openSSL v...