1 of 101

API

Designing, Security and Monitoring

/home/daniellek/Téléchargements/sflive_paris2020_square_white@2x.png

2 of 101

danielleKayumbi

Danielle

KAYUMBI BONKOTO

Software Engineer

dkwavetech

Freelance PHP / Symfony

CTO DK Wave Technology

3 of 101

API

Application Programming Interfaces

Engine of business growth

4 of 101

01

Designing

Technologies

Standards

Summary

03

02

Security

Security models,

Security Strategies

Api gateways

Monitoring

Service levels

Tools

5 of 101

Designing.

<

6 of 101

GraphQL

The purists

The pragmatics

7 of 101

Technologies

REST, gRPC

8 of 101

Technologies

9 of 101

gRPC

RPC Framework by google

Open source in February 2015

Languages & platforms agnostic

Transported over HTTP2 or TLS-encrypted

Bidirectional streaming

10 of 101

gRPC is based on RPC

Remote Procedure Call

11 of 101

GraphQL

Client (Java)

Server (PHP)

Call function

12 of 101

GraphQL

Call function

Pack

stub (protocol buffer)

Client (Java)

Server (PHP)

13 of 101

GraphQL

Call function

Pack

Send & wait

Client (Java)

Server (PHP)

stub (protocol buffer)

RPC runtime (compiler protobuf)

14 of 101

GraphQL

Call function

Pack

Send & wait

Receive

Call

RPC runtime

Client (Java)

Server (PHP)

stub (protocol buffer)

RPC runtime (protobuf compiler)

15 of 101

GraphQL

Call function

Pack

Send & wait

Unpack

Receive

Call

RPC runtime

Client (Java)

Server (PHP)

stub (protocol buffer)

stub (protocol buffer)

RPC runtime (protobuf compiler)

16 of 101

GraphQL

Call function

Pack

Send & wait

Unpack

Receive

Call

Call function

RPC runtime

Client (Java)

Server (PHP)

stub (protocol buffer)

stub (protocol buffer)

RPC runtime (protobuf compiler)

17 of 101

GraphQL

Call function

Pack

Send & wait

Unpack

Receive

Call

Call function

RPC runtime

Return

Pack

stub

Client (Java)

Server (PHP)

stub (protocol buffer)

RPC runtime (protobuf compiler)

18 of 101

GraphQL

Call function

Pack

Send & wait

Unpack

Receive

Call

Call function

RPC runtime

Return

Pack

Send

stub

Client (Java)

Server (PHP)

stub (protocol buffer)

RPC runtime (protobuf compiler)

19 of 101

GraphQL

Call function

Pack

Send & wait

Unpack

Receive

Call

Call function

RPC runtime

RPC runtime

Return

Pack

Send

Receive

stub

Result

Client (Java)

Server (PHP)

stub (protocol buffer)

20 of 101

GraphQL

Call function

Pack

Send & wait

Unpack

Receive

Call

Call function

stub

RPC runtime

RPC runtime

Return

Pack

Send

Receive

Unpack

Result

stub

Result

Client (Java)

Server (PHP)

21 of 101

gRPC is based on HTTP/2

Remote Procedure Call

22 of 101

GraphQL

Call function

Pack

Send & wait

Unpack

Receive

Call

Call function

stub

RPC runtime

RPC runtime

Return

Pack

Send

Receive

Unpack

Result

stub

Result

Client (Java)

Server (PHP)

23 of 101

GraphQL

Call function

Pack

Send & wait

Unpack

Receive

Streaming Call

Call function

stub

RPC runtime

RPC runtime

Return

Pack

Send

Receive

Unpack

Result

stub

Streaming Response

Client (Java)

Server (PHP)

24 of 101

25 of 101

ProtoBuf

http://blog.davidvassallo.me/2018/10/17/pentesting-grpc-protobuf-decoding-first-steps/

0d1c0000001203596f751a024d65202b2a0a0a06616263313233120�Packet capture of an RPC exchange

to: "You"�from: "Me"�query {� 1: "abc123"�}

Initial message

26 of 101

GraphQL

Libraries

"require": {

"grpc/grpc": "v1.7.0",

"google/protobug": "v3.4.0",

}

  • PHP Protoc plugin (to generate the client stub)

make grpc_php_plugin

27 of 101

GraphQL

https://grpc.io/blog/state-of-grpc-web/

28 of 101

When use gRPC ?

Systems that require low latency and efficient, fast calling

Inter-microservices communication

29 of 101

GraphQL

https://medium.com/@EdgePress/is-grpc-the-future-of-client-server-communication-b112acf9f365

30 of 101

GraphQL

https://newslab.iith.ac.in/files/conference/Vamshi_NETSOFT19_gRPC_5G.pdf

31 of 101

Technologies

32 of 101

Representational State Transfer

Architecture style Protocol

Set of constraints

