How to implement SAP BTP Audit log service in a CAP Application

Estimated read time 18 min read

Introduction

SAP Cloud Application Programming Model (CAP) is a robust framework designed to streamline the development of enterprise-grade applications on the SAP Business Technology Platform (BTP). It encompasses a collection of languages, libraries, and tools that enable developers to focus on core business logic rather than the complexities of underlying technologies. By adhering to proven best practices and providing out-of-the-box solutions for common tasks, CAP significantly accelerates application development while minimizing technical debt and maintenance costs. This model is particularly beneficial for organizations looking to enhance their cloud capabilities without getting bogged down by repetitive coding tasks.

In today’s dynamic business landscape, maintaining data integrity, ensuring compliance, and fostering trust are paramount. As organizations increasingly rely on cloud-based solutions, robust audit logging mechanisms become indispensable for tracking data access, modifications, and critical events. This blog post delves into the world of audit logging within the SAP Business Technology Platform (BTP), focusing on applications built with the Cloud Application Programming Model (CAP). The blog emphasises Audit log implementation on the CAP Java application, it can also be implemented using CAP Node.js.

Implementing Auditlog is a must in the application to follow the application Security Standards ISO/IEC 27001 (Information Security Management), SOC 2 (System and Organization Controls) and others too.

The Link for creating a CAP Application on SAP BTP is cap.cloud.sap

What are Audit logs?

Audit logs are a specific category of logs that serve as chronological, security-relevant records, providing documented evidence of events or activities. They capture the sequence of actions and occurrences within a system, network, or organization, ensuring traceability and accountability

Why Audit logs are needed?

Security

         Audit logs help to identify security breaches and unauthorized access attempts and pinpoint the root cause of data loss or manipulation.

Compliance

         Audit logs support organizations in meeting compliance standards by documenting information that satisfies legal and regulatory requirements.

Accountability

         By maintaining detailed records of user actions, audit logs foster accountability and transparency within the system.

Fraud investigations

         Audit logs can help with fraud investigations and deter fraud by providing records of staff, clients, or third-party interactions.

Problem detection

         Audit logs can help detect problems and improve team productivity.

 

Audit Log Service in SAP BTP

SAP Audit Log is a core, security, and compliance-based SAP BTP service to provide means for audit purposes. The following features of Audit Log Service are available for SAP BTP Applications and Services:

The default features come with a standard SAP BTP subscription, where you have:

Written compliance audit data from SAP BTP services and applications, through the oAuth2 service plan.Audit data is securely stored for a default retention time of 90 days with no additional costs applied.Retrieval of audit data within the default retention period is ensured as part of the Audit log Management Service.

The advanced features are licensed separately, where you can:

Write audit data from your owned BTP applications.Configure the retention period.

The advanced features enable you to comply with the SAP Product Standards and Business Industry regulations you’re subject to. To enable the advanced features, you need to enable the premium edition service plan, where additional costs are applied based on the consumed volumes.

Discovery Center link for SAP Audit Log Service Discovery Center – SAP Audit log Service 

The SAP Audit Log stores audit logs representing different actions taken over your account and/or data. There are predefined audit categories, which represent such kinds of actions:

Data protection and Privacy related –

audit.data-access read-access logging records for access to sensitive personal data;audit.data-modification data modification logging records for sensitive personal data.

Security related – 

audit.security-events logging of general security events like login, logout, and other;audit.configuration logging of security critical configuration changes.

The Audit Log service is available for CAP Java applications and can be used to generate audit log events that are sent to registered handlers. These audit log events are usually associated with business transactions. To ensure transactional consistency and decouple the request from outbound calls to a consumer, the events are handled in a transactional manner.

Default Handler

By default, the CAP Java SDK provides an Audit Log handler that writes the Audit Log messages to the application log. This default handler is registered on all Audit Log events and writes DEBUG log entries. However, the application log does not log DEBUG entries by default. To enable audit logging to the application log, the log level of the default handler needs to be set to DEBUG level:

 

srv/src/main/resources/application.yaml

logging:
level:
com.sap.cds.Audit Log: DEBUG

 

Audit Log v2 Handler

Additionally, the CAP Java SDK provides an Audit Log v2 handler that writes the audit messages to the SAP Audit Log service via its API version 2. To enable this handler, an additional feature dependency must be added to the srv/pom.xml of the CAP Java project:

 

<dependency>
<groupId>com.sap.cds</groupId>
<artifactId>cds-feature-Audit Log-v2</artifactId>
<scope>runtime</scope>
</dependency>

 

Additionally required dependency –

 

<dependency>
<groupId>com.sap.cloud.sdk</groupId>
<artifactId>sdk-modules-bom</artifactId>
<version>${cloud.sdk.version}</version>
<type>pom</type>
<scope>runtime</scope>
</dependency>

 

