@cap-js/audit-logging 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,25 @@
1
+ # Welcome to @cap-js/audit-logging
2
+
3
+ ## About this project
4
+
5
+ `@cap-js/audit-logging` is a CDS plugin providing integration to the SAP BTP Audit Logging Service as well as out-of-the-box personal data-related audit logging based on annotations.
6
+
7
+ Documentation can be found at [cap.cloud.sap](https://cap.cloud.sap/docs/guides/data-privacy).
8
+
9
+ ## Requirements
10
+
11
+ See [Getting Started](https://cap.cloud.sap/docs/get-started) on how to jumpstart your development and grow as you go with SAP Cloud Application Programming Model.
12
+
13
+ The end-to-end out-of-the-box functionality provided by this plugin requires a paid-for instance of the [SAP Audit Logging Service for SAP BTP]([url](https://help.sap.com/docs/application-logging-service?locale=en-US)). However, it is possible to provide an own implementation that writes the audit logs to a custom store.
14
+
15
+ ## Support, Feedback, Contributing
16
+
17
+ This project is open to feature requests/suggestions, bug reports etc. via [GitHub issues](https://github.com/cap-js/audit-logging/issues). Contribution and feedback are encouraged and always welcome. For more information about how to contribute, the project structure, as well as additional contribution information, see our [Contribution Guidelines](CONTRIBUTING.md).
18
+
19
+ ## Code of Conduct
20
+
21
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone. By participating in this project, you agree to abide by its [Code of Conduct](CODE_OF_CONDUCT.md) at all times.
22
+
23
+ ## Licensing
24
+
25
+ Copyright 2023 SAP SE or an SAP affiliate company and contributors. Please see our [LICENSE](LICENSE) for copyright and license information. Detailed information including third-party components and their licensing/copyright information is available [via the REUSE tool](https://api.reuse.software/info/github.com/cap-js/audit-logging).
package/cds-plugin.js ADDED
@@ -0,0 +1,48 @@
1
+ const cds = require('@sap/cds')
2
+
3
+ const { auditAccess } = require('./lib/access')
4
+ const { addDiffToCtx, calcModLogs4Before, calcModLogs4After, emitModLogs } = require('./lib/modification')
5
+ const { hasPersonalData } = require('./lib/utils')
6
+
7
+ const WRITE = ['CREATE', 'UPDATE', 'DELETE']
8
+
9
+ /*
10
+ * Add generic audit logging handlers
11
+ */
12
+ cds.on('served', services => {
13
+ const db = cds.db
14
+
15
+ for (const service of services) {
16
+ if (!(service instanceof cds.ApplicationService)) continue
17
+
18
+ const relevantEntities = []
19
+ for (const entity of service.entities) if (hasPersonalData(entity)) relevantEntities.push(entity)
20
+ if (!relevantEntities.length) return
21
+
22
+ for (const entity of relevantEntities) {
23
+ /*
24
+ * data access
25
+ */
26
+ service.after('READ', entity, auditAccess)
27
+
28
+ /*
29
+ * data modification
30
+ */
31
+ // common
32
+ db.before(WRITE, entity, addDiffToCtx)
33
+ service.after(WRITE, entity, emitModLogs)
34
+ /*
35
+ * for new or modified data, modifications are calculated in after phase
36
+ * for deleted data, modifications are calculated in before phase
37
+ * deep updates can contain new, modified and deleted data -> both phases
38
+ */
39
+ // create
40
+ db.after('CREATE', entity, calcModLogs4After)
41
+ // update
42
+ db.before('UPDATE', entity, calcModLogs4Before)
43
+ db.after('UPDATE', entity, calcModLogs4After)
44
+ // delete
45
+ db.before('DELETE', entity, calcModLogs4Before)
46
+ }
47
+ }
48
+ })
package/lib/access.js ADDED
@@ -0,0 +1,72 @@
1
+ const cds = require('@sap/cds')
2
+
3
+ // REVISIT: don't require internal stuff
4
+ const getTemplate = require('@sap/cds/libx/_runtime/common/utils/template')
5
+ const templateProcessor = require('@sap/cds/libx/_runtime/common/utils/templateProcessor')
6
+
7
+ const {
8
+ getRootEntity,
9
+ getPick,
10
+ createLogEntry,
11
+ addObjectID,
12
+ addDataSubject,
13
+ addDataSubjectForDetailsEntity,
14
+ resolveDataSubjectPromises
15
+ } = require('./utils')
16
+
17
+ let audit
18
+
19
+ const _processorFnAccess = (accessLogs, model, req) => {
20
+ return ({ row, key, element, plain }) => {
21
+ if (row.IsActiveEntity === false) return
22
+
23
+ const entity = getRootEntity(element)
24
+
25
+ // create or augment log entry
26
+ const entry = createLogEntry(accessLogs, entity, row)
27
+
28
+ // process categories
29
+ for (const category of plain.categories) {
30
+ if (category === 'ObjectID') addObjectID(entry, row, key)
31
+ else if (category === 'DataSubjectID') addDataSubject(entry, row, key, entity)
32
+ else if (category === 'IsPotentiallySensitive' && key in row) {
33
+ if (!entry.attributes.some(e => e.name === key)) entry.attributes.push({ name: key })
34
+ // REVISIT: attribute vs. attachment?
35
+ }
36
+ }
37
+
38
+ // add promise to determine data subject if a DataSubjectDetails entity
39
+ const semantics = entity['@PersonalData.EntitySemantics']
40
+ if (
41
+ (semantics === 'DataSubjectDetails' || semantics === 'Other') &&
42
+ Object.keys(entry.data_subject.id).length === 0 // > id still an empty object -> promise not yet set
43
+ ) {
44
+ addDataSubjectForDetailsEntity(row, entry, req, entity, model)
45
+ }
46
+ }
47
+ }
48
+
49
+ const auditAccess = async function (data, req) {
50
+ if (!cds.env.requires['audit-log'].handle?.includes('READ')) return
51
+
52
+ if (typeof data !== 'object' || data == null) return
53
+
54
+ const mock = Object.assign({ name: req.target._service.name, model: this.model })
55
+ const template = getTemplate('personal_read', mock, req.target, { pick: getPick('READ') })
56
+ if (!template.elements.size) return
57
+
58
+ const accessLogs = {}
59
+ const _data = Array.isArray(data) ? data : [data]
60
+ _data.forEach(row => templateProcessor({ processFn: _processorFnAccess(accessLogs, this.model, req), row, template }))
61
+
62
+ const accesses = (await resolveDataSubjectPromises(accessLogs)).filter(ele => ele.attributes.length)
63
+ if (!accesses.length) return
64
+
65
+ audit = audit || (await cds.connect.to('audit-log'))
66
+
67
+ await Promise.all(accesses.map(access => audit.log('SensitiveDataRead', access)))
68
+ }
69
+
70
+ module.exports = {
71
+ auditAccess
72
+ }
@@ -0,0 +1,184 @@
1
+ const cds = require('@sap/cds')
2
+
3
+ // REVISIT: don't require internal stuff
4
+ const getTemplate = require('@sap/cds/libx/_runtime/common/utils/template')
5
+ const templateProcessor = require('@sap/cds/libx/_runtime/common/utils/templateProcessor')
6
+
7
+ const {
8
+ getMapKeyForCurrentRequest,
9
+ getRootEntity,
10
+ getPick,
11
+ createLogEntry,
12
+ addObjectID,
13
+ addDataSubject,
14
+ addDataSubjectForDetailsEntity,
15
+ resolveDataSubjectPromises
16
+ } = require('./utils')
17
+
18
+ let audit
19
+
20
+ // REVISIT: remove once old database impl is removed
21
+ const _getDataWithAppliedTransitions = (data, req) => {
22
+ let d
23
+ const query = req.query.INSERT || req.query.UPDATE || req.query.DELETE
24
+ // NOTE: there will only be transitions if old database impl is used
25
+ const transition = query._transitions?.find(t => t.queryTarget.name === req.target.name)
26
+ if (transition) {
27
+ d = { _op: data._op }
28
+ if (data._old) d._old = {}
29
+ for (const [k, v] of transition.mapping) {
30
+ if (v.ref[0] in data) d[k] = data[v.ref[0]]
31
+ if (data._old && v.ref[0] in data._old) d._old[k] = data._old[v.ref[0]]
32
+ }
33
+ }
34
+ return d || data
35
+ }
36
+
37
+ /*
38
+ * REVISIT: diff() doesn't work in srv after phase but foreign key propagation has not yet taken place in srv before phase
39
+ * -> calc diff in db layer and store in audit data structure at context
40
+ * -> REVISIT for GA: clear req._.partialPersistentState?
41
+ */
42
+ const addDiffToCtx = async function (req) {
43
+ // store diff in audit data structure at context
44
+ const _audit = (req.context._audit ??= {})
45
+ if (!_audit.diffs) _audit.diffs = new Map()
46
+
47
+ // get diff
48
+ let diff = await req.diff()
49
+ diff = _getDataWithAppliedTransitions(diff, req)
50
+
51
+ // add keys, if necessary
52
+ let keys = _getDataWithAppliedTransitions(Object.assign({}, req.data), req)
53
+ for (const key in keys) if (!(key in req.target.keys)) delete keys[key]
54
+ Object.assign(diff, keys)
55
+
56
+ _audit.diffs.set(req._.query, diff)
57
+ }
58
+ addDiffToCtx._initial = true
59
+
60
+ const _getOldAndNew = (action, row, key) => {
61
+ let oldValue = action === 'Create' ? null : row._old && row._old[key]
62
+ if (oldValue === undefined) oldValue = null
63
+ else if (Array.isArray(oldValue)) oldValue = JSON.stringify(oldValue)
64
+ let newValue = action === 'Delete' ? null : row[key]
65
+ if (newValue === undefined) newValue = null
66
+ else if (Array.isArray(newValue)) newValue = JSON.stringify(newValue)
67
+ return { oldValue, newValue }
68
+ }
69
+
70
+ const _addAttribute = (log, action, row, key) => {
71
+ if (!log.attributes.find(ele => ele.name === key)) {
72
+ const { oldValue, newValue } = _getOldAndNew(action, row, key)
73
+ if (oldValue !== newValue) {
74
+ const attr = { name: key }
75
+ if (action !== 'Create') attr.old = oldValue
76
+ if (action !== 'Delete') attr.new = newValue
77
+ log.attributes.push(attr)
78
+ }
79
+ }
80
+ }
81
+
82
+ const _maskAttribute = (attributes, key) => {
83
+ const attribute = attributes?.find(ele => ele.name === key)
84
+ if (attribute) {
85
+ if ('old' in attribute) attribute.old = '***'
86
+ if ('new' in attribute) attribute.new = '***'
87
+ }
88
+ }
89
+
90
+ const _processorFnModification = (modificationLogs, model, req, beforeWrite) => elementInfo => {
91
+ if (!elementInfo.row?._op) return
92
+
93
+ let { row, key, element, plain } = elementInfo
94
+
95
+ // delete in before phase, create and update in after phase
96
+ if ((row._op === 'delete') !== !!beforeWrite) return
97
+
98
+ const entity = getRootEntity(element)
99
+ const action = row._op[0].toUpperCase() + row._op.slice(1)
100
+
101
+ // create or augment log entry
102
+ const modificationLog = createLogEntry(modificationLogs, entity, row)
103
+
104
+ // process categories
105
+ for (const category of plain.categories) {
106
+ if (category === 'ObjectID') {
107
+ addObjectID(modificationLog, row, key)
108
+ } else if (category === 'DataSubjectID') {
109
+ addDataSubject(modificationLog, row, key, entity)
110
+ } else if (category === 'IsPotentiallyPersonal' || category === 'IsPotentiallySensitive') {
111
+ _addAttribute(modificationLog, action, row, key)
112
+ // do not log the value of a sensitive attribute
113
+ if (element['@PersonalData.IsPotentiallySensitive']) _maskAttribute(modificationLog.attributes, key)
114
+ }
115
+ }
116
+
117
+ // add promise to determine data subject if a DataSubjectDetails entity
118
+ if (
119
+ (entity['@PersonalData.EntitySemantics'] === 'DataSubjectDetails' ||
120
+ entity['@PersonalData.EntitySemantics'] === 'Other') &&
121
+ Object.keys(modificationLog.data_subject.id).length === 0 // > id still an empty object -> promise not yet set
122
+ ) {
123
+ addDataSubjectForDetailsEntity(row, modificationLog, req, entity, model)
124
+ }
125
+ }
126
+
127
+ const _getDataModificationLogs = (req, tx, diff, beforeWrite) => {
128
+ const template = getTemplate(
129
+ `personal_${req.event}`.toLowerCase(),
130
+ Object.assign({ name: req.target._service.name, model: tx.model }),
131
+ req.target,
132
+ { pick: getPick(req.event) }
133
+ )
134
+
135
+ const modificationLogs = {}
136
+ const processFn = _processorFnModification(modificationLogs, tx.model, req, beforeWrite)
137
+ templateProcessor({ processFn, row: diff, template })
138
+
139
+ return modificationLogs
140
+ }
141
+
142
+ const _calcModificationLogsHandler = async function (req, beforeWrite, that) {
143
+ const mapKey = getMapKeyForCurrentRequest(req)
144
+
145
+ const _audit = (req.context._audit ??= {})
146
+ const modificationLogs = _getDataModificationLogs(req, that, _audit.diffs.get(mapKey), beforeWrite)
147
+
148
+ // store modificationLogs in audit data structure at context
149
+ if (!_audit.modificationLogs) _audit.modificationLogs = new Map()
150
+ const existingLogs = _audit.modificationLogs.get(mapKey) || {}
151
+ _audit.modificationLogs.set(mapKey, Object.assign(existingLogs, modificationLogs))
152
+
153
+ // execute the data subject promises before going along to on phase
154
+ // guarantees that the reads are executed before the data is modified
155
+ await resolveDataSubjectPromises(modificationLogs)
156
+ }
157
+
158
+ const calcModLogs4Before = function (req) {
159
+ return _calcModificationLogsHandler(req, true, this)
160
+ }
161
+
162
+ const calcModLogs4After = function (_, req) {
163
+ return _calcModificationLogsHandler(req, false, this)
164
+ }
165
+
166
+ const emitModLogs = async function (_, req) {
167
+ const modificationLogs = req.context?._audit?.modificationLogs?.get(req.query)
168
+ if (!modificationLogs) return
169
+
170
+ audit = audit || (await cds.connect.to('audit-log'))
171
+
172
+ const modifications = Object.keys(modificationLogs)
173
+ .map(k => modificationLogs[k])
174
+ .filter(log => log.attributes.length)
175
+
176
+ await Promise.all(modifications.map(modification => audit.log('PersonalDataModified', modification)))
177
+ }
178
+
179
+ module.exports = {
180
+ addDiffToCtx,
181
+ calcModLogs4Before,
182
+ calcModLogs4After,
183
+ emitModLogs
184
+ }
package/lib/utils.js ADDED
@@ -0,0 +1,237 @@
1
+ const WRITE = { CREATE: 1, UPDATE: 1, DELETE: 1 }
2
+
3
+ const hasPersonalData = entity => {
4
+ if (!entity['@PersonalData.DataSubjectRole']) return
5
+ if (!entity['@PersonalData.EntitySemantics']) return
6
+ return !!Object.values(entity.elements).some(
7
+ element =>
8
+ element['@PersonalData.IsPotentiallyPersonal'] ||
9
+ element['@PersonalData.IsPotentiallySensitive'] ||
10
+ (element['@PersonalData.FieldSemantics'] && element['@PersonalData.FieldSemantics'] === 'DataSubjectID')
11
+ )
12
+ }
13
+
14
+ const getMapKeyForCurrentRequest = req => {
15
+ // running in srv or db layer? -> srv's req.query used as key of diff and logs maps at req.context
16
+ // REVISIT: req._tx should not be used like that!
17
+ return req.tx.isDatabaseService ? req._.query : req.query
18
+ }
19
+
20
+ const getRootEntity = element => {
21
+ let entity = element.parent
22
+ while (entity.kind !== 'entity') entity = entity.parent
23
+ return entity
24
+ }
25
+
26
+ const _isDataSubject = (element, target) => {
27
+ return (
28
+ !element.isAssociation &&
29
+ element['@PersonalData.FieldSemantics'] === 'DataSubjectID' &&
30
+ target['@PersonalData.EntitySemantics'] === 'DataSubject'
31
+ )
32
+ }
33
+
34
+ const getPick = event => {
35
+ return (element, target) => {
36
+ if (!hasPersonalData(target)) return
37
+ const categories = []
38
+ if (!element.isAssociation && element.key) categories.push('ObjectID')
39
+ if (_isDataSubject(element, target)) categories.push('DataSubjectID')
40
+ if (event in WRITE && element['@PersonalData.IsPotentiallyPersonal']) categories.push('IsPotentiallyPersonal')
41
+ if (element['@PersonalData.IsPotentiallySensitive']) categories.push('IsPotentiallySensitive')
42
+ if (categories.length) return { categories }
43
+ }
44
+ }
45
+
46
+ const _getHash = (entity, row) => {
47
+ return `${entity.name}(${Object.keys(entity.keys)
48
+ .map(k => `${k}=${row[k]}`)
49
+ .join(',')})`
50
+ }
51
+
52
+ const createLogEntry = (logs, entity, row) => {
53
+ const hash = _getHash(entity, row)
54
+ let log = logs[hash]
55
+ if (!log) {
56
+ logs[hash] = {
57
+ data_subject: { id: {}, role: entity['@PersonalData.DataSubjectRole'] },
58
+ object: { type: entity.name, id: {} },
59
+ attributes: []
60
+ }
61
+ log = logs[hash]
62
+ }
63
+ return log
64
+ }
65
+
66
+ const addObjectID = (log, row, key) => {
67
+ if (!(key in log.object.id) && key !== 'IsActiveEntity') log.object.id[key] = row[key] || row._old?.[key]
68
+ }
69
+
70
+ const addDataSubject = (log, row, key, entity) => {
71
+ if (!log.data_subject.type) log.data_subject.type = entity.name
72
+ if (!(key in log.data_subject.id)) {
73
+ const value = row[key] || row._old?.[key]
74
+ log.data_subject.id[key] = value
75
+ }
76
+ }
77
+
78
+ const _addKeysToWhere = (keys, row, alias) => {
79
+ return keys
80
+ .filter(key => !key.isAssociation && key.name !== 'IsActiveEntity')
81
+ .reduce((keys, key) => {
82
+ if (keys.length) keys.push('and')
83
+ keys.push({ ref: [alias, key.name] }, '=', { val: row[key.name] })
84
+ return keys
85
+ }, [])
86
+ }
87
+
88
+ const _keyColumns = (keys, alias) => {
89
+ return keys
90
+ .filter(key => !key.isAssociation && key.name !== 'IsActiveEntity')
91
+ .map(key => ({ ref: [alias, key.name] }))
92
+ }
93
+
94
+ const _alias = entity => entity.name.replace(`${entity._service.name}.`, '').replace('.', '_')
95
+
96
+ const _buildSubSelect = (model, { entity, relative, element, next }, row, previousCqn) => {
97
+ // relative is a parent or an entity itself
98
+
99
+ const keys = Object.values(entity.keys)
100
+
101
+ const entityName = entity.name
102
+ const as = _alias(entity)
103
+
104
+ const childCqn = SELECT.from({ ref: [entityName], as }).columns(_keyColumns(keys, as))
105
+
106
+ const targetAlias = _alias(element._target)
107
+ const relativeAlias = _alias(relative)
108
+
109
+ childCqn.where(relative._relations[element.name].join(targetAlias, relativeAlias))
110
+
111
+ if (previousCqn) childCqn.where('exists', previousCqn)
112
+ else childCqn.where(_addKeysToWhere(keys, row, as))
113
+
114
+ if (next) return _buildSubSelect(model, next, {}, childCqn)
115
+
116
+ return childCqn
117
+ }
118
+
119
+ const _getDataSubjectIdPromise = ({ dataSubjectEntity, subs }, row, model) => {
120
+ const keys = Object.values(dataSubjectEntity.keys)
121
+ const as = _alias(dataSubjectEntity)
122
+
123
+ const cqn = SELECT.from({ ref: [dataSubjectEntity.name], as })
124
+ .columns(_keyColumns(keys, as))
125
+ .where(['exists', _buildSubSelect(model, subs[0], row)])
126
+
127
+ // entity reused in different branches => must check all
128
+ for (let i = 1; i < subs.length; i++) cqn.or(['exists', _buildSubSelect(model, subs[i], row)])
129
+
130
+ return cqn.then(res => {
131
+ const id = {}
132
+ for (const k in res[0]) id[k] = res[0][k]
133
+ return id
134
+ })
135
+ }
136
+
137
+ const _getUps = (entity, model) => {
138
+ if (entity.own('__parents')) return entity.__parents
139
+ const ups = []
140
+ for (const def of Object.values(model.definitions)) {
141
+ if (def.kind !== 'entity' || !def.associations) continue
142
+ for (const element of Object.values(def.associations)) {
143
+ if (element.target !== entity.name || element._isBacklink) continue
144
+ if (element.name === 'SiblingEntity') continue
145
+ ups.push(element)
146
+ }
147
+ }
148
+ return entity.set('__parents', ups)
149
+ }
150
+
151
+ const _ifDataSubject = (entity, role) => {
152
+ return entity['@PersonalData.EntitySemantics'] === 'DataSubject' && entity['@PersonalData.DataSubjectRole'] === role
153
+ }
154
+
155
+ const _getDataSubjectUp = (role, model, entity, prev, next, result) => {
156
+ for (const element of _getUps(entity, model)) {
157
+ const me = { entity, relative: element.parent, element }
158
+ if (prev) prev.next = me
159
+ if (_ifDataSubject(element.parent, role)) {
160
+ if (!result) result = { dataSubjectEntity: element.parent, subs: [] }
161
+ result.subs.push(next || me)
162
+ return result
163
+ } else {
164
+ // dfs is a must here
165
+ result = _getDataSubjectUp(role, model, element.parent, me, next || me, result)
166
+ }
167
+ }
168
+ return result
169
+ }
170
+
171
+ const _getDataSubjectDown = (role, entity, prev, next) => {
172
+ const associations = Object.values(entity.associations || {}).filter(e => !e._isBacklink)
173
+ for (const element of associations) {
174
+ const me = { entity, relative: entity, element }
175
+ if (_ifDataSubject(element._target, role)) {
176
+ if (prev) prev.next = me
177
+ return { dataSubjectEntity: element._target, subs: [next || me] }
178
+ }
179
+ }
180
+ // bfs makes more sense here
181
+ for (const element of associations) {
182
+ const me = { entity, relative: entity, element }
183
+ if (prev) prev.next = me
184
+ const dataSubject = _getDataSubjectDown(role, element._target, me, next || me)
185
+ if (dataSubject) return dataSubject
186
+ }
187
+ }
188
+
189
+ const getDataSubject = (entity, model, role) => {
190
+ const hash = '__dataSubject4' + role
191
+ if (entity.own(hash)) return entity[hash]
192
+ // entities with EntitySemantics 'DataSubjectDetails' or 'Other' must not necessarily
193
+ // be always below or always above 'DataSubject' entity in CSN tree
194
+ let dataSubject = _getDataSubjectUp(role, model, entity)
195
+ if (!dataSubject) dataSubject = _getDataSubjectDown(role, entity)
196
+ return entity.set(hash, dataSubject)
197
+ }
198
+
199
+ const addDataSubjectForDetailsEntity = (row, log, req, entity, model) => {
200
+ const role = entity['@PersonalData.DataSubjectRole']
201
+ const dataSubjectInfo = getDataSubject(entity, model, role)
202
+ log.data_subject.type = dataSubjectInfo.dataSubjectEntity.name
203
+ /*
204
+ * for each req (cf. $batch with atomicity) and data subject role (e.g., customer vs supplier),
205
+ * store (in audit data structure at context) and reuse a single promise to look up the respective data subject
206
+ */
207
+ const mapKey = getMapKeyForCurrentRequest(req)
208
+ const _audit = (req.context._audit ??= {})
209
+ if (!_audit.dataSubjects) _audit.dataSubjects = new Map()
210
+ if (!_audit.dataSubjects.has(mapKey)) _audit.dataSubjects.set(mapKey, new Map())
211
+ const map = _audit.dataSubjects.get(mapKey)
212
+ if (map.has(role)) log.data_subject.id = map.get(role)
213
+ // REVISIT by downward lookups row might already contain ID - some potential to optimize
214
+ else map.set(role, _getDataSubjectIdPromise(dataSubjectInfo, row, model))
215
+ }
216
+
217
+ const resolveDataSubjectPromises = log => {
218
+ const logs = Object.values(log)
219
+ return Promise.all(logs.map(log => log.data_subject.id)).then(IDs =>
220
+ logs.map((log, i) => {
221
+ log.data_subject.id = IDs[i]
222
+ return log
223
+ })
224
+ )
225
+ }
226
+
227
+ module.exports = {
228
+ hasPersonalData,
229
+ getMapKeyForCurrentRequest,
230
+ getRootEntity,
231
+ getPick,
232
+ createLogEntry,
233
+ addObjectID,
234
+ addDataSubject,
235
+ addDataSubjectForDetailsEntity,
236
+ resolveDataSubjectPromises
237
+ }
package/package.json ADDED
@@ -0,0 +1,57 @@
1
+ {
2
+ "name": "@cap-js/audit-logging",
3
+ "version": "0.1.0",
4
+ "description": "CDS plugin providing integration to the SAP BTP Audit Logging Service as well as out-of-the-box personal data-related audit logging based on annotations.",
5
+ "repository": "cap-js/audit-logging",
6
+ "author": "SAP SE (https://www.sap.com)",
7
+ "homepage": "https://cap.cloud.sap/",
8
+ "license": "SEE LICENSE IN LICENSE",
9
+ "main": "cds-plugin.js",
10
+ "files": [
11
+ "lib",
12
+ "srv"
13
+ ],
14
+ "scripts": {
15
+ "lint": "npx eslint .",
16
+ "test": "npx jest --silent"
17
+ },
18
+ "peerDependencies": {
19
+ "@sap/cds": "^7"
20
+ },
21
+ "devDependencies": {
22
+ "@cap-js/sqlite": "^1.0.1",
23
+ "axios": "^1.4.0",
24
+ "eslint": "^8",
25
+ "express": "^4.18.2",
26
+ "jest": "^29.5.0"
27
+ },
28
+ "cds": {
29
+ "requires": {
30
+ "audit-log": true,
31
+ "kinds": {
32
+ "audit-log": {
33
+ "handle": [
34
+ "WRITE"
35
+ ],
36
+ "[development]": {
37
+ "kind": "audit-log-to-console"
38
+ },
39
+ "[production]": {
40
+ "kind": "audit-log-to-restv2"
41
+ }
42
+ },
43
+ "audit-log-to-console": {
44
+ "impl": "@cap-js/audit-logging/srv/log2console",
45
+ "outbox": false
46
+ },
47
+ "audit-log-to-restv2": {
48
+ "impl": "@cap-js/audit-logging/srv/log2restv2",
49
+ "vcap": {
50
+ "label": "auditlog"
51
+ },
52
+ "outbox": true
53
+ }
54
+ }
55
+ }
56
+ }
57
+ }
@@ -0,0 +1,14 @@
1
+ const AuditLogService = require('./service')
2
+
3
+ module.exports = class AuditLog2Console extends AuditLogService {
4
+ async init() {
5
+ this.on('*', function (req) {
6
+ const { event, data } = req
7
+
8
+ console.log(`[audit-log] - ${event}:`, data)
9
+ })
10
+
11
+ // call AuditLogService's init
12
+ await super.init()
13
+ }
14
+ }
@@ -0,0 +1,170 @@
1
+ const cds = require('@sap/cds')
2
+
3
+ const LOG = cds.log('audit-log')
4
+
5
+ const AuditLogService = require('./service')
6
+
7
+ module.exports = class AuditLog2RESTv2 extends AuditLogService {
8
+ async init() {
9
+ // credentials stuff
10
+ const { credentials } = this.options
11
+ if (!credentials) throw new Error('No or malformed credentials for "audit-log"')
12
+ if (credentials.uaa) {
13
+ this._oauth2 = true
14
+ this._tokens = new Map()
15
+ this._providerTenant = credentials.uaa.tenantid
16
+ } else {
17
+ this._auth = 'Basic ' + Buffer.from(credentials.user + ':' + credentials.password).toString('base64')
18
+ }
19
+ this._vcap = process.env.VCAP_APPLICATION ? JSON.parse(process.env.VCAP_APPLICATION) : null
20
+
21
+ this.on('*', function (req) {
22
+ const { event, data } = req
23
+
24
+ // event.match() is used to support the old event names
25
+ if (event === 'SensitiveDataRead' || event.match(/^dataAccess/i)) {
26
+ return this._handle(data, 'DATA_ACCESS')
27
+ }
28
+ if (event === 'PersonalDataModified' || event.match(/^dataModification/i)) {
29
+ data.success = true
30
+ return this._handle(data, 'DATA_MODIFICATION')
31
+ }
32
+ if (event === 'ConfigurationModified' || event.match(/^configChange/i)) {
33
+ data.success = true
34
+ return this._handle(data, 'CONFIGURATION_CHANGE')
35
+ }
36
+ if (event === 'SecurityEvent' || event.match(/^security/i)) {
37
+ if (typeof data.data === 'object') data.data = JSON.stringify(data.data)
38
+ return this._handle(data, 'SECURITY_EVENT')
39
+ }
40
+
41
+ LOG._warn && LOG.warn(`Event "${event}" is not implemented`)
42
+ })
43
+
44
+ // call AuditLogService's init
45
+ await super.init()
46
+ }
47
+
48
+ async _getToken(tenant) {
49
+ const { _tokens: tokens } = this
50
+ if (tokens.has(tenant)) return tokens.get(tenant)
51
+
52
+ const url = this.options.credentials.uaa.url + '/oauth/token'
53
+ const data = {
54
+ grant_type: 'client_credentials',
55
+ response_type: 'token',
56
+ client_id: this.options.credentials.uaa.clientid,
57
+ client_secret: this.options.credentials.uaa.clientsecret
58
+ }
59
+ const urlencoded = Object.keys(data).reduce((acc, cur) => {
60
+ acc += (acc ? '&' : '') + cur + '=' + data[cur]
61
+ return acc
62
+ }, '')
63
+ const headers = { 'content-type': 'application/x-www-form-urlencoded' }
64
+ if (tenant !== this._providerTenant) headers['x-zid'] = tenant
65
+ try {
66
+ const { access_token, expires_in } = await _post(url, urlencoded, headers)
67
+ tokens.set(tenant, access_token)
68
+ // remove token from cache 60 seconds before it expires
69
+ setTimeout(() => tokens.delete(tenant), (expires_in - 60) * 1000)
70
+ return access_token
71
+ } catch (err) {
72
+ // 401 could also mean x-zid is not valid
73
+ if (String(err.response?.statusCode).match(/^4\d\d$/)) err.unrecoverable = true
74
+ throw err
75
+ }
76
+ }
77
+
78
+ async _send(data, path) {
79
+ let url
80
+ const headers = { 'content-type': 'application/json' }
81
+ // TODO: what are these for?
82
+ if (this._vcap) {
83
+ headers.XS_AUDIT_ORG = this._vcap.organization_name
84
+ headers.XS_AUDIT_SPACE = this._vcap.space_name
85
+ headers.XS_AUDIT_APP = this._vcap.application_name
86
+ }
87
+ if (this._oauth2) {
88
+ url = this.options.credentials.url + PATHS.OAUTH2[path]
89
+ headers.authorization = 'Bearer ' + (await this._getToken(data.tenant))
90
+ data.tenant = data.tenant === this._providerTenant ? '$PROVIDER' : '$SUBSCRIBER'
91
+ } else {
92
+ url = this.options.credentials.url + PATHS.STANDARD[path]
93
+ headers.authorization = this._auth
94
+ }
95
+ try {
96
+ await _post(url, data, headers)
97
+ } catch (err) {
98
+ // 429 (rate limit) is not unrecoverable
99
+ if (String(err.response?.statusCode).match(/^4\d\d$/) && err.response?.statusCode !== 429)
100
+ err.unrecoverable = true
101
+ throw err
102
+ }
103
+ }
104
+
105
+ async _handle(logs, path) {
106
+ if (!Array.isArray(logs)) logs = [logs]
107
+
108
+ // write the logs
109
+ const errors = []
110
+ await Promise.all(logs.map(log => this._send(log, path).catch(err => errors.push(err))))
111
+ if (errors.length) throw _getErrorToThrow(errors)
112
+ }
113
+ }
114
+
115
+ /*
116
+ * consts
117
+ */
118
+
119
+ const PATHS = {
120
+ STANDARD: {
121
+ DATA_ACCESS: '/audit-log/v2/data-accesses',
122
+ DATA_MODIFICATION: '/audit-log/v2/data-modifications',
123
+ CONFIGURATION_CHANGE: '/audit-log/v2/configuration-changes',
124
+ SECURITY_EVENT: '/audit-log/v2/security-events'
125
+ },
126
+ OAUTH2: {
127
+ DATA_ACCESS: '/audit-log/oauth2/v2/data-accesses',
128
+ DATA_MODIFICATION: '/audit-log/oauth2/v2/data-modifications',
129
+ CONFIGURATION_CHANGE: '/audit-log/oauth2/v2/configuration-changes',
130
+ SECURITY_EVENT: '/audit-log/oauth2/v2/security-events'
131
+ }
132
+ }
133
+
134
+ /*
135
+ * utils
136
+ */
137
+
138
+ const https = require('https')
139
+
140
+ async function _post(url, data, headers) {
141
+ return new Promise((resolve, reject) => {
142
+ const req = https.request(url, { method: 'POST', headers }, res => {
143
+ const chunks = []
144
+ res.on('data', chunk => chunks.push(chunk))
145
+ res.on('end', () => {
146
+ let body = Buffer.concat(chunks).toString()
147
+ if (res.headers['content-type']?.match(/json/)) body = JSON.parse(body)
148
+ if (res.statusCode >= 400) {
149
+ const err = new Error(res.statusMessage)
150
+ err.response = res
151
+ err.body = body
152
+ reject(err)
153
+ } else {
154
+ resolve(body)
155
+ }
156
+ })
157
+ })
158
+ req.on('error', reject)
159
+ req.write(typeof data === 'object' ? JSON.stringify(data) : data)
160
+ req.end()
161
+ })
162
+ }
163
+
164
+ function _getErrorToThrow(errors) {
165
+ if (errors.length === 1) return errors[0]
166
+ const error = new cds.error('MULTIPLE_ERRORS')
167
+ error.details = errors
168
+ if (errors.some(e => e.unrecoverable)) error.unrecoverable = true
169
+ return error
170
+ }
package/srv/service.js ADDED
@@ -0,0 +1,21 @@
1
+ const cds = require('@sap/cds')
2
+
3
+ // REVISIT: cds.OutboxService or technique to avoid extending OutboxService
4
+ const OutboxService = require('@sap/cds/libx/_runtime/messaging/Outbox')
5
+
6
+ module.exports = class AuditLogService extends OutboxService {
7
+ async init() {
8
+ // add common audit log entry fields
9
+ this.before('*', req => {
10
+ const { tenant, user, timestamp: time } = cds.context
11
+ Object.assign(req.data, { uuid: cds.utils.uuid(), tenant, user: user.id, time })
12
+ })
13
+
14
+ // call OutboxService's init
15
+ await super.init()
16
+
17
+ // add self-explanatory api (await audit.log/logSync(event, data))
18
+ this.log = this.emit
19
+ this.logSync = this.send
20
+ }
21
+ }