Sign inSign up

teamdigitale/italia-backend

By teamdigitale

•Updated almost 7 years ago

Backend of the Digital Citizenship app

Image
0

10K+

teamdigitale/italia-backend repository overview

CircleCI

Codacy Badge

codecov

dependencies

Docker Build Status

Maintainability

FOSSA Status

⁠Digital citizenship web and mobile backend

This repository contains the code of the backend used by the web⁠ and mobile⁠ applications of the Digital citizenship project.

⁠Table of content


⁠What is this?

This is the backend that supports the italia-app⁠ mobile application.

This project is part of the Italian Digital Citizenship initiative, see the main repository⁠ for further information.

⁠Authentication process

The italia-app application will authenticate to the backend in two steps:

  1. an initial user initiated SPID authentication process (SAML2 based) that identifies the user and, on success, triggers the creation of a new authentication session (associated to a session token)
  2. subsequent requests to the backend will be authenticated via a bearer session token

authentication_process

⁠User authentication

When a client (the mobile app or a browser) wants to login with the backend it will call the /login endpoint with the IDP entityID as parameter in the query string. The backend will then builds an authorization URL and performs a redirect to the chosen IDP. The authentication process will continue to the IDP website. If the authentication process ends with success the IDP will redirect the client to an HTML page with a form that will auto-post itself to the /assertionConsumerService endpoint with a SAMLResponse as an hidden field. The backend will parse and validate the SAMLResponse to extract all the user attributes (fiscal code, first name, last name, email), then it will generates an unique alphanumeric string as token and saves an User object to the SessionStorage service using the token as key. Finally the backend will redirect the client to the value of the environment variable CLIENT_REDIRECTION_URL with the token in the query string. The client must saves the token and use it in all API request.

The code that manage this flow are in the spid-passport package (more info here⁠), and in the src/strategies/spidStrategy.ts and src/controllers/authenticationController.ts files.

⁠Token authentication

All API requests sent by the client to the backend must have an Authorization: Bearer header with the value of the token obtained from the SPID authentication process. The token is used to retrieve the User object from the SessionStorage service.

The code that manage this flow are in the src/strategies/bearerSessionTokenStrategy.ts file.

⁠How to run the application

⁠Dependencies

To fully simulate the SPID authentication process we use the images provided by the spid-testenv2⁠ project.

A Linux/macOS environment is required at the moment.

⁠Installation steps
  1. clone the project in a folder called italia-backend

  2. go to the project's folder

  3. run scripts/build-tools.sh to build the tools Docker image

  4. run scripts/yarn.sh to install backend dependencies

  5. run scripts/generate-proxy-api-models.sh to generate the models defined in api_proxy.yaml and api_notifications.yaml

  6. run scripts/build.sh to compile the Typescript files

  7. run scripts/generate-test-certs-task.sh to create SAML (SPID) certificates

  8. run docker-compose up -d to start the containers

  9. edit your /etc/hosts file by adding:

    localhost    spid-testenv2
    localhost    italia-backend
    
  10. copy .env.example to .env and fill the variables with your values

  11. point your browser to https://italia-backend/metadata⁠ and copy the source of the page to a new testenv2/conf/sp_metadata.xml file

  12. run docker-compose up -d to restart the containers

  13. point your browser to https://italia-backend⁠

If you are using Docker with a Docker Machine replace localhost with the IP of the Docker Machine (More details here⁠).

⁠Container description
  • backend: the backend Node application that serves the web and mobile applications
  • spid-testenv2: the test IDP server

Nginx is reachable at https://italia-backend:80⁠
IDP is reachable at https://spid-testenv2:8088⁠ \

⁠Environment variables

Those are all Environment variables needed by the application:

Variable nameDescriptiontype
API_KEYThe key used to authenticate to the API backendstring
API_URLThe API backend URLstring
CLIENT_REDIRECTION_URLThe path where the user will be redirected after a successful SPID loginstring
CLIENT_ERROR_REDIRECTION_URLThe path where the user will be redirected when en error occurs during SPID loginstring
PORTThe HTTP port the Express server is listening toint
REDIS_URLThe URL of a Redis instancestring
TOKEN_DURATION_IN_SECONDSThe number of seconds a session token is considered validint
SAML_CALLBACK_URLThe absolute URL of the assertion consumer service endpointstring
SAML_ISSUERThe issuer id for this Service Providerstring
SAML_ATTRIBUTE_CONSUMING_SERVICE_INDEXThe index in the attribute consumer listint
PRE_SHARED_KEYThe key shared with the API backend to authenticate the webhook notificationsstring
ALLOW_NOTIFY_IP_SOURCE_RANGEThe range in CIDR form of allowed IPs for the webhook notificationsstring
AZURE_NH_HUB_NAMEThe hub name configured in the Azure Notification HUBstring
AZURE_NH_ENDPOINTThe endpoint URL configured in the Azure Notification HUBstring
ALLOW_PAGOPA_IP_SOURCE_RANGEThe range in CIDR form of allowed IPs for the PagoPA APIstring
AUTHENTICATION_BASE_PATHThe root path for the authentication endpointsstring
API_BASE_PATHThe root path for the api endpointsstring
PAGOPA_API_URLThe url for the PagoPA api endpointsstring
PAGOPA_API_URL_TESTThe url for the PagoPA api endpoints in test modestring
PAGOPA_BASE_PATHThe root path for the PagoPA endpointsstring
SPID_AUTOLOGINThe user used in the autologin feature, omit this to disable autologinstring
IDP_METADATA_URLUrl to download IDP metadata fromstring
IDP_METADATA_REFRESH_INTERVAL_SECONDSThe number of seconds when the IDPs Metadata are refreshedint
CACHE_MAX_AGE_SECONDSThe value in seconds for duration of in-memory api cacheint
APICACHE_DEBUGWhen is true enable the apicache debug modeboolean
⁠Logs

Application logs are saved into the logs folder.

⁠SPID user management

The setup procedure adds some test users to the test IDP server, the full list could be retrieved in testenv2/conf/users.json. To add more users simply add more items to this file and restart the spid-testenv2 container.


⁠API Monitoring

Is possible link the API to AppInsignts service by setting the ENV variable APPINSIGHTS_INSTRUMENTATIONKEY. Stats of API CPU and RAM usage, API call execution time, success or failure of API calls are collected. Realtime data collection is enabled.

⁠Redis Database

⁠Data Structure

Redis Database stores data required only by application side functionalities. Below a table with an example of data for an hypothetical user with fiscal code MRARSS80A01H501T and with session token HexToken.

KeyValuetypeexpire in
SESSION-HexTokena JSON representing the user objectUserTOKEN_DURATION_IN_SECONDS
WALLET-WalletHexToken"SESSION-HexToken"StringTOKEN_DURATION_IN_SECONDS
SESSIONINFO-HexTokena JSON representing the SessionInfo objectSessionInfoTOKEN_DURATION_IN_SECONDS
USERSESSIONS-MRARSS80A01H501Ta Set of SessionInfo KeysSet<SessionInfoKey>never

⁠Mobile App compatibility

To handle Backend compatibility with several Mobile App versions, the oldest mobile app version supported by the backend is stored into the property minAppVersion inside the package.json. This value is provided to the app through the /info API. If the mobile app version is lower an upgrade is required.

⁠How to contribute

⁠Dependencies

A Linux/macOS environment is required at the moment.

⁠Starting steps
  • use nodenv to run the correct version of Nodejs as specified in app/.node-version
  • run Jest tests directly or with scripts/test.sh

In general follow the Node Best Practices⁠.

⁠Generate SAML (SPID) certs (development)

The backend implements a SAML Service Provider - for authenticating the clients it needs a certificate that you can generate with the following command (you need to have openssl available in your path):

$ yarn generate:test-certs
⁠Generate SAML (SPID) certs (production)

For production, the SPID certificate must be generated with the following command:

$ openssl req -x509 -nodes -sha256 -days 365 -newkey rsa:4096 -keyout key.pem -out cert.pem

Then, the key and the certificate must be stored in the Kubernetes secrets:

$ kubectl create secret generic spid-cert --from-file=./cert.pem --from-file=./key.pem
⁠Architecture decision records

In a world of evolutionary architecture, it's important to record certain design decisions for the benefit of future team members as well as for external oversight. Architecture Decision Records is a technique for capturing important architectural decisions along with their context and consequences. We store these details in source control, along with code, as then they can provide a record that remains in sync with the code itself.

We use ADR⁠s to track architectural decisions of this initiative.

This repository is configured for Nat Pryce's adr-tools⁠.

Here's the decisions we taken so far:


⁠Troubleshooting

I installed on my mac but seems that https://italia-backend:80⁠ is not working (ping italia-backend return a host error)

Check out /etc/hosts Remember that in some cases you need to use your docker-machine ip (get it from >docker-machine ip) instead of localhost.

I followed all the steps but when i go to https://italia-backend⁠ it shows me the same as https://italia-backend:8080⁠

This problem seems to be dependent on how Docker for Mac (doesn't) manage well the /etc/hosts file. If you install Docker Toolbox it works fine (and can coexist⁠) (Read more at https://medium.com/@itseranga/set-hosts-in-docker-for-mac-2029276fd448⁠)

⁠License

FOSSA Status

Tag summary

Content type

Image

Digest

Size

55.4 MB

Last updated

almost 7 years ago

docker pull teamdigitale/italia-backend:v2.6.0