Defined by Roy Fielding

in 2000 in his PHD thesis

REST

33 of 101

REST

Architectural constraints of RESTful API

34 of 101

1- Client-server

2- Stateless

3- Cache

4- Layered system

5- Uniform interface

6- Code-on-demand (optional)

REST

35 of 101

1- Identification of resource

2- Manipulation of resources

3- Self descriptive messages

4- Hypermedia As The Engine Of Application State

(HATEOAS)

REST

Uniform interface

36 of 101

“Hypermedia as the engine of application state (HATEAOS) is a REST constraint. Not an option. Not an ideal. Hypermedia is a constraint. As in, you either do it or you aren’t doing REST.”

Roy Fielding �“Roy Fielding on versioning, Hypermedia and REST”

https://www.infoq.com/articles/roy-fielding-on-versioning/

37 of 101

REST

HATEOAS

38 of 101

GraphQL

DEMO

Richardson Maturity Model

39 of 101

API Standards/Specifications

JSON-LD, HAL, JSON:API, Collection+JSON, SIREN, Hydra, ...

40 of 101

JSON-LD

Linking Data

41 of 101

v

Javascript Object Notation for Linked Data

W3C candidate recommendation

created in 2008 by Many Sporny

Lightweight syntax

No breaking changes

JSON-LD

42 of 101

GraphQL

43 of 101

GraphQL

44 of 101

API Platform

api-platform/api-platform

REST and GraphQL PHP Framework

Supporting many formats

thephpleague/fractal

Supports HAL, JSON-API

API Standards

PHP Examples

45 of 101

Security.

46 of 101

Connect services and transfer data

Vulnerable or hacked APIs

Security strategy

47 of 101

Some famous breaches

48 of 101

GraphQL

Instagram

2017 hackers could access

High profile user’s contact information

49 of 101

GraphQL

Nissan Leaf

2017 insecure API

control remotely the climate,

the charge of the battery

and get the driving range

50 of 101

47% Developers

https://nordicapis.com/why-api-security-is-more-important-than-ever

80%

20%

10%

30%

53% Security team

51 of 101

47% Developers

https://nordicapis.com/why-api-security-is-more-important-than-ever

80%

20%

10%

30%

53% Security team

52 of 101

80%

20%

10%

30%

The friend

responsible of the key

The user

must keep carefully his credentials

53 of 101

The 3 security models

54 of 101

https://swoopnow.com/security-authentication-vs-authorization/

Guard

Voter

55 of 101

api:

pattern: ^/api

guard:

provider: token_user_provider

authenticators:

- AppBundle\Security\Token\ApiTokenAuthenticator

security.yaml

56 of 101

/**

* Guard Authenticator that reads a JWT token from a Bearer Authorization header

*/

class ApiTokenAuthenticator implements AuthenticatorInterface

{

public function __construct(TokenDecoder $decoder, TokenStorageInterface $tokenStorage)

{

parent::__construct($decoder, $tokenStorage);

}

public function supports(Request $request): bool

{

return $request->headers->has('Authorization')

&& 0 === mb_strpos($request->headers->get('Authorization'), 'Bearer ');

}

public function getUser($credentials, UserProviderInterface $userProvider): ?UserInterface

{

try {

$accessToken = $this->decoder->decode($credentials['accessToken']);

} catch (\Throwable $throwable) {

throw new AuthenticationException('An error occured while trying to get the user');

}

return $userProvider->loadByToken($accessToken);

}

}

ApiTokenAuthenticator

check access token in the header

57 of 101

/**

* @Route("/posts/{id}", name="post_show")

*/

public function show($id)

{

// get a Post object - e.g. query for it

$post = ...;

// check for "view" access: calls all voters

$this->denyAccessUnlessGranted('view', $post);

// ...

}

}

https://symfony.com/doc/current/security/voters.html

Voters

58 of 101

3 Major Security Mechanisms

API SECURITY

HTTP Basic Auth

API Keys

OAuth 2

59 of 101

OAUTH 2

60 of 101

OAUTH 2

Both Authentication and Authorization

Access token generated with JWT

Roles

resource owner, resource server, client, authorization server

61 of 101

GraphQL

https://developer.okta.com/blog/2017/06/21/what-the-heck-is-oauth

confidential / public

62 of 101

Tokens

63 of 101

Access token

access protected resources

short-lived

JWT format

OAUTH 2

Tokens

Refresh token

to refresh access token without interaction with the user

long-lived

only sent to confidential clients

JWT format

64 of 101

JWT

Json Web Token

API authentication mechanism

Signed JSON Token with secret (HMAC) or RSA

Exchanges in HTTP headers to encrypt communications

Does not require database

Open standard - RFC 7519

65 of 101

GraphQL

HMAC

66 of 101

GraphQL

public/private key

67 of 101

public function onKernelResponse(ResponseEvent $event)

