Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: security log for 403 errors #120

Merged
merged 5 commits into from
Oct 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 44 additions & 1 deletion test/api/api.test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
const cds = require('@sap/cds')

const { POST, GET } = cds.test().in(__dirname)
const { axios, POST, GET } = cds.test().in(__dirname)

// do not throw for 4xx responses
axios.defaults.validateStatus = () => true

cds.env.requires['audit-log'] = {
kind: 'audit-log-to-console',
Expand All @@ -22,6 +25,7 @@ describe('AuditLogService API', () => {
}

const ALICE = { username: 'alice', password: 'password' }
const BOB = { username: 'bob', password: 'password' }

beforeAll(() => {
__log = global.console.log
Expand Down Expand Up @@ -135,4 +139,43 @@ describe('AuditLogService API', () => {
})
})
})

describe('custom log 403', () => {
test('early reject', async () => {
const response = await GET('/api/Books', { auth: BOB })
expect(response).toMatchObject({ status: 403 })
expect(_logs.length).toBe(1)
expect(_logs).toContainMatchObject({ user: 'bob', ip: '::1' })
})

test('late reject', async () => {
const response = await GET('/api/Books', { auth: ALICE })
expect(response).toMatchObject({ status: 403 })
expect(_logs.length).toBe(1)
expect(_logs).toContainMatchObject({ user: 'alice', ip: '::1' })
})

test('early reject in batch', async () => {
const response = await POST(
'/api/$batch',
{ requests: [{ method: 'GET', url: '/Books', id: 'r1' }] },
{ auth: BOB }
)
expect(response).toMatchObject({ status: 403 })
expect(_logs.length).toBeGreaterThan(0) //> coding in ./srv/server.js results in 2 logs on @sap/cds^7
expect(_logs).toContainMatchObject({ user: 'bob', ip: '::1' })
})

test('late reject in batch', async () => {
const response = await POST(
'/api/$batch',
{ requests: [{ method: 'GET', url: '/Books', id: 'r1' }] },
{ auth: ALICE }
)
expect(response).toMatchObject({ status: 200 })
expect(response.data.responses[0]).toMatchObject({ status: 403 })
expect(_logs.length).toBe(1)
expect(_logs).toContainMatchObject({ user: 'alice', ip: '::1' })
})
})
})
7 changes: 7 additions & 0 deletions test/api/srv/api-service.cds
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
@path: '/api'
@requires: 'admin'
service APIService {

// default
Expand All @@ -9,6 +10,12 @@ service APIService {
action testLog();
action testLogSync();

@requires: 'cds.ExtensionDeveloper'
entity Books {
key ID : Integer;
title : String;
}

// test helpers
function getSequence() returns many String;
action resetSequence();
Expand Down
47 changes: 47 additions & 0 deletions test/api/srv/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
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 requests that are rejected with 403
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 that are rejected with 403 (but the batch request itself is successful)
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.server
Loading