In the Cloud Foundry subaccount, you need to subscribe to 3 services in Instances and Subscriptions for using Audit log as a service in our application –

Auditlog Management –

Audit log Service –

Auditlog Viewer –

Steps to create a Role collection required to Access Audit Log Viewer service

Create a RoleCollection.Search for roles with the name “Auditlog_Auditor” and select both entries with the following application identifiers:auditlog-management!b*auditlog-viewer!t*Assign the role to a user or create a rule to assign it to users based on the SAML Assertion coming from the IDP

Create a service binding through an MTA deployment manifest:

Now we need to bind the service created in Cloud Foundry to our application using MTA.yaml file as follows:

 

modules:
– name: <module using the Audit Log Service>
requires:
– name: <Audit Log Service Premium Instance Name>
parameters:
config:
xsuaa:
credential-type: x509
x509:
key-length: 2048
validity: 2
validity-type: MONTHS
– name: <other modules>

resources:
– name: <Audit Log Service Premium Instance Name>
type: org.cloudfoundry.managed-service
parameters:
service: auditlog
service-plan: oauth2/Premium

 

Note –  service-plan can be either oauth2 or premium as per subscription.

How to get an AuditLog Service Instance –

Once you have subscribed to the above-mentioned service then the implementation of the Audit log is straightforward, The Audit Log Service can be injected into a custom handler class, if the CAP Java project uses Spring Boot:

 

import com.sap.cds.services.AuditLog.AuditLogService;

@Autowired
private AuditLogService auditLogService;

 

Alternatively, the Audit Log service can be retrieved from the Service Catalog:

 

ServiceCatalog catalog = context.getServiceCatalog();
auditLogService = (AuditLogService)catalog.getService(AuditLogService.DEFAULT_NAME);

 

The following events can be emitted with the Auditlog Service to the registered handlers:

Emit Personal Data Access Event

To emit a personal data access event use method logDataAccess of the auditLogService.

 

List<Access> accesses = new ArrayList<>();
Access access = Access.create();
// fill access object with data
accesses.add(access);
auditLogService.logDataAccess(accesses);

 

Emit Personal Data Modification Event

To emit a personal data modification event use the method logDataModification of the auditLogService.

 

List<DataModification> dataModifications = new ArrayList<>();
DataModification modification = DataModification.create();
// fill data modification object with data
dataModifications.add(modification);
auditLogService.logDataModification(dataModifications);

 

Emit Configuration Change Event

To emit a configuration change event use the method logConfigChange of the auditLogService.

 

List<ConfigChange> configChanges = new ArrayList<>();
ConfigChange configChange = ConfigChange.create();
// fill config change object with data
configChanges.add(configChange);
auditLogService.logConfigChange(Action.UPDATE, configChanges);

 

Emit Security Event

Use the method logSecurityEvent of the auditLogService to emit a security event.

 

String action = “login”;
String data = “user-name”;
auditLogService.logSecurityEvent(action, data);

 

Audit Log Retrieval –

The Audit Log Retrieval API incorporates server-side paging to address the efficient handling of queries producing substantial result sets.

When a query produces a large result set, the API automatically breaks it down into smaller, manageable chunks. The response includes an HTTP header containing a handle, which you can use to retrieve subsequent chunks. Each chunk has a fixed size of 500 records.

Note – After the audit logs are generated and sent to the Audit Log service, the logs are not immediately accessible for retrieval.

This API allows you to retrieve audit logs with various filtering options:

Time Range: You can specify a time range using the time_from and time_to parameters. If no time frame is provided, the default is the last 30 days.Large Result Sets: If the number of results is too large, the API returns them in chunks. A handle is provided in the response header to retrieve subsequent chunks.Event Types: You can filter logs by specific event types using the category parameter. The available event types are:audit.security-eventsaudit.configurationaudit.data-accessaudit.data-modification

Note – You can specify multiple event types by separating them with commas.

Conclusion –

Implementing Audit Log is essential for enhancing security, compliance, and operational transparency in modern business environments. The robust capabilities provided by the SAP BTP Audit Log service allow organizations to effectively monitor and document critical activities across their systems.

In summary,  adopting SAP BTP’s Audit Log service not only strengthens security frameworks but also fosters a culture of accountability and proactive management within organizations. This implementation is a strategic investment in safeguarding data integrity and enhancing overall business resilience and satisfying the security standard for the application.

DISCLAIMER

The content of this blog post is provided “AS IS”. This information could contain technical inaccuracies, typographical errors, and out-of-date information. This document may be updated or changed without notice at any time. Use of the information is therefore at your own risk. In no event shall SAP be liable for special, indirect, incidental, or consequential damages resulting from or related to the use of this document.

Links to refer –

https://pages.github.tools.sap/cap/docs/java/auditlog