{

$response = $event->getResponse();

$request = $event->getRequest();

if (Response::HTTP_UNAUTHORIZED !== $response->getStatusCode()) {

return;

}

$accessToken = $this>getAccessToken();

if (null !== $accessToken) {

try {

$this->tokenDecoder->decode($accessToken);

return;

} catch (ExpiredException $e) { // log }

}

try {

$tokens = $this->refreshAccessTokenHandler->handle($request);

} catch (\Exception $e) {

return;

}

$kernel = $event->getKernel();

try {

$response = $kernel->handle($request);

$this->storeTokens($response, $tokens);

$event->setResponse($response);

} catch (\Exception $e) { // log }

}

Subscriber

listen 401

check token expiration

get new access token

replay the request

68 of 101

Password

Grant types

Client credentials

Refresh token

Token exchange

69 of 101

Servers

Oauth 2

70 of 101

thephpleague/oauth2-server

PHP Implementations

thephpleague/oauth2-client

71 of 101

API Gateway

72 of 101

API Gateway is a “gatekeeper”

between the microservices and clients

73 of 101

GraphQL

https://learnk8s.io/kubernetes-ingress-api-gateway

74 of 101

API Gateways

Features

Authentication

Traffic control

Monitoring

Rate limiting

75 of 101

API Gateways

Examples

Amazon’s API Gateway

Ambassador

Kong

Tyk

Express Gateway

76 of 101

GraphQL

v

_workspace: public

services:� host: internal-host-user-ms.mycompany.com

name: user.microservice

port: 80

protocol: http

routes:

- name: get-user-by-id

hosts:

- api.mycompany.com

methods:

- GET

paths:

- /api/users/\d+

preserve_host: false

protocols:

- https

regex_priority: 0

yaml

77 of 101

Strategy

78 of 101

GraphQL

What’s the worst thing someone can do with our API ?

79 of 101

GraphQL

What’s the worst thing someone can do with our API ?

What happens if our competitors get our data ?

80 of 101

GraphQL

What’s the worst thing someone can do with our API ?

What happens if our competitors get our data ?

What data do we need to collect

and what do we need to expose ?

81 of 101

GraphQL

What’s the worst thing someone can do with our API ?

What happens if our competitors get our data ?

What data do we need to collect

and what do we need to expose ?

Who are your users now, and who will they be

in a week, month, or year ?

82 of 101

GraphQL

What’s the worst thing someone can do with our API ?

What happens if our competitors get our data ?

What data do we need to collect

and what do we need to expose ?

Who are your users now, and who will they be

in a week, month, or year ?

How are we monitoring when things go wrong ?

83 of 101

MONITORING

84 of 101

“An API is like a book;

you should be analyzing every bit of data associated with it”

https://nordicapis.com/7-tips-on-api-monitoring

85 of 101

SLA, SLO, SLI

Service Levels

86 of 101

GraphQL

Service Level Agreement

Service Level Objective

“Less than 1% of users should experience an idle time of 5s”

Service Level Indicator

87 of 101

The Four Golden Signals

88 of 101

2

Traffic

How many users requests

are being received over a given time

https://cloud.google.com/blog/products/management-tools/the-right-metrics-to-monitor-cloud-data-pipelines

89 of 101

1

Latency

How long it takes

to service a request over a given time ?

https://cloud.google.com/blog/products/management-tools/the-right-metrics-to-monitor-cloud-data-pipelines

90 of 101

4 Saturation

How utilized the resources

are that run your service ?

https://cloud.google.com/blog/products/management-tools/the-right-metrics-to-monitor-cloud-data-pipelines

91 of 101

3

Errors

What is the rate of HTTP errors 5xx, 4xx ?

https://cloud.google.com/blog/products/management-tools/the-right-metrics-to-monitor-cloud-data-pipelines

92 of 101

GraphQL

PSR-3: Logger Interface

93 of 101

GraphQL

94 of 101

Monolog - Logging for PHP

Sends your logs to files, sockets, inboxes, database, …

Datadog

Cloud Scale Monitoring

ELK Stack

Elasticsearch, Kibana, Beats, Logstash

Libraries & Tools

95 of 101

CONCLUSION

The 4th Industrial Revolution

96 of 101

GraphQL

Cloud computing

Artificial intelligence

IoT-style devices

https://dzone.com/articles/how-integration-platform-is-driving-the-4th-indust

97 of 101

GraphQL

The way we live, work & interact with each other

98 of 101

GraphQL

The way we live, work & interact with each other

99 of 101

83%of web traffic is now processed thougth APIs

https://nordicapis.com/7-tips-on-api-monitoring

Web traffic

100 of 101

GraphQL

APIs really are everywhere,

powering our lives from behind the scenes

and bringing us to the 4th industrial revolution

101 of 101

Merci

de votre attention !

@danielleKayumbi