Compare commits
46
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1e2d6352d4
|
||
|
|
3ddcf7ec9d
|
||
|
|
7d0e54eeca
|
||
|
|
a366e8b96e
|
||
|
|
7f1b5988af
|
||
|
|
d99db4738f
|
||
|
|
4cd0fd1f54
|
||
|
|
ab283c79b9
|
||
|
|
eb98ec5fd0
|
||
|
|
f09fe866ad
|
||
|
|
c4ebc6833c
|
||
|
|
2431b4723a
|
||
|
|
9fb168b96d
|
||
|
|
e0459a99ff | ||
|
|
84e2311d84
|
||
|
|
5987cb53ac
|
||
|
|
a087988f11
|
||
|
|
894c3023b4
|
||
|
|
15c2906fc1
|
||
|
|
45015b6912
|
||
|
|
0f94818084
|
||
|
|
7b302ed2b1 | ||
|
|
b917b51656 | ||
|
|
dc4734eef1 | ||
|
|
eb912ebf07 | ||
|
|
9091f26dd7 | ||
|
|
4942b7e994 | ||
|
|
0875069488 | ||
|
|
bf81c587bc | ||
|
|
70058c1ef6
|
||
|
|
af62471cf6 | ||
|
|
325150a938
|
||
|
|
72ec4a08be | ||
|
|
ef5c096e84
|
||
|
|
75b5f0b64f | ||
|
|
2cb37a067d
|
||
|
|
971ddbed2d | ||
|
|
e2f5199e06
|
||
|
|
214bd75298
|
||
|
|
6bb55f332a
|
||
|
|
781bae3efe | ||
|
|
677d611b15
|
||
|
|
527ee4fc96
|
||
|
|
c0a2d67026
|
||
|
|
f415f2cc8d | ||
|
|
0dec9463a6
|
No files matched your search
+10
-61
@@ -1,65 +1,14 @@
|
||||
version: 2.1
|
||||
|
||||
setup: true
|
||||
orbs:
|
||||
qqq-orb: kingsrook/qqq-orb@0.6.9
|
||||
|
||||
commands:
|
||||
configure-package-install:
|
||||
steps:
|
||||
- run:
|
||||
name: Keep package installation unattended
|
||||
command: |
|
||||
# These build machines are discarded after the job.
|
||||
sudo install -d /etc/needrestart/conf.d
|
||||
printf '%s\n' '$nrconf{restart} = "l";' | sudo tee /etc/needrestart/conf.d/99-qqq-ci.conf >/dev/null
|
||||
|
||||
qqq-orb: kingsrook/qqq-orb@0.8
|
||||
workflows:
|
||||
|
||||
test_only:
|
||||
setup:
|
||||
jobs:
|
||||
- qqq-orb/mvn_test_only:
|
||||
pre-steps:
|
||||
- configure-package-install
|
||||
context: [ qqq-maven-registry-credentials ]
|
||||
filters:
|
||||
branches:
|
||||
ignore: /(develop|release/.*|integration.*)/
|
||||
tags:
|
||||
only: []
|
||||
|
||||
publish_snapshot:
|
||||
jobs:
|
||||
- qqq-orb/mvn_publish:
|
||||
pre-steps:
|
||||
- configure-package-install
|
||||
context: [ qqq-maven-registry-credentials ]
|
||||
branch_type: snapshot
|
||||
filters:
|
||||
branches:
|
||||
only:
|
||||
- develop
|
||||
|
||||
publish_release_candidate:
|
||||
jobs:
|
||||
- qqq-orb/mvn_publish:
|
||||
pre-steps:
|
||||
- configure-package-install
|
||||
context: [ qqq-maven-registry-credentials ]
|
||||
branch_type: release_candidate
|
||||
filters:
|
||||
branches:
|
||||
only:
|
||||
- /release\/.*/
|
||||
|
||||
publish_release:
|
||||
jobs:
|
||||
- qqq-orb/mvn_publish:
|
||||
pre-steps:
|
||||
- configure-package-install
|
||||
context: [ qqq-maven-registry-credentials ]
|
||||
branch_type: release
|
||||
filters:
|
||||
branches:
|
||||
ignore: /.*/
|
||||
tags:
|
||||
only: [ /^v\d+\.\d+\.\d+$/ ]
|
||||
- qqq-orb/generate_pipeline:
|
||||
orb_version: '0.8'
|
||||
filters:
|
||||
branches:
|
||||
ignore: automation/qbit-rc-pending
|
||||
tags:
|
||||
only: /^v\d+\.\d+\.\d+$/
|
||||
@@ -0,0 +1,7 @@
|
||||
name: build
|
||||
on:
|
||||
push:
|
||||
jobs:
|
||||
maven:
|
||||
uses: self:KofTwentyTwo/ci-workflows/.gitea/workflows/maven.yaml@v1
|
||||
secrets: inherit
|
||||
@@ -0,0 +1,23 @@
|
||||
name: CodeQL
|
||||
'on':
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
- develop
|
||||
- release/**
|
||||
- hotfix/**
|
||||
pull_request: {}
|
||||
schedule:
|
||||
- cron: 41 16 * * 0
|
||||
workflow_dispatch: {}
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
security-events: write
|
||||
packages: read
|
||||
concurrency:
|
||||
group: codeql-${{ github.event.pull_request.number || github.ref }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
jobs:
|
||||
analyze:
|
||||
uses: QRun-IO/qqq-orb/.github/workflows/qbit-codeql.yml@c288a8864fe9054f68410e1d78f5863aea4c4d22
|
||||
@@ -1,25 +1,74 @@
|
||||
# Cut the next release candidate (QRun-IO/qqq docs/QRUN-QBIT-REPO-STANDARD.md, C6):
|
||||
# run this workflow by hand, or merge a develop PR labelled `release:rc`. It merges develop into
|
||||
# the release line and the release/* push runs CircleCI publish_release_candidate.
|
||||
name: Release candidate
|
||||
|
||||
on:
|
||||
'on':
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
dry_run:
|
||||
description: Print the plan without merging or creating branches
|
||||
description: Plan a cut without changing release state
|
||||
type: boolean
|
||||
default: false
|
||||
finalize:
|
||||
description: Retry finalization of an existing cut; do not cut another RC
|
||||
type: boolean
|
||||
default: false
|
||||
recover:
|
||||
description: Recover the same published RC after a deployment timeout; never
|
||||
reupload
|
||||
type: boolean
|
||||
default: false
|
||||
circle_build:
|
||||
description: Original Circle publisher build number (recovery only)
|
||||
type: string
|
||||
default: ''
|
||||
merge_sha:
|
||||
description: Existing cut merge_sha (finalize retry only)
|
||||
type: string
|
||||
default: ''
|
||||
bump_sha:
|
||||
description: Existing cut bump_sha (finalize retry only)
|
||||
type: string
|
||||
default: ''
|
||||
branch:
|
||||
description: Existing cut branch (finalize retry only)
|
||||
type: string
|
||||
default: ''
|
||||
version:
|
||||
description: Existing cut version (finalize retry only)
|
||||
type: string
|
||||
default: ''
|
||||
pull_request:
|
||||
types: [closed]
|
||||
branches: [develop]
|
||||
|
||||
types:
|
||||
- closed
|
||||
branches:
|
||||
- develop
|
||||
repository_dispatch:
|
||||
types:
|
||||
- qbit-rc-published
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
actions: read
|
||||
checks: read
|
||||
jobs:
|
||||
release-rc:
|
||||
if: github.event_name == 'workflow_dispatch' || (github.event.pull_request.merged == true && contains(github.event.pull_request.labels.*.name, 'release:rc'))
|
||||
uses: QRun-IO/.github/.github/workflows/qbit-release-rc.yml@main
|
||||
if: github.event_name == 'workflow_dispatch' || github.event_name == 'repository_dispatch'
|
||||
|| (github.event_name == 'pull_request' && github.event.pull_request.merged
|
||||
== true && github.event.pull_request.base.ref == 'develop' && contains(github.event.pull_request.labels.*.name,
|
||||
'release:rc'))
|
||||
uses: QRun-IO/qqq-orb/.github/workflows/qbit-release-rc.yml@cc30f599e63c8e41629c99d23395bac1adb8bc44
|
||||
with:
|
||||
dry_run: ${{ github.event_name == 'workflow_dispatch' && inputs.dry_run }}
|
||||
dry_run: ${{ github.event_name == 'workflow_dispatch' && inputs.dry_run || false
|
||||
}}
|
||||
finalize: ${{ github.event_name == 'repository_dispatch' || (github.event_name
|
||||
== 'workflow_dispatch' && inputs.finalize) }}
|
||||
recover: ${{ github.event_name == 'workflow_dispatch' && inputs.recover || false
|
||||
}}
|
||||
circle_build: ${{ github.event_name == 'workflow_dispatch' && inputs.circle_build
|
||||
|| '' }}
|
||||
merge_sha: ${{ github.event_name == 'repository_dispatch' && github.event.client_payload.merge_sha
|
||||
|| inputs.merge_sha || '' }}
|
||||
bump_sha: ${{ github.event_name == 'repository_dispatch' && github.event.client_payload.bump_sha
|
||||
|| inputs.bump_sha || '' }}
|
||||
branch: ${{ github.event_name == 'repository_dispatch' && github.event.client_payload.branch
|
||||
|| inputs.branch || '' }}
|
||||
version: ${{ github.event_name == 'repository_dispatch' && github.event.client_payload.version
|
||||
|| inputs.version || '' }}
|
||||
secrets: inherit
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
profile: qbit
|
||||
orb_version: '0.8'
|
||||
default_branch: develop
|
||||
java_version: '21'
|
||||
browsers: true
|
||||
api_checks: false
|
||||
docs_only: false
|
||||
release_on_main: false
|
||||
release_tag_policy: stable
|
||||
test_branch_policy: non-release-no-integration
|
||||
publish:
|
||||
snapshot: true
|
||||
release_candidate: true
|
||||
release: true
|
||||
asciidoc: false
|
||||
release_completion: true
|
||||
+38
-1
@@ -4,6 +4,43 @@ All notable changes are documented here, following [Keep a Changelog](https://ke
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Added: a create date and a modify date on every table
|
||||
- Every table has a create date and a modify date: `DATE_TIME`, not editable, with QQQ's `CREATE_DATE` and `MODIFY_DATE` behaviors, in the columns `create_date` and `modify_date`. Seven tables did not have them: reveal grant, break-glass session, access log, wipe run, wipe marker, legal hold and audit key. Their fields are named `createDate` and `modifyDate`. Classification, policy and retention rule already had `create_date` and `modify_date`; they keep those field names, and the two fields are now not editable and have the behaviors.
|
||||
- A new row gets both dates, equal, in the insert that writes it. A changed row keeps its create date and gets a later modify date (for an edit that arrives over HTTP this holds from this release on: see the fix below). An update that names the create date itself still sets it: not editable is what the metadata tells a client. The access log and wipe runs are only ever inserted, so their dates stay equal. The access-log writer still runs one insert per row, with no other statement, lock or transaction.
|
||||
- **Upgrade: run the DDL first.** Before deploying this release on an existing database, run the last block of `docs/ddl/secured-data-postgres.sql` (from the line `-- Standard dates:` to the end). It adds the two nullable columns to the seven tables, defaults them to the current time and gives existing rows the row's own time. It rewrites no table and can be run while the release before this one is running, which goes on working with the columns present. This release does not run without them. See "Upgrading an existing database" in the README.
|
||||
- The dates have no classification, policy or assistant exposure of their own, and nothing that is signed or verified covers them. Rows written before the columns existed are unchanged apart from the two columns: wrapped data keys unwrap as before and audit tokens verify as before.
|
||||
- QQQ uses a field with the `MODIFY_DATE` behavior as the record version of its table. That now holds for every table of the QBit, classification, policy and retention rule included: on an update core sets the modify date itself, and an update that sends the version it read is refused (409) if the row has changed since. Updates that send no version, the QBit's own among them, behave as before. The QBit's own updates move the version all the same: a wipe, the scheduled one included, records its run on its retention rule, so an API client that reads a rule and edits it with that version after a wipe has run gets 409 and has to read the rule again.
|
||||
- On a live database, set a `lock_timeout` before running the upgrade block and run it again when a statement is cancelled (an `ALTER` waits behind an open transaction on its table, and other readers and writers wait behind it). On a large access log, run its backfill `UPDATE` in ranges of `id`, or leave it out: rows without the two dates are read and written like any others. The README has both.
|
||||
|
||||
### Fixed: an edit over HTTP was treated as a new row
|
||||
- The table customizer matched an update with its stored row by comparing ids of different types: the id of a request over HTTP is text, the stored id a number. An edit made through the API or the UI was therefore validated and stamped as an insert. Ids are now compared as text.
|
||||
- What that did, for an edit over HTTP: a classification, policy or retention rule got a new `create_date` on every edit. Releasing a legal hold overwrote when and by whom it was placed. Editing a classification while naming its table and field was refused as a second classification of the same field. Editing a retention rule without sending every field was refused. Editing a legal hold without sending its status failed with a server error; a client that sends only the changed fields of a table with a modify date does exactly that.
|
||||
|
||||
### Fixed: a reveal and the access-log writer waiting for each other
|
||||
- A reveal, or the start, end or expiry of a break-glass session, no longer deadlocks with a thread that asks for a classification while it holds another lock of this QBit. The access-log writer is such a thread: it holds the anomaly counters while it inserts a row, and that insert asks for classifications (it counts earlier rows and writes an audit, both queries with criteria). A reveal holds the runtime's monitor and then inserts its own access-log row. When both happened at once, neither finished, and neither did any later request, because every request asks for a classification. A person who opens a record with a masked field and reveals it straight away does both at once.
|
||||
- The rule rows a node keeps (classifications, active retention rules) have a lock of their own, held only while they are answered or read. Asking for a classification no longer takes the monitor that reveal and break-glass hold for their whole operation.
|
||||
|
||||
### Fixed: rule reads that ask for their own rows
|
||||
- Reading the rule rows a node keeps (classifications, active retention rules, policies) no longer recurses when code that runs inside that read asks for the same rows. Another QBit's virtual field value provider, or a post-query customizer, on a secured-data table that ran a query with filter criteria did exactly that: with one classification row present, every request that needed a classification ended in a `StackOverflowError`.
|
||||
- The QBit's system reads of its own tables (`SystemWrites.query`, the audit key lookup) name the stored fields of the table, so core runs no virtual field value provider inside them.
|
||||
- A question asked from inside a rule read is answered from the rows held when that read began (none before the first read) and starts no other read. Only the reading thread, inside the QBit's system read, can be given that answer; every request gets the rows the read returns. The same holds for a transaction's read of its own retention rule edits.
|
||||
- A rule read that fails is tried again by the next question instead of failing or recursing from then on.
|
||||
|
||||
### Fixed: access-log lifecycle
|
||||
- The access-log worker and JVM shutdown hook hold the logger weakly, so an instance the host drops (tests, reloads) can be collected; its worker stops at the next tick.
|
||||
- `withRegisterShutdownHook(false)` for hosts that call `SecuredDataRuntime.close()` themselves; `SecuredDataAccessLogger.isWorkerRunning()`.
|
||||
- Virtual (computed) fields resolve through the table classification instead of throwing (#18).
|
||||
- Idle access-log ticks open no context, so the worker never validates an unfinished host instance, and a failed tick no longer stops the worker (#18).
|
||||
|
||||
### Changed: UI API 1.6.0
|
||||
- UI API extension secured-data 1.1.0 (requires QQQ 4.1.0-RC.15, UI API 1.6.0): operationIds, standard error responses with BasicErrorResponseV1, extension tags, and retained SecuredDataErrorV1 schema deprecated since 1.1.0.
|
||||
|
||||
### Changed — direct core field access and audit protection
|
||||
- Remove all #1172/#1182 stand-ins and reflective bridges; use core field-access, classified-value token, audit protection, wipe flag and shredded-event APIs directly.
|
||||
- Register the resolver, key source and audit protector through core supplemental metadata.
|
||||
- Run core field-access integration and retention proof tests unconditionally.
|
||||
- Pin QQQ to `4.1.0-RC.7`, which ships field access (#1172) and audit value protection (#1182); all core stand-ins and reflective bridges are removed.
|
||||
|
||||
### Changed — RC.6 migration
|
||||
- Pin QQQ to 4.1.0-RC.6; use released classification, client-channel and table-feature APIs directly.
|
||||
- Fold UI API code and tests into the main build and remove the profile and reflective registration.
|
||||
@@ -15,7 +52,7 @@ All notable changes are documented here, following [Keep a Changelog](https://ke
|
||||
- Atomic wipe batches (fields, markers, key deletions, audits, access log and run row in one rollback-capable transaction), per-record and per-table legal holds, a Review/Result "Run wipe now" process and a daily scheduled run.
|
||||
- Per-record-field AES-GCM wrapped DEKs (AAD-bound) for crypto-shredding of audit tokens, `CHANGED_ONLY` audit treatment, and the audit-value protector.
|
||||
- App-home warning when known backup retention exceeds a rule's `age_days`; `withBackupRetentionDays` and `withArchiveSink` options; README retention section and the backups residual risk.
|
||||
- Tests: all actions, holds, rollback, Review/Result, schedule, permissions, wrap/unwrap, and (on the SECUREDATA snapshot) the section 15 canary and wipe-proof tests.
|
||||
- Tests: all actions, holds, rollback, Review/Result, schedule, permissions, wrap/unwrap, and the section 15 canary and wipe-proof tests.
|
||||
|
||||
### Fixed
|
||||
- The key source returned a DEK array it then zeroed; it now returns copies, with a regression test.
|
||||
|
||||
@@ -4,11 +4,11 @@ Phases (b), (c), (e) and (f) of [SECURED-DATA](https://github.com/QRun-IO/qqq/bl
|
||||
|
||||
## Compatibility
|
||||
|
||||
Java 21, Maven wrapper 3.9.11, **QQQ 4.1.0-RC.6**.
|
||||
Java 21, Maven wrapper 3.9.11, and **QQQ 4.1.0-RC.15** or later (UI API 1.6.0, field access #1172 and audit value protection #1182).
|
||||
|
||||
RC.6 supplies core classifications, AI metadata, client channels, table-feature permissions and the UI API extension points. These are used directly; the UI API and its contract test are part of the main build. The installed middleware jar provides `UiApiContract`, but no `UiApiContractAssertions` facade, so the contract test calls that released API directly.
|
||||
Core classifications, AI metadata, client channels, table-feature permissions and UI API extension points are used directly. The UI API and its contract test are part of the main build; the contract test calls `UiApiContract` directly.
|
||||
|
||||
Field access (#1172) and audit-value protection (#1182) are not in RC.6. Field-access stand-ins and `CoreFieldAccessBridge` remain until the first QQQ RC that ships both #1172 and #1182 (expected RC.8). RC.6 **does not enforce field tiers**. Integration tests can use `4.1.0-SECUREDATA-SNAPSHOT`.
|
||||
Field access (#1172), classified-value tokens and audit-value protection (#1182) use core types directly. The producer registers the resolver, key source and audit protector through core supplemental metadata; QQQ core enforces field tiers.
|
||||
|
||||
## Install and register
|
||||
|
||||
@@ -16,7 +16,7 @@ Field access (#1172) and audit-value protection (#1182) are not in RC.6. Field-a
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qbits</groupId>
|
||||
<artifactId>qbit-secured-data</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<version>0.1.0-RC.1</version>
|
||||
</dependency>
|
||||
```
|
||||
|
||||
@@ -30,7 +30,45 @@ new SecuredDataQBitProducer()
|
||||
|
||||
Register the host backend and application tables before producing the QBit. Enable core permissions (`qInstance.withEnforcePermissionsInCoreActions(true)`) at application entry points. Only one secured-data runtime is supported per instance. A namespace labels the QBit identity; table names remain fixed.
|
||||
|
||||
The host supplies database connection metadata. Physical table names and field backend names are the same snake_case names as the QQQ metadata; an RDBMS host may set `RDBMSTableBackendDetails.withTableName(table.getName())` through `withTableMetaDataCustomizer(...)`. Apply [the PostgreSQL 15+ DDL](docs/ddl/secured-data-postgres.sql) before serving requests. The same SQL is tested with H2 in PostgreSQL mode.
|
||||
The host supplies database connection metadata. Physical table names and field backend names are the same snake_case names as the QQQ metadata (the fields `createDate` and `modifyDate` are the columns `create_date` and `modify_date`); an RDBMS host may set `RDBMSTableBackendDetails.withTableName(table.getName())` through `withTableMetaDataCustomizer(...)`. Apply [the PostgreSQL 15+ DDL](docs/ddl/secured-data-postgres.sql) before serving requests. The same SQL is tested with H2 in PostgreSQL mode.
|
||||
|
||||
### Upgrading an existing database: create and modify dates
|
||||
|
||||
Every table has the columns `create_date` and `modify_date`, and the QBit reads and writes them on all ten tables. Seven tables were first created without them: `secured_data_reveal_grant`, `secured_data_break_glass`, `secured_data_access_log`, `secured_data_wipe_run`, `secured_data_wipe_marker`, `secured_data_legal_hold` and `secured_data_audit_key`.
|
||||
|
||||
Before deploying a release that has the two dates on every table, run the last block of [the DDL](docs/ddl/secured-data-postgres.sql) on the existing database: everything from the line `-- Standard dates:` to the end of the file. The order matters. The release before it runs unchanged once the columns are there. The release with the dates does not run without them: its reads of the seven tables fail, and with them every request that needs a field decision. The block does three things to each of the seven tables:
|
||||
|
||||
- It adds the two columns, nullable. That changes the catalog only; the table is not rewritten.
|
||||
- It gives each column a default of the current time, so a release that does not know the columns goes on inserting while both releases run.
|
||||
- It gives the rows that were already there the row's own time (below). The `UPDATE` touches only rows whose `create_date` is null and takes row locks only.
|
||||
|
||||
Every statement of the block can be run again and then changes nothing. Two things to plan for on a live database:
|
||||
|
||||
- **Locks.** Each `ALTER` takes a brief exclusive lock on its table. It waits behind any open transaction that has touched the table (one that has inserted a log row, for one), and every other reader and writer of the table then waits behind the `ALTER`. Set a lock timeout for the session first, and run the block again when a statement is cancelled:
|
||||
|
||||
```sql
|
||||
SET lock_timeout = '5s';
|
||||
```
|
||||
|
||||
- **A large access log.** The `UPDATE` of `secured_data_access_log` writes every existing row in one transaction. One measurement on PostgreSQL 16 with 2,000,000 rows: 24 s, and the table grew from 146 MB to 324 MB. On a large log run it in ranges of `id` instead, one range per transaction, up to the highest `id`:
|
||||
|
||||
```sql
|
||||
UPDATE secured_data_access_log SET create_date = created_at, modify_date = created_at WHERE create_date IS NULL AND id BETWEEN 1 AND 100000;
|
||||
```
|
||||
|
||||
Or leave it out. A row without the two dates is read and written like any other, and the columns are filled for every row inserted from then on.
|
||||
|
||||
| Table | `create_date` of an existing row | `modify_date` of an existing row |
|
||||
|---|---|---|
|
||||
| `secured_data_reveal_grant` | `granted_at` | `granted_at` |
|
||||
| `secured_data_break_glass` | `started_at` | `ended_at`, else `started_at` |
|
||||
| `secured_data_access_log` | `created_at` | `created_at` |
|
||||
| `secured_data_wipe_run` | `finished_at`, else `started_at` | the same |
|
||||
| `secured_data_wipe_marker` | `wiped_at` | `wiped_at` |
|
||||
| `secured_data_legal_hold` | `placed_at`, else the time of the upgrade | `released_at`, else `placed_at`, else the time of the upgrade |
|
||||
| `secured_data_audit_key` | `created_at` | `created_at` |
|
||||
|
||||
Nothing else changes in a row: wrapped data keys, search fingerprints and every other column are left as they are.
|
||||
|
||||
## Tables, screens and permissions
|
||||
|
||||
@@ -44,6 +82,12 @@ The host supplies database connection metadata. Physical table names and field b
|
||||
|
||||
Every table has audit rules, explicit record sections and CONFIDENTIAL code classification. The Secured Data app navigates to Classification, Policy, Access log and Break-glass session. Reveal grants are a read-only child list joined by `access_log_id`; no process or home widget appears in navigation. The classification target `(table_name, field_name)` is unique, including the null field used for a table-wide override.
|
||||
|
||||
Every table has a create date and a modify date: date-time fields that nobody edits, in the columns `create_date` and `modify_date`. The fields are named `createDate` and `modifyDate`. Classification, Policy and Retention rules had the two dates before the other tables did and keep the field names `create_date` and `modify_date`. A new row gets both, equal. A changed row keeps its create date and gets a later modify date. (Not editable is what the metadata tells a client, as everywhere in QQQ: an update that names the create date itself still sets it.) Every write of the QBit is a QQQ insert or update action, so the dates are in the one statement that writes the row, the access-log writer's insert included. The access log and wipe runs are only ever inserted, so their two dates stay equal.
|
||||
|
||||
The two dates have no classification of their own. They are CONFIDENTIAL with the rest of their table, are given the tier of its other fields, and are closed to the assistant with it. Nothing that is signed or verified covers them: a wrapped data key is bound to its table, field and record id, and the search fingerprints of a log row are made from the search values.
|
||||
|
||||
The modify date has QQQ's modify-date behavior, and QQQ uses such a field as the record version of its table. On an update core sets it to the current time (or one millisecond after the stored value, if that is later). When a caller sends the version it read, core refuses the update (409) if the row has changed since. The QBit's own updates send no version, but they move it: a wipe records its run on its retention rule, so a client that reads a rule and saves it with that version after a wipe has run is refused and has to read the rule again.
|
||||
|
||||
`secured_data.admin` gates configuration editing and activity reads through a standard QQQ custom permission checker. It gives no implicit access to classified fields on application tables. `secured_data.hasAccess` is the catalog base permission; the custom checker requires admin. Activity writes are refused for ordinary users even when they hold admin. Customizers also protect system-only writes, and update/delete capabilities are disabled on the access log, including system calls.
|
||||
|
||||
Both table features are registered for **all tables**: `secured_data_full` (Secured data: full) and `secured_data_reveal` (Secured data: reveal). This deliberate catalog choice supports new admin classification rows without a restart. Core's permission-base, READ prerequisite and NOT_PROTECTED semantics are preserved: NOT_PROTECTED application tables grant their features without an explicit permission. Use protected table permission rules when field policies must restrict users. Feature grants have no standard WRITE/admin implication.
|
||||
@@ -101,7 +145,7 @@ Policy/break-glass caches are bounded per instance and keyed by relevant user pe
|
||||
|
||||
The extra `search_value_fingerprints` TEXT column persists JSON arrays of HMAC-SHA256 fingerprints for distinct-value detection after restarts and across nodes. Use a shared secret key supplier on multi-node deployments; the default is a random per-JVM key, so historical fingerprints from another JVM/key cannot be compared reliably.
|
||||
|
||||
One daemon worker drains a bounded queue as a system session. Enqueueing does not wait for persistence. Full queues and failed writes warn without values and increment `getDroppedCount()`. The app can expose this counter later. Explicitly call the instance's `SecuredDataRuntime.close()` at host shutdown; a JVM shutdown hook also drains accepted rows. An abrupt process crash can lose queued rows.
|
||||
One daemon worker drains a bounded queue as a system session. Enqueueing does not wait for persistence. Full queues and failed writes warn without values and increment `getDroppedCount()`. The app can expose this counter later. Explicitly call the instance's `SecuredDataRuntime.close()` at host shutdown; a JVM shutdown hook also drains accepted rows unless `withRegisterShutdownHook(false)` turns it off (hosts that close the runtime themselves). Neither the worker nor the hook holds the instance strongly: an instance the host drops (tests, reloads) can be collected, and its worker stops at the next tick. An abrupt process crash can lose queued rows.
|
||||
|
||||
Flagged rows raise the optional alerts producer signal `secured_data.enumeration`, deduplicated by `secured_data.enumeration:<user>:<table>.<field>:<UTC date>`. RC.5 already provides `QAlerts`; without an installed sink it logs the signal. Its catalog validator rejects underscores in type names, so this mandated type is sent through the producer without catalog registration until that core restriction is reconciled. No values or fingerprints are sent to the alert sink.
|
||||
|
||||
@@ -121,7 +165,7 @@ Configure `.withSchedulerName("yourScheduler")` to register the hidden `secured_
|
||||
|
||||
## UI API extension
|
||||
|
||||
The `secured-data` extension is version **1.0.0**:
|
||||
The `secured-data` extension is version **1.1.0**:
|
||||
|
||||
- `POST /qqq/v1/qbit/secured-data/reveal`
|
||||
- `GET /qqq/v1/qbit/secured-data/reveal/options?tableName=&fieldName=`
|
||||
@@ -144,6 +188,7 @@ The classification field picker uses CUSTOM possible values, reading `table_name
|
||||
| `withFingerprintKeySupplier(Supplier<byte[]>)` | Random 32-byte JVM key; supplied key must be at least 16 bytes |
|
||||
| `withAccessLogQueueCapacity(int)` | 4096 rows |
|
||||
| `withAccessLogFlushIntervalMillis(long)` | 250 ms |
|
||||
| `withRegisterShutdownHook(boolean)` | true; JVM hook that drains the access log at shutdown |
|
||||
| `withExactMatchPerHour(int)` | 20; zero disables |
|
||||
| `withMissAlertConsecutive(int)` | 5; zero disables |
|
||||
| `withDistinctValueAlert(int)` | 15; zero disables |
|
||||
@@ -159,10 +204,9 @@ Configure before producing the QBit; runtime infrastructure and HMAC keys are ca
|
||||
|
||||
```powershell
|
||||
./mvnw.cmd -q -o clean verify
|
||||
./mvnw.cmd -q -o clean verify -Dqqq.snapshot.version=4.1.0-SECUREDATA-SNAPSHOT
|
||||
```
|
||||
|
||||
The direct suite uses memory and H2. `CoreFieldAccessBridgeIT` is included by Surefire and uses JUnit assumptions to skip unless the actual core resolver metadata is present. With the installed core snapshot it exercises Query/Get, policy tiers, masking, exact matches and outcomes, sorting denial, rate/entropy refusal and the assistant wall. Checkstyle and JaCoCo remain 70% instructions / 90% classes; stand-ins are not excluded.
|
||||
The suite uses memory and H2. `CoreFieldAccessIT` runs unconditionally through Surefire and exercises Query/Get, policy tiers, masking, exact matches and outcomes, sorting denial, rate/entropy refusal and the assistant wall. `RetentionProofTest` also runs unconditionally. Checkstyle and JaCoCo gates remain 70% instructions / 90% classes.
|
||||
|
||||
## Anomaly monitoring (phase e)
|
||||
|
||||
@@ -243,11 +287,11 @@ Each is read from a JVM property or the environment and is never logged. Losing
|
||||
|
||||
### Core hooks
|
||||
|
||||
Audit-value protection (QRun-IO/qqq#1182) and the wipe audit flag need core classes that are not in RC.6. On RC.6 the qbit uses marked stand-ins (`removeBy=RC.8`), writes value-free wipe audit details itself, and core does not tokenise ordinary audits. Run the build with `-Dqqq.snapshot.version=4.1.0-SECUREDATA-SNAPSHOT` to exercise the real hooks, including the section 15 canary and wipe-proof tests (`RetentionProofTest`), which skip themselves when the hooks are absent.
|
||||
Audit-value protection, wipe audit flags and shredded audit events use the core #1182 APIs directly. Core tokenises ordinary audits and writes value-free wipe details. The section 15 canary and wipe-proof tests (`RetentionProofTest`) are mandatory in the normal build.
|
||||
|
||||
## Remaining phases
|
||||
|
||||
RC.6 migration is complete; field-access and audit-token compatibility types remain until RC.8.
|
||||
Field-access and audit-token stand-ins and reflective bridges have been removed. The coordinator will replace the temporary snapshot pin with the first QQQ RC containing #1172 and #1182.
|
||||
|
||||
## License
|
||||
|
||||
|
||||
@@ -138,3 +138,64 @@ CREATE TABLE secured_data_audit_key (
|
||||
CREATE INDEX secured_data_hold_lookup ON secured_data_legal_hold (table_name, status, record_id);
|
||||
CREATE INDEX secured_data_retention_lookup ON secured_data_retention_rule (table_name, is_active);
|
||||
CREATE INDEX secured_data_wipe_rule_lookup ON secured_data_wipe_marker (rule_id);
|
||||
|
||||
-- Standard dates: create_date and modify_date on the seven tables created above without them.
|
||||
-- A new database runs the whole file. An existing database runs this block alone, BEFORE the release
|
||||
-- that writes the two columns is deployed. The columns are nullable and default to the current time, so
|
||||
-- a release that does not know them goes on inserting while both run. Adding a nullable column and
|
||||
-- setting a default change the catalog only (no table rewrite). Each UPDATE gives the rows that were
|
||||
-- already there the row's own time, once: it touches only rows whose create_date is still null and
|
||||
-- takes row locks only. Every statement can be run again and then changes nothing.
|
||||
--
|
||||
-- Locks. Each ALTER takes a brief exclusive lock on its table. It waits behind any open transaction
|
||||
-- that has touched the table (one that has inserted a log row, for one), and every other reader and
|
||||
-- writer of the table then waits behind the ALTER. On a live database set a lock timeout for the
|
||||
-- session first (SET lock_timeout = '5s') and run the block again when a statement is cancelled.
|
||||
--
|
||||
-- A large access log. The UPDATE of secured_data_access_log writes every existing row in one
|
||||
-- transaction. One measurement on PostgreSQL 16 with 2,000,000 rows: 24 s, and the table grew from
|
||||
-- 146 MB to 324 MB. On a large log run it in ranges of id instead, one range per transaction (add
|
||||
-- AND id BETWEEN 1 AND 100000 to its WHERE, then the next range, up to the highest id), or leave it
|
||||
-- out: a row without the two dates is read and written like any other, and the columns are filled
|
||||
-- for every row inserted from then on.
|
||||
ALTER TABLE secured_data_reveal_grant ADD COLUMN IF NOT EXISTS create_date TIMESTAMP WITH TIME ZONE;
|
||||
ALTER TABLE secured_data_reveal_grant ADD COLUMN IF NOT EXISTS modify_date TIMESTAMP WITH TIME ZONE;
|
||||
ALTER TABLE secured_data_reveal_grant ALTER COLUMN create_date SET DEFAULT CURRENT_TIMESTAMP;
|
||||
ALTER TABLE secured_data_reveal_grant ALTER COLUMN modify_date SET DEFAULT CURRENT_TIMESTAMP;
|
||||
UPDATE secured_data_reveal_grant SET create_date = granted_at, modify_date = granted_at WHERE create_date IS NULL;
|
||||
|
||||
ALTER TABLE secured_data_break_glass ADD COLUMN IF NOT EXISTS create_date TIMESTAMP WITH TIME ZONE;
|
||||
ALTER TABLE secured_data_break_glass ADD COLUMN IF NOT EXISTS modify_date TIMESTAMP WITH TIME ZONE;
|
||||
ALTER TABLE secured_data_break_glass ALTER COLUMN create_date SET DEFAULT CURRENT_TIMESTAMP;
|
||||
ALTER TABLE secured_data_break_glass ALTER COLUMN modify_date SET DEFAULT CURRENT_TIMESTAMP;
|
||||
UPDATE secured_data_break_glass SET create_date = started_at, modify_date = COALESCE(ended_at, started_at) WHERE create_date IS NULL;
|
||||
|
||||
ALTER TABLE secured_data_access_log ADD COLUMN IF NOT EXISTS create_date TIMESTAMP WITH TIME ZONE;
|
||||
ALTER TABLE secured_data_access_log ADD COLUMN IF NOT EXISTS modify_date TIMESTAMP WITH TIME ZONE;
|
||||
ALTER TABLE secured_data_access_log ALTER COLUMN create_date SET DEFAULT CURRENT_TIMESTAMP;
|
||||
ALTER TABLE secured_data_access_log ALTER COLUMN modify_date SET DEFAULT CURRENT_TIMESTAMP;
|
||||
UPDATE secured_data_access_log SET create_date = created_at, modify_date = created_at WHERE create_date IS NULL;
|
||||
|
||||
ALTER TABLE secured_data_wipe_run ADD COLUMN IF NOT EXISTS create_date TIMESTAMP WITH TIME ZONE;
|
||||
ALTER TABLE secured_data_wipe_run ADD COLUMN IF NOT EXISTS modify_date TIMESTAMP WITH TIME ZONE;
|
||||
ALTER TABLE secured_data_wipe_run ALTER COLUMN create_date SET DEFAULT CURRENT_TIMESTAMP;
|
||||
ALTER TABLE secured_data_wipe_run ALTER COLUMN modify_date SET DEFAULT CURRENT_TIMESTAMP;
|
||||
UPDATE secured_data_wipe_run SET create_date = COALESCE(finished_at, started_at), modify_date = COALESCE(finished_at, started_at) WHERE create_date IS NULL;
|
||||
|
||||
ALTER TABLE secured_data_wipe_marker ADD COLUMN IF NOT EXISTS create_date TIMESTAMP WITH TIME ZONE;
|
||||
ALTER TABLE secured_data_wipe_marker ADD COLUMN IF NOT EXISTS modify_date TIMESTAMP WITH TIME ZONE;
|
||||
ALTER TABLE secured_data_wipe_marker ALTER COLUMN create_date SET DEFAULT CURRENT_TIMESTAMP;
|
||||
ALTER TABLE secured_data_wipe_marker ALTER COLUMN modify_date SET DEFAULT CURRENT_TIMESTAMP;
|
||||
UPDATE secured_data_wipe_marker SET create_date = wiped_at, modify_date = wiped_at WHERE create_date IS NULL;
|
||||
|
||||
ALTER TABLE secured_data_legal_hold ADD COLUMN IF NOT EXISTS create_date TIMESTAMP WITH TIME ZONE;
|
||||
ALTER TABLE secured_data_legal_hold ADD COLUMN IF NOT EXISTS modify_date TIMESTAMP WITH TIME ZONE;
|
||||
ALTER TABLE secured_data_legal_hold ALTER COLUMN create_date SET DEFAULT CURRENT_TIMESTAMP;
|
||||
ALTER TABLE secured_data_legal_hold ALTER COLUMN modify_date SET DEFAULT CURRENT_TIMESTAMP;
|
||||
UPDATE secured_data_legal_hold SET create_date = COALESCE(placed_at, CURRENT_TIMESTAMP), modify_date = COALESCE(released_at, placed_at, CURRENT_TIMESTAMP) WHERE create_date IS NULL;
|
||||
|
||||
ALTER TABLE secured_data_audit_key ADD COLUMN IF NOT EXISTS create_date TIMESTAMP WITH TIME ZONE;
|
||||
ALTER TABLE secured_data_audit_key ADD COLUMN IF NOT EXISTS modify_date TIMESTAMP WITH TIME ZONE;
|
||||
ALTER TABLE secured_data_audit_key ALTER COLUMN create_date SET DEFAULT CURRENT_TIMESTAMP;
|
||||
ALTER TABLE secured_data_audit_key ALTER COLUMN modify_date SET DEFAULT CURRENT_TIMESTAMP;
|
||||
UPDATE secured_data_audit_key SET create_date = created_at, modify_date = created_at WHERE create_date IS NULL;
|
||||
@@ -22,9 +22,10 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
|
||||
<properties>
|
||||
<!-- Released APIs; fieldaccess and audit protection remain RC.7 stand-ins. -->
|
||||
<qqq.snapshot.version>4.1.0-RC.6</qqq.snapshot.version>
|
||||
<revision>1.0.0-SNAPSHOT</revision>
|
||||
<qqq.version>4.1.0-RC.26</qqq.version> <!-- feeds qbit-build-parent's qqq-bom-pom import -->
|
||||
<!-- QQQ 4.1.0-RC.15 ships UI API 1.6.0, field access and audit value protection -->
|
||||
<qqq.snapshot.version>4.1.0-RC.26</qqq.snapshot.version>
|
||||
<revision>0.1.0-SNAPSHOT</revision>
|
||||
<maven.compiler.source>21</maven.compiler.source>
|
||||
<maven.compiler.target>21</maven.compiler.target>
|
||||
<jacoco.version>0.8.15</jacoco.version>
|
||||
@@ -34,7 +35,7 @@
|
||||
<parent>
|
||||
<groupId>com.kingsrook</groupId>
|
||||
<artifactId>qbit-build-parent</artifactId>
|
||||
<version>2.0.0</version>
|
||||
<version>2.2.1</version>
|
||||
</parent>
|
||||
|
||||
<groupId>com.kingsrook.qbits</groupId>
|
||||
@@ -92,7 +93,7 @@
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qqq</groupId>
|
||||
<artifactId>qqq-frontend-next</artifactId>
|
||||
<version>1.0.0-RC.14</version>
|
||||
<version>1.0.0-RC.38</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
|
||||
@@ -1,220 +0,0 @@
|
||||
/*
|
||||
* QQQ - Low-code Application Framework for Engineers.
|
||||
* Copyright (C) 2021-2025. Kingsrook, LLC
|
||||
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
|
||||
* contact@kingsrook.com
|
||||
* https://github.com/Kingsrook/
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.secureddata;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Proxy;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import com.kingsrook.qbits.secureddata.standin.ClassifiedValueKeySource;
|
||||
import com.kingsrook.qbits.secureddata.standin.ClassifiedValueTokens;
|
||||
import com.kingsrook.qbits.secureddata.standin.DMLType;
|
||||
import com.kingsrook.qqq.backend.core.actions.QBackendTransaction;
|
||||
import com.kingsrook.qqq.backend.core.actions.audits.AuditAction;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QException;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.audits.AuditInput;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.ActionFlag;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.update.UpdateInput;
|
||||
import com.kingsrook.qqq.backend.core.model.data.QRecord;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
|
||||
|
||||
/*******************************************************************************
|
||||
** A single reflection boundary for #1182, failing closed for incompatible hooks.
|
||||
*******************************************************************************/
|
||||
// STAND-IN(core=QRun-IO/qqq#1182, removeBy=RC.8)
|
||||
public final class CoreAuditBridge
|
||||
{
|
||||
private static final String TOKENS = "com.kingsrook.qqq.backend.core.actions.permissions.fieldaccess.";
|
||||
private static final String AUDITS = "com.kingsrook.qqq.backend.core.actions.audits.";
|
||||
|
||||
/*******************************************************************************
|
||||
** Utility class.
|
||||
*******************************************************************************/
|
||||
private CoreAuditBridge()
|
||||
{
|
||||
}
|
||||
|
||||
/*******************************************************************************
|
||||
** Core hook availability (RC.6 has none).
|
||||
*******************************************************************************/
|
||||
public static boolean available()
|
||||
{
|
||||
try
|
||||
{
|
||||
Class.forName(TOKENS + "ClassifiedValueTokens");
|
||||
return (true);
|
||||
}
|
||||
catch(ClassNotFoundException expected)
|
||||
{
|
||||
return (false);
|
||||
}
|
||||
}
|
||||
|
||||
/*******************************************************************************
|
||||
** Register exact #1182 contracts when present; no silent partial registration.
|
||||
*******************************************************************************/
|
||||
public static void register(QInstance instance, SecuredDataRuntime runtime)
|
||||
{
|
||||
if(!available())
|
||||
{
|
||||
return;
|
||||
}
|
||||
try
|
||||
{
|
||||
Class<?> contract = Class.forName(TOKENS + "ClassifiedValueKeySource");
|
||||
Object keyProxy = Proxy.newProxyInstance(contract.getClassLoader(), new Class<?>[] {contract}, (self, method, args) ->
|
||||
{
|
||||
if(method.getDeclaringClass() == Object.class)
|
||||
{
|
||||
return (objectMethod(self, method.getName(), args));
|
||||
}
|
||||
Optional<ClassifiedValueKeySource.KeyAndId> key = switch(method.getName())
|
||||
{
|
||||
case "instanceKey" -> runtime.keys().instanceKey();
|
||||
case "keyForRecordField" -> runtime.keys().keyForRecordField((String) args[0], (String) args[1], (Serializable) args[2], (Boolean) args[3]);
|
||||
default -> throw new UnsupportedOperationException(method.getName());
|
||||
};
|
||||
return (key.isEmpty() ? Optional.empty() : Optional.of(Class.forName(TOKENS + "ClassifiedValueKeySource$KeyAndId")
|
||||
.getConstructor(byte[].class, String.class).newInstance(key.get().key(), key.get().id())));
|
||||
});
|
||||
Class<?> metadata = Class.forName(TOKENS + "ClassifiedValueKeySourceMetaData");
|
||||
Object registry = metadata.getMethod("ofOrWithNew", QInstance.class).invoke(null, instance);
|
||||
metadata.getMethod("withKeySourceInstance", contract).invoke(registry, keyProxy);
|
||||
SecuredDataAuditProtector protector = new SecuredDataAuditProtector();
|
||||
Class<?> auditContract = Class.forName(AUDITS + "AuditValueProtectorInterface");
|
||||
Object auditProxy = Proxy.newProxyInstance(auditContract.getClassLoader(), new Class<?>[] {auditContract}, (self, method, args) ->
|
||||
{
|
||||
if(method.getDeclaringClass() == Object.class)
|
||||
{
|
||||
return (objectMethod(self, method.getName(), args));
|
||||
}
|
||||
if("classificationOf".equals(method.getName()))
|
||||
{
|
||||
return (protector.classificationOf((QTableMetaData) args[0], (QFieldMetaData) args[1]));
|
||||
}
|
||||
if(!"protect".equals(method.getName()))
|
||||
{
|
||||
throw (new UnsupportedOperationException(method.getName()));
|
||||
}
|
||||
var values = protector.protect((QTableMetaData) args[0], (QFieldMetaData) args[1], (Serializable) args[2], (Serializable) args[3], (Serializable) args[4], DMLType.valueOf(args[5].toString()));
|
||||
return (Class.forName(AUDITS + "ProtectedAuditValues").getConstructor(String.class, String.class, String.class)
|
||||
.newInstance(values.oldToken(), values.newToken(), values.message()));
|
||||
});
|
||||
metadata = Class.forName(AUDITS + "AuditValueProtectionMetaData");
|
||||
registry = metadata.getMethod("ofOrWithNew", QInstance.class).invoke(null, instance);
|
||||
metadata.getMethod("withProtectorInstance", auditContract).invoke(registry, auditProxy);
|
||||
}
|
||||
catch(ReflectiveOperationException e)
|
||||
{
|
||||
throw (new IllegalStateException("Unable to register core audit protection", e));
|
||||
}
|
||||
}
|
||||
|
||||
/*******************************************************************************
|
||||
** Stable object behavior for registered service proxies.
|
||||
*******************************************************************************/
|
||||
private static Object objectMethod(Object self, String name, Object[] args)
|
||||
{
|
||||
return (switch(name)
|
||||
{
|
||||
case "toString" -> "Secured-data audit bridge";
|
||||
case "hashCode" -> System.identityHashCode(self);
|
||||
case "equals" -> self == args[0];
|
||||
default -> throw new UnsupportedOperationException(name);
|
||||
});
|
||||
}
|
||||
|
||||
/*******************************************************************************
|
||||
** Delegate to the installed core helper, with contract-identical RC.6 fallback.
|
||||
*******************************************************************************/
|
||||
public static String token(QTableMetaData table, QFieldMetaData field, Serializable pk, Serializable value)
|
||||
{
|
||||
if(!available())
|
||||
{
|
||||
return (ClassifiedValueTokens.forRecordField(table, field, pk, value));
|
||||
}
|
||||
try
|
||||
{
|
||||
return ((String) Class.forName(TOKENS + "ClassifiedValueTokens").getMethod("forRecordField", QTableMetaData.class, QFieldMetaData.class, Serializable.class, Serializable.class)
|
||||
.invoke(null, table, field, pk, value));
|
||||
}
|
||||
catch(InvocationTargetException e)
|
||||
{
|
||||
throw (new IllegalStateException("Classified token creation failed"));
|
||||
}
|
||||
catch(ReflectiveOperationException e)
|
||||
{
|
||||
throw (new IllegalStateException("Incompatible core token API", e));
|
||||
}
|
||||
}
|
||||
|
||||
/*******************************************************************************
|
||||
** Real WipeAuditFlag on snapshot; RC.6 uses a value-free explicit audit below.
|
||||
*******************************************************************************/
|
||||
public static void flag(UpdateInput input, String ruleId)
|
||||
{
|
||||
if(!available())
|
||||
{
|
||||
input.setOmitDmlAudit(true);
|
||||
return;
|
||||
}
|
||||
try
|
||||
{
|
||||
ActionFlag flag = (ActionFlag) Class.forName("com.kingsrook.qqq.backend.core.model.actions.tables.WipeAuditFlag").getConstructor(String.class).newInstance(ruleId);
|
||||
input.setFlags(Set.of(flag));
|
||||
}
|
||||
catch(ReflectiveOperationException e)
|
||||
{
|
||||
throw (new IllegalStateException("Incompatible core wipe API", e));
|
||||
}
|
||||
}
|
||||
|
||||
/*******************************************************************************
|
||||
** Append immutable value-free audit evidence in the batch transaction.
|
||||
*******************************************************************************/
|
||||
public static void detail(QTableMetaData table, Serializable pk, String field, String ruleId, boolean shredded, QBackendTransaction transaction) throws QException
|
||||
{
|
||||
if(shredded && available())
|
||||
{
|
||||
try
|
||||
{
|
||||
Class.forName(AUDITS + "AuditShreddedEvent").getMethod("shreddedDetail", QTableMetaData.class, Serializable.class, QFieldMetaData.class, String.class, QBackendTransaction.class)
|
||||
.invoke(null, table, pk, table.getField(field), ruleId, transaction);
|
||||
return;
|
||||
}
|
||||
catch(ReflectiveOperationException e)
|
||||
{
|
||||
throw (new QException("Unable to append shredded audit detail"));
|
||||
}
|
||||
}
|
||||
String message = (shredded ? "Audit values shredded" : "Wiped") + " per policy";
|
||||
QRecord detail = new QRecord().withValue("fieldName", field).withValue("newValue", (shredded ? "shredded:v1:" : "wiped:v1:") + ruleId).withValue("message", message);
|
||||
AuditInput input = new AuditInput();
|
||||
input.setTransaction(transaction);
|
||||
AuditAction.appendToInput(input, table.getName(), pk, AuditAction.getRecordSecurityKeyValues(table,
|
||||
new QRecord().withValue(table.getPrimaryKeyField(), pk), Optional.empty()), message, List.of(detail));
|
||||
new AuditAction().execute(input);
|
||||
}
|
||||
}
|
||||
@@ -1,167 +0,0 @@
|
||||
/*
|
||||
* QQQ - Low-code Application Framework for Engineers.
|
||||
* Copyright (C) 2021-2025. Kingsrook, LLC
|
||||
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
|
||||
* contact@kingsrook.com
|
||||
* https://github.com/Kingsrook/
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.secureddata;
|
||||
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Proxy;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import com.kingsrook.qbits.secureddata.standin.FieldAccessDecision;
|
||||
import com.kingsrook.qbits.secureddata.standin.FieldAccessEvent;
|
||||
import com.kingsrook.qbits.secureddata.standin.FieldAccessEventType;
|
||||
import com.kingsrook.qbits.secureddata.standin.FieldAccessOutcome;
|
||||
import com.kingsrook.qbits.secureddata.standin.FieldAccessResolverInterface;
|
||||
import com.kingsrook.qqq.backend.core.logging.QLogger;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The only boundary between the temporary field-access API and unreleased core.
|
||||
*******************************************************************************/
|
||||
// STAND-IN(core=QRun-IO/qqq#1172, removeBy=RC.8)
|
||||
public final class CoreFieldAccessBridge
|
||||
{
|
||||
private static final String PACKAGE = "com.kingsrook.qqq.backend.core.actions.permissions.fieldaccess.";
|
||||
private static final QLogger LOG = QLogger.getLogger(CoreFieldAccessBridge.class);
|
||||
private static final AtomicBoolean WARNED = new AtomicBoolean();
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Utility class.
|
||||
*******************************************************************************/
|
||||
private CoreFieldAccessBridge()
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Register only when core can actually enforce field access.
|
||||
*******************************************************************************/
|
||||
public static boolean register(QInstance instance, FieldAccessResolverInterface resolver)
|
||||
{
|
||||
try
|
||||
{
|
||||
Class<?> metadata = Class.forName(PACKAGE + "FieldAccessResolverMetaData");
|
||||
Class<?> contract = Class.forName(PACKAGE + "FieldAccessResolverInterface");
|
||||
Object proxy = Proxy.newProxyInstance(contract.getClassLoader(), new Class<?>[] {contract}, (self, method, args) ->
|
||||
{
|
||||
return (switch(method.getName())
|
||||
{
|
||||
case "resolve" -> decision(resolver.resolve((QTableMetaData) args[0], (QFieldMetaData) args[1]));
|
||||
case "getAccessFingerprint" -> resolver.getAccessFingerprint();
|
||||
case "isRevealActive" -> resolver.isRevealActive((String) args[0], (String) args[1], (Serializable) args[2]);
|
||||
case "fingerprintSearchValue" -> resolver.fingerprintSearchValue((Serializable) args[0]);
|
||||
case "checkExactMatch" ->
|
||||
{
|
||||
resolver.checkExactMatch(event(args[0]));
|
||||
yield null;
|
||||
}
|
||||
case "onAccess" ->
|
||||
{
|
||||
resolver.onAccess(event(args[0]));
|
||||
yield null;
|
||||
}
|
||||
case "toString" -> "SecuredData core bridge";
|
||||
case "hashCode" -> System.identityHashCode(self);
|
||||
case "equals" -> self == args[0];
|
||||
default -> throw new UnsupportedOperationException(method.getName());
|
||||
});
|
||||
});
|
||||
Object registry = metadata.getMethod("ofOrWithNew", QInstance.class).invoke(null, instance);
|
||||
metadata.getMethod("withResolverInstance", contract).invoke(registry, proxy);
|
||||
return (true);
|
||||
}
|
||||
catch(ClassNotFoundException e)
|
||||
{
|
||||
if(WARNED.compareAndSet(false, true))
|
||||
{
|
||||
LOG.info("Secured-data field enforcement needs QQQ RC.6+; policy and access-log services are available.");
|
||||
}
|
||||
return (false);
|
||||
}
|
||||
catch(ReflectiveOperationException e)
|
||||
{
|
||||
throw (new IllegalStateException("Core field-access API is incompatible", unwrap(e)));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Construct the core record by its declared component types and enum names.
|
||||
*******************************************************************************/
|
||||
private static Object decision(FieldAccessDecision decision) throws ReflectiveOperationException
|
||||
{
|
||||
Class<?> type = Class.forName(PACKAGE + "FieldAccessDecision");
|
||||
Class<?> tier = type.getRecordComponents()[0].getType();
|
||||
Class<?> mask = type.getRecordComponents()[1].getType();
|
||||
return (type.getConstructor(tier, mask, String.class, boolean.class).newInstance(
|
||||
enumValue(tier, decision.tier().name()), decision.maskStyle() == null ? null : enumValue(mask, decision.maskStyle().name()),
|
||||
decision.reason(), decision.exactMatchAllowed()));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Convert enum types without sharing class identity across the bridge.
|
||||
*******************************************************************************/
|
||||
private static Object enumValue(Class<?> type, String name) throws ReflectiveOperationException
|
||||
{
|
||||
return (type.getMethod("valueOf", String.class).invoke(null, name));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Events carry identifiers and keyed fingerprints, never search literals.
|
||||
*******************************************************************************/
|
||||
@SuppressWarnings("unchecked")
|
||||
private static FieldAccessEvent event(Object source) throws ReflectiveOperationException
|
||||
{
|
||||
Class<?> type = source.getClass();
|
||||
Object outcome = type.getMethod("getOutcome").invoke(source);
|
||||
return (new FieldAccessEvent()
|
||||
.withType(FieldAccessEventType.valueOf(type.getMethod("getType").invoke(source).toString()))
|
||||
.withTableName((String) type.getMethod("getTableName").invoke(source))
|
||||
.withFieldNames((List<String>) type.getMethod("getFieldNames").invoke(source))
|
||||
.withPrimaryKeys((List<Serializable>) type.getMethod("getPrimaryKeys").invoke(source))
|
||||
.withRecordCount((Integer) type.getMethod("getRecordCount").invoke(source))
|
||||
.withActionName((String) type.getMethod("getActionName").invoke(source))
|
||||
.withOutcome(outcome == null ? null : FieldAccessOutcome.valueOf(outcome.toString()))
|
||||
.withSearchValueFingerprints((List<String>) type.getMethod("getSearchValueFingerprints").invoke(source)));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Preserve the startup failure, including duplicate resolver registration.
|
||||
*******************************************************************************/
|
||||
private static Throwable unwrap(ReflectiveOperationException exception)
|
||||
{
|
||||
return (exception instanceof InvocationTargetException invocation ? invocation.getCause() : exception);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
/*
|
||||
* QQQ - Low-code Application Framework for Engineers.
|
||||
* Copyright (C) 2021-2025. Kingsrook, LLC
|
||||
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
|
||||
* contact@kingsrook.com
|
||||
* https://github.com/Kingsrook/
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.secureddata;
|
||||
|
||||
|
||||
import java.util.List;
|
||||
import java.util.function.Supplier;
|
||||
import com.kingsrook.qqq.backend.core.model.data.QRecord;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** One kind of rule rows a node keeps in memory (classifications, policies or
|
||||
** active retention rules): read once per version, never used unread past
|
||||
** SecuredDataRuntime.MAX_RULE_AGE, and safe against a read that asks for the
|
||||
** same rows again.
|
||||
**
|
||||
** Not synchronized: every call must be made holding the owner's lock (the
|
||||
** runtime's rule lock for classifications and retention rules, the resolver's
|
||||
** monitor for policies). That lock is what makes the re-entry answer below
|
||||
** private to one thread: while a read is running, only the thread running it
|
||||
** can get in here; every other thread waits for the lock and is given the rows
|
||||
** that read returns.
|
||||
**
|
||||
** Re-entry: reading rule rows is itself a query, and anything that runs inside
|
||||
** it (a table customizer, a record-security lookup, a value provider) may ask a
|
||||
** question that needs the very rows being read. Such a nested question is
|
||||
** answered with the rows this node held when the read began - the answer every
|
||||
** request was given until now, and no rows before the first read - and never
|
||||
** starts another read. The request that started the read gets the new rows.
|
||||
**
|
||||
** Failure: a read that throws leaves the previous rows and version in place
|
||||
** and is not remembered, so the next question reads again. The previous rows
|
||||
** are never handed to a request in place of rows that could not be read.
|
||||
*******************************************************************************/
|
||||
final class RuleRows
|
||||
{
|
||||
private List<QRecord> rows = List.of();
|
||||
private long version;
|
||||
private long loadedAt;
|
||||
private boolean loaded;
|
||||
private boolean reading;
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The rows of this version, reading them when the rows held are of another
|
||||
** version, too old, or were never read.
|
||||
**
|
||||
** @param currentVersion the owner's invalidation clock, read by the caller
|
||||
** before this call: a change during the read leaves a
|
||||
** version that no longer matches, so the next question
|
||||
** reads again
|
||||
** @param read the query; whatever it throws is thrown to the caller
|
||||
*******************************************************************************/
|
||||
List<QRecord> get(long currentVersion, Supplier<List<QRecord>> read)
|
||||
{
|
||||
if(loaded && version == currentVersion && !SecuredDataRuntime.tooOld(loadedAt))
|
||||
{
|
||||
return (rows);
|
||||
}
|
||||
if(reading)
|
||||
{
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
// the read that is running on this thread asked for its own rows: give //
|
||||
// it the rows held when it began, and do not start another read //
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
return (rows);
|
||||
}
|
||||
reading = true;
|
||||
try
|
||||
{
|
||||
long startedAt = System.nanoTime();
|
||||
List<QRecord> fresh = List.copyOf(read.get());
|
||||
rows = fresh;
|
||||
version = currentVersion;
|
||||
loadedAt = startedAt;
|
||||
loaded = true;
|
||||
}
|
||||
finally
|
||||
{
|
||||
reading = false;
|
||||
}
|
||||
return (rows);
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,7 @@
|
||||
package com.kingsrook.qbits.secureddata;
|
||||
|
||||
|
||||
import java.lang.ref.WeakReference;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.ArrayDeque;
|
||||
@@ -38,11 +39,11 @@ import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import com.kingsrook.qbits.secureddata.metadata.SecuredDataTables;
|
||||
import com.kingsrook.qbits.secureddata.standin.FieldAccessEvent;
|
||||
import com.kingsrook.qbits.secureddata.standin.FieldAccessEventType;
|
||||
import com.kingsrook.qbits.secureddata.standin.FieldAccessOutcome;
|
||||
import com.kingsrook.qbits.secureddata.support.SecuredDataMetadata;
|
||||
import com.kingsrook.qbits.secureddata.support.SystemWrites;
|
||||
import com.kingsrook.qqq.backend.core.actions.permissions.fieldaccess.FieldAccessEvent;
|
||||
import com.kingsrook.qqq.backend.core.actions.permissions.fieldaccess.FieldAccessEventType;
|
||||
import com.kingsrook.qqq.backend.core.actions.permissions.fieldaccess.FieldAccessOutcome;
|
||||
import com.kingsrook.qqq.backend.core.alerts.AlertSignal;
|
||||
import com.kingsrook.qqq.backend.core.alerts.QAlerts;
|
||||
import com.kingsrook.qqq.backend.core.context.CapturedContext;
|
||||
@@ -60,7 +61,6 @@ import com.kingsrook.qqq.backend.core.model.session.QSession;
|
||||
import com.kingsrook.qqq.backend.core.model.session.QSystemUserSession;
|
||||
import com.kingsrook.qqq.backend.core.utils.JsonUtils;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Bounded asynchronous value-free audit, with persisted and local enumeration accounting.
|
||||
*******************************************************************************/
|
||||
@@ -91,7 +91,12 @@ public class SecuredDataAccessLogger implements AutoCloseable
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** One daemon drains this instance's queue; the JVM hook flushes on shutdown.
|
||||
** One daemon drains this instance's queue; the optional JVM hook flushes on
|
||||
** shutdown. Neither holds the logger strongly: once the host drops its
|
||||
** instance (a test, a reloaded instance), the logger, runtime and instance
|
||||
** can be collected, and the worker stops at its next tick. Hosts that close
|
||||
** the runtime themselves can turn the hook off
|
||||
** (SecuredDataQBitConfig.withRegisterShutdownHook(false)).
|
||||
*******************************************************************************/
|
||||
public SecuredDataAccessLogger(QInstance instance, SecuredDataRuntime runtime)
|
||||
{
|
||||
@@ -104,10 +109,69 @@ public class SecuredDataAccessLogger implements AutoCloseable
|
||||
thread.setDaemon(true);
|
||||
return (thread);
|
||||
});
|
||||
WeakReference<SecuredDataAccessLogger> self = new WeakReference<>(this);
|
||||
long interval = runtime.config().getAccessLogFlushIntervalMillis();
|
||||
worker.scheduleWithFixedDelay(this::flush, interval, interval, TimeUnit.MILLISECONDS);
|
||||
shutdownHook = new Thread(this::close, "secured-data-access-log-shutdown");
|
||||
Runtime.getRuntime().addShutdownHook(shutdownHook);
|
||||
worker.scheduleWithFixedDelay(new WeakTick(self, worker), interval, interval, TimeUnit.MILLISECONDS);
|
||||
shutdownHook = runtime.config().getRegisterShutdownHook() ? new Thread(new WeakClose(self), "secured-data-access-log-shutdown") : null;
|
||||
if(shutdownHook != null)
|
||||
{
|
||||
Runtime.getRuntime().addShutdownHook(shutdownHook);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The worker's task, holding the logger weakly: when the logger has been
|
||||
** collected the worker shuts itself down.
|
||||
*******************************************************************************/
|
||||
private record WeakTick(WeakReference<SecuredDataAccessLogger> logger, ScheduledExecutorService worker) implements Runnable
|
||||
{
|
||||
/*******************************************************************************
|
||||
** Drain, or stop once the logger is gone.
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public void run()
|
||||
{
|
||||
SecuredDataAccessLogger target = logger.get();
|
||||
if(target == null)
|
||||
{
|
||||
worker.shutdown();
|
||||
return;
|
||||
}
|
||||
target.scheduledFlush();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The JVM shutdown hook, holding the logger weakly.
|
||||
*******************************************************************************/
|
||||
private record WeakClose(WeakReference<SecuredDataAccessLogger> logger) implements Runnable
|
||||
{
|
||||
/*******************************************************************************
|
||||
** Drain accepted rows at JVM shutdown, if the logger still exists.
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public void run()
|
||||
{
|
||||
SecuredDataAccessLogger target = logger.get();
|
||||
if(target != null)
|
||||
{
|
||||
target.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Whether the background worker is still running (false after close).
|
||||
*******************************************************************************/
|
||||
public boolean isWorkerRunning()
|
||||
{
|
||||
return (!worker.isShutdown());
|
||||
}
|
||||
|
||||
|
||||
@@ -333,13 +397,38 @@ public class SecuredDataAccessLogger implements AutoCloseable
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The worker's tick. An exception would cancel every later run of a
|
||||
** scheduled task, so a failed drain is logged (value-free) and retried on
|
||||
** the next tick; the rows stay queued.
|
||||
*******************************************************************************/
|
||||
void scheduledFlush()
|
||||
{
|
||||
try
|
||||
{
|
||||
flush();
|
||||
}
|
||||
catch(RuntimeException e)
|
||||
{
|
||||
LOG.warn("Unable to drain the secured-data access log; retrying on the next tick");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Drain safely both from the worker and explicit test/host shutdown calls.
|
||||
** An empty queue opens no context: QContext validates an unvalidated
|
||||
** instance, and the worker starts while the host is still building it.
|
||||
*******************************************************************************/
|
||||
public void flush()
|
||||
{
|
||||
synchronized(flushLock)
|
||||
{
|
||||
if(queue.isEmpty())
|
||||
{
|
||||
return;
|
||||
}
|
||||
QContext.withTemporaryContext(new CapturedContext(instance, new QSystemUserSession(instance)), () ->
|
||||
{
|
||||
PendingLog pending;
|
||||
@@ -464,7 +553,7 @@ public class SecuredDataAccessLogger implements AutoCloseable
|
||||
}
|
||||
worker.shutdown();
|
||||
flush();
|
||||
if(Thread.currentThread() != shutdownHook)
|
||||
if(shutdownHook != null && Thread.currentThread() != shutdownHook)
|
||||
{
|
||||
try
|
||||
{
|
||||
|
||||
@@ -22,10 +22,11 @@ package com.kingsrook.qbits.secureddata;
|
||||
|
||||
import java.io.Serializable;
|
||||
import com.kingsrook.qbits.secureddata.retention.RetentionRules;
|
||||
import com.kingsrook.qbits.secureddata.standin.AuditValueProtectorInterface;
|
||||
import com.kingsrook.qbits.secureddata.standin.DMLType;
|
||||
import com.kingsrook.qbits.secureddata.standin.ProtectedAuditValues;
|
||||
import com.kingsrook.qqq.backend.core.actions.ai.DataClassification;
|
||||
import com.kingsrook.qqq.backend.core.actions.audits.AuditValueProtectorInterface;
|
||||
import com.kingsrook.qqq.backend.core.actions.audits.DMLAuditAction.DMLType;
|
||||
import com.kingsrook.qqq.backend.core.actions.audits.ProtectedAuditValues;
|
||||
import com.kingsrook.qqq.backend.core.actions.permissions.fieldaccess.ClassifiedValueTokens;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
|
||||
|
||||
@@ -56,7 +57,7 @@ public final class SecuredDataAuditProtector implements AuditValueProtectorInter
|
||||
{
|
||||
boolean changed = RetentionRules.changedOnly(table.getName(), field.getName());
|
||||
String message = (oldValue == null ? "Set " : newValue == null ? "Removed " : "Changed ") + field.getLabel();
|
||||
return (new ProtectedAuditValues(oldValue == null ? null : changed ? "changed:v1" : CoreAuditBridge.token(table, field, pk, oldValue),
|
||||
newValue == null ? null : changed ? "changed:v1" : CoreAuditBridge.token(table, field, pk, newValue), message));
|
||||
return (new ProtectedAuditValues(oldValue == null ? null : changed ? "changed:v1" : ClassifiedValueTokens.forRecordField(table, field, pk, oldValue),
|
||||
newValue == null ? null : changed ? "changed:v1" : ClassifiedValueTokens.forRecordField(table, field, pk, newValue), message));
|
||||
}
|
||||
}
|
||||
@@ -54,7 +54,11 @@ public final class SecuredDataClassifications
|
||||
{
|
||||
return (DataClassification.valueOf(row.getValueString("classification")));
|
||||
}
|
||||
QFieldMetaData field = table.getField(fieldName);
|
||||
////////////////////////////////////////////////////////////////////
|
||||
// getFields, not getField: a virtual field is not in the map and //
|
||||
// getField throws, while it still takes the table classification //
|
||||
////////////////////////////////////////////////////////////////////
|
||||
QFieldMetaData field = table.getFields() == null || fieldName == null ? null : table.getFields().get(fieldName);
|
||||
DataClassification classification = field == null ? null : SecuredDataMetadata.classification(table, field);
|
||||
return (classification == null ? SecuredDataMetadata.classification(table, null) : classification);
|
||||
}
|
||||
|
||||
@@ -37,9 +37,10 @@ import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import com.kingsrook.qbits.secureddata.metadata.SecuredDataTables;
|
||||
import com.kingsrook.qbits.secureddata.retention.RetentionRules;
|
||||
import com.kingsrook.qbits.secureddata.standin.ClassifiedValueKeySource;
|
||||
import com.kingsrook.qbits.secureddata.support.SystemWrites;
|
||||
import com.kingsrook.qqq.backend.core.actions.ai.DataClassification;
|
||||
import com.kingsrook.qqq.backend.core.actions.permissions.fieldaccess.ClassifiedValueKeySource;
|
||||
import com.kingsrook.qqq.backend.core.actions.permissions.fieldaccess.ClassifiedValueTokens;
|
||||
import com.kingsrook.qqq.backend.core.actions.tables.QueryAction;
|
||||
import com.kingsrook.qqq.backend.core.context.QContext;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QException;
|
||||
@@ -123,7 +124,7 @@ public final class SecuredDataKeySource implements ClassifiedValueKeySource, Aut
|
||||
try
|
||||
{
|
||||
List<QRecord> rows = SystemWrites.call(() -> new QueryAction().execute(new QueryInput(SecuredDataTables.AUDIT_KEY)
|
||||
.withFilter(recordField(table, field, pk)).withShouldOmitHiddenFields(false)
|
||||
.withFilter(recordField(table, field, pk)).withShouldOmitHiddenFields(false).withFieldNamesToInclude(SystemWrites.storedFields(SecuredDataTables.AUDIT_KEY))
|
||||
.withTransaction(QContext.getQBackendTransaction())).getRecords());
|
||||
if(rows.isEmpty())
|
||||
{
|
||||
@@ -280,7 +281,7 @@ public final class SecuredDataKeySource implements ClassifiedValueKeySource, Aut
|
||||
instanceOnly.set(true);
|
||||
try
|
||||
{
|
||||
return (CoreAuditBridge.token(table, field, pk, value));
|
||||
return (ClassifiedValueTokens.forRecordField(table, field, pk, value));
|
||||
}
|
||||
finally
|
||||
{
|
||||
|
||||
@@ -29,13 +29,12 @@ import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.function.Supplier;
|
||||
import com.kingsrook.qbits.secureddata.standin.FieldAccessTier;
|
||||
import com.kingsrook.qqq.backend.core.actions.ai.DataClassification;
|
||||
import com.kingsrook.qqq.backend.core.actions.permissions.fieldaccess.FieldAccessTier;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.producers.MetaDataCustomizerInterface;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.qbits.QBitConfig;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Configuration for policy resolution and bounded asynchronous access logging.
|
||||
*******************************************************************************/
|
||||
@@ -116,6 +115,7 @@ public class SecuredDataQBitConfig implements QBitConfig
|
||||
private Clock clock = Clock.systemUTC();
|
||||
private int accessLogQueueCapacity = 4096;
|
||||
private long accessLogFlushIntervalMillis = 250;
|
||||
private boolean registerShutdownHook = true;
|
||||
private int exactMatchPerHour = 20;
|
||||
private int missAlertConsecutive = 5;
|
||||
private int distinctValueAlert = 15;
|
||||
@@ -217,6 +217,29 @@ public class SecuredDataQBitConfig implements QBitConfig
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Whether the access logger registers a JVM shutdown hook that drains
|
||||
** accepted rows (default true). Hosts that call SecuredDataRuntime.close()
|
||||
** from their own shutdown sequence turn it off.
|
||||
*******************************************************************************/
|
||||
public boolean getRegisterShutdownHook()
|
||||
{
|
||||
return (registerShutdownHook);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Configure registerShutdownHook.
|
||||
*******************************************************************************/
|
||||
public SecuredDataQBitConfig withRegisterShutdownHook(boolean registerShutdownHook)
|
||||
{
|
||||
this.registerShutdownHook = registerShutdownHook;
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Configure accessLogFlushIntervalMillis.
|
||||
*******************************************************************************/
|
||||
|
||||
@@ -29,7 +29,10 @@ import com.kingsrook.qbits.secureddata.metadata.SecuredDataTableCustomizers;
|
||||
import com.kingsrook.qbits.secureddata.metadata.SecuredDataTables;
|
||||
import com.kingsrook.qbits.secureddata.support.SecuredDataMetadata;
|
||||
import com.kingsrook.qqq.backend.core.actions.ai.DataClassification;
|
||||
import com.kingsrook.qqq.backend.core.actions.audits.AuditValueProtectionMetaData;
|
||||
import com.kingsrook.qqq.backend.core.actions.customizers.TableCustomizers;
|
||||
import com.kingsrook.qqq.backend.core.actions.permissions.fieldaccess.ClassifiedValueKeySourceMetaData;
|
||||
import com.kingsrook.qqq.backend.core.actions.permissions.fieldaccess.FieldAccessResolverMetaData;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QException;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.MetaDataProducerMultiOutput;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
@@ -39,7 +42,6 @@ import com.kingsrook.qqq.backend.core.model.metadata.qbits.QBitMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.qbits.QBitMetaDataProducer;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Entry point for secured-data policy, classification and access logging.
|
||||
*******************************************************************************/
|
||||
@@ -47,7 +49,7 @@ public class SecuredDataQBitProducer implements QBitMetaDataProducer<SecuredData
|
||||
{
|
||||
public static final String GROUP_ID = "com.kingsrook.qbits";
|
||||
public static final String ARTIFACT_ID = "qbit-secured-data";
|
||||
public static final String VERSION = "1.0.0";
|
||||
public static final String VERSION = "0.1.0";
|
||||
|
||||
private SecuredDataQBitConfig qBitConfig;
|
||||
private String namespace;
|
||||
@@ -171,8 +173,9 @@ public class SecuredDataQBitProducer implements QBitMetaDataProducer<SecuredData
|
||||
runtime.addSelfToInstance(qInstance);
|
||||
try
|
||||
{
|
||||
CoreFieldAccessBridge.register(qInstance, runtime.resolver());
|
||||
CoreAuditBridge.register(qInstance, runtime);
|
||||
FieldAccessResolverMetaData.ofOrWithNew(qInstance).withResolverInstance(runtime.resolver());
|
||||
ClassifiedValueKeySourceMetaData.ofOrWithNew(qInstance).withKeySourceInstance(runtime.keys());
|
||||
AuditValueProtectionMetaData.ofOrWithNew(qInstance).withProtectorInstance(new SecuredDataAuditProtector());
|
||||
}
|
||||
catch(RuntimeException e)
|
||||
{
|
||||
|
||||
@@ -36,14 +36,14 @@ import java.util.Objects;
|
||||
import java.util.TreeSet;
|
||||
import com.kingsrook.qbits.secureddata.metadata.SecuredDataTables;
|
||||
import com.kingsrook.qbits.secureddata.permissions.SecuredDataPermissions;
|
||||
import com.kingsrook.qbits.secureddata.standin.FieldAccessDecision;
|
||||
import com.kingsrook.qbits.secureddata.standin.FieldAccessEvent;
|
||||
import com.kingsrook.qbits.secureddata.standin.FieldAccessResolverInterface;
|
||||
import com.kingsrook.qbits.secureddata.standin.FieldAccessTier;
|
||||
import com.kingsrook.qbits.secureddata.standin.FieldMaskStyle;
|
||||
import com.kingsrook.qbits.secureddata.support.SecuredDataMetadata;
|
||||
import com.kingsrook.qbits.secureddata.support.SystemWrites;
|
||||
import com.kingsrook.qqq.backend.core.actions.ai.DataClassification;
|
||||
import com.kingsrook.qqq.backend.core.actions.permissions.fieldaccess.FieldAccessDecision;
|
||||
import com.kingsrook.qqq.backend.core.actions.permissions.fieldaccess.FieldAccessEvent;
|
||||
import com.kingsrook.qqq.backend.core.actions.permissions.fieldaccess.FieldAccessResolverInterface;
|
||||
import com.kingsrook.qqq.backend.core.actions.permissions.fieldaccess.FieldAccessTier;
|
||||
import com.kingsrook.qqq.backend.core.actions.permissions.fieldaccess.FieldMaskStyle;
|
||||
import com.kingsrook.qqq.backend.core.context.QContext;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QPermissionDeniedException;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QCriteriaOperator;
|
||||
@@ -57,7 +57,6 @@ import com.kingsrook.qqq.backend.core.model.session.QSession;
|
||||
import com.kingsrook.qqq.backend.core.model.session.QSystemUserSession;
|
||||
import com.kingsrook.qqq.backend.core.utils.JsonUtils;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Seven-step policy resolution with instance-versioned, bounded per-user state.
|
||||
*******************************************************************************/
|
||||
@@ -75,10 +74,14 @@ public class SecuredDataResolver implements FieldAccessResolverInterface
|
||||
{
|
||||
}
|
||||
|
||||
private long cachedVersion;
|
||||
/** Used only inside methods synchronized on this resolver. */
|
||||
private final RuleRows policyRows = new RuleRows();
|
||||
private List<QRecord> policies = List.of();
|
||||
private final Map<String, UserState> users = new HashMap<>();
|
||||
|
||||
/** Request-scoped (QContext) holder of the access fingerprint. */
|
||||
private static final String FINGERPRINT_KEY = SecuredDataResolver.class.getName() + ".accessFingerprint";
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
@@ -289,16 +292,19 @@ public class SecuredDataResolver implements FieldAccessResolverInterface
|
||||
|
||||
/*******************************************************************************
|
||||
** Refresh policy rows once per version and matched state per relevant permissions.
|
||||
** A read that fails throws and is tried again by the next call. A question
|
||||
** asked from inside the read itself (see RuleRows) is answered from the
|
||||
** policies held when the read began; whatever it matched for its user is
|
||||
** dropped with every other user's state when the read returns.
|
||||
*******************************************************************************/
|
||||
private synchronized UserState state()
|
||||
{
|
||||
long version = runtime.policyVersion();
|
||||
if(cachedVersion != version)
|
||||
policies = policyRows.get(runtime.policyVersion(), () ->
|
||||
{
|
||||
policies = List.copyOf(SystemWrites.query(SecuredDataTables.POLICY, new QQueryFilter()));
|
||||
List<QRecord> rows = SystemWrites.query(SecuredDataTables.POLICY, new QQueryFilter());
|
||||
users.clear();
|
||||
cachedVersion = version;
|
||||
}
|
||||
return (rows);
|
||||
});
|
||||
QSession session = QContext.getQSession();
|
||||
TreeSet<String> held = new TreeSet<>();
|
||||
for(QRecord policy : policies)
|
||||
@@ -309,7 +315,7 @@ public class SecuredDataResolver implements FieldAccessResolverInterface
|
||||
held.add(permission);
|
||||
}
|
||||
}
|
||||
String key = JsonUtils.toJson(List.of(userId(), held));
|
||||
String key = userId() + '\u0000' + String.join("\u0000", held);
|
||||
UserState state = users.get(key);
|
||||
if(state == null)
|
||||
{
|
||||
@@ -357,11 +363,82 @@ public class SecuredDataResolver implements FieldAccessResolverInterface
|
||||
** Stable across unrelated permissions/records; includes channel and exact expiry.
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public synchronized String getAccessFingerprint()
|
||||
public String getAccessFingerprint()
|
||||
{
|
||||
state();
|
||||
TreeSet<String> relevant = new TreeSet<>();
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
// core asks for the fingerprint before every field decision (once per //
|
||||
// field of every record of a result), so the value is kept for the //
|
||||
// request - and only while everything it is derived from is unchanged //
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
QSession session = QContext.getQSession();
|
||||
String channel = Objects.requireNonNullElse(SecuredDataMetadata.channel(session), "");
|
||||
Instant now = runtime.config().getClock().instant();
|
||||
RequestFingerprint kept = QContext.getObject(FINGERPRINT_KEY, RequestFingerprint.class).orElse(null);
|
||||
if(kept != null && kept.matches(this, session, channel, runtime.policyVersion(), runtime.classificationVersion(), now))
|
||||
{
|
||||
return (kept.value());
|
||||
}
|
||||
RequestFingerprint computed = computeAccessFingerprint(session, channel, now);
|
||||
QContext.setObject(FINGERPRINT_KEY, computed);
|
||||
return (computed.value());
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The fingerprint and what it was derived from. It stops matching when the
|
||||
** session, its permissions, the channel, a policy or classification version
|
||||
** changes, or when the first active break-glass grant expires.
|
||||
*******************************************************************************/
|
||||
private record RequestFingerprint(int resolver, QSession session, int permissionsIdentity, int permissionCount, String channel, long policyVersion,
|
||||
long classificationVersion, Instant validUntil, String value) implements Serializable
|
||||
{
|
||||
/*******************************************************************************
|
||||
** Whether the kept value is still the one a fresh computation would give.
|
||||
*******************************************************************************/
|
||||
boolean matches(SecuredDataResolver owner, QSession current, String currentChannel, long currentPolicyVersion, long currentClassificationVersion, Instant now)
|
||||
{
|
||||
return (resolver == System.identityHashCode(owner) && session == current && permissionsIdentity == identityOfPermissions(current) && permissionCount == countOfPermissions(current)
|
||||
&& channel.equals(currentChannel) && policyVersion == currentPolicyVersion && classificationVersion == currentClassificationVersion && now.isBefore(validUntil));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The permission set object of a session (it is replaced, not edited, when a
|
||||
** session is given new permissions).
|
||||
*******************************************************************************/
|
||||
private static int identityOfPermissions(QSession session)
|
||||
{
|
||||
return (session == null || session.getPermissions() == null ? 0 : System.identityHashCode(session.getPermissions()));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** How many permissions a session holds (an edit in place changes it).
|
||||
*******************************************************************************/
|
||||
private static int countOfPermissions(QSession session)
|
||||
{
|
||||
return (session == null || session.getPermissions() == null ? -1 : session.getPermissions().size());
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Stable across unrelated permissions/records; includes channel and exact expiry.
|
||||
*******************************************************************************/
|
||||
private synchronized RequestFingerprint computeAccessFingerprint(QSession session, String channel, Instant now)
|
||||
{
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
// versions are read before the rows they describe, so a change during the //
|
||||
// computation leaves a kept value that no longer matches //
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
long policyVersion = runtime.policyVersion();
|
||||
long classificationVersion = runtime.classificationVersion();
|
||||
TreeSet<String> relevant = new TreeSet<>();
|
||||
List<QRecord> breakGlass = state().breakGlass();
|
||||
for(QRecord row : policies)
|
||||
{
|
||||
String permission = row.getValueString("permission_name");
|
||||
@@ -381,12 +458,15 @@ public class SecuredDataResolver implements FieldAccessResolverInterface
|
||||
}
|
||||
}
|
||||
}
|
||||
List<String> breaks = activeBreakGlass().stream().map(row -> row.getValueString("id")).sorted().toList();
|
||||
String payload = JsonUtils.toJson(List.of(userId(), relevant, runtime.policyVersion(), runtime.classificationVersion(), breaks,
|
||||
Objects.requireNonNullElse(SecuredDataMetadata.channel(session), "")));
|
||||
List<QRecord> activeBreaks = breakGlass.stream().filter(row -> "ACTIVE".equals(row.getValueString("status")))
|
||||
.filter(row -> row.getValueInstant("expires_at") != null && row.getValueInstant("expires_at").isAfter(now)).toList();
|
||||
List<String> breaks = activeBreaks.stream().map(row -> row.getValueString("id")).sorted().toList();
|
||||
Instant validUntil = activeBreaks.stream().map(row -> row.getValueInstant("expires_at")).min(Instant::compareTo).orElse(Instant.MAX);
|
||||
String payload = JsonUtils.toJson(List.of(userId(), relevant, policyVersion, classificationVersion, breaks, channel));
|
||||
try
|
||||
{
|
||||
return (Base64.getUrlEncoder().withoutPadding().encodeToString(MessageDigest.getInstance("SHA-256").digest(payload.getBytes(StandardCharsets.UTF_8))));
|
||||
String value = Base64.getUrlEncoder().withoutPadding().encodeToString(MessageDigest.getInstance("SHA-256").digest(payload.getBytes(StandardCharsets.UTF_8)));
|
||||
return (new RequestFingerprint(System.identityHashCode(this), session, identityOfPermissions(session), countOfPermissions(session), channel, policyVersion, classificationVersion, validUntil, value));
|
||||
}
|
||||
catch(java.security.NoSuchAlgorithmException e)
|
||||
{
|
||||
|
||||
@@ -21,9 +21,21 @@
|
||||
package com.kingsrook.qbits.secureddata;
|
||||
|
||||
|
||||
import java.lang.ref.WeakReference;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import com.kingsrook.qbits.secureddata.metadata.SecuredDataTables;
|
||||
import com.kingsrook.qbits.secureddata.support.SystemWrites;
|
||||
import com.kingsrook.qqq.backend.core.cluster.ClusterBus;
|
||||
import com.kingsrook.qqq.backend.core.cluster.ClusterCaches;
|
||||
import com.kingsrook.qqq.backend.core.cluster.ClusterEvent;
|
||||
import com.kingsrook.qqq.backend.core.context.QContext;
|
||||
import com.kingsrook.qqq.backend.core.logging.QLogger;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QCriteriaOperator;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QFilterCriteria;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter;
|
||||
import com.kingsrook.qqq.backend.core.model.data.QRecord;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QSupplementalInstanceMetaData;
|
||||
|
||||
@@ -34,16 +46,58 @@ import com.kingsrook.qqq.backend.core.model.metadata.QSupplementalInstanceMetaDa
|
||||
public class SecuredDataRuntime implements QSupplementalInstanceMetaData, AutoCloseable
|
||||
{
|
||||
public static final String NAME = "securedDataRuntime";
|
||||
|
||||
private static final QLogger LOG = QLogger.getLogger(SecuredDataRuntime.class);
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////////
|
||||
// the three sets of rule rows a node keeps in memory. A change clears them on //
|
||||
// this node at once and, through QQQ's cluster bus (ClusterCaches), on every //
|
||||
// other node. MAX_RULE_AGE is the safety net for a lost event: no node uses //
|
||||
// rule rows older than that without reading them again. //
|
||||
/////////////////////////////////////////////////////////////////////////////////
|
||||
public static final String POLICY_CACHE = "securedData.policies";
|
||||
public static final String CLASSIFICATION_CACHE = "securedData.classifications";
|
||||
public static final String RETENTION_CACHE = "securedData.retentionRules";
|
||||
|
||||
public static final Duration MAX_RULE_AGE = Duration.ofSeconds(30);
|
||||
|
||||
static
|
||||
{
|
||||
ClusterCaches.shared(POLICY_CACHE, POLICY_CACHE, () -> clearOnThisNode(POLICY_CACHE), null);
|
||||
ClusterCaches.shared(CLASSIFICATION_CACHE, CLASSIFICATION_CACHE, () -> clearOnThisNode(CLASSIFICATION_CACHE), null);
|
||||
ClusterCaches.shared(RETENTION_CACHE, RETENTION_CACHE, () -> clearOnThisNode(RETENTION_CACHE), null);
|
||||
}
|
||||
|
||||
private static final AtomicLong STARTUP_VERSION = new AtomicLong(System.currentTimeMillis());
|
||||
private final AtomicLong classificationVersion = new AtomicLong(STARTUP_VERSION.incrementAndGet());
|
||||
private final AtomicLong policyVersion = new AtomicLong(STARTUP_VERSION.incrementAndGet());
|
||||
private final AtomicLong retentionVersion = new AtomicLong(STARTUP_VERSION.incrementAndGet());
|
||||
private final transient WeakReference<QInstance> owner;
|
||||
private final transient SecuredDataQBitConfig config;
|
||||
private final transient SecuredDataResolver resolver;
|
||||
private final transient SecuredDataKeySource keys = new SecuredDataKeySource();
|
||||
private final transient SecuredDataAccessLogger logger;
|
||||
private final transient SecuredDataAnomalies anomalies;
|
||||
private transient long cachedClassificationVersion;
|
||||
private transient List<com.kingsrook.qqq.backend.core.model.data.QRecord> classificationRows = List.of();
|
||||
/////////////////////////////////////////////////////////////////////////////////
|
||||
// both are used only while holding ruleLock: one lock for the two, because //
|
||||
// reading either may ask for the other. //
|
||||
// //
|
||||
// It is a lock of its own, never this runtime's monitor. A reveal and the //
|
||||
// start, end and expiry of a break-glass session hold the runtime's monitor //
|
||||
// for their whole operation, and every thread asks for a classification all //
|
||||
// the time (core asks for every field it decides on and for every criterion //
|
||||
// of every query), including threads that hold another lock of this QBit: the //
|
||||
// access-log writer inside the anomaly counters, the resolver, the key //
|
||||
// source. When the question needed the runtime's monitor, such a thread and //
|
||||
// a reveal that needed its lock next waited for each other for ever. //
|
||||
// //
|
||||
// ruleLock is held only while rule rows are answered or read. A read is a //
|
||||
// query made as the system: it takes none of the QBit's other locks, so no //
|
||||
// thread holding ruleLock ever waits for one of them. //
|
||||
/////////////////////////////////////////////////////////////////////////////////
|
||||
private final transient Object ruleLock = new Object();
|
||||
private final transient RuleRows classificationRows = new RuleRows();
|
||||
private final transient RuleRows activeRetentionRules = new RuleRows();
|
||||
|
||||
|
||||
|
||||
@@ -53,6 +107,7 @@ public class SecuredDataRuntime implements QSupplementalInstanceMetaData, AutoCl
|
||||
public SecuredDataRuntime(QInstance instance, SecuredDataQBitConfig config)
|
||||
{
|
||||
this.config = config;
|
||||
this.owner = new WeakReference<>(instance);
|
||||
this.resolver = new SecuredDataResolver(this);
|
||||
this.anomalies = new SecuredDataAnomalies(config);
|
||||
this.logger = new SecuredDataAccessLogger(instance, this);
|
||||
@@ -137,6 +192,7 @@ public class SecuredDataRuntime implements QSupplementalInstanceMetaData, AutoCl
|
||||
public void invalidateClassifications()
|
||||
{
|
||||
classificationVersion.incrementAndGet();
|
||||
announce(CLASSIFICATION_CACHE);
|
||||
}
|
||||
|
||||
|
||||
@@ -147,23 +203,115 @@ public class SecuredDataRuntime implements QSupplementalInstanceMetaData, AutoCl
|
||||
public void invalidatePolicies()
|
||||
{
|
||||
policyVersion.incrementAndGet();
|
||||
announce(POLICY_CACHE);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Read classification rows once per version, always as the system.
|
||||
** A retention rule changed: forget the active rules here and on every node.
|
||||
*******************************************************************************/
|
||||
synchronized List<com.kingsrook.qqq.backend.core.model.data.QRecord> classificationRows()
|
||||
public void invalidateRetentionRules()
|
||||
{
|
||||
long version = classificationVersion();
|
||||
if(cachedClassificationVersion != version)
|
||||
retentionVersion.incrementAndGet();
|
||||
announce(RETENTION_CACHE);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Version of the retention rules this node holds.
|
||||
*******************************************************************************/
|
||||
public long retentionVersion()
|
||||
{
|
||||
return (retentionVersion.get());
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Whether rows loaded at this System.nanoTime are too old to use unread.
|
||||
*******************************************************************************/
|
||||
static boolean tooOld(long loadedAtNanos)
|
||||
{
|
||||
return (System.nanoTime() - loadedAtNanos > MAX_RULE_AGE.toNanos());
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Every active retention rule, read once per version and at most MAX_RULE_AGE
|
||||
** old. A read that fails throws and leaves nothing in place of the rules:
|
||||
** callers never see "no rules" because the rules could not be read, and the
|
||||
** next call reads again. A question asked from inside the read itself (see
|
||||
** RuleRows) is answered with the rules held when the read began.
|
||||
*******************************************************************************/
|
||||
public List<QRecord> activeRetentionRules()
|
||||
{
|
||||
synchronized(ruleLock)
|
||||
{
|
||||
classificationRows = List.copyOf(com.kingsrook.qbits.secureddata.support.SystemWrites.query(
|
||||
com.kingsrook.qbits.secureddata.metadata.SecuredDataTables.CLASSIFICATION, new com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter()));
|
||||
cachedClassificationVersion = version;
|
||||
return (activeRetentionRules.get(retentionVersion(), () -> SystemWrites.query(SecuredDataTables.RETENTION_RULE, new QQueryFilter()
|
||||
.withCriteria(new QFilterCriteria("is_active", QCriteriaOperator.EQUALS, true)))));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Tell the other nodes (this node has already moved its version). A failure
|
||||
** to send is logged: the other nodes then read again within MAX_RULE_AGE.
|
||||
*******************************************************************************/
|
||||
private void announce(String cache)
|
||||
{
|
||||
try
|
||||
{
|
||||
QInstance instance = owner.get();
|
||||
if(instance != null)
|
||||
{
|
||||
ClusterBus.publish(instance, new ClusterEvent(ClusterEvent.TYPE_MEMO_INVALIDATE, cache, null));
|
||||
}
|
||||
}
|
||||
catch(RuntimeException e)
|
||||
{
|
||||
LOG.warn("Could not announce a secured-data rule change; other nodes read again within " + MAX_RULE_AGE.toSeconds() + " seconds", e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A rule change announced on the cluster bus (also by this node): move the
|
||||
** version of the runtime of the instance the event arrived on.
|
||||
*******************************************************************************/
|
||||
private static void clearOnThisNode(String cache)
|
||||
{
|
||||
SecuredDataRuntime runtime = current();
|
||||
if(runtime == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
switch(cache)
|
||||
{
|
||||
case POLICY_CACHE -> runtime.policyVersion.incrementAndGet();
|
||||
case CLASSIFICATION_CACHE -> runtime.classificationVersion.incrementAndGet();
|
||||
default -> runtime.retentionVersion.incrementAndGet();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Read classification rows once per version, always as the system. A read
|
||||
** that fails throws and is tried again by the next call. A question asked from
|
||||
** inside the read itself (see RuleRows) is answered with the rows held when
|
||||
** the read began, and never starts another read.
|
||||
*******************************************************************************/
|
||||
List<QRecord> classificationRows()
|
||||
{
|
||||
synchronized(ruleLock)
|
||||
{
|
||||
return (classificationRows.get(classificationVersion(), () -> SystemWrites.query(SecuredDataTables.CLASSIFICATION, new QQueryFilter())));
|
||||
}
|
||||
return (classificationRows);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -31,12 +31,16 @@ import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.tables.SectionFactory;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.tables.UniqueKey;
|
||||
import static com.kingsrook.qbits.secureddata.metadata.SecuredDataTables.AUDIT_KEY;
|
||||
import static com.kingsrook.qbits.secureddata.metadata.SecuredDataTables.CREATE_DATE;
|
||||
import static com.kingsrook.qbits.secureddata.metadata.SecuredDataTables.LEGAL_HOLD;
|
||||
import static com.kingsrook.qbits.secureddata.metadata.SecuredDataTables.MODIFY_DATE;
|
||||
import static com.kingsrook.qbits.secureddata.metadata.SecuredDataTables.RETENTION_RULE;
|
||||
import static com.kingsrook.qbits.secureddata.metadata.SecuredDataTables.WIPE_MARKER;
|
||||
import static com.kingsrook.qbits.secureddata.metadata.SecuredDataTables.WIPE_RUN;
|
||||
import static com.kingsrook.qbits.secureddata.metadata.SecuredDataTables.base;
|
||||
import static com.kingsrook.qbits.secureddata.metadata.SecuredDataTables.createDate;
|
||||
import static com.kingsrook.qbits.secureddata.metadata.SecuredDataTables.field;
|
||||
import static com.kingsrook.qbits.secureddata.metadata.SecuredDataTables.modifyDate;
|
||||
|
||||
/*******************************************************************************
|
||||
** Retention policies, value-free history, legal holds and mutable audit keys.
|
||||
@@ -74,8 +78,8 @@ public final class RetentionTables
|
||||
.withField(field("is_active", QFieldType.BOOLEAN).withDefaultValue(true))
|
||||
.withField(field("last_run_at", QFieldType.DATE_TIME).withIsEditable(false))
|
||||
.withField(field("last_run_count", QFieldType.INTEGER).withIsEditable(false))
|
||||
.withField(field("create_date", QFieldType.DATE_TIME))
|
||||
.withField(field("modify_date", QFieldType.DATE_TIME))
|
||||
.withField(createDate("create_date"))
|
||||
.withField(modifyDate("modify_date"))
|
||||
.withField(field("modified_by", QFieldType.STRING).withMaxLength(255));
|
||||
rule.withSection(SectionFactory.defaultT1("id", "name", "table_name", "field_names"));
|
||||
rule.withSection(SectionFactory.defaultT2("age_field_name", "age_days", "action", "overwrite_text", "audit_treatment", "archive_storage_name", "batch_size", "is_active"));
|
||||
@@ -92,8 +96,11 @@ public final class RetentionTables
|
||||
.withField(field("action", QFieldType.STRING).withMaxLength(40).withIsRequired(true))
|
||||
.withField(field("wiped_at", QFieldType.DATE_TIME).withIsRequired(true))
|
||||
.withField(field("run_id", QFieldType.INTEGER).withIsRequired(true))
|
||||
.withField(createDate(CREATE_DATE))
|
||||
.withField(modifyDate(MODIFY_DATE))
|
||||
.withUniqueKey(new UniqueKey().withFieldNames(List.of("table_name", "record_id", "field_name")));
|
||||
marker.withSection(SectionFactory.defaultT1("id", "table_name", "record_id", "field_name", "rule_id", "action", "wiped_at", "run_id"));
|
||||
marker.withSection(SectionFactory.defaultT3(CREATE_DATE, MODIFY_DATE));
|
||||
QTableMetaData hold = base(config, LEGAL_HOLD, "Legal hold")
|
||||
.withField(field("table_name", QFieldType.STRING).withMaxLength(255).withIsRequired(true).withPossibleValueSourceName("tables"))
|
||||
.withField(field("record_id", QFieldType.STRING).withMaxLength(255))
|
||||
@@ -102,9 +109,11 @@ public final class RetentionTables
|
||||
.withField(field("placed_at", QFieldType.DATE_TIME))
|
||||
.withField(field("released_by", QFieldType.STRING).withMaxLength(255))
|
||||
.withField(field("released_at", QFieldType.DATE_TIME))
|
||||
.withField(field("status", QFieldType.STRING).withMaxLength(20).withDefaultValue("ACTIVE"));
|
||||
.withField(field("status", QFieldType.STRING).withMaxLength(20).withDefaultValue("ACTIVE"))
|
||||
.withField(createDate(CREATE_DATE))
|
||||
.withField(modifyDate(MODIFY_DATE));
|
||||
hold.withSection(SectionFactory.defaultT1("id", "table_name", "record_id", "reason", "status"));
|
||||
hold.withSection(SectionFactory.defaultT3("placed_by", "placed_at", "released_by", "released_at"));
|
||||
hold.withSection(SectionFactory.defaultT3("placed_by", "placed_at", "released_by", "released_at", CREATE_DATE, MODIFY_DATE));
|
||||
QTableMetaData run = base(config, WIPE_RUN, "Wipe run")
|
||||
.withField(field("rule_id", QFieldType.INTEGER).withIsRequired(true))
|
||||
.withField(field("started_at", QFieldType.DATE_TIME).withIsRequired(true))
|
||||
@@ -115,9 +124,11 @@ public final class RetentionTables
|
||||
.withField(field("wiped_count", QFieldType.INTEGER))
|
||||
.withField(field("error_count", QFieldType.INTEGER))
|
||||
.withField(field("record_ids", QFieldType.STRING).withMaxLength(4000))
|
||||
.withField(field("message", QFieldType.STRING).withMaxLength(500));
|
||||
.withField(field("message", QFieldType.STRING).withMaxLength(500))
|
||||
.withField(createDate(CREATE_DATE))
|
||||
.withField(modifyDate(MODIFY_DATE));
|
||||
run.withSection(SectionFactory.defaultT1("id", "rule_id", "status", "eligible_count", "held_count", "wiped_count", "error_count"));
|
||||
run.withSection(SectionFactory.defaultT3("started_at", "finished_at", "record_ids", "message"));
|
||||
run.withSection(SectionFactory.defaultT3("started_at", "finished_at", "record_ids", "message", CREATE_DATE, MODIFY_DATE));
|
||||
QTableMetaData key = base(config, AUDIT_KEY, "Audit key")
|
||||
.withAuditRules(new QAuditRules().withAuditLevel(AuditLevel.NONE))
|
||||
.withoutCapabilities(Capability.TABLE_EXPORT)
|
||||
@@ -127,8 +138,11 @@ public final class RetentionTables
|
||||
.withField(field("wrapped_key", QFieldType.TEXT).withIsRequired(true).withIsSensitive(true).withIsHidden(true)
|
||||
.withFieldSecurityLock(new FieldSecurityLock().withSecurityKeyType(KEY_LOCK).withDefaultBehavior(FieldSecurityLock.Behavior.DENY).withOverrideValues(List.of(KEY_LOCK_NEVER_GRANTED))))
|
||||
.withField(field("created_at", QFieldType.DATE_TIME).withIsRequired(true))
|
||||
.withField(createDate(CREATE_DATE))
|
||||
.withField(modifyDate(MODIFY_DATE))
|
||||
.withUniqueKey(new UniqueKey().withFieldNames(List.of("table_name", "record_id", "field_name")));
|
||||
key.withSection(SectionFactory.defaultT1("id", "table_name", "record_id", "field_name", "created_at"));
|
||||
key.withSection(SectionFactory.defaultT3(CREATE_DATE, MODIFY_DATE));
|
||||
return (List.of(rule, marker, hold, run, key));
|
||||
}
|
||||
}
|
||||
@@ -23,15 +23,14 @@ package com.kingsrook.qbits.secureddata.metadata;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import com.kingsrook.qbits.secureddata.standin.FieldAccessTier;
|
||||
import com.kingsrook.qbits.secureddata.standin.FieldMaskStyle;
|
||||
import com.kingsrook.qqq.backend.core.actions.ai.DataClassification;
|
||||
import com.kingsrook.qqq.backend.core.actions.permissions.fieldaccess.FieldAccessTier;
|
||||
import com.kingsrook.qqq.backend.core.actions.permissions.fieldaccess.FieldMaskStyle;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldType;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.possiblevalues.QPossibleValue;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.possiblevalues.QPossibleValueSource;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.possiblevalues.QPossibleValueSourceType;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** String-valued possible-value sources shared by UI metadata and the DDL.
|
||||
*******************************************************************************/
|
||||
|
||||
+40
-8
@@ -63,11 +63,16 @@ public class SecuredDataTableCustomizers implements TableCustomizerInterface
|
||||
{
|
||||
for(QRecord record : records)
|
||||
{
|
||||
QRecord old = oldRecords.orElse(List.of()).stream().filter(row -> Objects.equals(row.getValue("id"), record.getValue("id"))).findFirst().orElse(null);
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
// ids are compared as text: a request over HTTP names its row by the id //
|
||||
// in its path, which is text, while the stored id is a number //
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
QRecord old = oldRecords.orElse(List.of()).stream().filter(row -> Objects.equals(row.getValueString("id"), record.getValueString("id"))).findFirst().orElse(null);
|
||||
QRecord effective = old == null ? new QRecord() : new QRecord(old);
|
||||
record.getValues().forEach(effective::setValue);
|
||||
validate(table, record, effective);
|
||||
Instant now = SecuredDataRuntime.current().config().getClock().instant();
|
||||
dates(table, record, old == null, now);
|
||||
if(SecuredDataTables.LEGAL_HOLD.equals(table))
|
||||
{
|
||||
if(old == null)
|
||||
@@ -82,19 +87,41 @@ public class SecuredDataTableCustomizers implements TableCustomizerInterface
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if(old == null)
|
||||
{
|
||||
record.setValue("create_date", now);
|
||||
}
|
||||
record.setValue("modify_date", now);
|
||||
record.setValue("modified_by", SecuredDataResolver.userId());
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Instant now = SecuredDataRuntime.current().config().getClock().instant();
|
||||
for(QRecord record : records)
|
||||
{
|
||||
dates(table, record, input instanceof InsertInput, now);
|
||||
}
|
||||
}
|
||||
return (records);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The two dates every table has, set in the write that is already being made:
|
||||
** a new row gets both, equal, from the clock every other time of this QBit
|
||||
** comes from, and a changed row a new modify date. Core has the last word on
|
||||
** a change: the modify date is the record version of its table, and core
|
||||
** moves it forward after this has run. A row of a table that is only ever
|
||||
** inserted (the access log, a wipe run) so keeps equal dates.
|
||||
*******************************************************************************/
|
||||
private static void dates(String table, QRecord record, boolean inserted, Instant now)
|
||||
{
|
||||
if(inserted)
|
||||
{
|
||||
record.setValue(SecuredDataTables.createDateField(table), now);
|
||||
}
|
||||
record.setValue(SecuredDataTables.modifyDateField(table), now);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Access logs are append-only even for the system.
|
||||
*******************************************************************************/
|
||||
@@ -154,7 +181,7 @@ public class SecuredDataTableCustomizers implements TableCustomizerInterface
|
||||
{
|
||||
for(QRecord row : SystemWrites.query(table, new QQueryFilter().withCriteria(new QFilterCriteria("table_name", QCriteriaOperator.EQUALS, target))))
|
||||
{
|
||||
if(Objects.equals(field, row.getValueString("field_name")) && !Objects.equals(row.getValue("id"), effective.getValue("id")))
|
||||
if(Objects.equals(field, row.getValueString("field_name")) && !Objects.equals(row.getValueString("id"), effective.getValueString("id")))
|
||||
{
|
||||
record.addError(new BadInputStatusMessage("A classification for this table and field already exists."));
|
||||
}
|
||||
@@ -238,7 +265,8 @@ public class SecuredDataTableCustomizers implements TableCustomizerInterface
|
||||
}
|
||||
SecuredDataRuntime runtime = SecuredDataRuntime.current();
|
||||
Runnable invalidate = SecuredDataTables.CLASSIFICATION.equals(table) ? runtime::invalidateClassifications
|
||||
: SecuredDataTables.POLICY.equals(table) || SecuredDataTables.BREAK_GLASS.equals(table) ? runtime::invalidatePolicies : null;
|
||||
: SecuredDataTables.POLICY.equals(table) || SecuredDataTables.BREAK_GLASS.equals(table) ? runtime::invalidatePolicies
|
||||
: SecuredDataTables.RETENTION_RULE.equals(table) ? runtime::invalidateRetentionRules : null;
|
||||
if(invalidate != null)
|
||||
{
|
||||
QBackendTransaction active = transaction == null ? QContext.getQBackendTransaction() : transaction;
|
||||
@@ -248,6 +276,10 @@ public class SecuredDataTableCustomizers implements TableCustomizerInterface
|
||||
}
|
||||
else
|
||||
{
|
||||
if(SecuredDataTables.RETENTION_RULE.equals(table))
|
||||
{
|
||||
com.kingsrook.qbits.secureddata.retention.RetentionRules.editedInTransaction();
|
||||
}
|
||||
active.addAfterCommitCallback(invalidate);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,6 +32,7 @@ import com.kingsrook.qqq.backend.core.model.metadata.audits.AuditLevel;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.audits.QAuditRules;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.code.QCodeReference;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.dashboard.QWidgetMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.fields.DynamicDefaultValueBehavior;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldType;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.joins.JoinOn;
|
||||
@@ -66,6 +67,8 @@ public final class SecuredDataTables
|
||||
public static final List<String> ALL = List.of(CLASSIFICATION, POLICY, REVEAL_GRANT, BREAK_GLASS, ACCESS_LOG, RETENTION_RULE, WIPE_MARKER, LEGAL_HOLD, WIPE_RUN, AUDIT_KEY);
|
||||
public static final List<String> MAIN = List.of(CLASSIFICATION, POLICY, ACCESS_LOG, BREAK_GLASS, RETENTION_RULE);
|
||||
public static final List<String> SYSTEM_WRITTEN = List.of(REVEAL_GRANT, BREAK_GLASS, ACCESS_LOG, WIPE_MARKER, WIPE_RUN, AUDIT_KEY);
|
||||
public static final String CREATE_DATE = "createDate";
|
||||
public static final String MODIFY_DATE = "modifyDate";
|
||||
public static final String REVEALS_JOIN = "secured_data_access_log_reveals";
|
||||
public static final String REVEALS_WIDGET = "securedDataReveals";
|
||||
|
||||
@@ -133,6 +136,51 @@ public final class SecuredDataTables
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** When a row was written. Every table has this field and a modify date;
|
||||
** neither is editable, and the columns are create_date and modify_date.
|
||||
*******************************************************************************/
|
||||
static QFieldMetaData createDate(String name)
|
||||
{
|
||||
return (field(name, QFieldType.DATE_TIME).withBackendName("create_date").withLabel("create date")
|
||||
.withIsEditable(false).withBehavior(DynamicDefaultValueBehavior.CREATE_DATE));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** When a row last changed: its create date until something changes it.
|
||||
*******************************************************************************/
|
||||
static QFieldMetaData modifyDate(String name)
|
||||
{
|
||||
return (field(name, QFieldType.DATE_TIME).withBackendName("modify_date").withLabel("modify date")
|
||||
.withIsEditable(false).withBehavior(DynamicDefaultValueBehavior.MODIFY_DATE));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The name of a table's create date field. Classification, policy and
|
||||
** retention rule had the two dates before the other tables did and keep the
|
||||
** field names they have always had.
|
||||
*******************************************************************************/
|
||||
static String createDateField(String table)
|
||||
{
|
||||
return (List.of(CLASSIFICATION, POLICY, RETENTION_RULE).contains(table) ? "create_date" : CREATE_DATE);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The name of a table's modify date field (see createDateField).
|
||||
*******************************************************************************/
|
||||
static String modifyDateField(String table)
|
||||
{
|
||||
return (List.of(CLASSIFICATION, POLICY, RETENTION_RULE).contains(table) ? "modify_date" : MODIFY_DATE);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Define Classification.
|
||||
*******************************************************************************/
|
||||
@@ -145,8 +193,8 @@ public final class SecuredDataTables
|
||||
.withField(field("mask_style", QFieldType.STRING).withMaxLength(255).withPossibleValueSourceName("secured_data_mask_style"))
|
||||
.withField(field("low_cardinality", QFieldType.BOOLEAN))
|
||||
.withField(field("notes", QFieldType.TEXT))
|
||||
.withField(field("create_date", QFieldType.DATE_TIME))
|
||||
.withField(field("modify_date", QFieldType.DATE_TIME))
|
||||
.withField(createDate("create_date"))
|
||||
.withField(modifyDate("modify_date"))
|
||||
.withField(field("modified_by", QFieldType.STRING).withMaxLength(255));
|
||||
table.withSection(SectionFactory.defaultT1("id", "table_name", "field_name", "classification"));
|
||||
table.withSection(SectionFactory.defaultT2("mask_style", "low_cardinality", "notes"));
|
||||
@@ -179,8 +227,8 @@ public final class SecuredDataTables
|
||||
.withField(field("distinct_value_alert", QFieldType.INTEGER).withDefaultValue(15))
|
||||
.withField(field("min_entropy_enabled", QFieldType.BOOLEAN).withDefaultValue(true))
|
||||
.withField(field("is_active", QFieldType.BOOLEAN).withDefaultValue(true))
|
||||
.withField(field("create_date", QFieldType.DATE_TIME))
|
||||
.withField(field("modify_date", QFieldType.DATE_TIME))
|
||||
.withField(createDate("create_date"))
|
||||
.withField(modifyDate("modify_date"))
|
||||
.withField(field("modified_by", QFieldType.STRING).withMaxLength(255));
|
||||
table.withSection(SectionFactory.defaultT1("id", "name", "permission_name", "classification"));
|
||||
table.withSection(SectionFactory.defaultT2("table_name", "tier", "reveal_minutes", "daily_reveal_cap", "reason_options", "allow_free_text_reason", "require_free_text", "client_channel", "exact_match_per_hour", "miss_alert_consecutive", "distinct_value_alert", "min_entropy_enabled", "is_active"));
|
||||
@@ -205,10 +253,12 @@ public final class SecuredDataTables
|
||||
.withField(field("reason_text", QFieldType.TEXT))
|
||||
.withField(field("granted_at", QFieldType.DATE_TIME).withIsRequired(true))
|
||||
.withField(field("expires_at", QFieldType.DATE_TIME).withIsRequired(true))
|
||||
.withField(field("access_log_id", QFieldType.INTEGER).withIsRequired(true));
|
||||
.withField(field("access_log_id", QFieldType.INTEGER).withIsRequired(true))
|
||||
.withField(createDate(CREATE_DATE))
|
||||
.withField(modifyDate(MODIFY_DATE));
|
||||
table.withSection(SectionFactory.defaultT1("id", "user_id", "user_name", "table_name"));
|
||||
table.withSection(SectionFactory.defaultT2("record_id", "field_name", "reason", "reason_text", "access_log_id"));
|
||||
table.withSection(SectionFactory.defaultT3("granted_at", "expires_at"));
|
||||
table.withSection(SectionFactory.defaultT3("granted_at", "expires_at", CREATE_DATE, MODIFY_DATE));
|
||||
return (table);
|
||||
}
|
||||
|
||||
@@ -230,10 +280,12 @@ public final class SecuredDataTables
|
||||
.withField(field("expires_at", QFieldType.DATE_TIME).withIsRequired(true))
|
||||
.withField(field("ended_at", QFieldType.DATE_TIME))
|
||||
.withField(field("ended_by", QFieldType.STRING).withMaxLength(255))
|
||||
.withField(field("status", QFieldType.STRING).withMaxLength(255).withDefaultValue("ACTIVE").withPossibleValueSourceName("secured_data_break_glass_status"));
|
||||
.withField(field("status", QFieldType.STRING).withMaxLength(255).withDefaultValue("ACTIVE").withPossibleValueSourceName("secured_data_break_glass_status"))
|
||||
.withField(createDate(CREATE_DATE))
|
||||
.withField(modifyDate(MODIFY_DATE));
|
||||
table.withSection(SectionFactory.defaultT1("id", "user_id", "user_name", "reason"));
|
||||
table.withSection(SectionFactory.defaultT2("reason_text", "classification_ceiling", "table_name", "ended_by", "status"));
|
||||
table.withSection(SectionFactory.defaultT3("started_at", "expires_at", "ended_at"));
|
||||
table.withSection(SectionFactory.defaultT3("started_at", "expires_at", "ended_at", CREATE_DATE, MODIFY_DATE));
|
||||
return (table);
|
||||
}
|
||||
|
||||
@@ -261,10 +313,12 @@ public final class SecuredDataTables
|
||||
.withField(field("break_glass_id", QFieldType.INTEGER))
|
||||
.withField(field("created_at", QFieldType.DATE_TIME).withIsRequired(true))
|
||||
.withField(field("search_value_fingerprints", QFieldType.TEXT))
|
||||
.withField(field("rule_id", QFieldType.INTEGER));
|
||||
.withField(field("rule_id", QFieldType.INTEGER))
|
||||
.withField(createDate(CREATE_DATE))
|
||||
.withField(modifyDate(MODIFY_DATE));
|
||||
table.withSection(SectionFactory.defaultT1("id", "event_type", "user_id", "user_name"));
|
||||
table.withSection(SectionFactory.defaultT2("table_name", "record_id", "field_name", "record_count", "action_name", "reason", "reason_text", "client_channel", "outcome", "anomaly_flag", "break_glass_id", "rule_id", "search_value_fingerprints"));
|
||||
table.withSection(SectionFactory.defaultT3("created_at"));
|
||||
table.withSection(SectionFactory.defaultT3("created_at", CREATE_DATE, MODIFY_DATE));
|
||||
table.withSection(SectionFactory.customT2("reveals", new QIcon("visibility")).withLabel("Reveals").withWidgetName(REVEALS_WIDGET));
|
||||
return (table);
|
||||
}
|
||||
|
||||
@@ -58,15 +58,86 @@ public final class RetentionRules
|
||||
return (names == null ? List.of() : Arrays.stream(names.split(",", -1)).map(String::trim).toList());
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
// set on a thread that changed a rule inside a transaction: until that //
|
||||
// transaction ends, the thread reads the rules through it (its own edits), //
|
||||
// not the rules every other thread shares //
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
private static final ThreadLocal<Boolean> EDITED_IN_TRANSACTION = ThreadLocal.withInitial(() -> false);
|
||||
|
||||
/** Set while this thread reads its own edits, so that a question from inside that read does not read them again. */
|
||||
private static final ThreadLocal<Boolean> READING_OWN_EDITS = ThreadLocal.withInitial(() -> false);
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fresh rules in the current transaction; edits take effect without a stale cache.
|
||||
** The active rules of a table that name this field. Core asks this for every
|
||||
** field of every audited write and every filter criterion of every query, so
|
||||
** the active rules are read once (SecuredDataRuntime.activeRetentionRules: per
|
||||
** change, and at most MAX_RULE_AGE old) instead of once per call. A committed
|
||||
** change is seen at once on the node that made it and on every node the
|
||||
** cluster event reaches; a transaction that edits rules reads its own edits.
|
||||
** A failed read throws: it is never "no rules". A question asked from inside
|
||||
** a read of the rules is answered from the rules held before that read (see
|
||||
** RuleRows) and never starts another.
|
||||
*******************************************************************************/
|
||||
public static List<QRecord> active(String table, String field)
|
||||
{
|
||||
return (SystemWrites.query(SecuredDataTables.RETENTION_RULE, new QQueryFilter()
|
||||
.withCriteria(new QFilterCriteria("is_active", QCriteriaOperator.EQUALS, true))
|
||||
.withCriteria(new QFilterCriteria("table_name", QCriteriaOperator.EQUALS, table)))
|
||||
.stream().filter(rule -> fields(rule).contains(field)).toList());
|
||||
SecuredDataRuntime runtime = SecuredDataRuntime.current();
|
||||
List<QRecord> rules;
|
||||
if(runtime != null && (!readsOwnEdits() || READING_OWN_EDITS.get()))
|
||||
{
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
// also the answer to a question asked from inside this thread's read //
|
||||
// of its own edits (code that runs inside that query): the rules //
|
||||
// every other thread shares, and never another read of the edits //
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
rules = runtime.activeRetentionRules();
|
||||
}
|
||||
else
|
||||
{
|
||||
READING_OWN_EDITS.set(true);
|
||||
try
|
||||
{
|
||||
rules = SystemWrites.query(SecuredDataTables.RETENTION_RULE, new QQueryFilter()
|
||||
.withCriteria(new QFilterCriteria("is_active", QCriteriaOperator.EQUALS, true))
|
||||
.withCriteria(new QFilterCriteria("table_name", QCriteriaOperator.EQUALS, table)));
|
||||
}
|
||||
finally
|
||||
{
|
||||
READING_OWN_EDITS.remove();
|
||||
}
|
||||
}
|
||||
return (rules.stream().filter(rule -> table != null && table.equals(rule.getValueString("table_name"))).filter(rule -> fields(rule).contains(field)).toList());
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A rule was written on this thread inside a transaction that is still open.
|
||||
*******************************************************************************/
|
||||
public static void editedInTransaction()
|
||||
{
|
||||
EDITED_IN_TRANSACTION.set(true);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Whether this thread must read the rules through its open transaction.
|
||||
*******************************************************************************/
|
||||
private static boolean readsOwnEdits()
|
||||
{
|
||||
if(!EDITED_IN_TRANSACTION.get())
|
||||
{
|
||||
return (false);
|
||||
}
|
||||
if(QContext.getQBackendTransaction() == null)
|
||||
{
|
||||
EDITED_IN_TRANSACTION.remove();
|
||||
return (false);
|
||||
}
|
||||
return (true);
|
||||
}
|
||||
|
||||
/*******************************************************************************
|
||||
|
||||
@@ -35,19 +35,20 @@ import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
import com.kingsrook.qbits.secureddata.CoreAuditBridge;
|
||||
import com.kingsrook.qbits.secureddata.SecuredDataKeySource;
|
||||
import com.kingsrook.qbits.secureddata.SecuredDataRuntime;
|
||||
import com.kingsrook.qbits.secureddata.metadata.SecuredDataTables;
|
||||
import com.kingsrook.qbits.secureddata.support.ActivityLog;
|
||||
import com.kingsrook.qbits.secureddata.support.SystemWrites;
|
||||
import com.kingsrook.qqq.backend.core.actions.QBackendTransaction;
|
||||
import com.kingsrook.qqq.backend.core.actions.audits.AuditShreddedEvent;
|
||||
import com.kingsrook.qqq.backend.core.actions.tables.DeleteAction;
|
||||
import com.kingsrook.qqq.backend.core.actions.tables.QueryAction;
|
||||
import com.kingsrook.qqq.backend.core.actions.tables.UpdateAction;
|
||||
import com.kingsrook.qqq.backend.core.context.QContext;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QException;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QPermissionDeniedException;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.WipeAuditFlag;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.delete.DeleteInput;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QCriteriaOperator;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QFilterCriteria;
|
||||
@@ -292,7 +293,7 @@ public final class WipeService
|
||||
{
|
||||
throw (new QException("Audit key deletion failed."));
|
||||
}
|
||||
CoreAuditBridge.detail(table, pk, field, rule.getValueString("id"), true, transaction);
|
||||
AuditShreddedEvent.shreddedDetail(table, pk, table.getField(field), rule.getValueString("id"), transaction);
|
||||
}
|
||||
markers.add(new QRecord().withValue("table_name", table.getName()).withValue("record_id", String.valueOf(pk)).withValue("field_name", field)
|
||||
.withValue("rule_id", rule.getValue("id")).withValue("action", action).withValue("wiped_at", started));
|
||||
@@ -385,15 +386,9 @@ public final class WipeService
|
||||
patch.setValue(field, value);
|
||||
}
|
||||
UpdateInput input = new UpdateInput(table.getName()).withRecord(patch).withTransaction(transaction);
|
||||
CoreAuditBridge.flag(input, rule.getValueString("id"));
|
||||
input.setFlags(Set.of(new WipeAuditFlag(rule.getValueString("id"))));
|
||||
check(new UpdateAction().execute(input).getRecords());
|
||||
if(!CoreAuditBridge.available())
|
||||
{
|
||||
for(String field : fields)
|
||||
{
|
||||
CoreAuditBridge.detail(table, pk, field, rule.getValueString("id"), false, transaction);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/*******************************************************************************
|
||||
|
||||
@@ -30,13 +30,13 @@ import java.util.Objects;
|
||||
import com.kingsrook.qbits.secureddata.SecuredDataResolver;
|
||||
import com.kingsrook.qbits.secureddata.SecuredDataRuntime;
|
||||
import com.kingsrook.qbits.secureddata.metadata.SecuredDataTables;
|
||||
import com.kingsrook.qbits.secureddata.standin.FieldAccessTier;
|
||||
import com.kingsrook.qbits.secureddata.support.ActivityLog;
|
||||
import com.kingsrook.qbits.secureddata.support.SecuredDataMetadata;
|
||||
import com.kingsrook.qbits.secureddata.support.SystemWrites;
|
||||
import com.kingsrook.qqq.backend.core.actions.permissions.CorePermissionEnforcer;
|
||||
import com.kingsrook.qqq.backend.core.actions.permissions.PermissionEnforcement;
|
||||
import com.kingsrook.qqq.backend.core.actions.permissions.TablePermissionSubType;
|
||||
import com.kingsrook.qqq.backend.core.actions.permissions.fieldaccess.FieldAccessTier;
|
||||
import com.kingsrook.qqq.backend.core.actions.tables.GetAction;
|
||||
import com.kingsrook.qqq.backend.core.alerts.AlertSignal;
|
||||
import com.kingsrook.qqq.backend.core.alerts.QAlerts;
|
||||
|
||||
-50
@@ -1,50 +0,0 @@
|
||||
/*
|
||||
* QQQ - Low-code Application Framework for Engineers.
|
||||
* Copyright (C) 2021-2026. Kingsrook, LLC
|
||||
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
|
||||
* contact@kingsrook.com
|
||||
* https://github.com/Kingsrook/
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.secureddata.standin;
|
||||
|
||||
|
||||
import java.io.Serializable;
|
||||
import com.kingsrook.qbits.secureddata.standin.DMLType;
|
||||
import com.kingsrook.qqq.backend.core.actions.ai.AiDataClassifications;
|
||||
import com.kingsrook.qqq.backend.core.actions.ai.DataClassification;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Application hook for audit tokens and effective classification. Never return plain values.
|
||||
*******************************************************************************/
|
||||
// STAND-IN(core=QRun-IO/qqq#1182, removeBy=RC.8)
|
||||
public interface AuditValueProtectorInterface
|
||||
{
|
||||
/*******************************************************************************
|
||||
** Protect the values in the current action's transaction before audit insertion.
|
||||
*******************************************************************************/
|
||||
ProtectedAuditValues protect(QTableMetaData table, QFieldMetaData field, Serializable primaryKey, Serializable oldValue, Serializable newValue, DMLType dmlType);
|
||||
|
||||
/*******************************************************************************
|
||||
** Override to use an application-owned classification source.
|
||||
*******************************************************************************/
|
||||
default DataClassification classificationOf(QTableMetaData table, QFieldMetaData field)
|
||||
{
|
||||
return (AiDataClassifications.ofField(table, field.getName()));
|
||||
}
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
/*
|
||||
* QQQ - Low-code Application Framework for Engineers.
|
||||
* Copyright (C) 2021-2026. Kingsrook, LLC
|
||||
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
|
||||
* contact@kingsrook.com
|
||||
* https://github.com/Kingsrook/
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.secureddata.standin;
|
||||
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Optional;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Supplies instance keys and optional per-record, per-field shreddable keys.
|
||||
*******************************************************************************/
|
||||
// STAND-IN(core=QRun-IO/qqq#1182, removeBy=RC.8)
|
||||
public interface ClassifiedValueKeySource
|
||||
{
|
||||
/*******************************************************************************
|
||||
** The active instance key, if configured.
|
||||
*******************************************************************************/
|
||||
Optional<KeyAndId> instanceKey();
|
||||
|
||||
/*******************************************************************************
|
||||
** Verification uses create=false and must never recreate a destroyed key.
|
||||
*******************************************************************************/
|
||||
Optional<KeyAndId> keyForRecordField(String table, String field, Serializable pk, boolean create);
|
||||
|
||||
/*******************************************************************************
|
||||
** Key bytes and the public identifier stored in a token.
|
||||
*******************************************************************************/
|
||||
record KeyAndId(byte[] key, String id)
|
||||
{
|
||||
/*******************************************************************************
|
||||
** Own the key bytes; identifiers must keep tokens ASCII and under 200 characters.
|
||||
*******************************************************************************/
|
||||
public KeyAndId
|
||||
{
|
||||
if(key == null || key.length == 0 || id == null || !id.matches("[A-Za-z0-9._-]{1,140}"))
|
||||
{
|
||||
throw new IllegalArgumentException("Invalid classified-value key or identifier");
|
||||
}
|
||||
key = key.clone();
|
||||
}
|
||||
|
||||
/*******************************************************************************
|
||||
** Do not expose mutable key material.
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public byte[] key()
|
||||
{
|
||||
return (key.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,218 +0,0 @@
|
||||
/*
|
||||
* QQQ - Low-code Application Framework for Engineers.
|
||||
* Copyright (C) 2021-2026. Kingsrook, LLC
|
||||
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
|
||||
* contact@kingsrook.com
|
||||
* https://github.com/Kingsrook/
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.secureddata.standin;
|
||||
|
||||
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.io.Serializable;
|
||||
import java.math.BigDecimal;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import com.kingsrook.qbits.secureddata.standin.ClassifiedValueKeySource.KeyAndId;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
|
||||
import com.kingsrook.qqq.backend.core.utils.ValueUtils;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Shared, versioned audit/email value tokens. The MAC input is UTF-8.
|
||||
*******************************************************************************/
|
||||
// STAND-IN(core=QRun-IO/qqq#1182, removeBy=RC.8)
|
||||
public final class ClassifiedValueTokens
|
||||
{
|
||||
|
||||
/*******************************************************************************
|
||||
** Static utility.
|
||||
*******************************************************************************/
|
||||
private ClassifiedValueTokens()
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Bind a value to the table, field and primary key, preferring a shreddable key.
|
||||
*******************************************************************************/
|
||||
public static String forRecordField(QTableMetaData table, QFieldMetaData field, Serializable pk, Serializable value)
|
||||
{
|
||||
if(value == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
ClassifiedValueKeySource source = source();
|
||||
Optional<KeyAndId> key = source.keyForRecordField(table.getName(), field.getName(), pk, true);
|
||||
return key.isPresent() ? token("shred", key.get(), binding(table, field, pk), value)
|
||||
: instanceToken(source, binding(table, field, pk), value);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Non-record bindings must start with a nonempty domain.
|
||||
*******************************************************************************/
|
||||
public static String forContext(List<String> bindingParts, Serializable value)
|
||||
{
|
||||
validateDomain(bindingParts);
|
||||
return value == null ? null : instanceToken(source(), bindingParts, value);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** No derivative of the original value.
|
||||
*******************************************************************************/
|
||||
public static String changed()
|
||||
{
|
||||
return "changed:v1";
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A key-destruction event, never a derivative of the value.
|
||||
*******************************************************************************/
|
||||
public static String shreddedToken(String ruleId)
|
||||
{
|
||||
if(ruleId == null || !ruleId.matches("[A-Za-z0-9._-]{1,180}"))
|
||||
{
|
||||
throw new IllegalArgumentException("Invalid shred rule identifier");
|
||||
}
|
||||
return "shredded:v1:" + ruleId;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Verify only keyed tokens, using existing keys and constant-time MAC comparison.
|
||||
*******************************************************************************/
|
||||
public static boolean verifyRecordField(QTableMetaData table, QFieldMetaData field, Serializable pk, Serializable candidate, String token)
|
||||
{
|
||||
if(candidate == null || token == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
ClassifiedValueKeySource source = source();
|
||||
if(token.startsWith("shred:v1:"))
|
||||
{
|
||||
return verify(source.keyForRecordField(table.getName(), field.getName(), pk, false), "shred", binding(table, field, pk), candidate, token);
|
||||
}
|
||||
return verify(source.instanceKey(), "hmac", binding(table, field, pk), candidate, token);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Verify a non-record token without creating a key.
|
||||
*******************************************************************************/
|
||||
public static boolean verifyContext(List<String> bindingParts, Serializable candidate, String token)
|
||||
{
|
||||
validateDomain(bindingParts);
|
||||
return candidate != null && token != null && verify(source().instanceKey(), "hmac", bindingParts, candidate, token);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Canonical ValueUtils strings, with scale-independent plain decimal notation.
|
||||
*******************************************************************************/
|
||||
public static String canonical(Serializable value)
|
||||
{
|
||||
return value instanceof BigDecimal decimal ? decimal.stripTrailingZeros().toPlainString() : ValueUtils.getValueAsString(value);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Validate the context even for absent values.
|
||||
*******************************************************************************/
|
||||
private static void validateDomain(List<String> parts)
|
||||
{
|
||||
if(parts == null || parts.isEmpty() || parts.get(0) == null || parts.get(0).isBlank() || parts.stream().anyMatch(p -> p == null || p.indexOf('\u001F') >= 0))
|
||||
{
|
||||
throw new IllegalArgumentException("A nonempty domain and unambiguous binding parts are required");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The agreed record binding does not prepend an additional domain.
|
||||
*******************************************************************************/
|
||||
private static List<String> binding(QTableMetaData table, QFieldMetaData field, Serializable pk)
|
||||
{
|
||||
return List.of(table.getName(), field.getName(), String.valueOf(pk));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Emit a keyed token or a value-free fallback.
|
||||
*******************************************************************************/
|
||||
private static String instanceToken(ClassifiedValueKeySource source, List<String> parts, Serializable value)
|
||||
{
|
||||
return source.instanceKey().map(key -> token("hmac", key, parts, value)).orElseGet(ClassifiedValueTokens::changed);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Compare full tokens, including the key identifier and version.
|
||||
*******************************************************************************/
|
||||
private static boolean verify(Optional<KeyAndId> key, String kind, List<String> parts, Serializable value, String supplied)
|
||||
{
|
||||
return key.map(k -> MessageDigest.isEqual(token(kind, k, parts, value).getBytes(StandardCharsets.UTF_8), supplied.getBytes(StandardCharsets.UTF_8))).orElse(false);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Encode the HMAC with URL-safe base64 and no padding.
|
||||
*******************************************************************************/
|
||||
private static String token(String kind, KeyAndId key, List<String> parts, Serializable value)
|
||||
{
|
||||
try
|
||||
{
|
||||
Mac mac = Mac.getInstance("HmacSHA256");
|
||||
mac.init(new SecretKeySpec(key.key(), "HmacSHA256"));
|
||||
byte[] digest = mac.doFinal((String.join("\u001F", parts) + "\u001F" + canonical(value)).getBytes(StandardCharsets.UTF_8));
|
||||
return kind + ":v1:" + key.id() + ":" + Base64.getUrlEncoder().withoutPadding().encodeToString(digest);
|
||||
}
|
||||
catch(GeneralSecurityException e)
|
||||
{
|
||||
throw new IllegalStateException("Unable to compute classified-value token", e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Use instance metadata, falling back to environment/property configuration.
|
||||
*******************************************************************************/
|
||||
private static ClassifiedValueKeySource source()
|
||||
{
|
||||
return (com.kingsrook.qbits.secureddata.SecuredDataRuntime.current().keys());
|
||||
}
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
/*
|
||||
* QQQ - Low-code Application Framework for Engineers.
|
||||
* Copyright (C) 2021-2025. Kingsrook, LLC
|
||||
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
|
||||
* contact@kingsrook.com
|
||||
* https://github.com/Kingsrook/
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.secureddata.standin;
|
||||
|
||||
/*******************************************************************************
|
||||
** RC.6's nested DMLType is package-private; #1182 makes it public.
|
||||
*******************************************************************************/
|
||||
// STAND-IN(core=QRun-IO/qqq#1182, removeBy=RC.8)
|
||||
public enum DMLType
|
||||
{
|
||||
INSERT, UPDATE, DELETE, OTHER
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
/*
|
||||
* QQQ - Low-code Application Framework for Engineers.
|
||||
* Copyright (C) 2021-2026. Kingsrook, LLC
|
||||
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
|
||||
* contact@kingsrook.com
|
||||
* https://github.com/Kingsrook/
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.secureddata.standin;
|
||||
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A resolver decision; the reason must never contain a field value.
|
||||
*******************************************************************************/
|
||||
// STAND-IN(core=QRun-IO/qqq#1172, removeBy=RC.8): copy of com.kingsrook.qqq.backend.core.actions.permissions.fieldaccess.FieldAccessDecision; delete when the pin moves to the first QQQ RC with #1172 and #1182 (RC.8).
|
||||
public record FieldAccessDecision(FieldAccessTier tier, FieldMaskStyle maskStyle, String reason, boolean exactMatchAllowed)
|
||||
{
|
||||
public static final FieldAccessDecision FULL = new FieldAccessDecision(FieldAccessTier.FULL, null, null);
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Compatibility constructor: exact-match searches are allowed by default.
|
||||
*******************************************************************************/
|
||||
public FieldAccessDecision(FieldAccessTier tier, FieldMaskStyle maskStyle, String reason)
|
||||
{
|
||||
this(tier, maskStyle, reason, true);
|
||||
}
|
||||
}
|
||||
@@ -1,272 +0,0 @@
|
||||
/*
|
||||
* QQQ - Low-code Application Framework for Engineers.
|
||||
* Copyright (C) 2021-2026. Kingsrook, LLC
|
||||
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
|
||||
* contact@kingsrook.com
|
||||
* https://github.com/Kingsrook/
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.secureddata.standin;
|
||||
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Value-free audit notification. Primary key samples contain at most 50 keys.
|
||||
*******************************************************************************/
|
||||
// STAND-IN(core=QRun-IO/qqq#1172, removeBy=RC.8): copy of com.kingsrook.qqq.backend.core.actions.permissions.fieldaccess.FieldAccessEvent; delete when the pin moves to the first QQQ RC with #1172 and #1182 (RC.8).
|
||||
public class FieldAccessEvent
|
||||
{
|
||||
private FieldAccessEventType type;
|
||||
private String tableName;
|
||||
private List<String> fieldNames;
|
||||
private List<Serializable> primaryKeys;
|
||||
private Integer recordCount;
|
||||
private String actionName;
|
||||
private FieldAccessOutcome outcome;
|
||||
private List<String> searchValueFingerprints;
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for type
|
||||
*******************************************************************************/
|
||||
public FieldAccessEventType getType()
|
||||
{
|
||||
return (this.type);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Setter for type
|
||||
*******************************************************************************/
|
||||
public void setType(FieldAccessEventType type)
|
||||
{
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fluent setter for type
|
||||
*******************************************************************************/
|
||||
public FieldAccessEvent withType(FieldAccessEventType type)
|
||||
{
|
||||
setType(type);
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for tableName
|
||||
*******************************************************************************/
|
||||
public String getTableName()
|
||||
{
|
||||
return (this.tableName);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Setter for tableName
|
||||
*******************************************************************************/
|
||||
public void setTableName(String tableName)
|
||||
{
|
||||
this.tableName = tableName;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fluent setter for tableName
|
||||
*******************************************************************************/
|
||||
public FieldAccessEvent withTableName(String tableName)
|
||||
{
|
||||
setTableName(tableName);
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for fieldNames
|
||||
*******************************************************************************/
|
||||
public List<String> getFieldNames()
|
||||
{
|
||||
return (this.fieldNames);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Setter for fieldNames
|
||||
*******************************************************************************/
|
||||
public void setFieldNames(List<String> fieldNames)
|
||||
{
|
||||
this.fieldNames = fieldNames == null ? null : new ArrayList<>(fieldNames);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fluent setter for fieldNames
|
||||
*******************************************************************************/
|
||||
public FieldAccessEvent withFieldNames(List<String> fieldNames)
|
||||
{
|
||||
setFieldNames(fieldNames);
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for primaryKeys
|
||||
*******************************************************************************/
|
||||
public List<Serializable> getPrimaryKeys()
|
||||
{
|
||||
return (this.primaryKeys == null ? null : Collections.unmodifiableList(this.primaryKeys));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Setter for primaryKeys
|
||||
*******************************************************************************/
|
||||
public void setPrimaryKeys(List<Serializable> primaryKeys)
|
||||
{
|
||||
this.primaryKeys = primaryKeys == null ? null : new ArrayList<>(primaryKeys.subList(0, Math.min(50, primaryKeys.size())));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fluent setter for primaryKeys
|
||||
*******************************************************************************/
|
||||
public FieldAccessEvent withPrimaryKeys(List<Serializable> primaryKeys)
|
||||
{
|
||||
setPrimaryKeys(primaryKeys);
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for recordCount
|
||||
*******************************************************************************/
|
||||
public Integer getRecordCount()
|
||||
{
|
||||
return (this.recordCount);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Setter for recordCount
|
||||
*******************************************************************************/
|
||||
public void setRecordCount(Integer recordCount)
|
||||
{
|
||||
this.recordCount = recordCount;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fluent setter for recordCount
|
||||
*******************************************************************************/
|
||||
public FieldAccessEvent withRecordCount(Integer recordCount)
|
||||
{
|
||||
setRecordCount(recordCount);
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for actionName
|
||||
*******************************************************************************/
|
||||
public String getActionName()
|
||||
{
|
||||
return (this.actionName);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Setter for actionName
|
||||
*******************************************************************************/
|
||||
public void setActionName(String actionName)
|
||||
{
|
||||
this.actionName = actionName;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fluent setter for actionName
|
||||
*******************************************************************************/
|
||||
public FieldAccessEvent withActionName(String actionName)
|
||||
{
|
||||
setActionName(actionName);
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for outcome
|
||||
*******************************************************************************/
|
||||
public FieldAccessOutcome getOutcome()
|
||||
{
|
||||
return (outcome);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fluent setter for outcome
|
||||
*******************************************************************************/
|
||||
public FieldAccessEvent withOutcome(FieldAccessOutcome outcome)
|
||||
{
|
||||
this.outcome = outcome;
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Getter for searchValueFingerprints
|
||||
*******************************************************************************/
|
||||
public List<String> getSearchValueFingerprints()
|
||||
{
|
||||
return (searchValueFingerprints);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fluent setter for searchValueFingerprints
|
||||
*******************************************************************************/
|
||||
public FieldAccessEvent withSearchValueFingerprints(List<String> searchValueFingerprints)
|
||||
{
|
||||
this.searchValueFingerprints = searchValueFingerprints == null ? null : List.copyOf(searchValueFingerprints);
|
||||
return (this);
|
||||
}
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
/*
|
||||
* QQQ - Low-code Application Framework for Engineers.
|
||||
* Copyright (C) 2021-2026. Kingsrook, LLC
|
||||
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
|
||||
* contact@kingsrook.com
|
||||
* https://github.com/Kingsrook/
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.secureddata.standin;
|
||||
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Kinds of field access reported to the resolver.
|
||||
*******************************************************************************/
|
||||
// STAND-IN(core=QRun-IO/qqq#1172, removeBy=RC.8): copy of com.kingsrook.qqq.backend.core.actions.permissions.fieldaccess.FieldAccessEventType; delete when the pin moves to the first QQQ RC with #1172 and #1182 (RC.8).
|
||||
public enum FieldAccessEventType
|
||||
{
|
||||
VIEW, EXACT_MATCH_FILTER, DENIED
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
/*
|
||||
* QQQ - Low-code Application Framework for Engineers.
|
||||
* Copyright (C) 2021-2026. Kingsrook, LLC
|
||||
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
|
||||
* contact@kingsrook.com
|
||||
* https://github.com/Kingsrook/
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.secureddata.standin;
|
||||
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Outcome of an exact-match search.
|
||||
*******************************************************************************/
|
||||
// STAND-IN(core=QRun-IO/qqq#1172, removeBy=RC.8): copy of com.kingsrook.qqq.backend.core.actions.permissions.fieldaccess.FieldAccessOutcome; delete when the pin moves to the first QQQ RC with #1172 and #1182 (RC.8).
|
||||
public enum FieldAccessOutcome
|
||||
{
|
||||
MATCH, NO_MATCH, REFUSED
|
||||
}
|
||||
-90
@@ -1,90 +0,0 @@
|
||||
/*
|
||||
* QQQ - Low-code Application Framework for Engineers.
|
||||
* Copyright (C) 2021-2026. Kingsrook, LLC
|
||||
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
|
||||
* contact@kingsrook.com
|
||||
* https://github.com/Kingsrook/
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.secureddata.standin;
|
||||
|
||||
|
||||
import java.io.Serializable;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QPermissionDeniedException;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Session-aware policy, reveal grants and value-free access notifications.
|
||||
*******************************************************************************/
|
||||
// STAND-IN(core=QRun-IO/qqq#1172, removeBy=RC.8): copy of com.kingsrook.qqq.backend.core.actions.permissions.fieldaccess.FieldAccessResolverInterface; delete when the pin moves to the first QQQ RC with #1172 and #1182 (RC.8).
|
||||
public interface FieldAccessResolverInterface
|
||||
{
|
||||
/*******************************************************************************
|
||||
** Resolve using the current QContext session.
|
||||
*******************************************************************************/
|
||||
FieldAccessDecision resolve(QTableMetaData table, QFieldMetaData field);
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Whether this record and field have an active reveal grant.
|
||||
*******************************************************************************/
|
||||
default boolean isRevealActive(String tableName, String fieldName, Serializable primaryKey)
|
||||
{
|
||||
return (false);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Stable identity of effective access, excluding reveal grants.
|
||||
*******************************************************************************/
|
||||
default String getAccessFingerprint()
|
||||
{
|
||||
return ("");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Receive an audit notification; failures never prevent enforcement.
|
||||
*******************************************************************************/
|
||||
default void onAccess(FieldAccessEvent event)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Refuse an exact-match search before execution; the exception message is user-facing.
|
||||
*******************************************************************************/
|
||||
default void checkExactMatch(FieldAccessEvent event) throws QPermissionDeniedException
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** One-way fingerprint of a search literal. Raw values never enter access events.
|
||||
*******************************************************************************/
|
||||
default String fingerprintSearchValue(Serializable value)
|
||||
{
|
||||
return (null);
|
||||
}
|
||||
}
|
||||
@@ -1,126 +0,0 @@
|
||||
/*
|
||||
* QQQ - Low-code Application Framework for Engineers.
|
||||
* Copyright (C) 2021-2026. Kingsrook, LLC
|
||||
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
|
||||
* contact@kingsrook.com
|
||||
* https://github.com/Kingsrook/
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.secureddata.standin;
|
||||
|
||||
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QCriteriaOperator;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Effective field access, ordered from least to most restrictive.
|
||||
*******************************************************************************/
|
||||
// STAND-IN(core=QRun-IO/qqq#1172, removeBy=RC.8): copy of com.kingsrook.qqq.backend.core.actions.permissions.fieldaccess.FieldAccessTier; delete when the pin moves to the first QQQ RC with #1172 and #1182 (RC.8).
|
||||
public enum FieldAccessTier
|
||||
{
|
||||
FULL, REVEALABLE, MASKED, HIDDEN;
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** canReadValue
|
||||
*******************************************************************************/
|
||||
public boolean canReadValue()
|
||||
{
|
||||
return (this == FULL);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** canSort
|
||||
*******************************************************************************/
|
||||
public boolean canSort()
|
||||
{
|
||||
return (this == FULL);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** canGroupOrAggregate
|
||||
*******************************************************************************/
|
||||
public boolean canGroupOrAggregate()
|
||||
{
|
||||
return (this == FULL);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** canQuickSearch
|
||||
*******************************************************************************/
|
||||
public boolean canQuickSearch()
|
||||
{
|
||||
return (this == FULL);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** canWrite
|
||||
*******************************************************************************/
|
||||
public boolean canWrite()
|
||||
{
|
||||
return (this == FULL);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Whether the operator is available for this tier.
|
||||
*******************************************************************************/
|
||||
public boolean canFilter(QCriteriaOperator operator)
|
||||
{
|
||||
return (this == FULL || (this == REVEALABLE && (operator == QCriteriaOperator.EQUALS || operator == QCriteriaOperator.IN)));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Whether the field may be described to the caller.
|
||||
*******************************************************************************/
|
||||
public boolean isInMetaData()
|
||||
{
|
||||
return (this != HIDDEN);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Combine tiers; null means FULL.
|
||||
*******************************************************************************/
|
||||
public FieldAccessTier mostRestrictive(FieldAccessTier other)
|
||||
{
|
||||
FieldAccessTier candidate = other == null ? FULL : other;
|
||||
return (ordinal() > candidate.ordinal() ? this : candidate);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Combine tiers; null means FULL.
|
||||
*******************************************************************************/
|
||||
public FieldAccessTier leastRestrictive(FieldAccessTier other)
|
||||
{
|
||||
FieldAccessTier candidate = other == null ? FULL : other;
|
||||
return (ordinal() < candidate.ordinal() ? this : candidate);
|
||||
}
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
/*
|
||||
* QQQ - Low-code Application Framework for Engineers.
|
||||
* Copyright (C) 2021-2026. Kingsrook, LLC
|
||||
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
|
||||
* contact@kingsrook.com
|
||||
* https://github.com/Kingsrook/
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.secureddata.standin;
|
||||
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Presentation rules for a restricted value.
|
||||
*******************************************************************************/
|
||||
// STAND-IN(core=QRun-IO/qqq#1172, removeBy=RC.8): copy of com.kingsrook.qqq.backend.core.actions.permissions.fieldaccess.FieldMaskStyle; delete when the pin moves to the first QQQ RC with #1172 and #1182 (RC.8).
|
||||
public enum FieldMaskStyle
|
||||
{
|
||||
AUTO, EMAIL, LAST_4, FIRST_LAST, FULL
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
/*
|
||||
* QQQ - Low-code Application Framework for Engineers.
|
||||
* Copyright (C) 2021-2026. Kingsrook, LLC
|
||||
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
|
||||
* contact@kingsrook.com
|
||||
* https://github.com/Kingsrook/
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.secureddata.standin;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Tokens and a value-free message supplied before an audit is inserted.
|
||||
*******************************************************************************/
|
||||
// STAND-IN(core=QRun-IO/qqq#1182, removeBy=RC.8)
|
||||
public record ProtectedAuditValues(String oldToken, String newToken, String message)
|
||||
{
|
||||
}
|
||||
@@ -21,7 +21,9 @@
|
||||
package com.kingsrook.qbits.secureddata.support;
|
||||
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import com.kingsrook.qqq.backend.core.actions.QBackendTransaction;
|
||||
import com.kingsrook.qqq.backend.core.actions.permissions.CorePermissionEnforcer;
|
||||
import com.kingsrook.qqq.backend.core.actions.tables.InsertAction;
|
||||
@@ -32,6 +34,7 @@ import com.kingsrook.qqq.backend.core.model.actions.tables.insert.InsertInput;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QueryInput;
|
||||
import com.kingsrook.qqq.backend.core.model.data.QRecord;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.session.QSession;
|
||||
import com.kingsrook.qqq.backend.core.model.session.QSystemUserSession;
|
||||
|
||||
@@ -100,13 +103,15 @@ public final class SystemWrites
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Query without user locks or field access recursion.
|
||||
** Query without user locks or field access recursion, for the stored fields of
|
||||
** the table only (see storedFields).
|
||||
*******************************************************************************/
|
||||
public static List<QRecord> query(String table, QQueryFilter filter)
|
||||
{
|
||||
try
|
||||
{
|
||||
return (call(() -> new QueryAction().execute(new QueryInput(table).withFilter(filter).withTransaction(QContext.getQBackendTransaction())).getRecords()));
|
||||
return (call(() -> new QueryAction().execute(new QueryInput(table).withFilter(filter).withFieldNamesToInclude(storedFields(table))
|
||||
.withTransaction(QContext.getQBackendTransaction())).getRecords()));
|
||||
}
|
||||
catch(QException e)
|
||||
{
|
||||
@@ -116,6 +121,22 @@ public final class SystemWrites
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The names of the stored fields of a table, as the projection of a system
|
||||
** read. A query that names its fields is not given virtual fields, so core
|
||||
** runs none of the value providers another QBit or the host may have added to
|
||||
** a secured-data table: this QBit reads its own columns and nothing else, and
|
||||
** a provider cannot be made to run inside a rule read. Null (every field, and
|
||||
** the error core reports) for a table the instance does not have.
|
||||
*******************************************************************************/
|
||||
public static Set<String> storedFields(String tableName)
|
||||
{
|
||||
QTableMetaData table = QContext.getQInstance().getTable(tableName);
|
||||
return (table == null ? null : new HashSet<>(table.getFields().keySet()));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Insert and reject backend record errors.
|
||||
*******************************************************************************/
|
||||
|
||||
@@ -37,11 +37,11 @@ public final class SecuredDataExtension
|
||||
}
|
||||
|
||||
/*******************************************************************************
|
||||
** The secured-data UI API, version 1.0.0.
|
||||
** The secured-data UI API, version 1.1.0.
|
||||
*******************************************************************************/
|
||||
public static MiddlewareSpecExtension defineExtension()
|
||||
{
|
||||
return (new MiddlewareSpecExtension().withName("secured-data").withSemanticVersion("1.0.0")
|
||||
return (new MiddlewareSpecExtension().withName("secured-data").withSemanticVersion("1.1.0")
|
||||
.withDescription("Reveal grants and break-glass status")
|
||||
.withSpec(SecuredDataRevealSpecV1.class).withSpec(SecuredDataRevealOptionsSpecV1.class).withSpec(SecuredDataStatusSpecV1.class));
|
||||
}
|
||||
|
||||
+1
-1
@@ -41,7 +41,7 @@ public class SecuredDataRevealOptionsSpecV1 extends AbstractJsonEndpointSpec
|
||||
public BasicOperation defineBasicOperation()
|
||||
{
|
||||
return (new BasicOperation().withPath("/qbit/secured-data/reveal/options").withHttpMethod(HttpMethod.GET)
|
||||
.withTag(() -> "Secured data").withShortSummary("RevealOptions"));
|
||||
.withTag(() -> "secured-data").withShortSummary("RevealOptions"));
|
||||
}
|
||||
|
||||
/*******************************************************************************
|
||||
|
||||
@@ -28,6 +28,7 @@ import com.kingsrook.qbits.secureddata.reveal.RevealService;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QBadRequestException;
|
||||
import com.kingsrook.qqq.middleware.javalin.specs.BasicOperation;
|
||||
import com.kingsrook.qqq.middleware.javalin.specs.extensions.AbstractJsonEndpointSpec;
|
||||
import com.kingsrook.qqq.middleware.javalin.specs.v1.responses.BasicErrorResponseV1;
|
||||
import com.kingsrook.qqq.openapi.model.HttpMethod;
|
||||
import com.kingsrook.qqq.openapi.model.Parameter;
|
||||
import com.kingsrook.qqq.openapi.model.Schema;
|
||||
@@ -44,7 +45,7 @@ public class SecuredDataRevealSpecV1 extends AbstractJsonEndpointSpec
|
||||
public BasicOperation defineBasicOperation()
|
||||
{
|
||||
return (new BasicOperation().withPath("/qbit/secured-data/reveal").withHttpMethod(HttpMethod.POST)
|
||||
.withTag(() -> "Secured data").withShortSummary("Reveal"));
|
||||
.withTag(() -> "secured-data").withShortSummary("Reveal"));
|
||||
}
|
||||
|
||||
/*******************************************************************************
|
||||
@@ -81,10 +82,10 @@ public class SecuredDataRevealSpecV1 extends AbstractJsonEndpointSpec
|
||||
@Override
|
||||
public List<com.kingsrook.qqq.middleware.javalin.specs.BasicResponse> defineAdditionalBasicResponses()
|
||||
{
|
||||
return (List.of(new com.kingsrook.qqq.middleware.javalin.specs.BasicResponse(io.javalin.http.HttpStatus.BAD_REQUEST, "Invalid reveal request", "SecuredDataErrorV1"),
|
||||
new com.kingsrook.qqq.middleware.javalin.specs.BasicResponse(io.javalin.http.HttpStatus.FORBIDDEN, "Reveal denied", "SecuredDataErrorV1"),
|
||||
new com.kingsrook.qqq.middleware.javalin.specs.BasicResponse(io.javalin.http.HttpStatus.NOT_FOUND, "Record not found or locked", "SecuredDataErrorV1"),
|
||||
new com.kingsrook.qqq.middleware.javalin.specs.BasicResponse(io.javalin.http.HttpStatus.TOO_MANY_REQUESTS, "Daily reveal cap reached", "SecuredDataErrorV1")));
|
||||
return (List.of(new com.kingsrook.qqq.middleware.javalin.specs.BasicResponse(io.javalin.http.HttpStatus.BAD_REQUEST, "Invalid reveal request", BasicErrorResponseV1.class.getSimpleName()),
|
||||
new com.kingsrook.qqq.middleware.javalin.specs.BasicResponse(io.javalin.http.HttpStatus.FORBIDDEN, "Reveal denied", BasicErrorResponseV1.class.getSimpleName()),
|
||||
new com.kingsrook.qqq.middleware.javalin.specs.BasicResponse(io.javalin.http.HttpStatus.NOT_FOUND, "Record not found or locked", BasicErrorResponseV1.class.getSimpleName()),
|
||||
new com.kingsrook.qqq.middleware.javalin.specs.BasicResponse(io.javalin.http.HttpStatus.TOO_MANY_REQUESTS, "Daily reveal cap reached", BasicErrorResponseV1.class.getSimpleName())));
|
||||
}
|
||||
|
||||
/*******************************************************************************
|
||||
|
||||
@@ -58,7 +58,8 @@ public final class SecuredDataSchemas
|
||||
schemas.put("SecuredDataRevealAllowanceV1", object("tableName", type(Type.STRING), "fieldName", type(Type.STRING), "remainingDailyAllowance", type(Type.INTEGER).withNullable(true)));
|
||||
schemas.put("SecuredDataStatusResponseV1", object("breakGlass", new Schema().withRefToSchema("SecuredDataBreakGlassV1").withNullable(true),
|
||||
"revealsUsedToday", type(Type.INTEGER), "revealAllowances", type(Type.ARRAY).withItems(new Schema().withRefToSchema("SecuredDataRevealAllowanceV1"))));
|
||||
schemas.put("SecuredDataErrorV1", object("error", type(Type.STRING)));
|
||||
schemas.put("SecuredDataErrorV1", object("error", type(Type.STRING))
|
||||
.withDescription("Deprecated since 1.1.0: errors use BasicErrorResponseV1."));
|
||||
return (schemas);
|
||||
}
|
||||
|
||||
|
||||
@@ -41,7 +41,7 @@ public class SecuredDataStatusSpecV1 extends AbstractJsonEndpointSpec
|
||||
public BasicOperation defineBasicOperation()
|
||||
{
|
||||
return (new BasicOperation().withPath("/qbit/secured-data/status").withHttpMethod(HttpMethod.GET)
|
||||
.withTag(() -> "Secured data").withShortSummary("Status"));
|
||||
.withTag(() -> "secured-data").withShortSummary("Status"));
|
||||
}
|
||||
|
||||
/*******************************************************************************
|
||||
|
||||
@@ -1,5 +1,44 @@
|
||||
components:
|
||||
schemas:
|
||||
BasicErrorResponseV1:
|
||||
description: "The error body of every UI API operation (core and extensions)."
|
||||
properties:
|
||||
error:
|
||||
description: "The error message (the same as message; kept for clients of\
|
||||
\ UI API 1.0 to 1.5)."
|
||||
type: "string"
|
||||
code:
|
||||
description: "A stable, machine-readable code. Well-known values: BAD_REQUEST\
|
||||
\ (400), UNAUTHENTICATED (401),\nPERMISSION_DENIED (403), NOT_FOUND (404),\
|
||||
\ CONFLICT (409), RATE_LIMITED (429), INTERNAL_ERROR (500),\nERROR (other).\
|
||||
\ Extensions may add codes; treat an unknown code by the HTTP status.\
|
||||
\ Since 1.6.0."
|
||||
type: "string"
|
||||
message:
|
||||
description: "A message to show the user. Since 1.6.0."
|
||||
type: "string"
|
||||
fieldErrors:
|
||||
description: "Errors about particular request fields, when known. Since\
|
||||
\ 1.6.0."
|
||||
items:
|
||||
properties:
|
||||
field:
|
||||
description: "The field (or parameter) name."
|
||||
type: "string"
|
||||
message:
|
||||
description: "The error about that field."
|
||||
type: "string"
|
||||
code:
|
||||
description: "An optional machine-readable code, e.g. REQUIRED, TOO_LONG,\
|
||||
\ PATTERN."
|
||||
type: "string"
|
||||
type: "object"
|
||||
type: "array"
|
||||
traceId:
|
||||
description: "Identifies this request in the server logs (also the X-QQQ-Trace-Id\
|
||||
\ response header); quote it when reporting a problem. Since 1.6.0."
|
||||
type: "string"
|
||||
type: "object"
|
||||
SecuredDataBreakGlassV1:
|
||||
properties:
|
||||
id:
|
||||
@@ -16,6 +55,7 @@ components:
|
||||
type: "string"
|
||||
type: "object"
|
||||
SecuredDataErrorV1:
|
||||
description: "Deprecated since 1.1.0: errors use BasicErrorResponseV1."
|
||||
properties:
|
||||
error:
|
||||
type: "string"
|
||||
@@ -96,19 +136,53 @@ components:
|
||||
type: "object"
|
||||
securitySchemes:
|
||||
sessionUuidCookie:
|
||||
description: "The session cookie set by POST /qqq/v1/manageSession (web clients)."
|
||||
in: "cookie"
|
||||
name: "sessionUUID"
|
||||
type: "apiKey"
|
||||
bearerAuth:
|
||||
bearerFormat: "JWT or session UUID"
|
||||
description: "`Authorization: Bearer <token>`, where the token is either\n-\
|
||||
\ an OAuth2 access token (a signed JWT) issued by the app's identity provider\
|
||||
\ to the app's client,\n or to its native client (`values.nativeClientId`\
|
||||
\ in GET /qqq/v1/metaData/authentication), for\n example from the device-authorization\
|
||||
\ grant or auth-code + PKCE. It is verified against the\n provider's keys\
|
||||
\ (issuer, audience, expiry, signature) and gives the same user and permissions\n\
|
||||
\ as signing in on the web. When it expires (401), refresh it at the provider\
|
||||
\ and retry; or\n- a session UUID returned by POST /qqq/v1/manageSession,\
|
||||
\ which the server keeps refreshed."
|
||||
scheme: "bearer"
|
||||
type: "http"
|
||||
oauth2:
|
||||
description: "The app's OAuth2 / OpenID Connect provider. The real endpoints\
|
||||
\ come from the provider's discovery\ndocument: `{values.baseUrl}.well-known/openid-configuration`,\
|
||||
\ with values from\nGET /qqq/v1/metaData/authentication. Native clients use\
|
||||
\ `values.nativeClientId` (a public client)\nwith auth-code + PKCE (loopback\
|
||||
\ or custom-scheme redirect URI registered at the provider) or the\ndevice-authorization\
|
||||
\ grant (`device_authorization_endpoint`, RFC 8628), then send the access\
|
||||
\ token\nas `Authorization: Bearer`."
|
||||
flows:
|
||||
authorizationCode:
|
||||
authorizationUrl: "/authorize"
|
||||
scopes:
|
||||
email: "Email address"
|
||||
offline_access: "A refresh token, to renew the access token without signing\
|
||||
\ in again"
|
||||
openid: "OpenID Connect sign-in"
|
||||
profile: "Name, username and groups (permissions come from the groups)"
|
||||
tokenUrl: "/token"
|
||||
type: "oauth2"
|
||||
info:
|
||||
contact:
|
||||
email: "contact@kingsrook.com"
|
||||
description: "Reveal grants and break-glass status"
|
||||
title: "QQQ Middleware API extension: secured-data"
|
||||
version: "1.0.0"
|
||||
version: "1.1.0"
|
||||
openapi: "3.0.3"
|
||||
paths:
|
||||
/qqq/v1/qbit/secured-data/reveal:
|
||||
post:
|
||||
operationId: "postQbitSecuredDataReveal"
|
||||
requestBody:
|
||||
content:
|
||||
application/json:
|
||||
@@ -120,19 +194,19 @@ paths:
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/SecuredDataErrorV1"
|
||||
$ref: "#/components/schemas/BasicErrorResponseV1"
|
||||
description: "Invalid reveal request"
|
||||
403:
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/SecuredDataErrorV1"
|
||||
$ref: "#/components/schemas/BasicErrorResponseV1"
|
||||
description: "Reveal denied"
|
||||
404:
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/SecuredDataErrorV1"
|
||||
$ref: "#/components/schemas/BasicErrorResponseV1"
|
||||
description: "Record not found or locked"
|
||||
200:
|
||||
content:
|
||||
@@ -144,16 +218,37 @@ paths:
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/SecuredDataErrorV1"
|
||||
$ref: "#/components/schemas/BasicErrorResponseV1"
|
||||
description: "Daily reveal cap reached"
|
||||
401:
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/BasicErrorResponseV1"
|
||||
description: "Not authenticated, or the session or token is invalid or expired\
|
||||
\ (code UNAUTHENTICATED). Sign in again, or refresh the token."
|
||||
409:
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/BasicErrorResponseV1"
|
||||
description: "Conflict with the current state, e.g. an edit conflict or\
|
||||
\ an invalid transition (code CONFLICT)."
|
||||
security:
|
||||
- sessionUuidCookie:
|
||||
- "N/A"
|
||||
- bearerAuth:
|
||||
- "N/A"
|
||||
- oauth2:
|
||||
- "openid"
|
||||
- "profile"
|
||||
- "email"
|
||||
summary: "Reveal"
|
||||
tags:
|
||||
- "Secured data"
|
||||
- "secured-data"
|
||||
/qqq/v1/qbit/secured-data/reveal/options:
|
||||
get:
|
||||
operationId: "getQbitSecuredDataRevealOptions"
|
||||
parameters:
|
||||
- in: "query"
|
||||
name: "tableName"
|
||||
@@ -172,14 +267,61 @@ paths:
|
||||
schema:
|
||||
$ref: "#/components/schemas/SecuredDataRevealOptionsResponseV1"
|
||||
description: "Successful Response"
|
||||
400:
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/BasicErrorResponseV1"
|
||||
description: "Bad request: a parameter or the body is invalid (code BAD_REQUEST);\
|
||||
\ fieldErrors may name the fields."
|
||||
401:
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/BasicErrorResponseV1"
|
||||
description: "Not authenticated, or the session or token is invalid or expired\
|
||||
\ (code UNAUTHENTICATED). Sign in again, or refresh the token."
|
||||
403:
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/BasicErrorResponseV1"
|
||||
description: "The user (or the credential's scope) may not do this (code\
|
||||
\ PERMISSION_DENIED)."
|
||||
404:
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/BasicErrorResponseV1"
|
||||
description: "Not found, or not visible to this user (code NOT_FOUND)."
|
||||
409:
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/BasicErrorResponseV1"
|
||||
description: "Conflict with the current state, e.g. an edit conflict or\
|
||||
\ an invalid transition (code CONFLICT)."
|
||||
429:
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/BasicErrorResponseV1"
|
||||
description: "Too many requests (code RATE_LIMITED); retry later."
|
||||
security:
|
||||
- sessionUuidCookie:
|
||||
- "N/A"
|
||||
- bearerAuth:
|
||||
- "N/A"
|
||||
- oauth2:
|
||||
- "openid"
|
||||
- "profile"
|
||||
- "email"
|
||||
summary: "RevealOptions"
|
||||
tags:
|
||||
- "Secured data"
|
||||
- "secured-data"
|
||||
/qqq/v1/qbit/secured-data/status:
|
||||
get:
|
||||
operationId: "getQbitSecuredDataStatus"
|
||||
responses:
|
||||
200:
|
||||
content:
|
||||
@@ -187,9 +329,61 @@ paths:
|
||||
schema:
|
||||
$ref: "#/components/schemas/SecuredDataStatusResponseV1"
|
||||
description: "Successful Response"
|
||||
400:
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/BasicErrorResponseV1"
|
||||
description: "Bad request: a parameter or the body is invalid (code BAD_REQUEST);\
|
||||
\ fieldErrors may name the fields."
|
||||
401:
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/BasicErrorResponseV1"
|
||||
description: "Not authenticated, or the session or token is invalid or expired\
|
||||
\ (code UNAUTHENTICATED). Sign in again, or refresh the token."
|
||||
403:
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/BasicErrorResponseV1"
|
||||
description: "The user (or the credential's scope) may not do this (code\
|
||||
\ PERMISSION_DENIED)."
|
||||
404:
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/BasicErrorResponseV1"
|
||||
description: "Not found, or not visible to this user (code NOT_FOUND)."
|
||||
409:
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/BasicErrorResponseV1"
|
||||
description: "Conflict with the current state, e.g. an edit conflict or\
|
||||
\ an invalid transition (code CONFLICT)."
|
||||
429:
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/BasicErrorResponseV1"
|
||||
description: "Too many requests (code RATE_LIMITED); retry later."
|
||||
security:
|
||||
- sessionUuidCookie:
|
||||
- "N/A"
|
||||
- bearerAuth:
|
||||
- "N/A"
|
||||
- oauth2:
|
||||
- "openid"
|
||||
- "profile"
|
||||
- "email"
|
||||
summary: "Status"
|
||||
tags:
|
||||
- "Secured data"
|
||||
- "secured-data"
|
||||
servers:
|
||||
- description: "The QQQ server that serves this document (paths include /qqq/v1)."
|
||||
url: "/"
|
||||
tags:
|
||||
- description: "Operations of the secured-data extension."
|
||||
name: "secured-data"
|
||||
+2
-25
@@ -35,8 +35,6 @@ import com.kingsrook.qqq.backend.core.model.actions.tables.query.QueryInput;
|
||||
import com.kingsrook.qqq.backend.core.model.data.QRecord;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Assumptions;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static com.kingsrook.qbits.secureddata.SecuredDataTestSupport.channelUser;
|
||||
@@ -55,34 +53,13 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Core field access bridge it.
|
||||
** Core field access integration tests.
|
||||
*******************************************************************************/
|
||||
class CoreFieldAccessBridgeIT
|
||||
class CoreFieldAccessIT
|
||||
{
|
||||
static final String EMAIL = "CANARY-EMAIL-918273@example.invalid";
|
||||
static final String SSN = "CANARY-PHI-192837465";
|
||||
|
||||
/*******************************************************************************
|
||||
** Require core.
|
||||
*******************************************************************************/
|
||||
@BeforeEach
|
||||
void requireCore()
|
||||
{
|
||||
boolean available;
|
||||
try
|
||||
{
|
||||
Class.forName("com.kingsrook.qqq.backend.core.actions.permissions.fieldaccess.FieldAccessResolverMetaData");
|
||||
available = true;
|
||||
}
|
||||
catch(ClassNotFoundException expected)
|
||||
{
|
||||
available = false;
|
||||
}
|
||||
Assumptions.assumeTrue(available, "QQQ field-access core (#1172) is not on this classpath");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Cleanup.
|
||||
*******************************************************************************/
|
||||
@@ -35,9 +35,9 @@ import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import com.kingsrook.qbits.secureddata.metadata.SecuredDataTables;
|
||||
import com.kingsrook.qbits.secureddata.retention.WipeService;
|
||||
import com.kingsrook.qbits.secureddata.standin.ClassifiedValueKeySource.KeyAndId;
|
||||
import com.kingsrook.qbits.secureddata.standin.ClassifiedValueTokens;
|
||||
import com.kingsrook.qbits.secureddata.support.SystemWrites;
|
||||
import com.kingsrook.qqq.backend.core.actions.permissions.fieldaccess.ClassifiedValueKeySource.KeyAndId;
|
||||
import com.kingsrook.qqq.backend.core.actions.permissions.fieldaccess.ClassifiedValueTokens;
|
||||
import com.kingsrook.qqq.backend.core.actions.reporting.ExportAction;
|
||||
import com.kingsrook.qqq.backend.core.actions.tables.InsertAction;
|
||||
import com.kingsrook.qqq.backend.core.actions.tables.QueryAction;
|
||||
@@ -56,8 +56,6 @@ import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
|
||||
import com.kingsrook.qqq.backend.core.utils.JsonUtils;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Assumptions;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static com.kingsrook.qbits.secureddata.RetentionTestSupport.rows;
|
||||
import static com.kingsrook.qbits.secureddata.RetentionTestSupport.rule;
|
||||
@@ -67,7 +65,6 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
/*******************************************************************************
|
||||
** SECURED-DATA section 15 proofs: a planted canary never leaves the host table,
|
||||
** and shredded audit tokens cannot be brute-forced once the data key is gone.
|
||||
** Both need the core audit-protection hooks (#1182), so RC.6 skips them.
|
||||
*******************************************************************************/
|
||||
class RetentionProofTest
|
||||
{
|
||||
@@ -76,17 +73,6 @@ class RetentionProofTest
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Skip unless core supplies the audit hooks.
|
||||
*******************************************************************************/
|
||||
@BeforeEach
|
||||
void requireCoreHooks()
|
||||
{
|
||||
Assumptions.assumeTrue(CoreAuditBridge.available(), "QQQ core audit-protection hooks (#1182) are not on this classpath");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Cleanup.
|
||||
*******************************************************************************/
|
||||
@@ -98,13 +84,23 @@ class RetentionProofTest
|
||||
|
||||
|
||||
|
||||
private static final String CANARY_PREFIX = "CANARY-PHI-";
|
||||
private static final int CANARY_RANDOM = 24;
|
||||
private static final int MIN_LEAK_FRAGMENT = 12;
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Letters g-v only, so a marker can never coincide with hex digests or tokens.
|
||||
** A fixed prefix and 24 random letters g-v (so it never coincides with hex
|
||||
** digests). Leaks are matched on the whole marker or on 12-letter windows of
|
||||
** its random part: 16^12 possibilities, so ordinary text, JSON words or
|
||||
** base64 tokens cannot match by chance, while a truncated or re-encoded
|
||||
** fragment of a real leak still does.
|
||||
*******************************************************************************/
|
||||
private static String canary()
|
||||
{
|
||||
StringBuilder marker = new StringBuilder("CANARY-PHI-");
|
||||
for(int i = 0; i < 16; i++)
|
||||
StringBuilder marker = new StringBuilder(CANARY_PREFIX);
|
||||
for(int i = 0; i < CANARY_RANDOM; i++)
|
||||
{
|
||||
marker.append((char) ('g' + RANDOM.nextInt(16)));
|
||||
}
|
||||
@@ -114,21 +110,25 @@ class RetentionProofTest
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The marker, or any substring of it longer than four characters.
|
||||
** The whole marker, or any MIN_LEAK_FRAGMENT-letter window of its random part.
|
||||
*******************************************************************************/
|
||||
private static List<String> leaks(String haystack, String... markers)
|
||||
{
|
||||
List<String> found = new ArrayList<>();
|
||||
for(String marker : markers)
|
||||
{
|
||||
for(int length = 5; length <= marker.length(); length++)
|
||||
if(haystack.contains(marker))
|
||||
{
|
||||
for(int start = 0; start + length <= marker.length(); start++)
|
||||
found.add("whole marker");
|
||||
continue;
|
||||
}
|
||||
|
||||
String random = marker.substring(CANARY_PREFIX.length());
|
||||
for(int start = 0; start + MIN_LEAK_FRAGMENT <= random.length(); start++)
|
||||
{
|
||||
if(haystack.contains(random.substring(start, start + MIN_LEAK_FRAGMENT)))
|
||||
{
|
||||
if(haystack.contains(marker.substring(start, start + length)))
|
||||
{
|
||||
found.add("length " + length + " at " + start);
|
||||
}
|
||||
found.add("fragment at " + start);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -137,6 +137,23 @@ class RetentionProofTest
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The leak scan: whole markers and 12-letter fragments are found; the shared
|
||||
** prefix and ordinary words made of the same letters are not.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void leakScanHasNoFalsePositives()
|
||||
{
|
||||
String marker = canary();
|
||||
String random = marker.substring(CANARY_PREFIX.length());
|
||||
assertThat(leaks("x" + marker + "x", marker)).containsExactly("whole marker");
|
||||
assertThat(leaks("{\"v\":\"" + random.substring(5, 5 + MIN_LEAK_FRAGMENT) + "\"}", marker)).isNotEmpty();
|
||||
assertThat(leaks(CANARY_PREFIX + " options joins strings rows points", marker)).isEmpty();
|
||||
assertThat(leaks(random.substring(0, MIN_LEAK_FRAGMENT - 1), marker)).isEmpty();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Canary through CRUD, a failing validation, a wipe run, a masked export and
|
||||
** the access log: it may appear only in the host table itself.
|
||||
|
||||
@@ -20,23 +20,23 @@
|
||||
|
||||
package com.kingsrook.qbits.secureddata;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Base64;
|
||||
import java.util.Set;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import com.kingsrook.qbits.secureddata.metadata.SecuredDataTables;
|
||||
import com.kingsrook.qbits.secureddata.retention.RetentionRules;
|
||||
import com.kingsrook.qbits.secureddata.retention.RetentionWidgets;
|
||||
import com.kingsrook.qbits.secureddata.retention.WipeService;
|
||||
import com.kingsrook.qbits.secureddata.retention.WipeProcesses;
|
||||
import com.kingsrook.qbits.secureddata.standin.DMLType;
|
||||
import com.kingsrook.qbits.secureddata.standin.ClassifiedValueTokens;
|
||||
import com.kingsrook.qbits.secureddata.retention.WipeService;
|
||||
import com.kingsrook.qbits.secureddata.support.SystemWrites;
|
||||
import com.kingsrook.qqq.backend.core.actions.audits.DMLAuditAction.DMLType;
|
||||
import com.kingsrook.qqq.backend.core.actions.customizers.TableCustomizerInterface;
|
||||
import com.kingsrook.qqq.backend.core.actions.customizers.TableCustomizers;
|
||||
import com.kingsrook.qqq.backend.core.actions.permissions.fieldaccess.ClassifiedValueTokens;
|
||||
import com.kingsrook.qqq.backend.core.actions.tables.QueryAction;
|
||||
import com.kingsrook.qqq.backend.core.actions.tables.UpdateAction;
|
||||
import com.kingsrook.qqq.backend.core.context.QContext;
|
||||
@@ -50,8 +50,8 @@ import com.kingsrook.qqq.backend.core.model.actions.widgets.RenderWidgetInput;
|
||||
import com.kingsrook.qqq.backend.core.model.data.QRecord;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.code.QCodeReference;
|
||||
import com.kingsrook.qqq.backend.core.model.session.QSystemUserSession;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import static com.kingsrook.qbits.secureddata.RetentionTestSupport.*;
|
||||
|
||||
@@ -31,9 +31,9 @@ import com.kingsrook.qbits.secureddata.metadata.SecuredDataTables;
|
||||
import com.kingsrook.qbits.secureddata.processes.BreakGlassProcesses;
|
||||
import com.kingsrook.qbits.secureddata.reveal.RevealCappedException;
|
||||
import com.kingsrook.qbits.secureddata.reveal.RevealService;
|
||||
import com.kingsrook.qqq.backend.core.actions.ai.DataClassification;
|
||||
import com.kingsrook.qbits.secureddata.standin.FieldAccessTier;
|
||||
import com.kingsrook.qbits.secureddata.support.SystemWrites;
|
||||
import com.kingsrook.qqq.backend.core.actions.ai.DataClassification;
|
||||
import com.kingsrook.qqq.backend.core.actions.permissions.fieldaccess.FieldAccessTier;
|
||||
import com.kingsrook.qqq.backend.core.actions.tables.GetAction;
|
||||
import com.kingsrook.qqq.backend.core.alerts.AlertResolution;
|
||||
import com.kingsrook.qqq.backend.core.alerts.AlertSeverity;
|
||||
|
||||
@@ -22,6 +22,7 @@ package com.kingsrook.qbits.secureddata;
|
||||
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.lang.ref.WeakReference;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
@@ -33,9 +34,9 @@ import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.stream.IntStream;
|
||||
import com.kingsrook.qbits.secureddata.metadata.SecuredDataTables;
|
||||
import com.kingsrook.qqq.backend.core.actions.ai.DataClassification;
|
||||
import com.kingsrook.qbits.secureddata.standin.FieldAccessEvent;
|
||||
import com.kingsrook.qbits.secureddata.standin.FieldAccessEventType;
|
||||
import com.kingsrook.qbits.secureddata.standin.FieldAccessOutcome;
|
||||
import com.kingsrook.qqq.backend.core.actions.permissions.fieldaccess.FieldAccessEvent;
|
||||
import com.kingsrook.qqq.backend.core.actions.permissions.fieldaccess.FieldAccessEventType;
|
||||
import com.kingsrook.qqq.backend.core.actions.permissions.fieldaccess.FieldAccessOutcome;
|
||||
import com.kingsrook.qqq.backend.core.alerts.AlertResolution;
|
||||
import com.kingsrook.qqq.backend.core.alerts.AlertSignal;
|
||||
import com.kingsrook.qqq.backend.core.alerts.AlertSinkInterface;
|
||||
@@ -46,10 +47,10 @@ import com.kingsrook.qqq.backend.core.exceptions.QPermissionDeniedException;
|
||||
import com.kingsrook.qqq.backend.core.model.data.QRecord;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.code.QCodeReference;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
|
||||
import com.kingsrook.qqq.backend.core.utils.JsonUtils;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static com.kingsrook.qbits.secureddata.SecuredDataTestSupport.CLOCK;
|
||||
import static com.kingsrook.qbits.secureddata.SecuredDataTestSupport.NOW;
|
||||
import static com.kingsrook.qbits.secureddata.SecuredDataTestSupport.channelUser;
|
||||
@@ -360,4 +361,92 @@ class SecuredDataAccessLoggerTest
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The worker starts while the host is still building its instance. An idle
|
||||
** tick opens no context, so it never validates (or enriches) an unfinished
|
||||
** instance on the worker thread, and a failing tick is logged instead of
|
||||
** cancelling every later tick.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void idleTicksNeverValidateAnUnfinishedInstance() throws Exception
|
||||
{
|
||||
setup();
|
||||
SecuredDataRuntime runtime = SecuredDataRuntime.current();
|
||||
QInstance unfinished = SecuredDataTestSupport.base();
|
||||
unfinished.addTable(new QTableMetaData().withName("unfinished").withBackendName("not_registered_yet"));
|
||||
SecuredDataAccessLogger idle = new SecuredDataAccessLogger(unfinished, runtime);
|
||||
try
|
||||
{
|
||||
idle.flush();
|
||||
idle.scheduledFlush();
|
||||
assertThat(unfinished.getHasBeenValidated()).isFalse();
|
||||
}
|
||||
finally
|
||||
{
|
||||
idle.close();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Neither the worker thread nor the JVM shutdown hook keeps a discarded
|
||||
** instance alive: a host or test that drops its instance without closing
|
||||
** the runtime lets it be collected.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void aDiscardedInstanceCanBeCollected() throws Exception
|
||||
{
|
||||
close();
|
||||
WeakReference<QInstance> discarded = discardedInstance();
|
||||
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
|
||||
List<byte[]> pressure = new ArrayList<>();
|
||||
while(discarded.get() != null && System.nanoTime() < deadline)
|
||||
{
|
||||
pressure.add(new byte[1 << 20]);
|
||||
if(pressure.size() > 64)
|
||||
{
|
||||
pressure.clear();
|
||||
}
|
||||
System.gc();
|
||||
Thread.sleep(20);
|
||||
}
|
||||
assertThat(discarded.get()).as("instance still reachable from the access logger").isNull();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Build, use and drop an instance whose worker ticks every 10 ms.
|
||||
*******************************************************************************/
|
||||
private static WeakReference<QInstance> discardedInstance() throws Exception
|
||||
{
|
||||
QInstance instance = SecuredDataTestSupport.base();
|
||||
instance.addBackend(new com.kingsrook.qqq.backend.core.model.metadata.QBackendMetaData().withName("memory")
|
||||
.withBackendType(com.kingsrook.qqq.backend.core.modules.backend.implementations.memory.MemoryBackendModule.class));
|
||||
instance.addTable(person("memory"));
|
||||
new SecuredDataQBitProducer().withQBitConfig(new SecuredDataQBitConfig().withAccessLogFlushIntervalMillis(10)).produce(instance);
|
||||
Thread.sleep(50);
|
||||
QContext.clear();
|
||||
return (new WeakReference<>(instance));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Hosts that close the runtime themselves can skip the JVM hook; close
|
||||
** still drains and stops the worker.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void shutdownHookIsOptional() throws Exception
|
||||
{
|
||||
setup(config -> config.withRegisterShutdownHook(false));
|
||||
var logger = SecuredDataRuntime.current().logger();
|
||||
assertThat(logger.isWorkerRunning()).isTrue();
|
||||
logger.onAccess(event(FieldAccessEventType.VIEW, null, null));
|
||||
logger.close();
|
||||
assertThat(logger.isWorkerRunning()).isFalse();
|
||||
assertThat(logs()).hasSize(1);
|
||||
}
|
||||
}
|
||||
@@ -25,16 +25,16 @@ import java.util.List;
|
||||
import com.kingsrook.qbits.secureddata.breakglass.BreakGlassService;
|
||||
import com.kingsrook.qbits.secureddata.metadata.SecuredDataTables;
|
||||
import com.kingsrook.qbits.secureddata.reveal.RevealService;
|
||||
import com.kingsrook.qbits.secureddata.standin.FieldAccessEventType;
|
||||
import com.kingsrook.qbits.secureddata.standin.FieldAccessOutcome;
|
||||
import com.kingsrook.qbits.secureddata.support.ActivityLog;
|
||||
import com.kingsrook.qbits.secureddata.support.SystemWrites;
|
||||
import com.kingsrook.qqq.backend.core.actions.permissions.fieldaccess.FieldAccessEventType;
|
||||
import com.kingsrook.qqq.backend.core.actions.permissions.fieldaccess.FieldAccessOutcome;
|
||||
import com.kingsrook.qqq.backend.core.actions.tables.InsertAction;
|
||||
import com.kingsrook.qqq.backend.core.alerts.AlertsInstanceMetaData;
|
||||
import com.kingsrook.qqq.backend.core.context.QContext;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.insert.InsertInput;
|
||||
import com.kingsrook.qqq.backend.core.model.data.QRecord;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.code.QCodeReference;
|
||||
import com.kingsrook.qbits.secureddata.support.SystemWrites;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static com.kingsrook.qbits.secureddata.SecuredDataTestSupport.*;
|
||||
|
||||
@@ -33,7 +33,6 @@ import com.kingsrook.qqq.backend.module.rdbms.model.metadata.RDBMSBackendMetaDat
|
||||
import com.kingsrook.qqq.backend.module.rdbms.model.metadata.RDBMSTableBackendDetails;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static com.kingsrook.qbits.secureddata.SecuredDataTestSupport.CLOCK;
|
||||
import static com.kingsrook.qbits.secureddata.SecuredDataTestSupport.RUNTIMES;
|
||||
import static com.kingsrook.qbits.secureddata.SecuredDataTestSupport.base;
|
||||
@@ -97,8 +96,8 @@ class SecuredDataDdlTest
|
||||
classification(null, "PII");
|
||||
policy("cs_admin", "PII", "REVEALABLE");
|
||||
assertThat(SecuredDataRuntime.current().resolver().resolve(instance.getTable("person"), instance.getTable("person").getField("email")).tier().name()).isEqualTo("REVEALABLE");
|
||||
SecuredDataRuntime.current().logger().onAccess(SecuredDataAccessLoggerTest.event(com.kingsrook.qbits.secureddata.standin.FieldAccessEventType.EXACT_MATCH_FILTER,
|
||||
com.kingsrook.qbits.secureddata.standin.FieldAccessOutcome.MATCH, "hmac"));
|
||||
SecuredDataRuntime.current().logger().onAccess(SecuredDataAccessLoggerTest.event(com.kingsrook.qqq.backend.core.actions.permissions.fieldaccess.FieldAccessEventType.EXACT_MATCH_FILTER,
|
||||
com.kingsrook.qqq.backend.core.actions.permissions.fieldaccess.FieldAccessOutcome.MATCH, "hmac"));
|
||||
SecuredDataRuntime.current().logger().flush();
|
||||
assertThat(logs()).extracting(row -> row.getValueString("event_type")).containsExactly("CLASSIFICATION_CHANGE", "POLICY_CHANGE", "EXACT_MATCH_FILTER");
|
||||
// Equal timestamps must be counted by SQL as well as the memory backend.
|
||||
@@ -121,4 +120,73 @@ class SecuredDataDdlTest
|
||||
.isInstanceOf(java.sql.SQLException.class);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Every table the producer declares has the columns create_date and
|
||||
** modify_date in a database made from the DDL. The tables that were first
|
||||
** created without them get them from the last block of the file, which is what
|
||||
** an existing database runs: nullable columns that default to the current
|
||||
** time, so an insert that names neither still succeeds, and a block that can
|
||||
** be run again and then changes nothing.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void postgresDdlGivesEveryDeclaredTableTheTwoDateColumns() throws Exception
|
||||
{
|
||||
String url = "jdbc:h2:mem:secured_data_dates;MODE=PostgreSQL;DATABASE_TO_UPPER=FALSE;DB_CLOSE_DELAY=-1";
|
||||
QInstance instance = SecuredDataTestSupport.setup();
|
||||
try(Connection connection = DriverManager.getConnection(url, "sa", ""))
|
||||
{
|
||||
SecuredDataStandardDatesTest.run(connection, SecuredDataStandardDatesTest.ddl(false));
|
||||
java.util.List<String> added = new java.util.ArrayList<>();
|
||||
for(var table : SecuredDataStandardDatesTest.declared(instance))
|
||||
{
|
||||
if(!hasColumn(connection, table.getName(), "create_date"))
|
||||
{
|
||||
assertThat(hasColumn(connection, table.getName(), "modify_date")).as(table.getName()).isFalse();
|
||||
added.add(table.getName());
|
||||
}
|
||||
}
|
||||
assertThat(added).hasSize(7);
|
||||
connection.createStatement().execute("INSERT INTO secured_data_legal_hold (table_name, reason) VALUES ('person', 'before the columns')");
|
||||
|
||||
SecuredDataStandardDatesTest.run(connection, SecuredDataStandardDatesTest.ddl(true));
|
||||
for(var table : SecuredDataStandardDatesTest.declared(instance))
|
||||
{
|
||||
for(String column : java.util.List.of("create_date", "modify_date"))
|
||||
{
|
||||
try(java.sql.ResultSet columns = connection.getMetaData().getColumns(null, null, table.getName(), column))
|
||||
{
|
||||
assertThat(columns.next()).as(table.getName() + "." + column).isTrue();
|
||||
assertThat(columns.getString("TYPE_NAME")).as(table.getName() + "." + column).isEqualTo("TIMESTAMP WITH TIME ZONE");
|
||||
assertThat(columns.getString("IS_NULLABLE")).as(table.getName() + "." + column).isEqualTo("YES");
|
||||
if(added.contains(table.getName()))
|
||||
{
|
||||
assertThat(columns.getString("COLUMN_DEF")).as(table.getName() + "." + column).isEqualTo("CURRENT_TIMESTAMP");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
connection.createStatement().execute("INSERT INTO secured_data_legal_hold (table_name, reason) VALUES ('person', 'by a release that does not know the columns')");
|
||||
var holds = SecuredDataStandardDatesTest.rows(connection, SecuredDataTables.LEGAL_HOLD, false);
|
||||
assertThat(holds).hasSize(2).allSatisfy(hold -> assertThat(hold.get("create_date")).isNotNull().isEqualTo(hold.get("modify_date")));
|
||||
SecuredDataStandardDatesTest.run(connection, SecuredDataStandardDatesTest.ddl(true));
|
||||
assertThat(SecuredDataStandardDatesTest.rows(connection, SecuredDataTables.LEGAL_HOLD, false)).isEqualTo(holds);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Whether a table has a column.
|
||||
*******************************************************************************/
|
||||
private static boolean hasColumn(Connection connection, String table, String column) throws java.sql.SQLException
|
||||
{
|
||||
try(java.sql.ResultSet columns = connection.getMetaData().getColumns(null, null, table, column))
|
||||
{
|
||||
return (columns.next());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -88,8 +88,8 @@ class SecuredDataHomeTest
|
||||
delete(SecuredDataTables.POLICY, policy);
|
||||
classification("email", "PII");
|
||||
var logger = SecuredDataRuntime.current().logger();
|
||||
logger.onAccess(SecuredDataAccessLoggerTest.event(com.kingsrook.qbits.secureddata.standin.FieldAccessEventType.VIEW, null, null));
|
||||
logger.onAccess(SecuredDataAccessLoggerTest.event(com.kingsrook.qbits.secureddata.standin.FieldAccessEventType.VIEW, null, null));
|
||||
logger.onAccess(SecuredDataAccessLoggerTest.event(com.kingsrook.qqq.backend.core.actions.permissions.fieldaccess.FieldAccessEventType.VIEW, null, null));
|
||||
logger.onAccess(SecuredDataAccessLoggerTest.event(com.kingsrook.qqq.backend.core.actions.permissions.fieldaccess.FieldAccessEventType.VIEW, null, null));
|
||||
var data = SecuredDataHomeData.load();
|
||||
assertThat(data.getKpis()).containsEntry("Reveals today", 15L).containsEntry("Active reveal grants", 1L)
|
||||
.containsEntry("Active break-glass sessions", 1L).containsEntry("Anomaly flags (7 days)", 1L)
|
||||
|
||||
@@ -0,0 +1,352 @@
|
||||
/*
|
||||
* QQQ - Low-code Application Framework for Engineers.
|
||||
* Copyright (C) 2021-2025. Kingsrook, LLC
|
||||
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
|
||||
* contact@kingsrook.com
|
||||
* https://github.com/Kingsrook/
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.secureddata;
|
||||
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.net.URI;
|
||||
import java.net.URLEncoder;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.TimeZone;
|
||||
import com.kingsrook.qbits.secureddata.metadata.SecuredDataTables;
|
||||
import com.kingsrook.qqq.backend.core.instances.AbstractQQQApplication;
|
||||
import com.kingsrook.qqq.backend.core.model.data.QRecord;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QAuthenticationType;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.code.QCodeReference;
|
||||
import com.kingsrook.qqq.backend.core.model.session.QSession;
|
||||
import com.kingsrook.qqq.backend.core.modules.authentication.QAuthenticationModuleCustomizerInterface;
|
||||
import com.kingsrook.qqq.middleware.javalin.QApplicationJavalinServer;
|
||||
import com.kingsrook.qqq.middleware.javalin.QJavalinImplementation;
|
||||
import org.h2.util.DateTimeUtils;
|
||||
import org.json.JSONObject;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static com.kingsrook.qbits.secureddata.SecuredDataTestSupport.CLOCK;
|
||||
import static com.kingsrook.qbits.secureddata.SecuredDataTestSupport.NOW;
|
||||
import static com.kingsrook.qbits.secureddata.SecuredDataTestSupport.insert;
|
||||
import static com.kingsrook.qbits.secureddata.SecuredDataTestSupport.policyRow;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A person edits a row of the QBit over HTTP, a day after it was written. The
|
||||
** request names the row by the id in its path, which arrives as text, while
|
||||
** the stored id is a number: the edit must still be an edit of that row. A
|
||||
** table with a modify date is edited the way a client that knows record
|
||||
** versions edits it, with the changed values only and the version it read.
|
||||
*******************************************************************************/
|
||||
class SecuredDataHttpEditTest
|
||||
{
|
||||
private QApplicationJavalinServer server;
|
||||
private int port;
|
||||
private final TimeZone zone = TimeZone.getDefault();
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** These tests run in UTC, whatever the zone of the machine. Core compares the
|
||||
** version a client sends with the stored modify date in the database, and
|
||||
** where the default zone of the JVM is not UTC that comparison never matches
|
||||
** (a version is then refused with 409 for a row nobody changed). That is
|
||||
** core's to fix. It is kept out of what is tested here, which is that an
|
||||
** edit is an edit of its row. The test database keeps the zone it first saw,
|
||||
** so it is told of each change.
|
||||
*******************************************************************************/
|
||||
@BeforeEach
|
||||
void utc()
|
||||
{
|
||||
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
|
||||
DateTimeUtils.resetCalendar();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Cleanup.
|
||||
*******************************************************************************/
|
||||
@AfterEach
|
||||
void cleanup()
|
||||
{
|
||||
TimeZone.setDefault(zone);
|
||||
DateTimeUtils.resetCalendar();
|
||||
if(server != null)
|
||||
{
|
||||
server.stop();
|
||||
}
|
||||
QJavalinImplementation.setSessionCookieHttpOnly(false);
|
||||
RetentionTestSupport.close();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The session of every request: an administrator of the QBit.
|
||||
*******************************************************************************/
|
||||
public static class Sessions implements QAuthenticationModuleCustomizerInterface
|
||||
{
|
||||
/*******************************************************************************
|
||||
** Customize session.
|
||||
*******************************************************************************/
|
||||
public void customizeSession(QInstance instance, QSession session, Map<String, Object> context)
|
||||
{
|
||||
session.setPermissions(Set.of("secured_data.admin", "secured_data.hasAccess", "secured_data.retention", "reading.read", "reading.write"));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Serve the instance, a day after its rows were written.
|
||||
*******************************************************************************/
|
||||
private void serveADayLater(QInstance instance) throws Exception
|
||||
{
|
||||
instance.getAuthentication().setType(QAuthenticationType.MOCK);
|
||||
instance.getAuthentication().setCustomizer(new QCodeReference(Sessions.class));
|
||||
server = new QApplicationJavalinServer(new AbstractQQQApplication()
|
||||
{
|
||||
public QInstance defineQInstance()
|
||||
{
|
||||
return (instance);
|
||||
}
|
||||
}).withPort(0).withServeFrontendNext(false).withServeFrontendMaterialDashboard(false).withServeLegacyUnversionedMiddlewareAPI(false).withStrictUiApiRoutes(true);
|
||||
server.start();
|
||||
var serviceField = QApplicationJavalinServer.class.getDeclaredField("service");
|
||||
serviceField.setAccessible(true);
|
||||
port = ((io.javalin.Javalin) serviceField.get(server)).port();
|
||||
CLOCK.now = NOW.plusSeconds(86400);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Request.
|
||||
*******************************************************************************/
|
||||
private HttpResponse<String> request(String method, String path, String body) throws Exception
|
||||
{
|
||||
var builder = HttpRequest.newBuilder(URI.create("http://127.0.0.1:" + port + "/qqq/v1" + path)).header("Cookie", "sessionUUID=edit-user");
|
||||
if(body != null)
|
||||
{
|
||||
builder.header("Content-Type", "application/json").method(method, HttpRequest.BodyPublishers.ofString(body));
|
||||
}
|
||||
return (HttpClient.newHttpClient().send(builder.build(), HttpResponse.BodyHandlers.ofString()));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The version a client reads with a row: the value of its modify date.
|
||||
*******************************************************************************/
|
||||
private String version(String table, Serializable id, String modifyDate) throws Exception
|
||||
{
|
||||
HttpResponse<String> get = request("GET", "/table/" + table + "/" + id, null);
|
||||
assertThat(get.statusCode()).as(get.body()).isEqualTo(200);
|
||||
JSONObject body = new JSONObject(get.body());
|
||||
JSONObject values = body.has("record") ? body.getJSONObject("record").getJSONObject("values") : body.getJSONObject("values");
|
||||
return (values.isNull(modifyDate) ? null : String.valueOf(values.get(modifyDate)));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Edit a row: the changed values, and the version that was read where the
|
||||
** client sends one.
|
||||
*******************************************************************************/
|
||||
private HttpResponse<String> patch(String table, Serializable id, String version, String body) throws Exception
|
||||
{
|
||||
return (request("PATCH", "/table/" + table + "/" + id + (version == null ? "" : "?expectedVersion=" + URLEncoder.encode(version, StandardCharsets.UTF_8)), body));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** One row as the database holds it, column by column.
|
||||
*******************************************************************************/
|
||||
private static Map<String, String> stored(String table, Serializable id) throws Exception
|
||||
{
|
||||
try(Connection connection = DriverManager.getConnection(SecuredDataStandardDatesTest.url(), "sa", ""))
|
||||
{
|
||||
return (SecuredDataStandardDatesTest.rows(connection, table, false).stream().filter(row -> String.valueOf(id).equals(row.get("id"))).findFirst().orElseThrow());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The columns an edit must leave as they were.
|
||||
*******************************************************************************/
|
||||
private static void assertKept(Map<String, String> before, Map<String, String> after, String... columns)
|
||||
{
|
||||
for(String column : columns)
|
||||
{
|
||||
assertThat(before.get(column)).as(column + " before").isNotNull();
|
||||
assertThat(after.get(column)).as(column).isEqualTo(before.get(column));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The reason of a hold is edited: only the reason is sent, with the version.
|
||||
** The hold stays the hold it was, and the version it was edited with is then
|
||||
** no longer its version.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void aPersonEditsTheReasonOfAHold() throws Exception
|
||||
{
|
||||
QInstance instance = RetentionTestSupport.setup();
|
||||
Serializable id = insert(SecuredDataTables.LEGAL_HOLD, new QRecord().withValue("table_name", "reading").withValue("reason", "Preservation")).getValue("id");
|
||||
serveADayLater(instance);
|
||||
Map<String, String> placed = stored(SecuredDataTables.LEGAL_HOLD, id);
|
||||
String version = version(SecuredDataTables.LEGAL_HOLD, id, "modifyDate");
|
||||
assertThat(version).isNotNull();
|
||||
|
||||
HttpResponse<String> edit = patch(SecuredDataTables.LEGAL_HOLD, id, version, "{\"reason\":\"Preservation, extended\"}");
|
||||
assertThat(edit.statusCode()).as(edit.body()).isEqualTo(200);
|
||||
Map<String, String> edited = stored(SecuredDataTables.LEGAL_HOLD, id);
|
||||
assertThat(edited.get("reason")).isEqualTo("Preservation, extended");
|
||||
assertKept(placed, edited, "table_name", "status", "placed_at", "placed_by", "create_date");
|
||||
assertThat(edited.get("released_at")).isNull();
|
||||
assertThat(edited.get("modify_date")).isNotNull().isNotEqualTo(placed.get("modify_date"));
|
||||
|
||||
HttpResponse<String> stale = patch(SecuredDataTables.LEGAL_HOLD, id, version, "{\"reason\":\"Preservation, extended again\"}");
|
||||
assertThat(stale.statusCode()).as(stale.body()).isEqualTo(409);
|
||||
assertThat(stored(SecuredDataTables.LEGAL_HOLD, id)).isEqualTo(edited);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A hold is released a day after it was placed: when and by whom it was
|
||||
** placed, and its create date, are those of the day it was placed.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void aHoldReleasedADayLaterKeepsWhenAndByWhomItWasPlaced() throws Exception
|
||||
{
|
||||
QInstance instance = RetentionTestSupport.setup();
|
||||
Serializable id = insert(SecuredDataTables.LEGAL_HOLD, new QRecord().withValue("table_name", "reading").withValue("record_id", "7").withValue("reason", "Preservation")).getValue("id");
|
||||
serveADayLater(instance);
|
||||
Map<String, String> placed = stored(SecuredDataTables.LEGAL_HOLD, id);
|
||||
|
||||
HttpResponse<String> release = patch(SecuredDataTables.LEGAL_HOLD, id, version(SecuredDataTables.LEGAL_HOLD, id, "modifyDate"), "{\"status\":\"RELEASED\"}");
|
||||
assertThat(release.statusCode()).as(release.body()).isEqualTo(200);
|
||||
Map<String, String> released = stored(SecuredDataTables.LEGAL_HOLD, id);
|
||||
assertThat(released.get("status")).isEqualTo("RELEASED");
|
||||
assertKept(placed, released, "table_name", "record_id", "reason", "placed_at", "placed_by", "create_date");
|
||||
assertThat(released.get("released_at")).isNotNull().isNotEqualTo(placed.get("placed_at"));
|
||||
assertThat(released.get("released_by")).isNotNull();
|
||||
assertThat(released.get("modify_date")).isNotNull().isNotEqualTo(placed.get("modify_date"));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A classification is edited by a client that sends its table and field back
|
||||
** with the change: the row is not taken for a second classification of the
|
||||
** same field, and it keeps its create date.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void aClassificationIsEditedNamingItsTableAndField() throws Exception
|
||||
{
|
||||
QInstance instance = RetentionTestSupport.setup();
|
||||
Serializable id = insert(SecuredDataTables.CLASSIFICATION, new QRecord().withValue("table_name", "reading").withValue("field_name", "notes").withValue("classification", "PII")).getValue("id");
|
||||
serveADayLater(instance);
|
||||
Map<String, String> written = stored(SecuredDataTables.CLASSIFICATION, id);
|
||||
|
||||
HttpResponse<String> edit = patch(SecuredDataTables.CLASSIFICATION, id, null, "{\"table_name\":\"reading\",\"field_name\":\"notes\",\"classification\":\"PHI\"}");
|
||||
assertThat(edit.statusCode()).as(edit.body()).isEqualTo(200);
|
||||
Map<String, String> edited = stored(SecuredDataTables.CLASSIFICATION, id);
|
||||
assertThat(edited.get("classification")).isEqualTo("PHI");
|
||||
assertKept(written, edited, "table_name", "field_name", "create_date");
|
||||
assertThat(edited.get("modify_date")).isNotNull().isNotEqualTo(written.get("modify_date"));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A policy and a retention rule are renamed: each keeps its create date and
|
||||
** everything else it had, and the rule is validated as the rule it is.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void aRenamedPolicyOrRetentionRuleKeepsItsCreateDate() throws Exception
|
||||
{
|
||||
QInstance instance = RetentionTestSupport.setup();
|
||||
Serializable policy = insert(SecuredDataTables.POLICY, policyRow("cs_admin", "PII", "REVEALABLE")).getValue("id");
|
||||
Serializable rule = RetentionTestSupport.rule("OVERWRITE_TEXT", "secret").getValue("id");
|
||||
serveADayLater(instance);
|
||||
Map<String, String> policyWritten = stored(SecuredDataTables.POLICY, policy);
|
||||
Map<String, String> ruleWritten = stored(SecuredDataTables.RETENTION_RULE, rule);
|
||||
|
||||
HttpResponse<String> policyEdit = patch(SecuredDataTables.POLICY, policy, null, "{\"name\":\"renamed\"}");
|
||||
assertThat(policyEdit.statusCode()).as(policyEdit.body()).isEqualTo(200);
|
||||
Map<String, String> policyEdited = stored(SecuredDataTables.POLICY, policy);
|
||||
assertThat(policyEdited.get("name")).isEqualTo("renamed");
|
||||
assertKept(policyWritten, policyEdited, "permission_name", "classification", "tier", "create_date");
|
||||
assertThat(policyEdited.get("modify_date")).isNotNull().isNotEqualTo(policyWritten.get("modify_date"));
|
||||
|
||||
HttpResponse<String> ruleEdit = patch(SecuredDataTables.RETENTION_RULE, rule, null, "{\"name\":\"renamed\"}");
|
||||
assertThat(ruleEdit.statusCode()).as(ruleEdit.body()).isEqualTo(200);
|
||||
Map<String, String> ruleEdited = stored(SecuredDataTables.RETENTION_RULE, rule);
|
||||
assertThat(ruleEdited.get("name")).isEqualTo("renamed");
|
||||
assertKept(ruleWritten, ruleEdited, "table_name", "field_names", "age_field_name", "action", "create_date");
|
||||
assertThat(ruleEdited.get("modify_date")).isNotNull().isNotEqualTo(ruleWritten.get("modify_date"));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A row that has neither date, as a row is that was written before the two
|
||||
** columns existed and was not given its own time afterwards: it is read and
|
||||
** edited like any other, and gets a modify date when it is changed.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void aRowWithoutDatesIsReadAndEdited() throws Exception
|
||||
{
|
||||
QInstance instance = RetentionTestSupport.setup();
|
||||
Serializable id = insert(SecuredDataTables.LEGAL_HOLD, new QRecord().withValue("table_name", "reading").withValue("reason", "Preservation")).getValue("id");
|
||||
try(Connection connection = DriverManager.getConnection(SecuredDataStandardDatesTest.url(), "sa", ""))
|
||||
{
|
||||
for(String table : List.of(SecuredDataTables.LEGAL_HOLD, SecuredDataTables.ACCESS_LOG, SecuredDataTables.BREAK_GLASS))
|
||||
{
|
||||
connection.createStatement().execute("UPDATE " + table + " SET create_date = NULL, modify_date = NULL");
|
||||
}
|
||||
}
|
||||
serveADayLater(instance);
|
||||
assertThat(version(SecuredDataTables.LEGAL_HOLD, id, "modifyDate")).isNull();
|
||||
|
||||
HttpResponse<String> edit = patch(SecuredDataTables.LEGAL_HOLD, id, null, "{\"reason\":\"Preservation, extended\"}");
|
||||
assertThat(edit.statusCode()).as(edit.body()).isEqualTo(200);
|
||||
Map<String, String> edited = stored(SecuredDataTables.LEGAL_HOLD, id);
|
||||
assertThat(edited.get("reason")).isEqualTo("Preservation, extended");
|
||||
assertThat(edited.get("create_date")).isNull();
|
||||
assertThat(edited.get("modify_date")).isNotNull();
|
||||
assertThat(version(SecuredDataTables.LEGAL_HOLD, id, "modifyDate")).isNotNull();
|
||||
}
|
||||
}
|
||||
@@ -109,11 +109,25 @@ class SecuredDataHttpTest
|
||||
var status = request("/qbit/secured-data/status", null, false);
|
||||
assertThat(status.statusCode()).as(status.body()).isEqualTo(200);
|
||||
assertThat(new JSONObject(status.body()).getInt("revealsUsedToday")).isEqualTo(1);
|
||||
assertThat(request("/qbit/secured-data/reveal", body, false).statusCode()).isEqualTo(429);
|
||||
assertThat(request("/qbit/secured-data/reveal", body, true).statusCode()).isEqualTo(403);
|
||||
assertThat(request("/qbit/secured-data/reveal", "{}", false).statusCode()).isEqualTo(400);
|
||||
assertThat(request("/qbit/secured-data/reveal", "{\"primaryKey\":1}", false).statusCode()).isEqualTo(400);
|
||||
assertThat(request("/qbit/secured-data/reveal/options?tableName=person&fieldName=missing", null, false).statusCode()).isEqualTo(404);
|
||||
assertErrorResponse(request("/qbit/secured-data/reveal", body, false), 429);
|
||||
assertErrorResponse(request("/qbit/secured-data/reveal", body, true), 403);
|
||||
assertErrorResponse(request("/qbit/secured-data/reveal", "{}", false), 400);
|
||||
assertErrorResponse(request("/qbit/secured-data/reveal", "{\"primaryKey\":1}", false), 400);
|
||||
assertErrorResponse(request("/qbit/secured-data/reveal/options?tableName=person&fieldName=missing", null, false), 404);
|
||||
}
|
||||
|
||||
/*******************************************************************************
|
||||
** Verify standard error bodies without changing endpoint status semantics.
|
||||
*******************************************************************************/
|
||||
private void assertErrorResponse(HttpResponse<String> response, int status)
|
||||
{
|
||||
assertThat(response.statusCode()).as(response.body()).isEqualTo(status);
|
||||
JSONObject body = new JSONObject(response.body());
|
||||
assertThat(body.keySet()).contains("error", "code", "message", "traceId");
|
||||
assertThat(body.getString("error")).isNotBlank();
|
||||
assertThat(body.getString("code")).isNotBlank();
|
||||
assertThat(body.getString("message")).isNotBlank();
|
||||
assertThat(body.getString("traceId")).isNotBlank();
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -0,0 +1,271 @@
|
||||
/*
|
||||
* QQQ - Low-code Application Framework for Engineers.
|
||||
* Copyright (C) 2021-2025. Kingsrook, LLC
|
||||
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
|
||||
* contact@kingsrook.com
|
||||
* https://github.com/Kingsrook/
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.secureddata;
|
||||
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import com.kingsrook.qbits.secureddata.breakglass.BreakGlassService;
|
||||
import com.kingsrook.qbits.secureddata.metadata.SecuredDataTables;
|
||||
import com.kingsrook.qbits.secureddata.reveal.RevealResult;
|
||||
import com.kingsrook.qbits.secureddata.reveal.RevealService;
|
||||
import com.kingsrook.qqq.backend.core.actions.ai.DataClassification;
|
||||
import com.kingsrook.qqq.backend.core.actions.permissions.fieldaccess.FieldAccessEvent;
|
||||
import com.kingsrook.qqq.backend.core.actions.permissions.fieldaccess.FieldAccessEventType;
|
||||
import com.kingsrook.qqq.backend.core.actions.permissions.fieldaccess.FieldAccessOutcome;
|
||||
import com.kingsrook.qqq.backend.core.context.QContext;
|
||||
import com.kingsrook.qqq.backend.core.model.data.QRecord;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.session.QSession;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.Timeout;
|
||||
import static com.kingsrook.qbits.secureddata.SecuredDataTestSupport.CLOCK;
|
||||
import static com.kingsrook.qbits.secureddata.SecuredDataTestSupport.insert;
|
||||
import static com.kingsrook.qbits.secureddata.SecuredDataTestSupport.logs;
|
||||
import static com.kingsrook.qbits.secureddata.SecuredDataTestSupport.policyRow;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.fail;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A reveal, and the start, end and expiry of a break-glass session, hold the
|
||||
** runtime's monitor from their first check to their last write, so that two of
|
||||
** them cannot both pass a check (the daily allowance, one active session).
|
||||
** Every other thread asks this QBit for a classification all the time: core
|
||||
** asks for every field it decides on and for every filter criterion of every
|
||||
** query, including the queries made inside this QBit's own writes.
|
||||
**
|
||||
** When that question needed the same monitor, a thread that asked it while
|
||||
** holding another of this QBit's locks could never be answered during a
|
||||
** reveal that was about to need that lock: the access-log writer holds the
|
||||
** anomaly counters' monitor while it inserts a row (the insert counts earlier
|
||||
** rows and writes an audit, both queries with criteria), and a reveal inserts
|
||||
** its own access-log row. Reveal: runtime, then counters. Writer: counters,
|
||||
** then runtime. Both waited for ever, and so did every later request, since
|
||||
** every request asks for a classification.
|
||||
**
|
||||
** The rule rows now have a lock of their own that is held only while they are
|
||||
** read. These tests run on a relational database (H2 in PostgreSQL mode, with
|
||||
** the audit tables), where an insert really writes its audit. Each parks one
|
||||
** thread inside the operation, holding the runtime's monitor, and requires
|
||||
** the access-log writer and a classification question on other threads to
|
||||
** finish meanwhile; then the parked operation finishes too. Without the fix
|
||||
** the writer does not finish and the test fails after WAIT_SECONDS.
|
||||
*******************************************************************************/
|
||||
@Timeout(180)
|
||||
class SecuredDataLockOrderTest
|
||||
{
|
||||
private static final long WAIT_SECONDS = 20;
|
||||
|
||||
private final ExecutorService threads = Executors.newCachedThreadPool(work ->
|
||||
{
|
||||
Thread thread = new Thread(work, "lock-order-test");
|
||||
thread.setDaemon(true);
|
||||
return (thread);
|
||||
});
|
||||
|
||||
private QInstance instance;
|
||||
private SecuredDataRuntime runtime;
|
||||
private QSession person;
|
||||
private QTableMetaData reading;
|
||||
private Serializable pk;
|
||||
|
||||
private final CountDownLatch parked = new CountDownLatch(1);
|
||||
private final CountDownLatch resume = new CountDownLatch(1);
|
||||
private final AtomicReference<Thread> working = new AtomicReference<>();
|
||||
private final AtomicBoolean heldTheRuntimesMonitor = new AtomicBoolean();
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Let a parked thread go, then close; a runtime whose threads are stuck was
|
||||
** already taken out of the list (see abandon).
|
||||
*******************************************************************************/
|
||||
@AfterEach
|
||||
void cleanup()
|
||||
{
|
||||
resume.countDown();
|
||||
threads.shutdownNow();
|
||||
RetentionTestSupport.close();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A reveal in progress holds up neither the access-log writer nor a question.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void theAccessLogWriterAndAClassificationQuestionFinishWhileARevealIsInProgress() throws Exception
|
||||
{
|
||||
setup();
|
||||
Future<RevealResult> reveal = parkInside(() -> new RevealService().reveal("reading", pk, "notes", null, "Synthetic reveal; lock order test."));
|
||||
|
||||
othersFinishMeanwhile();
|
||||
|
||||
resume.countDown();
|
||||
assertThat(reveal.get(WAIT_SECONDS, TimeUnit.SECONDS).value()).isEqualTo("test-notes");
|
||||
assertThat(logs()).extracting(row -> row.getValueString("event_type")).contains("EXACT_MATCH_FILTER", "REVEAL");
|
||||
assertThat(runtime.resolver().isRevealActive("reading", "notes", pk)).isTrue();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The same for the start of a break-glass session, which holds the same monitor.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void theAccessLogWriterAndAClassificationQuestionFinishWhileBreakGlassStarts() throws Exception
|
||||
{
|
||||
setup();
|
||||
person.getPermissions().add(BreakGlassService.START + ".hasAccess");
|
||||
Future<QRecord> started = parkInside(() -> new BreakGlassService().start("Synthetic break-glass session; lock order test.", 5, "reading", DataClassification.PHI));
|
||||
|
||||
othersFinishMeanwhile();
|
||||
|
||||
resume.countDown();
|
||||
assertThat(started.get(WAIT_SECONDS, TimeUnit.SECONDS).getValueString("status")).isEqualTo("ACTIVE");
|
||||
assertThat(logs()).extracting(row -> row.getValueString("event_type")).contains("EXACT_MATCH_FILTER", "BREAK_GLASS_START");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A relational instance with audit tables; a PII field one policy makes
|
||||
** revealable to the person; one row; and one search of that field waiting in
|
||||
** the access-log queue, as it waits after a person filters a list by it.
|
||||
*******************************************************************************/
|
||||
private void setup() throws Exception
|
||||
{
|
||||
instance = RetentionTestSupport.setup();
|
||||
runtime = SecuredDataRuntime.current();
|
||||
person = QContext.getQSession();
|
||||
reading = instance.getTable("reading");
|
||||
insert(SecuredDataTables.POLICY, policyRow("secured_data.admin", "PII", "REVEALABLE"));
|
||||
pk = RetentionTestSupport.reading(120).getValue("id");
|
||||
|
||||
runtime.resolver().onAccess(new FieldAccessEvent().withType(FieldAccessEventType.EXACT_MATCH_FILTER).withOutcome(FieldAccessOutcome.MATCH)
|
||||
.withTableName("reading").withFieldNames(List.of("notes")).withActionName("query").withRecordCount(1)
|
||||
.withSearchValueFingerprints(List.of(runtime.resolver().fingerprintSearchValue("known"))));
|
||||
assertThat(logs()).as("the search is queued, not yet written").extracting(row -> row.getValueString("event_type")).doesNotContain("EXACT_MATCH_FILTER");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Run the operation as the person on another thread and return once it is
|
||||
** parked at its first reading of the clock, which both operations make
|
||||
** inside their synchronized block.
|
||||
*******************************************************************************/
|
||||
private <T> Future<T> parkInside(Callable<T> operation) throws Exception
|
||||
{
|
||||
CLOCK.beforeInstant = () ->
|
||||
{
|
||||
if(Thread.currentThread() == working.get() && parked.getCount() == 1)
|
||||
{
|
||||
heldTheRuntimesMonitor.set(Thread.holdsLock(runtime));
|
||||
parked.countDown();
|
||||
try
|
||||
{
|
||||
resume.await();
|
||||
}
|
||||
catch(InterruptedException e)
|
||||
{
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
};
|
||||
Future<T> future = threads.submit(() ->
|
||||
{
|
||||
QContext.init(instance, person);
|
||||
try
|
||||
{
|
||||
working.set(Thread.currentThread());
|
||||
return (operation.call());
|
||||
}
|
||||
finally
|
||||
{
|
||||
QContext.clear();
|
||||
}
|
||||
});
|
||||
assertThat(parked.await(WAIT_SECONDS, TimeUnit.SECONDS)).as("the operation read the clock").isTrue();
|
||||
assertThat(heldTheRuntimesMonitor).as("the operation is parked holding the runtime's monitor").isTrue();
|
||||
return (future);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** While the operation is parked: the access-log writer drains its queue (what
|
||||
** its worker does on every tick), and a thread that holds no lock is told
|
||||
** the classification of a field and the active retention rules.
|
||||
*******************************************************************************/
|
||||
private void othersFinishMeanwhile() throws Exception
|
||||
{
|
||||
Future<?> writer = threads.submit(() -> runtime.logger().flush());
|
||||
Future<DataClassification> question = threads.submit(() ->
|
||||
{
|
||||
QContext.init(instance, person);
|
||||
try
|
||||
{
|
||||
runtime.activeRetentionRules();
|
||||
return (SecuredDataClassifications.effective(reading, "notes"));
|
||||
}
|
||||
finally
|
||||
{
|
||||
QContext.clear();
|
||||
}
|
||||
});
|
||||
|
||||
try
|
||||
{
|
||||
writer.get(WAIT_SECONDS, TimeUnit.SECONDS);
|
||||
assertThat(question.get(WAIT_SECONDS, TimeUnit.SECONDS)).isEqualTo(DataClassification.PII);
|
||||
}
|
||||
catch(TimeoutException e)
|
||||
{
|
||||
abandon();
|
||||
fail("A thread waited " + WAIT_SECONDS + " seconds for the monitor the parked operation holds (writer done: " + writer.isDone() + ", question done: " + question.isDone()
|
||||
+ "): the operation needs the lock that thread holds next, so neither would ever finish");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Threads of this runtime are stuck holding its locks: closing it would wait
|
||||
** for them, so it is left to the daemon threads instead of being closed.
|
||||
*******************************************************************************/
|
||||
private void abandon()
|
||||
{
|
||||
SecuredDataTestSupport.RUNTIMES.remove(runtime);
|
||||
}
|
||||
}
|
||||
@@ -26,11 +26,9 @@ import java.util.Map;
|
||||
import com.kingsrook.qbits.secureddata.metadata.FieldsOfTablePossibleValueSource;
|
||||
import com.kingsrook.qbits.secureddata.metadata.SecuredDataEnums;
|
||||
import com.kingsrook.qbits.secureddata.metadata.SecuredDataTables;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.permissions.ClientChannelsMetaData;
|
||||
import com.kingsrook.qqq.backend.core.actions.ai.DataClassification;
|
||||
import com.kingsrook.qbits.secureddata.standin.FieldAccessTier;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.permissions.TableFeaturePermissionsMetaData;
|
||||
import com.kingsrook.qbits.secureddata.support.SecuredDataMetadata;
|
||||
import com.kingsrook.qqq.backend.core.actions.ai.DataClassification;
|
||||
import com.kingsrook.qqq.backend.core.actions.permissions.fieldaccess.FieldAccessTier;
|
||||
import com.kingsrook.qqq.backend.core.actions.tables.InsertAction;
|
||||
import com.kingsrook.qqq.backend.core.actions.tables.QueryAction;
|
||||
import com.kingsrook.qqq.backend.core.context.QContext;
|
||||
@@ -40,11 +38,12 @@ import com.kingsrook.qqq.backend.core.model.actions.values.SearchPossibleValueSo
|
||||
import com.kingsrook.qqq.backend.core.model.data.QRecord;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.audits.AuditLevel;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.permissions.ClientChannelsMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.permissions.TableFeaturePermissionsMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.tables.Capability;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static com.kingsrook.qbits.secureddata.SecuredDataTestSupport.NOW;
|
||||
import static com.kingsrook.qbits.secureddata.SecuredDataTestSupport.RUNTIMES;
|
||||
import static com.kingsrook.qbits.secureddata.SecuredDataTestSupport.base;
|
||||
@@ -89,14 +88,16 @@ class SecuredDataQBitProducerTest
|
||||
{
|
||||
QInstance instance = setup();
|
||||
assertThat(instance.getTables().keySet()).containsAll(SecuredDataTables.ALL);
|
||||
assertThat(instance.getQBits().get("com.kingsrook.qbits:qbit-secured-data").getVersion()).isEqualTo("1.0.0");
|
||||
assertThat(instance.getQBits().get("com.kingsrook.qbits:qbit-secured-data").getVersion()).isEqualTo("0.1.0");
|
||||
for(String name : SecuredDataTables.ALL)
|
||||
{
|
||||
QTableMetaData table = instance.getTable(name);
|
||||
assertThat(table.getAuditRules().getAuditLevel()).isEqualTo(name.equals(SecuredDataTables.AUDIT_KEY) ? AuditLevel.NONE : AuditLevel.FIELD);
|
||||
assertThat(table.getSections()).isNotEmpty();
|
||||
assertThat(SecuredDataMetadata.classification(table, null)).isEqualTo(DataClassification.CONFIDENTIAL);
|
||||
table.getFields().values().forEach(field -> assertThat(field.getBackendName()).isEqualTo(field.getName()));
|
||||
// A column has the name of its field. The two standard dates are always the columns create_date and modify_date.
|
||||
table.getFields().values().forEach(field -> assertThat(field.getBackendName())
|
||||
.isEqualTo("createDate".equals(field.getName()) ? "create_date" : "modifyDate".equals(field.getName()) ? "modify_date" : field.getName()));
|
||||
}
|
||||
assertThat(SecuredDataTables.esbTableNames()).containsExactlyElementsOf(SecuredDataTables.MAIN);
|
||||
assertThat(SecuredDataEnums.sources()).hasSize(6);
|
||||
|
||||
@@ -23,23 +23,23 @@ package com.kingsrook.qbits.secureddata;
|
||||
|
||||
import java.util.List;
|
||||
import com.kingsrook.qbits.secureddata.metadata.SecuredDataTables;
|
||||
import com.kingsrook.qqq.backend.core.actions.ai.AiTableMetaData;
|
||||
import com.kingsrook.qqq.backend.core.actions.ai.DataClassification;
|
||||
import com.kingsrook.qbits.secureddata.standin.FieldAccessTier;
|
||||
import com.kingsrook.qbits.secureddata.standin.FieldMaskStyle;
|
||||
import com.kingsrook.qbits.secureddata.support.SecuredDataMetadata;
|
||||
import com.kingsrook.qbits.secureddata.support.SystemWrites;
|
||||
import com.kingsrook.qqq.backend.core.actions.ai.AiTableMetaData;
|
||||
import com.kingsrook.qqq.backend.core.actions.ai.DataClassification;
|
||||
import com.kingsrook.qqq.backend.core.actions.permissions.fieldaccess.FieldAccessTier;
|
||||
import com.kingsrook.qqq.backend.core.actions.permissions.fieldaccess.FieldMaskStyle;
|
||||
import com.kingsrook.qqq.backend.core.context.QContext;
|
||||
import com.kingsrook.qqq.backend.core.model.data.QRecord;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldType;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.fields.QVirtualFieldMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
|
||||
import static com.kingsrook.qbits.secureddata.SecuredDataTestSupport.CLOCK;
|
||||
import static com.kingsrook.qbits.secureddata.SecuredDataTestSupport.NOW;
|
||||
import static com.kingsrook.qbits.secureddata.SecuredDataTestSupport.channelUser;
|
||||
@@ -327,4 +327,22 @@ class SecuredDataResolverTest
|
||||
CLOCK.now = NOW.plusSeconds(10);
|
||||
assertThat(resolver.isRevealActive("person", "email", 7)).isFalse();
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A virtual (computed) field is not in getFields, and getField throws for
|
||||
** it: it resolves through the table classification instead of failing the
|
||||
** whole read.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void virtualFieldsTakeTheTableClassification() throws Exception
|
||||
{
|
||||
QVirtualFieldMetaData display = new QVirtualFieldMetaData("displayName", QFieldType.STRING);
|
||||
person.withVirtualFields(List.of(display));
|
||||
assertThat(SecuredDataClassifications.effective(person, "displayName")).isNull();
|
||||
assertThat(resolver.resolve(person, display).tier()).isEqualTo(FieldAccessTier.FULL);
|
||||
person.withSupplementalMetaData(new AiTableMetaData().withClassification(DataClassification.PII));
|
||||
assertThat(SecuredDataClassifications.effective(person, "displayName")).isEqualTo(DataClassification.PII);
|
||||
assertThat(resolver.resolve(person, display).tier()).isEqualTo(FieldAccessTier.MASKED);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
/*
|
||||
* QQQ - Low-code Application Framework for Engineers.
|
||||
* Copyright (C) 2021-2025. Kingsrook, LLC
|
||||
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
|
||||
* contact@kingsrook.com
|
||||
* https://github.com/Kingsrook/
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.secureddata;
|
||||
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import com.kingsrook.qbits.secureddata.metadata.SecuredDataTables;
|
||||
import com.kingsrook.qbits.secureddata.permissions.SecuredDataPermissions;
|
||||
import com.kingsrook.qbits.secureddata.retention.RetentionRules;
|
||||
import com.kingsrook.qbits.secureddata.support.SecuredDataMetadata;
|
||||
import com.kingsrook.qqq.backend.core.cluster.ClusterBus;
|
||||
import com.kingsrook.qqq.backend.core.cluster.ClusterCaches;
|
||||
import com.kingsrook.qqq.backend.core.cluster.ClusterEvent;
|
||||
import com.kingsrook.qqq.backend.core.context.QContext;
|
||||
import com.kingsrook.qqq.backend.core.model.data.QRecord;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldType;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.session.QSession;
|
||||
import com.kingsrook.qqq.backend.core.modules.backend.implementations.memory.MemoryRecordStore;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static com.kingsrook.qbits.secureddata.SecuredDataTestSupport.close;
|
||||
import static com.kingsrook.qbits.secureddata.SecuredDataTestSupport.delete;
|
||||
import static com.kingsrook.qbits.secureddata.SecuredDataTestSupport.insert;
|
||||
import static com.kingsrook.qbits.secureddata.SecuredDataTestSupport.setup;
|
||||
import static com.kingsrook.qbits.secureddata.SecuredDataTestSupport.update;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The rule rows a node keeps (retention rules, policies, classifications) and
|
||||
** the access fingerprint of a request: read once, cleared by every change on
|
||||
** every node, never older than the maximum age, and never an empty answer when
|
||||
** the rules cannot be read.
|
||||
*******************************************************************************/
|
||||
class SecuredDataRuleCachesTest
|
||||
{
|
||||
private static final List<String> ANNOUNCED = new ArrayList<>();
|
||||
|
||||
static
|
||||
{
|
||||
ClusterBus.on(ClusterEvent.TYPE_MEMO_INVALIDATE, (instance, event) -> ANNOUNCED.add(event.getName()));
|
||||
}
|
||||
|
||||
QInstance instance;
|
||||
QTableMetaData person;
|
||||
SecuredDataRuntime runtime;
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A person table with a date, so a retention rule on it is valid.
|
||||
*******************************************************************************/
|
||||
@BeforeEach
|
||||
void init() throws Exception
|
||||
{
|
||||
instance = setup();
|
||||
person = instance.getTable("person");
|
||||
person.withField(new QFieldMetaData("createDate", QFieldType.DATE_TIME).withBackendName("createDate"));
|
||||
runtime = SecuredDataRuntime.current();
|
||||
MemoryRecordStore.setCollectStatistics(true);
|
||||
MemoryRecordStore.resetStatistics();
|
||||
ANNOUNCED.clear();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Cleanup.
|
||||
*******************************************************************************/
|
||||
@AfterEach
|
||||
void cleanup()
|
||||
{
|
||||
MemoryRecordStore.setCollectStatistics(false);
|
||||
close();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** An active rule on one field of the person table.
|
||||
*******************************************************************************/
|
||||
private static QRecord rule(String field) throws Exception
|
||||
{
|
||||
return (insert(SecuredDataTables.RETENTION_RULE, new QRecord().withValue("name", "30 days: " + field).withValue("table_name", "person")
|
||||
.withValue("field_names", field).withValue("age_field_name", "createDate").withValue("age_days", 30).withValue("action", "NULL_WITH_MARKER")));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Queries the in-memory store has run since the last reset.
|
||||
*******************************************************************************/
|
||||
private static int queries()
|
||||
{
|
||||
return (MemoryRecordStore.getStatistics().getOrDefault(MemoryRecordStore.STAT_QUERIES_RAN, 0));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Core asks for the rules of a field on every audited field and filter
|
||||
** criterion: many questions are one read, and every committed change (insert,
|
||||
** update, delete) is seen by the next question.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void activeRetentionRulesAreReadOncePerChange() throws Exception
|
||||
{
|
||||
QRecord notes = rule("notes");
|
||||
assertThat(notes.getErrors()).isNullOrEmpty();
|
||||
MemoryRecordStore.resetStatistics();
|
||||
for(int i = 0; i < 50; i++)
|
||||
{
|
||||
assertThat(RetentionRules.active("person", "notes")).hasSize(1);
|
||||
assertThat(RetentionRules.active("person", "email")).isEmpty();
|
||||
assertThat(RetentionRules.active("anotherTable", "notes")).isEmpty();
|
||||
assertThat(RetentionRules.changedOnly("person", "notes")).isFalse();
|
||||
}
|
||||
assertThat(queries()).isLessThanOrEqualTo(1);
|
||||
|
||||
QRecord ssn = rule("ssn");
|
||||
assertThat(RetentionRules.active("person", "ssn")).hasSize(1);
|
||||
|
||||
update(SecuredDataTables.RETENTION_RULE, new QRecord().withValue("id", notes.getValue("id")).withValue("is_active", false));
|
||||
assertThat(RetentionRules.active("person", "notes")).isEmpty();
|
||||
|
||||
delete(SecuredDataTables.RETENTION_RULE, ssn);
|
||||
assertThat(RetentionRules.active("person", "ssn")).isEmpty();
|
||||
assertThat(ANNOUNCED).contains(SecuredDataRuntime.RETENTION_CACHE);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A rule change made on another node arrives as a cluster cache event: each
|
||||
** of the three kinds of rules is read again here. A change made here is
|
||||
** announced to the other nodes.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void aChangeOnAnyNodeClearsTheRulesOnEveryNode() throws Exception
|
||||
{
|
||||
rule("notes");
|
||||
assertThat(RetentionRules.active("person", "notes")).hasSize(1);
|
||||
|
||||
long retention = runtime.retentionVersion();
|
||||
long policies = runtime.policyVersion();
|
||||
long classifications = runtime.classificationVersion();
|
||||
ClusterCaches.invalidate(SecuredDataRuntime.RETENTION_CACHE);
|
||||
ClusterCaches.invalidate(SecuredDataRuntime.POLICY_CACHE);
|
||||
ClusterCaches.invalidate(SecuredDataRuntime.CLASSIFICATION_CACHE);
|
||||
assertThat(runtime.retentionVersion()).isGreaterThan(retention);
|
||||
assertThat(runtime.policyVersion()).isGreaterThan(policies);
|
||||
assertThat(runtime.classificationVersion()).isGreaterThan(classifications);
|
||||
|
||||
MemoryRecordStore.resetStatistics();
|
||||
assertThat(RetentionRules.active("person", "notes")).hasSize(1);
|
||||
assertThat(queries()).isGreaterThanOrEqualTo(1);
|
||||
MemoryRecordStore.resetStatistics();
|
||||
assertThat(RetentionRules.active("person", "notes")).hasSize(1);
|
||||
assertThat(queries()).isZero();
|
||||
|
||||
ANNOUNCED.clear();
|
||||
runtime.invalidatePolicies();
|
||||
runtime.invalidateClassifications();
|
||||
runtime.invalidateRetentionRules();
|
||||
assertThat(ANNOUNCED).contains(SecuredDataRuntime.POLICY_CACHE, SecuredDataRuntime.CLASSIFICATION_CACHE, SecuredDataRuntime.RETENTION_CACHE);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fail closed: when the rules cannot be read, asking for them throws. The
|
||||
** rules read before are not used, and the answer is never an empty list.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void rulesThatCannotBeReadAreNeverAnEmptyAnswer() throws Exception
|
||||
{
|
||||
rule("notes");
|
||||
assertThat(RetentionRules.active("person", "notes")).hasSize(1);
|
||||
|
||||
QTableMetaData ruleTable = instance.getTables().remove(SecuredDataTables.RETENTION_RULE);
|
||||
try
|
||||
{
|
||||
runtime.invalidateRetentionRules();
|
||||
assertThatThrownBy(() -> RetentionRules.active("person", "notes")).isInstanceOf(RuntimeException.class);
|
||||
assertThatThrownBy(() -> RetentionRules.active("person", "notes")).isInstanceOf(RuntimeException.class);
|
||||
}
|
||||
finally
|
||||
{
|
||||
instance.getTables().put(SecuredDataTables.RETENTION_RULE, ruleTable);
|
||||
}
|
||||
assertThat(RetentionRules.active("person", "notes")).hasSize(1);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The safety net for a lost cluster event: rows are read again once they are
|
||||
** older than the maximum age.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void ruleRowsAreNotUsedPastTheirMaximumAge()
|
||||
{
|
||||
assertThat(SecuredDataRuntime.tooOld(System.nanoTime())).isFalse();
|
||||
assertThat(SecuredDataRuntime.tooOld(System.nanoTime() - SecuredDataRuntime.MAX_RULE_AGE.plusSeconds(1).toNanos())).isTrue();
|
||||
assertThat(SecuredDataRuntime.MAX_RULE_AGE.toSeconds()).isLessThanOrEqualTo(60);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Core asks for the access fingerprint before every field decision. Within a
|
||||
** request the same value object is returned; a permission that matters, given
|
||||
** to the same session object, changes it at once.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void theAccessFingerprintIsKeptForTheRequestAndTracksThePermissions()
|
||||
{
|
||||
SecuredDataResolver resolver = runtime.resolver();
|
||||
QSession session = QContext.getQSession();
|
||||
String first = resolver.getAccessFingerprint();
|
||||
for(int i = 0; i < 20; i++)
|
||||
{
|
||||
assertThat(resolver.getAccessFingerprint()).isSameAs(first);
|
||||
}
|
||||
|
||||
session.getPermissions().add("unrelated.permission");
|
||||
assertThat(resolver.getAccessFingerprint()).isEqualTo(first);
|
||||
|
||||
session.getPermissions().add(SecuredDataMetadata.permissionBase(person) + "." + SecuredDataPermissions.FULL);
|
||||
String granted = resolver.getAccessFingerprint();
|
||||
assertThat(granted).isNotEqualTo(first);
|
||||
|
||||
session.setPermissions(new HashSet<>(List.of("person.read")));
|
||||
assertThat(resolver.getAccessFingerprint()).isNotEqualTo(granted);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,682 @@
|
||||
/*
|
||||
* QQQ - Low-code Application Framework for Engineers.
|
||||
* Copyright (C) 2021-2025. Kingsrook, LLC
|
||||
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
|
||||
* contact@kingsrook.com
|
||||
* https://github.com/Kingsrook/
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.secureddata;
|
||||
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import com.kingsrook.qbits.secureddata.metadata.SecuredDataTables;
|
||||
import com.kingsrook.qbits.secureddata.retention.RetentionRules;
|
||||
import com.kingsrook.qbits.secureddata.support.SystemWrites;
|
||||
import com.kingsrook.qqq.backend.core.actions.QBackendTransaction;
|
||||
import com.kingsrook.qqq.backend.core.actions.ai.DataClassification;
|
||||
import com.kingsrook.qqq.backend.core.actions.customizers.TableCustomizerInterface;
|
||||
import com.kingsrook.qqq.backend.core.actions.customizers.TableCustomizers;
|
||||
import com.kingsrook.qqq.backend.core.actions.permissions.fieldaccess.FieldAccessDecision;
|
||||
import com.kingsrook.qqq.backend.core.actions.tables.QueryAction;
|
||||
import com.kingsrook.qqq.backend.core.actions.tables.query.VirtualFieldValueProviderInterface;
|
||||
import com.kingsrook.qqq.backend.core.context.QContext;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QException;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.QueryOrGetInputInterface;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.insert.InsertInput;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QCriteriaOperator;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QFilterCriteria;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QueryInput;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.update.UpdateInput;
|
||||
import com.kingsrook.qqq.backend.core.model.data.QRecord;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.code.QCodeReference;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldType;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.fields.QVirtualFieldMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.session.QSystemUserSession;
|
||||
import com.kingsrook.qqq.backend.core.modules.backend.implementations.memory.MemoryRecordStore;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static com.kingsrook.qbits.secureddata.SecuredDataTestSupport.classification;
|
||||
import static com.kingsrook.qbits.secureddata.SecuredDataTestSupport.close;
|
||||
import static com.kingsrook.qbits.secureddata.SecuredDataTestSupport.policyRow;
|
||||
import static com.kingsrook.qbits.secureddata.SecuredDataTestSupport.setup;
|
||||
import static com.kingsrook.qbits.secureddata.SecuredDataTestSupport.user;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Reading rule rows (classifications, retention rules, policies) is a query on
|
||||
** a secured-data table, and other code runs inside that query: a virtual field
|
||||
** value provider or a post-query customizer that another QBit or the host put
|
||||
** on the table. When that code runs a query with filter criteria, core asks
|
||||
** this QBit for a classification - which needs the rows being read.
|
||||
**
|
||||
** These tests put such code on the rule tables and prove: the read asks for
|
||||
** stored fields only, so no value provider runs inside it; a question asked
|
||||
** inside a read is answered from the rows held before and starts no other
|
||||
** read; only the reading thread, as the system, can be given that answer; and
|
||||
** a read that fails is tried again by the next question.
|
||||
*******************************************************************************/
|
||||
class SecuredDataRuleReloadTest
|
||||
{
|
||||
QInstance instance;
|
||||
QTableMetaData person;
|
||||
SecuredDataRuntime runtime;
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Something to do inside a query on a rule table.
|
||||
*******************************************************************************/
|
||||
@FunctionalInterface
|
||||
interface NestedWork
|
||||
{
|
||||
/*******************************************************************************
|
||||
** Do it.
|
||||
*******************************************************************************/
|
||||
void run() throws Exception;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Stands in for another QBit's virtual field on a secured-data table: filling
|
||||
** it runs a query that has filter criteria.
|
||||
*******************************************************************************/
|
||||
public static class NestedQueryProvider implements VirtualFieldValueProviderInterface
|
||||
{
|
||||
static final AtomicInteger RUNS = new AtomicInteger();
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Fill the field from a query with criteria, as a real provider does.
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public void fill(QTableMetaData table, String fieldName, List<QRecord> records, QueryInput input) throws QException
|
||||
{
|
||||
RUNS.incrementAndGet();
|
||||
queryWithCriteria();
|
||||
records.forEach(record -> record.setValue(fieldName, "filled"));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A post-query customizer on a secured-data table. Core runs it for every
|
||||
** query on the table, whatever fields the query names.
|
||||
*******************************************************************************/
|
||||
public static class NestedWorkCustomizer implements TableCustomizerInterface
|
||||
{
|
||||
static final AtomicInteger RUNS = new AtomicInteger();
|
||||
static volatile NestedWork work;
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Run the work the test asked for, inside the query.
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public List<QRecord> postQuery(QueryOrGetInputInterface queryInput, List<QRecord> records) throws QException
|
||||
{
|
||||
NestedWork toRun = work;
|
||||
if(toRun != null)
|
||||
{
|
||||
RUNS.incrementAndGet();
|
||||
try
|
||||
{
|
||||
toRun.run();
|
||||
}
|
||||
catch(QException | RuntimeException e)
|
||||
{
|
||||
throw (e);
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
throw (new QException("Nested work failed", e));
|
||||
}
|
||||
}
|
||||
return (records);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A person table with a date, so a retention rule on it is valid.
|
||||
*******************************************************************************/
|
||||
@BeforeEach
|
||||
void init() throws Exception
|
||||
{
|
||||
instance = setup();
|
||||
person = instance.getTable("person");
|
||||
person.withField(new QFieldMetaData("createDate", QFieldType.DATE_TIME).withBackendName("createDate"));
|
||||
runtime = SecuredDataRuntime.current();
|
||||
NestedQueryProvider.RUNS.set(0);
|
||||
NestedWorkCustomizer.RUNS.set(0);
|
||||
NestedWorkCustomizer.work = null;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Cleanup.
|
||||
*******************************************************************************/
|
||||
@AfterEach
|
||||
void cleanup()
|
||||
{
|
||||
NestedWorkCustomizer.work = null;
|
||||
close();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A query with filter criteria on a host table: core validates the operand
|
||||
** of a classified field, so it asks for the field's classification - and
|
||||
** this QBit then asks whether a retention rule names the field.
|
||||
*******************************************************************************/
|
||||
private static void queryWithCriteria() throws QException
|
||||
{
|
||||
new QueryAction().execute(new QueryInput("person").withFilter(new QQueryFilter(new QFilterCriteria("id", QCriteriaOperator.EQUALS, 1))));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Another QBit's virtual field on a secured-data table.
|
||||
*******************************************************************************/
|
||||
private void addProvider(String table)
|
||||
{
|
||||
instance.getTable(table).addVirtualField(new QVirtualFieldMetaData("labels", QFieldType.STRING).withIsQuerySelectable(true)
|
||||
.withValueProvider(new QCodeReference(NestedQueryProvider.class)));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A post-query customizer on a secured-data table.
|
||||
*******************************************************************************/
|
||||
private void addCustomizer(String table)
|
||||
{
|
||||
instance.getTable(table).withCustomizer(TableCustomizers.POST_QUERY_RECORD, new QCodeReference(NestedWorkCustomizer.class));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A row as another node writes it: straight into the store. None of this
|
||||
** node's customizers run and nothing here reads the rule rows; this node
|
||||
** learns of the change when its version moves (the cluster event).
|
||||
*******************************************************************************/
|
||||
private static QRecord writtenElsewhere(String table, QRecord row) throws QException
|
||||
{
|
||||
return (MemoryRecordStore.getInstance().insert(new InsertInput(table).withRecord(row), true).getFirst());
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A classification of a person field, written by another node.
|
||||
*******************************************************************************/
|
||||
private QRecord classifiedElsewhere(String field, String classification) throws QException
|
||||
{
|
||||
QRecord row = writtenElsewhere(SecuredDataTables.CLASSIFICATION, new QRecord().withValue("table_name", "person")
|
||||
.withValue("field_name", field).withValue("classification", classification));
|
||||
runtime.invalidateClassifications();
|
||||
return (row);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A classification row changed by another node.
|
||||
*******************************************************************************/
|
||||
private void reclassifiedElsewhere(QRecord row, String classification) throws QException
|
||||
{
|
||||
MemoryRecordStore.getInstance().update(new UpdateInput(SecuredDataTables.CLASSIFICATION).withRecord(new QRecord()
|
||||
.withValue("id", row.getValue("id")).withValue("classification", classification)), false);
|
||||
runtime.invalidateClassifications();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** An active retention rule on one field of the person table, written by
|
||||
** another node.
|
||||
*******************************************************************************/
|
||||
private void ruleWrittenElsewhere(String field) throws QException
|
||||
{
|
||||
writtenElsewhere(SecuredDataTables.RETENTION_RULE, new QRecord().withValue("name", "30 days: " + field).withValue("table_name", "person")
|
||||
.withValue("field_names", field).withValue("age_field_name", "createDate").withValue("age_days", 30).withValue("action", "NULL_WITH_MARKER")
|
||||
.withValue("audit_treatment", "SHREDDABLE").withValue("is_active", true));
|
||||
runtime.invalidateRetentionRules();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The classification of a person field.
|
||||
*******************************************************************************/
|
||||
private DataClassification classificationOf(String field)
|
||||
{
|
||||
return (SecuredDataClassifications.effective(person, field));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The reported failure: a value provider on the classification table whose
|
||||
** work is a query with criteria, and one classification row. Before the fix
|
||||
** the next classification question recursed until the stack overflowed, and
|
||||
** so did every question after it. Now the rule read names its stored fields,
|
||||
** so the provider does not run inside it at all.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void aValueProviderOnTheClassificationTableDoesNotRunInsideTheRuleRead() throws Exception
|
||||
{
|
||||
addProvider(SecuredDataTables.CLASSIFICATION);
|
||||
classification("notes", "PHI");
|
||||
|
||||
assertThat(classificationOf("notes")).isEqualTo(DataClassification.PHI);
|
||||
queryWithCriteria();
|
||||
assertThat(NestedQueryProvider.RUNS).hasValue(0);
|
||||
assertThat(SystemWrites.query(SecuredDataTables.CLASSIFICATION, new QQueryFilter())).singleElement()
|
||||
.satisfies(row -> assertThat(row.getValues()).doesNotContainKey("labels").containsEntry("field_name", "notes"));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The virtual field is still there for a query that asks for every field (a
|
||||
** screen listing the classifications). Its provider's query with criteria
|
||||
** asks for a classification while the rows are out of date: the rows are
|
||||
** read once, inside the provider, and nothing recurses.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void anOrdinaryQueryOnTheClassificationTableStillFillsTheVirtualField() throws Exception
|
||||
{
|
||||
addProvider(SecuredDataTables.CLASSIFICATION);
|
||||
classifiedElsewhere("notes", "PHI");
|
||||
|
||||
List<QRecord> rows = SystemWrites.call(() -> new QueryAction().execute(new QueryInput(SecuredDataTables.CLASSIFICATION)).getRecords());
|
||||
assertThat(rows).singleElement().satisfies(row -> assertThat(row.getValueString("labels")).isEqualTo("filled"));
|
||||
assertThat(NestedQueryProvider.RUNS).hasValue(1);
|
||||
assertThat(classificationOf("notes")).isEqualTo(DataClassification.PHI);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A post-query customizer runs inside the rule read whatever fields the read
|
||||
** names. Its query with criteria asks for a classification in the middle of
|
||||
** the read of the classifications: before the fix that started the read again
|
||||
** and recursed until the stack overflowed. Now the rows are read once.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void aQuestionAskedInsideTheClassificationReadDoesNotStartAnotherRead() throws Exception
|
||||
{
|
||||
addCustomizer(SecuredDataTables.CLASSIFICATION);
|
||||
classifiedElsewhere("notes", "PHI");
|
||||
|
||||
NestedWorkCustomizer.work = SecuredDataRuleReloadTest::queryWithCriteria;
|
||||
assertThat(classificationOf("notes")).isEqualTo(DataClassification.PHI);
|
||||
assertThat(NestedWorkCustomizer.RUNS).hasValue(1);
|
||||
|
||||
assertThat(classificationOf("email")).isEqualTo(DataClassification.PII);
|
||||
assertThat(NestedWorkCustomizer.RUNS).hasValue(1);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** What a question asked inside the read is told, and who can ask it.
|
||||
**
|
||||
** The nested question gets the rows this node held when the read began (no
|
||||
** rows, the first time; then the rows of the previous version), in both
|
||||
** directions of a change. It can only be asked by the thread doing the read,
|
||||
** which is inside the QBit's system read: the session is the system session
|
||||
** and the resolver answers FULL there without looking at any classification,
|
||||
** so no person's field access is decided from that answer. The question that
|
||||
** started the read gets the new rows.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void aQuestionAskedInsideTheReadIsAnsweredFromTheRowsHeldBefore() throws Exception
|
||||
{
|
||||
addCustomizer(SecuredDataTables.CLASSIFICATION);
|
||||
assertThat(classificationOf("notes")).isNull();
|
||||
|
||||
List<DataClassification> nestedAnswers = new ArrayList<>();
|
||||
List<Boolean> nestedAsSystem = new ArrayList<>();
|
||||
List<FieldAccessDecision> nestedDecisions = new ArrayList<>();
|
||||
NestedWork ask = () ->
|
||||
{
|
||||
nestedAnswers.add(classificationOf("notes"));
|
||||
nestedAsSystem.add(QContext.getQSession() instanceof QSystemUserSession && SystemWrites.active());
|
||||
nestedDecisions.add(runtime.resolver().resolve(person, person.getField("notes")));
|
||||
};
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////
|
||||
// a row raises the field: inside the read it is still unclassified, //
|
||||
// and the question that started the read is answered PHI //
|
||||
/////////////////////////////////////////////////////////////////////////
|
||||
QRecord row = classifiedElsewhere("notes", "PHI");
|
||||
NestedWorkCustomizer.work = ask;
|
||||
assertThat(classificationOf("notes")).isEqualTo(DataClassification.PHI);
|
||||
NestedWorkCustomizer.work = null;
|
||||
assertThat(nestedAnswers).containsExactly((DataClassification) null);
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////
|
||||
// the row is changed to lower the field: inside the read it is still //
|
||||
// PHI, and the question that started the read is answered PUBLIC //
|
||||
/////////////////////////////////////////////////////////////////////////
|
||||
reclassifiedElsewhere(row, "PUBLIC");
|
||||
NestedWorkCustomizer.work = ask;
|
||||
assertThat(classificationOf("notes")).isEqualTo(DataClassification.PUBLIC);
|
||||
NestedWorkCustomizer.work = null;
|
||||
assertThat(nestedAnswers).containsExactly(null, DataClassification.PHI);
|
||||
|
||||
assertThat(nestedAsSystem).containsExactly(true, true);
|
||||
assertThat(nestedDecisions).containsExactly(FieldAccessDecision.FULL, FieldAccessDecision.FULL);
|
||||
assertThat(NestedWorkCustomizer.RUNS).hasValue(2);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A request on another thread is never given the rows held before: while the
|
||||
** read is running it waits, and then it is answered from the rows the read
|
||||
** returned.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void aRequestOnAnotherThreadWaitsForTheReadAndIsGivenItsRows() throws Exception
|
||||
{
|
||||
addCustomizer(SecuredDataTables.CLASSIFICATION);
|
||||
QRecord row = classifiedElsewhere("notes", "PUBLIC");
|
||||
assertThat(classificationOf("notes")).isEqualTo(DataClassification.PUBLIC);
|
||||
reclassifiedElsewhere(row, "PHI");
|
||||
|
||||
CountDownLatch readIsRunning = new CountDownLatch(1);
|
||||
CountDownLatch letReadFinish = new CountDownLatch(1);
|
||||
NestedWorkCustomizer.work = () ->
|
||||
{
|
||||
readIsRunning.countDown();
|
||||
assertThat(letReadFinish.await(30, TimeUnit.SECONDS)).isTrue();
|
||||
};
|
||||
|
||||
ExecutorService pool = Executors.newFixedThreadPool(2);
|
||||
try
|
||||
{
|
||||
Future<DataClassification> reader = pool.submit(asUser("u2", () -> classificationOf("notes")));
|
||||
assertThat(readIsRunning.await(30, TimeUnit.SECONDS)).isTrue();
|
||||
|
||||
Future<DataClassification> other = pool.submit(asUser("u3", () -> classificationOf("notes")));
|
||||
assertThatThrownBy(() -> other.get(500, TimeUnit.MILLISECONDS)).isInstanceOf(TimeoutException.class);
|
||||
|
||||
letReadFinish.countDown();
|
||||
assertThat(reader.get(30, TimeUnit.SECONDS)).isEqualTo(DataClassification.PHI);
|
||||
assertThat(other.get(30, TimeUnit.SECONDS)).isEqualTo(DataClassification.PHI);
|
||||
assertThat(NestedWorkCustomizer.RUNS).hasValue(1);
|
||||
}
|
||||
finally
|
||||
{
|
||||
letReadFinish.countDown();
|
||||
pool.shutdownNow();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A person's request on its own thread.
|
||||
*******************************************************************************/
|
||||
private <T> Callable<T> asUser(String id, Callable<T> work)
|
||||
{
|
||||
return (() ->
|
||||
{
|
||||
QContext.init(instance, user(id));
|
||||
try
|
||||
{
|
||||
return (work.call());
|
||||
}
|
||||
finally
|
||||
{
|
||||
QContext.clear();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A read that fails (here, in code running inside it, after that code asked a
|
||||
** nested question) throws to the request that started it and leaves nothing
|
||||
** behind: the next request reads again and gets the current rows - not the
|
||||
** rows held before, and not another failure. An Error, such as the stack
|
||||
** overflow this defect used to end in, is no different.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void aClassificationReadThatFailsIsTriedAgainByTheNextQuestion() throws Exception
|
||||
{
|
||||
addCustomizer(SecuredDataTables.CLASSIFICATION);
|
||||
QRecord row = classifiedElsewhere("notes", "PUBLIC");
|
||||
assertThat(classificationOf("notes")).isEqualTo(DataClassification.PUBLIC);
|
||||
reclassifiedElsewhere(row, "PHI");
|
||||
|
||||
NestedWorkCustomizer.work = () ->
|
||||
{
|
||||
classificationOf("notes");
|
||||
throw (new QException("The store is unavailable"));
|
||||
};
|
||||
assertThatThrownBy(() -> classificationOf("notes")).isInstanceOf(IllegalStateException.class);
|
||||
|
||||
NestedWorkCustomizer.work = () ->
|
||||
{
|
||||
classificationOf("notes");
|
||||
throw (new StackOverflowError());
|
||||
};
|
||||
assertThatThrownBy(() -> classificationOf("notes")).isInstanceOf(StackOverflowError.class);
|
||||
|
||||
NestedWorkCustomizer.work = null;
|
||||
assertThat(classificationOf("notes")).isEqualTo(DataClassification.PHI);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The active retention rules have the same shape: core's classification
|
||||
** question for a host field also asks whether a retention rule names the
|
||||
** field. A value provider on the retention rule table, with one active rule,
|
||||
** recursed the same way before the fix; it does not run inside the rule read.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void aValueProviderOnTheRetentionRuleTableDoesNotRunInsideTheRuleRead() throws Exception
|
||||
{
|
||||
addProvider(SecuredDataTables.RETENTION_RULE);
|
||||
ruleWrittenElsewhere("notes");
|
||||
|
||||
assertThat(RetentionRules.active("person", "notes")).hasSize(1);
|
||||
queryWithCriteria();
|
||||
assertThat(NestedQueryProvider.RUNS).hasValue(0);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A question asked inside the read of the retention rules starts no other
|
||||
** read and is answered from the rules held before; the question that started
|
||||
** the read gets the new rules. A read that fails is tried again.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void aQuestionAskedInsideTheRetentionRuleReadIsAnsweredFromTheRulesHeldBefore() throws Exception
|
||||
{
|
||||
addCustomizer(SecuredDataTables.RETENTION_RULE);
|
||||
assertThat(RetentionRules.active("person", "notes")).isEmpty();
|
||||
ruleWrittenElsewhere("notes");
|
||||
|
||||
List<Integer> nestedAnswers = new ArrayList<>();
|
||||
NestedWorkCustomizer.work = () ->
|
||||
{
|
||||
queryWithCriteria();
|
||||
nestedAnswers.add(RetentionRules.active("person", "notes").size());
|
||||
if(nestedAnswers.size() == 1)
|
||||
{
|
||||
throw (new QException("The store is unavailable"));
|
||||
}
|
||||
};
|
||||
assertThatThrownBy(() -> RetentionRules.active("person", "notes")).isInstanceOf(IllegalStateException.class);
|
||||
assertThat(RetentionRules.active("person", "notes")).hasSize(1);
|
||||
assertThat(nestedAnswers).containsExactly(0, 0);
|
||||
assertThat(NestedWorkCustomizer.RUNS).hasValue(2);
|
||||
|
||||
assertThat(RetentionRules.active("person", "notes")).hasSize(1);
|
||||
assertThat(NestedWorkCustomizer.RUNS).hasValue(2);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A transaction that edited a rule reads the rules through itself, not from
|
||||
** the rules the node keeps. A question asked inside that read is answered
|
||||
** from the rules every thread shares: before the fix it read the edits again,
|
||||
** and recursed until the stack overflowed.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void aQuestionAskedInsideAReadOfATransactionsOwnEditsDoesNotReadThemAgain() throws Exception
|
||||
{
|
||||
addCustomizer(SecuredDataTables.RETENTION_RULE);
|
||||
ruleWrittenElsewhere("notes");
|
||||
assertThat(RetentionRules.active("person", "notes")).hasSize(1);
|
||||
|
||||
QContext.setTransaction(new QBackendTransaction());
|
||||
RetentionRules.editedInTransaction();
|
||||
try
|
||||
{
|
||||
NestedWorkCustomizer.work = SecuredDataRuleReloadTest::queryWithCriteria;
|
||||
assertThat(RetentionRules.active("person", "notes")).hasSize(1);
|
||||
assertThat(NestedWorkCustomizer.RUNS).hasValue(1);
|
||||
}
|
||||
finally
|
||||
{
|
||||
////////////////////////////////////////////////////////////////////////
|
||||
// the next question outside a transaction ends this thread's edits //
|
||||
////////////////////////////////////////////////////////////////////////
|
||||
NestedWorkCustomizer.work = null;
|
||||
QContext.setTransaction(null);
|
||||
RetentionRules.active("person", "notes");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The policies are read the same way (rows first, version afterwards), so
|
||||
** they are guarded the same way: code inside the policy read that asks the
|
||||
** resolver a policy question starts no other read, and a read that fails is
|
||||
** tried again.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void aQuestionAskedInsideThePolicyReadDoesNotStartAnotherRead() throws Exception
|
||||
{
|
||||
addCustomizer(SecuredDataTables.POLICY);
|
||||
addProvider(SecuredDataTables.POLICY);
|
||||
assertThat(runtime.resolver().revealPolicies(person, "email")).isEmpty();
|
||||
writtenElsewhere(SecuredDataTables.POLICY, policyRow("cs_admin", "PII", "REVEALABLE"));
|
||||
runtime.invalidatePolicies();
|
||||
|
||||
List<Integer> nestedAnswers = new ArrayList<>();
|
||||
NestedWorkCustomizer.work = () ->
|
||||
{
|
||||
nestedAnswers.add(runtime.resolver().revealPolicies(person, "email").size());
|
||||
if(nestedAnswers.size() == 1)
|
||||
{
|
||||
throw (new QException("The store is unavailable"));
|
||||
}
|
||||
};
|
||||
assertThatThrownBy(() -> runtime.resolver().revealPolicies(person, "email")).isInstanceOf(IllegalStateException.class);
|
||||
assertThat(runtime.resolver().revealPolicies(person, "email")).hasSize(1);
|
||||
assertThat(nestedAnswers).containsExactly(0, 0);
|
||||
assertThat(NestedQueryProvider.RUNS).hasValue(0);
|
||||
|
||||
NestedWorkCustomizer.RUNS.set(0);
|
||||
assertThat(runtime.resolver().revealPolicies(person, "email")).hasSize(1);
|
||||
assertThat(NestedWorkCustomizer.RUNS).hasValue(0);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The rows themselves, without a table: nothing is held before the first
|
||||
** read, a nested question never reads, a failed read is forgotten, and a new
|
||||
** version is read once.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void ruleRowsAreReadOncePerVersionAndNeverFromInsideTheirOwnRead()
|
||||
{
|
||||
RuleRows rows = new RuleRows();
|
||||
AtomicInteger reads = new AtomicInteger();
|
||||
List<QRecord> first = List.of(new QRecord().withValue("id", 1));
|
||||
List<QRecord> second = List.of(new QRecord().withValue("id", 2));
|
||||
|
||||
assertThatThrownBy(() -> rows.get(1, () ->
|
||||
{
|
||||
reads.incrementAndGet();
|
||||
assertThat(rows.get(1, () -> fail("a nested question must not read"))).isEmpty();
|
||||
throw (new IllegalStateException("The store is unavailable"));
|
||||
})).isInstanceOf(IllegalStateException.class);
|
||||
|
||||
assertThat(rows.get(1, () ->
|
||||
{
|
||||
reads.incrementAndGet();
|
||||
assertThat(rows.get(1, () -> fail("a nested question must not read"))).isEmpty();
|
||||
return (first);
|
||||
})).isEqualTo(first);
|
||||
assertThat(rows.get(1, () -> fail("rows of this version are held"))).isEqualTo(first);
|
||||
|
||||
assertThat(rows.get(2, () ->
|
||||
{
|
||||
reads.incrementAndGet();
|
||||
assertThat(rows.get(2, () -> fail("a nested question must not read"))).isEqualTo(first);
|
||||
return (second);
|
||||
})).isEqualTo(second);
|
||||
assertThat(reads).hasValue(3);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A read that must not happen.
|
||||
*******************************************************************************/
|
||||
private static List<QRecord> fail(String why)
|
||||
{
|
||||
throw (new AssertionError(why));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,774 @@
|
||||
/*
|
||||
* QQQ - Low-code Application Framework for Engineers.
|
||||
* Copyright (C) 2021-2025. Kingsrook, LLC
|
||||
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
|
||||
* contact@kingsrook.com
|
||||
* https://github.com/Kingsrook/
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.secureddata;
|
||||
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.Serializable;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.ResultSetMetaData;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Timestamp;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import com.kingsrook.qbits.secureddata.breakglass.BreakGlassService;
|
||||
import com.kingsrook.qbits.secureddata.metadata.SecuredDataTables;
|
||||
import com.kingsrook.qbits.secureddata.retention.WipeService;
|
||||
import com.kingsrook.qbits.secureddata.reveal.RevealService;
|
||||
import com.kingsrook.qbits.secureddata.support.SystemWrites;
|
||||
import com.kingsrook.qqq.backend.core.actions.ai.AiExposure;
|
||||
import com.kingsrook.qqq.backend.core.actions.ai.AiFieldMetaData;
|
||||
import com.kingsrook.qqq.backend.core.actions.ai.AiTableMetaData;
|
||||
import com.kingsrook.qqq.backend.core.actions.ai.DataClassification;
|
||||
import com.kingsrook.qqq.backend.core.actions.permissions.fieldaccess.ClassifiedValueTokens;
|
||||
import com.kingsrook.qqq.backend.core.actions.permissions.fieldaccess.FieldAccessEvent;
|
||||
import com.kingsrook.qqq.backend.core.actions.permissions.fieldaccess.FieldAccessEventType;
|
||||
import com.kingsrook.qqq.backend.core.actions.permissions.fieldaccess.FieldAccessOutcome;
|
||||
import com.kingsrook.qqq.backend.core.actions.permissions.fieldaccess.FieldAccessTier;
|
||||
import com.kingsrook.qqq.backend.core.actions.tables.DeleteAction;
|
||||
import com.kingsrook.qqq.backend.core.actions.tables.InsertAction;
|
||||
import com.kingsrook.qqq.backend.core.actions.tables.UpdateAction;
|
||||
import com.kingsrook.qqq.backend.core.context.QContext;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.delete.DeleteInput;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.insert.InsertInput;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QCriteriaOperator;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QFilterCriteria;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QFilterOrderBy;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.update.UpdateInput;
|
||||
import com.kingsrook.qqq.backend.core.model.data.QRecord;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QBackendMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.fields.DynamicDefaultValueBehavior;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldType;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.session.QSession;
|
||||
import com.kingsrook.qqq.backend.core.modules.backend.implementations.memory.MemoryBackendModule;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static com.kingsrook.qbits.secureddata.SecuredDataTestSupport.CLOCK;
|
||||
import static com.kingsrook.qbits.secureddata.SecuredDataTestSupport.NOW;
|
||||
import static com.kingsrook.qbits.secureddata.SecuredDataTestSupport.RUNTIMES;
|
||||
import static com.kingsrook.qbits.secureddata.SecuredDataTestSupport.base;
|
||||
import static com.kingsrook.qbits.secureddata.SecuredDataTestSupport.classification;
|
||||
import static com.kingsrook.qbits.secureddata.SecuredDataTestSupport.insert;
|
||||
import static com.kingsrook.qbits.secureddata.SecuredDataTestSupport.logs;
|
||||
import static com.kingsrook.qbits.secureddata.SecuredDataTestSupport.person;
|
||||
import static com.kingsrook.qbits.secureddata.SecuredDataTestSupport.policyRow;
|
||||
import static com.kingsrook.qbits.secureddata.SecuredDataTestSupport.setup;
|
||||
import static com.kingsrook.qbits.secureddata.SecuredDataTestSupport.update;
|
||||
import static com.kingsrook.qbits.secureddata.SecuredDataTestSupport.user;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Every table has a create date and a modify date: what the metadata says of
|
||||
** them, who may read them, every writer of this QBit setting them, what the
|
||||
** access-log writer runs for a row, the records of a changed policy, and rows
|
||||
** that were written before the two columns existed.
|
||||
*******************************************************************************/
|
||||
class SecuredDataStandardDatesTest
|
||||
{
|
||||
static final String DDL = "docs/ddl/secured-data-postgres.sql";
|
||||
|
||||
/** The first line of the block of the DDL that an existing database runs to get the two columns. */
|
||||
static final String DDL_BLOCK = "-- Standard dates:";
|
||||
|
||||
/** The tables that had the two dates before the other tables did: they keep the field names they have always had. */
|
||||
private static final Set<String> SNAKE_CASE_NAMES = Set.of("secured_data_classification", "secured_data_policy", "secured_data_retention_rule");
|
||||
|
||||
private static final Instant LATER = NOW.plusSeconds(90);
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Cleanup.
|
||||
*******************************************************************************/
|
||||
@AfterEach
|
||||
void cleanup()
|
||||
{
|
||||
RetentionTestSupport.close();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The tables the producer put in an instance, whichever class declares them,
|
||||
** so that a table added later is covered without being named here.
|
||||
*******************************************************************************/
|
||||
static List<QTableMetaData> declared(QInstance instance)
|
||||
{
|
||||
String qBit = instance.getQBits().get("com.kingsrook.qbits:qbit-secured-data").getName();
|
||||
List<QTableMetaData> tables = instance.getTables().values().stream().filter(table -> qBit.equals(table.getSourceQBitName())).toList();
|
||||
assertThat(tables).extracting(QTableMetaData::getName).containsAll(SecuredDataTables.ALL);
|
||||
return (tables);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Create date field name.
|
||||
*******************************************************************************/
|
||||
private static String createDate(String table)
|
||||
{
|
||||
return (SNAKE_CASE_NAMES.contains(table) ? "create_date" : "createDate");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Modify date field name.
|
||||
*******************************************************************************/
|
||||
private static String modifyDate(String table)
|
||||
{
|
||||
return (SNAKE_CASE_NAMES.contains(table) ? "modify_date" : "modifyDate");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** What the QBit declares, before core enriches anything: core gives a field
|
||||
** named createDate or modifyDate its behavior by itself, unless a host turned
|
||||
** that off, and gives the snake_case names nothing.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void everyDeclaredTableHasACreateDateAndAModifyDate() throws Exception
|
||||
{
|
||||
QInstance instance = base();
|
||||
instance.addBackend(new QBackendMetaData().withName("memory").withBackendType(MemoryBackendModule.class));
|
||||
instance.addTable(person("memory"));
|
||||
new SecuredDataQBitProducer().withQBitConfig(new SecuredDataQBitConfig().withClock(CLOCK).withAccessLogFlushIntervalMillis(60000)).produce(instance);
|
||||
QContext.init(instance, user("u1"));
|
||||
RUNTIMES.add(SecuredDataRuntime.current());
|
||||
|
||||
for(QTableMetaData table : declared(instance))
|
||||
{
|
||||
assertDate(table, createDate(table.getName()), "create_date", DynamicDefaultValueBehavior.CREATE_DATE);
|
||||
assertDate(table, modifyDate(table.getName()), "modify_date", DynamicDefaultValueBehavior.MODIFY_DATE);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** One date field: a date-time nobody edits, kept by core, in a section.
|
||||
*******************************************************************************/
|
||||
private static void assertDate(QTableMetaData table, String name, String column, DynamicDefaultValueBehavior behavior)
|
||||
{
|
||||
String where = table.getName() + "." + name;
|
||||
assertThat(table.getFields()).as(where).containsKey(name);
|
||||
QFieldMetaData field = table.getField(name);
|
||||
assertThat(field.getType()).as(where).isEqualTo(QFieldType.DATE_TIME);
|
||||
assertThat(field.getIsEditable()).as(where).isFalse();
|
||||
assertThat(field.getBehaviorOnlyIfSet(DynamicDefaultValueBehavior.class)).as(where).isEqualTo(behavior);
|
||||
assertThat(field.getBackendName()).as(where).isEqualTo(column);
|
||||
assertThat(table.getFields().values()).as(where).filteredOn(other -> other.getBehaviorOnlyIfSet(DynamicDefaultValueBehavior.class) == behavior).hasSize(1);
|
||||
assertThat(table.getSections()).as(where).anySatisfy(section -> assertThat(section.getFieldNames()).contains(name));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The two dates have no classification, policy or assistant exposure of their
|
||||
** own. Whoever asks, they are given the tier of every other field of their
|
||||
** table that has none of its own either, and the assistant is given nothing.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void theDatesAreReadableExactlyWhereTheOtherFieldsOfTheirTableAre() throws Exception
|
||||
{
|
||||
QInstance instance = setup(config -> config.withDefaultTier(DataClassification.CONFIDENTIAL, FieldAccessTier.MASKED));
|
||||
insert(SecuredDataTables.POLICY, policyRow("hidden", "CONFIDENTIAL", "HIDDEN"));
|
||||
insert(SecuredDataTables.POLICY, policyRow("full", "CONFIDENTIAL", "FULL"));
|
||||
insert(SecuredDataTables.POLICY, policyRow("capped", "CONFIDENTIAL", "FULL"));
|
||||
insert(SecuredDataTables.POLICY, policyRow("capped", "CONFIDENTIAL", "HIDDEN").withValue("client_channel", "web"));
|
||||
|
||||
Map<String, QSession> sessions = new LinkedHashMap<>();
|
||||
sessions.put("the default tier", user("u1"));
|
||||
sessions.put("a policy that hides", user("u2", "hidden"));
|
||||
sessions.put("a policy that shows", user("u3", "full"));
|
||||
sessions.put("a channel cap", SecuredDataTestSupport.channelUser("web", "capped"));
|
||||
sessions.put("the administrator", user("u4", "secured_data.admin"));
|
||||
Map<String, FieldAccessTier> expected = Map.of("the default tier", FieldAccessTier.MASKED, "a policy that hides", FieldAccessTier.HIDDEN,
|
||||
"a policy that shows", FieldAccessTier.FULL, "a channel cap", FieldAccessTier.HIDDEN, "the administrator", FieldAccessTier.FULL);
|
||||
|
||||
for(Map.Entry<String, QSession> session : sessions.entrySet())
|
||||
{
|
||||
QContext.setQSession(session.getValue());
|
||||
for(QTableMetaData table : declared(instance))
|
||||
{
|
||||
for(String name : List.of(createDate(table.getName()), modifyDate(table.getName())))
|
||||
{
|
||||
String where = session.getKey() + ": " + table.getName() + "." + name;
|
||||
QFieldMetaData date = table.getField(name);
|
||||
assertThat(AiFieldMetaData.of(date)).as(where).isNull();
|
||||
assertThat(SecuredDataClassifications.effective(table, name)).as(where).isEqualTo(DataClassification.CONFIDENTIAL);
|
||||
FieldAccessTier tier = SecuredDataRuntime.current().resolver().resolve(table, date).tier();
|
||||
assertThat(tier).as(where).isEqualTo(expected.get(session.getKey()));
|
||||
for(QFieldMetaData other : table.getFields().values())
|
||||
{
|
||||
if(!other.getName().equals(table.getPrimaryKeyField()))
|
||||
{
|
||||
assertThat(SecuredDataRuntime.current().resolver().resolve(table, other).tier()).as(where + " and " + other.getName()).isEqualTo(tier);
|
||||
}
|
||||
}
|
||||
}
|
||||
assertThat(AiTableMetaData.of(table).getExposure()).as(table.getName()).isEqualTo(AiExposure.NONE);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Every writer of this QBit, on the memory backend: the access-log writer, a
|
||||
** changed policy and classification with their own log rows, a legal hold, a
|
||||
** reveal and a break-glass session from its start to its end and its expiry.
|
||||
** A new row has both dates, equal, from the clock of the QBit. A changed row
|
||||
** keeps its create date and has a later modify date, which core chooses (the
|
||||
** modify date is the record version of its table).
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void everyWriterSetsBothDatesAndOnlyAChangeMovesTheModifyDate() throws Exception
|
||||
{
|
||||
setup();
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////
|
||||
// the access-log writer: created_at is when the access happened, the two //
|
||||
// dates are when the writer's one insert wrote the row //
|
||||
////////////////////////////////////////////////////////////////////////////
|
||||
SecuredDataRuntime.current().logger().onAccess(SecuredDataAccessLoggerTest.event(FieldAccessEventType.EXACT_MATCH_FILTER, FieldAccessOutcome.MATCH, "hmac"));
|
||||
CLOCK.now = LATER;
|
||||
SecuredDataRuntime.current().logger().flush();
|
||||
QRecord logged = logs().getLast();
|
||||
assertThat(logged.getValueString("event_type")).isEqualTo("EXACT_MATCH_FILTER");
|
||||
assertThat(logged.getValueInstant("created_at")).isEqualTo(NOW);
|
||||
assertDates(logged, SecuredDataTables.ACCESS_LOG, LATER, LATER);
|
||||
assertThatThrownBy(() -> update(SecuredDataTables.ACCESS_LOG, new QRecord().withValue("id", logged.getValue("id")).withValue("outcome", "DENIED"))).isInstanceOf(Exception.class);
|
||||
assertDates(row(SecuredDataTables.ACCESS_LOG, logged.getValue("id")), SecuredDataTables.ACCESS_LOG, LATER, LATER);
|
||||
CLOCK.now = NOW;
|
||||
|
||||
///////////////////////////////////////////////////////////////////////
|
||||
// the rows the rules are read from, and the log row of every change //
|
||||
///////////////////////////////////////////////////////////////////////
|
||||
QRecord policy = insert(SecuredDataTables.POLICY, policyRow("cs_admin", "PII", "REVEALABLE").withValue("reason_options", "Support").withValue("allow_free_text_reason", false));
|
||||
QRecord classification = classification("notes", "PII");
|
||||
QRecord hold = insert(SecuredDataTables.LEGAL_HOLD, new QRecord().withValue("table_name", "person").withValue("reason", "Preservation"));
|
||||
Map<String, Serializable> written = new LinkedHashMap<>();
|
||||
written.put(SecuredDataTables.POLICY, policy.getValue("id"));
|
||||
written.put(SecuredDataTables.CLASSIFICATION, classification.getValue("id"));
|
||||
written.put(SecuredDataTables.LEGAL_HOLD, hold.getValue("id"));
|
||||
for(Map.Entry<String, Serializable> row : written.entrySet())
|
||||
{
|
||||
assertDates(row(row.getKey(), row.getValue()), row.getKey(), NOW, NOW);
|
||||
}
|
||||
assertDates(log("POLICY_CHANGE", "INSERT"), SecuredDataTables.ACCESS_LOG, NOW, NOW);
|
||||
assertDates(log("CLASSIFICATION_CHANGE", "INSERT"), SecuredDataTables.ACCESS_LOG, NOW, NOW);
|
||||
|
||||
CLOCK.now = LATER;
|
||||
update(SecuredDataTables.POLICY, new QRecord().withValue("id", policy.getValue("id")).withValue("name", "renamed"));
|
||||
update(SecuredDataTables.CLASSIFICATION, new QRecord().withValue("id", classification.getValue("id")).withValue("notes", "reviewed"));
|
||||
update(SecuredDataTables.LEGAL_HOLD, new QRecord().withValue("id", hold.getValue("id")).withValue("status", "RELEASED"));
|
||||
for(Map.Entry<String, Serializable> row : written.entrySet())
|
||||
{
|
||||
assertChanged(row(row.getKey(), row.getValue()), row.getKey(), NOW, NOW);
|
||||
}
|
||||
assertDates(log("POLICY_CHANGE", "UPDATE"), SecuredDataTables.ACCESS_LOG, LATER, LATER);
|
||||
assertDates(log("CLASSIFICATION_CHANGE", "UPDATE"), SecuredDataTables.ACCESS_LOG, LATER, LATER);
|
||||
CLOCK.now = NOW;
|
||||
|
||||
////////////////////////////////////////////
|
||||
// a reveal: its grant and its log row //
|
||||
////////////////////////////////////////////
|
||||
Serializable person = insert("person", new QRecord().withValue("email", "someone@example.invalid")).getValue("id");
|
||||
new RevealService().reveal("person", person, "email", "Support", null);
|
||||
assertDates(SystemWrites.query(SecuredDataTables.REVEAL_GRANT, new QQueryFilter()).getFirst(), SecuredDataTables.REVEAL_GRANT, NOW, NOW);
|
||||
assertDates(log("REVEAL", null), SecuredDataTables.ACCESS_LOG, NOW, NOW);
|
||||
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
// a break-glass session: started, then ended; started, then expired //
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
BreakGlassService breaks = new BreakGlassService();
|
||||
QContext.setQSession(user("u1", "cs_admin", BreakGlassService.START + ".hasAccess"));
|
||||
Serializable ended = breaks.start("Investigating urgent incident", 60, null, null).getValue("id");
|
||||
assertDates(breaks.find(ended), SecuredDataTables.BREAK_GLASS, NOW, NOW);
|
||||
CLOCK.now = LATER;
|
||||
breaks.end(ended);
|
||||
Instant endedAt = assertChanged(breaks.find(ended), SecuredDataTables.BREAK_GLASS, NOW, NOW);
|
||||
assertDates(log("BREAK_GLASS_END", null), SecuredDataTables.ACCESS_LOG, LATER, LATER);
|
||||
|
||||
Serializable expired = breaks.start("Investigating another incident", 1, null, null).getValue("id");
|
||||
assertDates(breaks.find(expired), SecuredDataTables.BREAK_GLASS, LATER, LATER);
|
||||
CLOCK.now = LATER.plusSeconds(60);
|
||||
assertThat(breaks.expire()).isEqualTo(1);
|
||||
assertChanged(breaks.find(expired), SecuredDataTables.BREAK_GLASS, LATER, LATER);
|
||||
assertDates(breaks.find(ended), SecuredDataTables.BREAK_GLASS, NOW, endedAt);
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////
|
||||
// the access log is only ever inserted, so no row's modify date moved //
|
||||
/////////////////////////////////////////////////////////////////////////
|
||||
assertThat(logs()).hasSizeGreaterThan(8).allSatisfy(row ->
|
||||
{
|
||||
assertThat(row.getValueInstant("createDate")).isNotNull();
|
||||
assertThat(row.getValueInstant("modifyDate")).isEqualTo(row.getValueInstant("createDate"));
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The writers of a wipe, in the shipped schema: the audit key, the run, the
|
||||
** marker (written once, then changed by a later wipe of the same field), the
|
||||
** log row, and the rule the run is recorded on. A time is compared with what
|
||||
** the same database gives back for another time written from the same clock,
|
||||
** not with the clock: the test database shifts a time by the zone of the
|
||||
** machine it runs on.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void aWipeSetsBothDatesInTheShippedSchema() throws Exception
|
||||
{
|
||||
RetentionTestSupport.setup();
|
||||
QRecord rule = RetentionTestSupport.rule("OVERWRITE_TEXT", "secret");
|
||||
QRecord reading = RetentionTestSupport.reading(120);
|
||||
assertThat(SecuredDataRuntime.current().keys().keyForRecordField("reading", "secret", reading.getValue("id"), true)).isPresent();
|
||||
QRecord key = RetentionTestSupport.rows(SecuredDataTables.AUDIT_KEY).getFirst();
|
||||
assertDates(key, SecuredDataTables.AUDIT_KEY, key.getValueInstant("created_at"), key.getValueInstant("created_at"));
|
||||
Instant ruleWritten = row(SecuredDataTables.RETENTION_RULE, rule.getValue("id")).getValueInstant("create_date");
|
||||
assertDates(row(SecuredDataTables.RETENTION_RULE, rule.getValue("id")), SecuredDataTables.RETENTION_RULE, ruleWritten, ruleWritten);
|
||||
|
||||
CLOCK.now = LATER;
|
||||
QRecord run = new WipeService().batch(rule.getValue("id"), List.of(reading.getValue("id")));
|
||||
assertThat(run.getValueInteger("wiped_count")).isEqualTo(1);
|
||||
Instant wiped = ruleWritten.plusSeconds(90);
|
||||
QRecord firstRun = row(SecuredDataTables.WIPE_RUN, run.getValue("id"));
|
||||
assertThat(firstRun.getValueInstant("finished_at")).isEqualTo(wiped);
|
||||
assertDates(firstRun, SecuredDataTables.WIPE_RUN, wiped, wiped);
|
||||
QRecord marker = RetentionTestSupport.rows(SecuredDataTables.WIPE_MARKER).getFirst();
|
||||
assertThat(marker.getValueInstant("wiped_at")).isEqualTo(wiped);
|
||||
assertDates(marker, SecuredDataTables.WIPE_MARKER, wiped, wiped);
|
||||
assertThat(log("WIPE", "OVERWRITE_TEXT").getValueInstant("created_at")).isEqualTo(wiped);
|
||||
assertDates(log("WIPE", "OVERWRITE_TEXT"), SecuredDataTables.ACCESS_LOG, wiped, wiped);
|
||||
Instant ruleRun = assertChanged(row(SecuredDataTables.RETENTION_RULE, rule.getValue("id")), SecuredDataTables.RETENTION_RULE, ruleWritten, ruleWritten);
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
// the field is given a value again and wiped again: the marker of that //
|
||||
// record and field is changed, and no second marker is written //
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
CLOCK.now = LATER.plusSeconds(90);
|
||||
Instant again = wiped.plusSeconds(90);
|
||||
update("reading", new QRecord().withValue("id", reading.getValue("id")).withValue("secret", "another-test-secret"));
|
||||
QRecord second = new WipeService().batch(rule.getValue("id"), List.of(reading.getValue("id")));
|
||||
assertThat(second.getValueInteger("wiped_count")).isEqualTo(1);
|
||||
assertThat(RetentionTestSupport.rows(SecuredDataTables.WIPE_MARKER)).hasSize(1);
|
||||
QRecord changed = row(SecuredDataTables.WIPE_MARKER, marker.getValue("id"));
|
||||
assertThat(changed.getValue("run_id")).isEqualTo(second.getValue("id"));
|
||||
assertThat(changed.getValueInstant("wiped_at")).isEqualTo(again);
|
||||
assertChanged(changed, SecuredDataTables.WIPE_MARKER, wiped, wiped);
|
||||
assertDates(row(SecuredDataTables.WIPE_RUN, run.getValue("id")), SecuredDataTables.WIPE_RUN, wiped, wiped);
|
||||
assertDates(row(SecuredDataTables.WIPE_RUN, second.getValue("id")), SecuredDataTables.WIPE_RUN, again, again);
|
||||
assertChanged(row(SecuredDataTables.RETENTION_RULE, rule.getValue("id")), SecuredDataTables.RETENTION_RULE, ruleWritten, ruleRun);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The access-log writer runs concurrently with reveals, so the dates must cost
|
||||
** it nothing: for each row it still runs one insert, which now names the two
|
||||
** columns, and no other statement that writes the log.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void theAccessLogWriterStillRunsOneInsertForARow() throws Exception
|
||||
{
|
||||
RetentionTestSupport.setup();
|
||||
try(Connection connection = DriverManager.getConnection(url(), "sa", ""))
|
||||
{
|
||||
connection.createStatement().execute("SET QUERY_STATISTICS TRUE");
|
||||
for(int i = 0; i < 3; i++)
|
||||
{
|
||||
SecuredDataRuntime.current().logger().onAccess(new FieldAccessEvent().withType(FieldAccessEventType.EXACT_MATCH_FILTER).withOutcome(FieldAccessOutcome.MATCH)
|
||||
.withTableName("reading").withFieldNames(List.of("secret")).withActionName("query").withRecordCount(1).withSearchValueFingerprints(List.of("hmac" + i)));
|
||||
}
|
||||
SecuredDataRuntime.current().logger().flush();
|
||||
assertThat(rows(connection, SecuredDataTables.ACCESS_LOG, false)).hasSize(3).allSatisfy(row -> assertThat(row.get("create_date")).isNotNull().isEqualTo(row.get("modify_date")));
|
||||
|
||||
Map<String, Integer> writes = new LinkedHashMap<>();
|
||||
try(ResultSet statistics = connection.createStatement().executeQuery("SELECT SQL_STATEMENT, EXECUTION_COUNT FROM INFORMATION_SCHEMA.QUERY_STATISTICS"))
|
||||
{
|
||||
while(statistics.next())
|
||||
{
|
||||
String sql = statistics.getString(1).strip();
|
||||
if(sql.contains(SecuredDataTables.ACCESS_LOG) && !sql.toUpperCase().startsWith("SELECT"))
|
||||
{
|
||||
writes.merge(sql, statistics.getInt(2), Integer::sum);
|
||||
}
|
||||
}
|
||||
}
|
||||
assertThat(writes).hasSize(1);
|
||||
assertThat(writes.keySet().iterator().next()).startsWithIgnoringCase("INSERT INTO").contains("create_date", "modify_date");
|
||||
assertThat(writes.values()).containsExactly(3);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A changed policy or classification writes what it wrote before the tables
|
||||
** had the standard dates: its core audit, field by field, and its
|
||||
** POLICY_CHANGE or CLASSIFICATION_CHANGE row in the access log.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void aChangedPolicyOrClassificationWritesItsAuditAndItsLogRowAsBefore() throws Exception
|
||||
{
|
||||
QInstance instance = RetentionTestSupport.setup();
|
||||
QRecord policy = new InsertAction().execute(new InsertInput(SecuredDataTables.POLICY).withRecord(policyRow("viewer", "PHI", "MASKED"))).getRecords().getFirst();
|
||||
QRecord classification = new InsertAction().execute(new InsertInput(SecuredDataTables.CLASSIFICATION).withRecord(new QRecord().withValue("table_name", "reading")
|
||||
.withValue("field_name", "notes").withValue("classification", "PHI"))).getRecords().getFirst();
|
||||
assertThat(policy.getErrors()).isNullOrEmpty();
|
||||
assertThat(classification.getErrors()).isNullOrEmpty();
|
||||
CLOCK.now = LATER;
|
||||
assertThat(new UpdateAction().execute(new UpdateInput(SecuredDataTables.POLICY).withRecord(new QRecord().withValue("id", policy.getValue("id")).withValue("tier", "HIDDEN")))
|
||||
.getRecords().getFirst().getErrors()).isNullOrEmpty();
|
||||
assertThat(new UpdateAction().execute(new UpdateInput(SecuredDataTables.CLASSIFICATION).withRecord(new QRecord().withValue("id", classification.getValue("id"))
|
||||
.withValue("classification", "PII"))).getRecords().getFirst().getErrors()).isNullOrEmpty();
|
||||
new DeleteAction().execute(new DeleteInput(SecuredDataTables.POLICY).withPrimaryKeys(List.of(policy.getValue("id"))));
|
||||
new DeleteAction().execute(new DeleteInput(SecuredDataTables.CLASSIFICATION).withPrimaryKeys(List.of(classification.getValue("id"))));
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
// the log rows: one per change, with every value they have always had //
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
List<String> changes = new ArrayList<>();
|
||||
List<QRecord> logged = RetentionTestSupport.rows(SecuredDataTables.ACCESS_LOG);
|
||||
Instant inserted = logged.getFirst().getValueInstant("created_at");
|
||||
for(QRecord row : logged)
|
||||
{
|
||||
changes.add(String.join(" ", row.getValueString("event_type"), row.getValueString("table_name"), row.getValueString("record_id"), row.getValueString("action_name"),
|
||||
row.getValueString("outcome"), row.getValueString("user_id"), row.getValueString("user_name"),
|
||||
"after " + Duration.between(inserted, row.getValueInstant("created_at")).toSeconds() + " s", String.valueOf(row.getValueBoolean("anomaly_flag"))));
|
||||
for(String empty : List.of("field_name", "record_count", "reason", "reason_text", "client_channel", "break_glass_id", "search_value_fingerprints", "rule_id"))
|
||||
{
|
||||
assertThat(row.getValue(empty)).as(empty).isNull();
|
||||
}
|
||||
}
|
||||
String policyId = policy.getValueString("id");
|
||||
String classificationId = classification.getValueString("id");
|
||||
assertThat(changes).containsExactly(
|
||||
"POLICY_CHANGE secured_data_policy " + policyId + " INSERT ALLOWED admin admin after 0 s false",
|
||||
"CLASSIFICATION_CHANGE secured_data_classification " + classificationId + " INSERT ALLOWED admin admin after 0 s false",
|
||||
"POLICY_CHANGE secured_data_policy " + policyId + " UPDATE ALLOWED admin admin after 90 s false",
|
||||
"CLASSIFICATION_CHANGE secured_data_classification " + classificationId + " UPDATE ALLOWED admin admin after 90 s false",
|
||||
"POLICY_CHANGE secured_data_policy " + policyId + " DELETE ALLOWED admin admin after 90 s false",
|
||||
"CLASSIFICATION_CHANGE secured_data_classification " + classificationId + " DELETE ALLOWED admin admin after 90 s false");
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
// the core audits of the two rows: the same audits with the same details, //
|
||||
// the two dates among them under the names they have always been audited by //
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
assertThat(audits(instance, SecuredDataTables.POLICY, policy.getValue("id"))).containsExactly(
|
||||
"Record was Inserted: allow_free_text_reason [Set allow free text reason to Yes], classification [Set classification to PHI], create_date,"
|
||||
+ " distinct_value_alert [Set distinct value alert to 15], exact_match_per_hour [Set exact match per hour to 20], id [Set Id to " + policyId + "],"
|
||||
+ " is_active [Set is active to Yes], min_entropy_enabled [Set min entropy enabled to Yes], miss_alert_consecutive [Set miss alert consecutive to 5],"
|
||||
+ " modified_by [Set modified by to admin], modify_date, name [Set name to viewer PHI], permission_name [Set permission name to viewer],"
|
||||
+ " require_free_text [Set require free text to No], reveal_minutes [Set reveal minutes to 5], tier [Set tier to MASKED]",
|
||||
"Record was Edited: modify_date, tier [Changed tier from \"MASKED\" to \"HIDDEN\"]",
|
||||
"Record was Deleted: ");
|
||||
assertThat(audits(instance, SecuredDataTables.CLASSIFICATION, classification.getValue("id"))).containsExactly(
|
||||
"Record was Inserted: classification [Set classification to PHI], create_date, field_name [Set field name to notes], id [Set Id to " + classificationId + "],"
|
||||
+ " modified_by [Set modified by to admin], modify_date, table_name [Set table name to Reading]",
|
||||
"Record was Edited: classification [Changed classification from \"PHI\" to \"PII\"], modify_date",
|
||||
"Record was Deleted: ");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The core audits of one record, oldest first: the message of each and, in
|
||||
** the order of the field names, the fields it has a detail for and what the
|
||||
** detail says. The two dates are named only: how a time reads depends on the
|
||||
** zone of the machine.
|
||||
*******************************************************************************/
|
||||
private static List<String> audits(QInstance instance, String table, Serializable id)
|
||||
{
|
||||
Serializable auditTable = SystemWrites.query("auditTable", new QQueryFilter().withCriteria(new QFilterCriteria("name", QCriteriaOperator.EQUALS, table))).getFirst().getValue("id");
|
||||
List<String> audits = new ArrayList<>();
|
||||
for(QRecord audit : SystemWrites.query("audit", new QQueryFilter().withCriteria(new QFilterCriteria("auditTableId", QCriteriaOperator.EQUALS, auditTable))
|
||||
.withCriteria(new QFilterCriteria("recordId", QCriteriaOperator.EQUALS, id)).withOrderBy(new QFilterOrderBy("id", true))))
|
||||
{
|
||||
List<String> fields = SystemWrites.query("auditDetail", new QQueryFilter().withCriteria(new QFilterCriteria("auditId", QCriteriaOperator.EQUALS, audit.getValue("id"))))
|
||||
.stream().map(detail -> detail.getValueString("fieldName") + (detail.getValueString("fieldName").endsWith("_date") ? ""
|
||||
: " [" + detail.getValueString("message") + "]")).sorted().toList();
|
||||
audits.add(audit.getValueString("message") + ": " + String.join(", ", fields));
|
||||
}
|
||||
assertThat(instance.getTable(table)).isNotNull();
|
||||
return (audits);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Rows written before the two columns existed. A reading is audited (its
|
||||
** audit token is made with a data key of its own, and that key is stored
|
||||
** wrapped, bound to its record and field), the log has rows, a rule and a
|
||||
** hold exist. The two columns are then taken away, which leaves the database
|
||||
** as the release before this one left it, and a key and a log row are
|
||||
** written the way that release wrote them. The block an existing database
|
||||
** runs must change nothing but the two columns: the same rows, the same
|
||||
** wrapped keys, which still unwrap to the same data keys, and the same
|
||||
** token, which still verifies the value and no other.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void rowsWrittenBeforeTheDatesExistedVerifyUnchangedAfterTheyAreAdded() throws Exception
|
||||
{
|
||||
QInstance instance = RetentionTestSupport.setup();
|
||||
QTableMetaData reading = instance.getTable("reading");
|
||||
SecuredDataTestSupport.policy("secured_data.admin", "PHI", "FULL");
|
||||
SecuredDataTestSupport.policy("secured_data.admin", "PII", "FULL");
|
||||
QRecord rule = RetentionTestSupport.rule("NULL_WITH_MARKER", "systolic");
|
||||
insert(SecuredDataTables.LEGAL_HOLD, new QRecord().withValue("table_name", "reading").withValue("record_id", "404").withValue("reason", "Preservation"));
|
||||
Serializable id = new InsertAction().execute(new InsertInput("reading").withRecord(new QRecord().withValue("systolic", 120).withValue("secret", "s")
|
||||
.withValue("reading_time", RetentionTestSupport.OLD))).getRecords().getFirst().getValue("id");
|
||||
Serializable wiped = new InsertAction().execute(new InsertInput("reading").withRecord(new QRecord().withValue("systolic", 130).withValue("secret", "s")
|
||||
.withValue("reading_time", RetentionTestSupport.OLD))).getRecords().getFirst().getValue("id");
|
||||
new WipeService().batch(rule.getValue("id"), List.of(wiped));
|
||||
|
||||
SecuredDataKeySource keys = SecuredDataRuntime.current().keys();
|
||||
byte[] dataKey = keys.keyForRecordField("reading", "systolic", id, false).orElseThrow().key();
|
||||
List<String> tokens = SystemWrites.query("auditDetail", new QQueryFilter().withCriteria(new QFilterCriteria("fieldName", QCriteriaOperator.EQUALS, "systolic"))).stream()
|
||||
.map(detail -> detail.getValueString("newValue")).filter(value -> value != null && value.startsWith("shred:v1:")).toList();
|
||||
String token = tokens.stream().filter(candidate -> ClassifiedValueTokens.verifyRecordField(reading, reading.getField("systolic"), id, 120, candidate)).findFirst().orElseThrow();
|
||||
assertThat(ClassifiedValueTokens.verifyRecordField(reading, reading.getField("systolic"), id, 121, token)).isFalse();
|
||||
|
||||
List<String> tables = declared(instance).stream().map(QTableMetaData::getName).filter(name -> !SNAKE_CASE_NAMES.contains(name)).toList();
|
||||
byte[] earlierKey = new byte[32];
|
||||
Arrays.fill(earlierKey, (byte) 7);
|
||||
Instant earlier = NOW.minusSeconds(86400);
|
||||
try(Connection connection = DriverManager.getConnection(url(), "sa", ""))
|
||||
{
|
||||
for(String table : tables)
|
||||
{
|
||||
assertThat(rows(connection, table, false)).as(table).allSatisfy(row -> assertThat(row.get("create_date")).isNotNull());
|
||||
connection.createStatement().execute("ALTER TABLE " + table + " DROP COLUMN create_date");
|
||||
connection.createStatement().execute("ALTER TABLE " + table + " DROP COLUMN modify_date");
|
||||
}
|
||||
try(PreparedStatement insert = connection.prepareStatement("INSERT INTO secured_data_audit_key (table_name, record_id, field_name, wrapped_key, created_at) VALUES ('reading', '9001', 'systolic', ?, ?)"))
|
||||
{
|
||||
insert.setString(1, Base64.getEncoder().encodeToString(SecuredDataKeySource.encrypt(earlierKey, "reading\u001fsystolic\u001f9001")));
|
||||
insert.setTimestamp(2, Timestamp.from(earlier));
|
||||
insert.executeUpdate();
|
||||
}
|
||||
try(PreparedStatement insert = connection.prepareStatement("INSERT INTO secured_data_access_log (event_type, user_id, table_name, field_name, outcome, anomaly_flag, created_at) VALUES ('VIEW', 'u1', 'reading', 'systolic', 'ALLOWED', false, ?)"))
|
||||
{
|
||||
insert.setTimestamp(1, Timestamp.from(earlier));
|
||||
insert.executeUpdate();
|
||||
}
|
||||
Map<String, List<Map<String, String>>> before = new LinkedHashMap<>();
|
||||
for(String table : tables)
|
||||
{
|
||||
before.put(table, rows(connection, table, false));
|
||||
}
|
||||
assertThat(before.get(SecuredDataTables.ACCESS_LOG)).hasSizeGreaterThan(3);
|
||||
assertThat(before.get(SecuredDataTables.AUDIT_KEY)).hasSize(2);
|
||||
for(String table : List.of(SecuredDataTables.WIPE_RUN, SecuredDataTables.WIPE_MARKER, SecuredDataTables.LEGAL_HOLD))
|
||||
{
|
||||
assertThat(before.get(table)).as(table).hasSize(1);
|
||||
}
|
||||
|
||||
run(connection, ddl(true));
|
||||
|
||||
for(String table : tables)
|
||||
{
|
||||
assertThat(rows(connection, table, true)).as(table).isEqualTo(before.get(table));
|
||||
assertThat(rows(connection, table, false)).as(table).allSatisfy(row ->
|
||||
{
|
||||
assertThat(row.get("create_date")).isNotNull();
|
||||
assertThat(row.get("modify_date")).isNotNull();
|
||||
});
|
||||
}
|
||||
assertThat(rows(connection, SecuredDataTables.ACCESS_LOG, false)).allSatisfy(row ->
|
||||
{
|
||||
assertThat(row.get("create_date")).isEqualTo(row.get("created_at"));
|
||||
assertThat(row.get("modify_date")).isEqualTo(row.get("created_at"));
|
||||
});
|
||||
assertThat(rows(connection, SecuredDataTables.AUDIT_KEY, false)).allSatisfy(row ->
|
||||
{
|
||||
assertThat(row.get("create_date")).isEqualTo(row.get("created_at"));
|
||||
assertThat(row.get("modify_date")).isEqualTo(row.get("created_at"));
|
||||
});
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
// the release before this one goes on writing while both run: its insert //
|
||||
// names neither column, and the row has both, equal, all the same //
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
connection.createStatement().execute("INSERT INTO secured_data_access_log (event_type, user_id, table_name, outcome, anomaly_flag, created_at) VALUES ('VIEW', 'u2', 'reading', 'ALLOWED', false, CURRENT_TIMESTAMP)");
|
||||
Map<String, String> concurrent = rows(connection, SecuredDataTables.ACCESS_LOG, false).getLast();
|
||||
assertThat(concurrent.get("user_id")).isEqualTo("u2");
|
||||
assertThat(concurrent.get("create_date")).isNotNull().isEqualTo(concurrent.get("modify_date"));
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
// nothing kept in memory: every key is unwrapped again from its row //
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
keys.close();
|
||||
assertThat(keys.keyForRecordField("reading", "systolic", id, false).orElseThrow().key()).isEqualTo(dataKey);
|
||||
assertThat(keys.keyForRecordField("reading", "systolic", 9001, false).orElseThrow().key()).isEqualTo(earlierKey);
|
||||
assertThat(keys.keyForRecordField("reading", "systolic", wiped, false)).isEmpty();
|
||||
assertThat(ClassifiedValueTokens.verifyRecordField(reading, reading.getField("systolic"), id, 120, token)).isTrue();
|
||||
assertThat(ClassifiedValueTokens.verifyRecordField(reading, reading.getField("systolic"), id, 121, token)).isFalse();
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////
|
||||
// and the rows that were there are read and written on as they were: the //
|
||||
// earlier log row is counted, and the reading is wiped under its rule //
|
||||
////////////////////////////////////////////////////////////////////////////
|
||||
assertThat(RetentionTestSupport.rows(SecuredDataTables.ACCESS_LOG)).anySatisfy(row ->
|
||||
{
|
||||
assertThat(row.getValueString("user_id")).isEqualTo("u1");
|
||||
assertThat(row.getValueInstant("createDate")).isNotNull().isEqualTo(row.getValueInstant("created_at"));
|
||||
assertThat(row.getValueInstant("modifyDate")).isEqualTo(row.getValueInstant("created_at"));
|
||||
});
|
||||
CLOCK.now = LATER;
|
||||
assertThat(new WipeService().batch(rule.getValue("id"), List.of(id)).getValueInteger("wiped_count")).isEqualTo(1);
|
||||
assertThat(keys.keyForRecordField("reading", "systolic", id, false)).isEmpty();
|
||||
assertThat(ClassifiedValueTokens.verifyRecordField(reading, reading.getField("systolic"), id, 120, token)).isFalse();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The database RetentionTestSupport made from the shipped DDL.
|
||||
*******************************************************************************/
|
||||
static String url()
|
||||
{
|
||||
return ("jdbc:h2:mem:" + RetentionTestSupport.BACKEND + ";MODE=PostgreSQL;DATABASE_TO_UPPER=FALSE;DB_CLOSE_DELAY=-1");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The statements of the shipped DDL: those of the block an existing database
|
||||
** runs to get the two columns, or those before it (the schema without them).
|
||||
*******************************************************************************/
|
||||
static List<String> ddl(boolean datesBlock) throws IOException
|
||||
{
|
||||
String ddl = Files.readString(Path.of(DDL));
|
||||
int block = ddl.indexOf(DDL_BLOCK);
|
||||
assertThat(block).as("the block of " + DDL + " that begins " + DDL_BLOCK).isPositive().isEqualTo(ddl.lastIndexOf(DDL_BLOCK));
|
||||
return (Arrays.stream((datesBlock ? ddl.substring(block) : ddl.substring(0, block)).split(";")).filter(sql -> !sql.isBlank()).toList());
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Run statements.
|
||||
*******************************************************************************/
|
||||
static void run(Connection connection, List<String> statements) throws SQLException
|
||||
{
|
||||
for(String sql : statements)
|
||||
{
|
||||
connection.createStatement().execute(sql);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Every row of a table as the database holds it, column by column, in id
|
||||
** order, with or without the two date columns.
|
||||
*******************************************************************************/
|
||||
static List<Map<String, String>> rows(Connection connection, String table, boolean withoutDates) throws SQLException
|
||||
{
|
||||
List<Map<String, String>> rows = new ArrayList<>();
|
||||
try(ResultSet results = connection.createStatement().executeQuery("SELECT * FROM " + table + " ORDER BY id"))
|
||||
{
|
||||
ResultSetMetaData columns = results.getMetaData();
|
||||
while(results.next())
|
||||
{
|
||||
Map<String, String> row = new LinkedHashMap<>();
|
||||
for(int i = 1; i <= columns.getColumnCount(); i++)
|
||||
{
|
||||
String column = columns.getColumnName(i);
|
||||
if(!withoutDates || !Set.of("create_date", "modify_date").contains(column))
|
||||
{
|
||||
row.put(column, results.getString(i));
|
||||
}
|
||||
}
|
||||
rows.add(row);
|
||||
}
|
||||
}
|
||||
return (rows);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** One stored row.
|
||||
*******************************************************************************/
|
||||
private static QRecord row(String table, Serializable id)
|
||||
{
|
||||
return (SystemWrites.query(table, new QQueryFilter().withCriteria(new QFilterCriteria("id", QCriteriaOperator.EQUALS, id))).getFirst());
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The newest log row of an event, and of an action where one is given.
|
||||
*******************************************************************************/
|
||||
private static QRecord log(String event, String action)
|
||||
{
|
||||
return (logs().stream().filter(row -> event.equals(row.getValueString("event_type")) && (action == null || action.equals(row.getValueString("action_name"))))
|
||||
.reduce((first, second) -> second).orElseThrow());
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Both dates of a stored row.
|
||||
*******************************************************************************/
|
||||
private static void assertDates(QRecord row, String table, Instant created, Instant modified)
|
||||
{
|
||||
assertThat(row.getValueInstant(createDate(table))).as(table + " create date").isEqualTo(created);
|
||||
assertThat(row.getValueInstant(modifyDate(table))).as(table + " modify date").isEqualTo(modified);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Both dates of a stored row that was changed: the create date it had, and a
|
||||
** modify date later than the one it had, which is returned.
|
||||
*******************************************************************************/
|
||||
private static Instant assertChanged(QRecord row, String table, Instant created, Instant modifiedBefore)
|
||||
{
|
||||
assertThat(row.getValueInstant(createDate(table))).as(table + " create date").isEqualTo(created);
|
||||
assertThat(row.getValueInstant(modifyDate(table))).as(table + " modify date").isAfter(modifiedBefore);
|
||||
return (row.getValueInstant(modifyDate(table)));
|
||||
}
|
||||
}
|
||||
@@ -234,6 +234,7 @@ final class SecuredDataTestSupport
|
||||
*******************************************************************************/
|
||||
static void close()
|
||||
{
|
||||
CLOCK.beforeInstant = null;
|
||||
RUNTIMES.forEach(SecuredDataRuntime::close);
|
||||
RUNTIMES.clear();
|
||||
QContext.clear();
|
||||
@@ -248,6 +249,9 @@ final class SecuredDataTestSupport
|
||||
{
|
||||
Instant now = NOW;
|
||||
|
||||
/** Run on the reading thread before every reading of the clock; a test parks a thread at a known point with it. */
|
||||
volatile Runnable beforeInstant;
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
@@ -275,6 +279,11 @@ final class SecuredDataTestSupport
|
||||
*******************************************************************************/
|
||||
public Instant instant()
|
||||
{
|
||||
Runnable hook = beforeInstant;
|
||||
if(hook != null)
|
||||
{
|
||||
hook.run();
|
||||
}
|
||||
return (now);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user