const cds = require('@sap/cds')
let audit
cds.on('served', async () => {
audit = await cds.connect.to('audit-log')
})
const audit_log_403 = (resource, ip) => {
// we need to start our own tx because the default tx may be burnt
audit.tx(async () => {
await audit.log('SecurityEvent', {
data: {
user: cds.context.user?.id || 'unknown',
action: `Attempt to access restricted resource "${resource}" with insufficient authority`
},
ip
})
})
}
// log for non-batch requests
cds.on('bootstrap', app => {
app.use((req, res, next) => {
req.on('close', () => {
if (res.statusCode == 403) {
const { originalUrl, ip } = req
audit_log_403(originalUrl, ip)
}
})
next()
})
})
// log for batch subrequests
cds.on('serving', srv => {
if (srv instanceof cds.ApplicationService) {
srv.on('error', (err, req) => {
if (err.code == 403) {
const { originalUrl, ip } = req.http.req
if (originalUrl.endsWith('/$batch')) audit_log_403(originalUrl.replace('/$batch', req.req.url), ip)
}
})
}
})
module.exports = cds.serverStep 2: Understanding the Implementation
The implementation consists of three key components:
The code handles two scenarios:
- Non-batch requests: Uses Express middleware to capture response status codes
- Batch requests: Leverages CAP's error handling for OData batch operations
To verify your implementation works correctly:
GET {{server}}/odata/v4/admin/Customers
Authorization: Basic {{username}}:{{password}}
[audit-log] - SecurityEvent: {
data: {
user: 'alice',
action: 'Attempt to access restricted resource "/odata/v4/admin/Customers" with insufficient authority'
},
ip: '::ffff:127.0.0.1',
uuid: '1109134c-64db-42f8-a780-2dde61cf6821',
tenant: undefined,
user: 'alice',
time: 2025-05-28T04:59:43.653Z
}
Custom audit logging in CAP applications provides the flexibility needed for comprehensive security monitoring and compliance. By leveraging CAP's event system and audit logging infrastructure, you can create robust audit trails that go beyond standard data access logging.
The implementation shown here focuses on security events, but the same principles apply to any custom audit logging requirements in your enterprise applications.
Learn more about SAP BTP Developer's Guide and More concepts: https://help.sap.com/docs/btp/btp-developers-guide/btp-developers-guide
Note: The views and opinions expressed in this post are my own.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
| User | Count |
|---|---|
| 24 | |
| 15 | |
| 14 | |
| 11 | |
| 9 | |
| 9 | |
| 9 | |
| 9 | |
| 9 | |
| 8 |