https://help.sap.com/docs/btp/sap-business-technology-platform/audit-logging-in-cloud-foundry-environment

 

 

​ IntroductionSAP Cloud Application Programming Model (CAP) is a robust framework designed to streamline the development of enterprise-grade applications on the SAP Business Technology Platform (BTP). It encompasses a collection of languages, libraries, and tools that enable developers to focus on core business logic rather than the complexities of underlying technologies. By adhering to proven best practices and providing out-of-the-box solutions for common tasks, CAP significantly accelerates application development while minimizing technical debt and maintenance costs. This model is particularly beneficial for organizations looking to enhance their cloud capabilities without getting bogged down by repetitive coding tasks.In today’s dynamic business landscape, maintaining data integrity, ensuring compliance, and fostering trust are paramount. As organizations increasingly rely on cloud-based solutions, robust audit logging mechanisms become indispensable for tracking data access, modifications, and critical events. This blog post delves into the world of audit logging within the SAP Business Technology Platform (BTP), focusing on applications built with the Cloud Application Programming Model (CAP). The blog emphasises Audit log implementation on the CAP Java application, it can also be implemented using CAP Node.js.Implementing Auditlog is a must in the application to follow the application Security Standards ISO/IEC 27001 (Information Security Management), SOC 2 (System and Organization Controls) and others too.The Link for creating a CAP Application on SAP BTP is cap.cloud.sapWhat are Audit logs?Audit logs are a specific category of logs that serve as chronological, security-relevant records, providing documented evidence of events or activities. They capture the sequence of actions and occurrences within a system, network, or organization, ensuring traceability and accountabilityWhy Audit logs are needed?Security         Audit logs help to identify security breaches and unauthorized access attempts and pinpoint the root cause of data loss or manipulation.Compliance         Audit logs support organizations in meeting compliance standards by documenting information that satisfies legal and regulatory requirements.Accountability         By maintaining detailed records of user actions, audit logs foster accountability and transparency within the system.Fraud investigations         Audit logs can help with fraud investigations and deter fraud by providing records of staff, clients, or third-party interactions.Problem detection         Audit logs can help detect problems and improve team productivity. Audit Log Service in SAP BTPSAP Audit Log is a core, security, and compliance-based SAP BTP service to provide means for audit purposes. The following features of Audit Log Service are available for SAP BTP Applications and Services:The default features come with a standard SAP BTP subscription, where you have:Written compliance audit data from SAP BTP services and applications, through the oAuth2 service plan.Audit data is securely stored for a default retention time of 90 days with no additional costs applied.Retrieval of audit data within the default retention period is ensured as part of the Audit log Management Service.The advanced features are licensed separately, where you can:Write audit data from your owned BTP applications.Configure the retention period.The advanced features enable you to comply with the SAP Product Standards and Business Industry regulations you’re subject to. To enable the advanced features, you need to enable the premium edition service plan, where additional costs are applied based on the consumed volumes.Discovery Center link for SAP Audit Log Service – Discovery Center – SAP Audit log Service The SAP Audit Log stores audit logs representing different actions taken over your account and/or data. There are predefined audit categories, which represent such kinds of actions:Data protection and Privacy related -audit.data-access read-access logging records for access to sensitive personal data;audit.data-modification data modification logging records for sensitive personal data.Security related – audit.security-events logging of general security events like login, logout, and other;audit.configuration logging of security critical configuration changes.The Audit Log service is available for CAP Java applications and can be used to generate audit log events that are sent to registered handlers. These audit log events are usually associated with business transactions. To ensure transactional consistency and decouple the request from outbound calls to a consumer, the events are handled in a transactional manner.Default HandlerBy default, the CAP Java SDK provides an Audit Log handler that writes the Audit Log messages to the application log. This default handler is registered on all Audit Log events and writes DEBUG log entries. However, the application log does not log DEBUG entries by default. To enable audit logging to the application log, the log level of the default handler needs to be set to DEBUG level: srv/src/main/resources/application.yaml

logging:
level:
com.sap.cds.Audit Log: DEBUG Audit Log v2 HandlerAdditionally, the CAP Java SDK provides an Audit Log v2 handler that writes the audit messages to the SAP Audit Log service via its API version 2. To enable this handler, an additional feature dependency must be added to the srv/pom.xml of the CAP Java project: <dependency>
<groupId>com.sap.cds</groupId>
<artifactId>cds-feature-Audit Log-v2</artifactId>
<scope>runtime</scope>
</dependency> Additionally required dependency – <dependency>
<groupId>com.sap.cloud.sdk</groupId>
<artifactId>sdk-modules-bom</artifactId>
<version>${cloud.sdk.version}</version>
<type>pom</type>
<scope>runtime</scope>
</dependency> In the Cloud Foundry subaccount, you need to subscribe to 3 services in Instances and Subscriptions for using Audit log as a service in our application –Auditlog Management -Audit log Service -Auditlog Viewer -Steps to create a Role collection required to Access Audit Log Viewer serviceCreate a RoleCollection.Search for roles with the name “Auditlog_Auditor” and select both entries with the following application identifiers:auditlog-management!b*auditlog-viewer!t*Assign the role to a user or create a rule to assign it to users based on the SAML Assertion coming from the IDPCreate a service binding through an MTA deployment manifest:Now we need to bind the service created in Cloud Foundry to our application using MTA.yaml file as follows: modules:
– name: <module using the Audit Log Service>
requires:
– name: <Audit Log Service Premium Instance Name>
parameters:
config:
xsuaa:
credential-type: x509
x509:
key-length: 2048
validity: 2
validity-type: MONTHS
– name: <other modules>

resources:
– name: <Audit Log Service Premium Instance Name>
type: org.cloudfoundry.managed-service
parameters:
service: auditlog
service-plan: oauth2/Premium Note –  service-plan can be either oauth2 or premium as per subscription.How to get an AuditLog Service Instance -Once you have subscribed to the above-mentioned service then the implementation of the Audit log is straightforward, The Audit Log Service can be injected into a custom handler class, if the CAP Java project uses Spring Boot: import com.sap.cds.services.AuditLog.AuditLogService;

@Autowired
private AuditLogService auditLogService;  Alternatively, the Audit Log service can be retrieved from the Service Catalog: ServiceCatalog catalog = context.getServiceCatalog();
auditLogService = (AuditLogService)catalog.getService(AuditLogService.DEFAULT_NAME); The following events can be emitted with the Auditlog Service to the registered handlers:Emit Personal Data Access EventTo emit a personal data access event use method logDataAccess of the auditLogService. List<Access> accesses = new ArrayList<>();
Access access = Access.create();
// fill access object with data
accesses.add(access);
auditLogService.logDataAccess(accesses); Emit Personal Data Modification EventTo emit a personal data modification event use the method logDataModification of the auditLogService. List<DataModification> dataModifications = new ArrayList<>();
DataModification modification = DataModification.create();
// fill data modification object with data
dataModifications.add(modification);
auditLogService.logDataModification(dataModifications); Emit Configuration Change EventTo emit a configuration change event use the method logConfigChange of the auditLogService. List<ConfigChange> configChanges = new ArrayList<>();
ConfigChange configChange = ConfigChange.create();
// fill config change object with data
configChanges.add(configChange);
auditLogService.logConfigChange(Action.UPDATE, configChanges); Emit Security EventUse the method logSecurityEvent of the auditLogService to emit a security event. String action = “login”;
String data = “user-name”;
auditLogService.logSecurityEvent(action, data); Audit Log Retrieval – The Audit Log Retrieval API incorporates server-side paging to address the efficient handling of queries producing substantial result sets.When a query produces a large result set, the API automatically breaks it down into smaller, manageable chunks. The response includes an HTTP header containing a handle, which you can use to retrieve subsequent chunks. Each chunk has a fixed size of 500 records.Note – After the audit logs are generated and sent to the Audit Log service, the logs are not immediately accessible for retrieval.This API allows you to retrieve audit logs with various filtering options:Time Range: You can specify a time range using the time_from and time_to parameters. If no time frame is provided, the default is the last 30 days.Large Result Sets: If the number of results is too large, the API returns them in chunks. A handle is provided in the response header to retrieve subsequent chunks.Event Types: You can filter logs by specific event types using the category parameter. The available event types are:audit.security-eventsaudit.configurationaudit.data-accessaudit.data-modificationNote – You can specify multiple event types by separating them with commas.Conclusion -Implementing Audit Log is essential for enhancing security, compliance, and operational transparency in modern business environments. The robust capabilities provided by the SAP BTP Audit Log service allow organizations to effectively monitor and document critical activities across their systems.In summary,  adopting SAP BTP’s Audit Log service not only strengthens security frameworks but also fosters a culture of accountability and proactive management within organizations. This implementation is a strategic investment in safeguarding data integrity and enhancing overall business resilience and satisfying the security standard for the application.DISCLAIMERThe content of this blog post is provided “AS IS”. This information could contain technical inaccuracies, typographical errors, and out-of-date information. This document may be updated or changed without notice at any time. Use of the information is therefore at your own risk. In no event shall SAP be liable for special, indirect, incidental, or consequential damages resulting from or related to the use of this document.Links to refer –https://pages.github.tools.sap/cap/docs/java/auditloghttps://help.sap.com/docs/btp/sap-business-technology-platform/audit-logging-in-cloud-foundry-environment    Read More Technology Blogs by SAP articles 

#SAP

#SAPTechnologyblog

You May Also Like

More From Author