Files
qbit-secured-data/src/test/java/com/kingsrook/qbits/secureddata/SecuredDataQBitProducerTest.java
T
james.maesandClaude Fable 5.2 3ddcf7ec9d
maven / build (push) Successful in 2m9s
build / maven (push) Successful in 2m9s
feat: a create date and a modify date on every table
Every table of the QBit has a create date and a modify date: DATE_TIME, not
editable, with core'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, set by the table customizer. They keep those
field names, because a rename would change what a host reads and what their
audits record, and the two fields are now not editable and have the
behaviors.

Writes. Every write of the QBit is a core insert or update action, so the
dates are in the statement that writes the row. The table customizer sets
them, as it did for the three tables: a new row gets both, equal, from the
QBit's clock, and a changed row a new modify date. The access-log writer
still runs one insert per row and no other statement, lock or transaction.
The access log and wipe runs are only ever inserted, so their dates stay
equal.

Core uses a DATE_TIME field with the MODIFY_DATE behavior as the record
version of its table. That now holds for all ten tables: on an update core
sets the modify date itself, after the customizer has run, and an update
that sends the version it read is refused when the row has changed since.
Updates that send no version, the QBit's own among them, behave as before.

Schema. docs/ddl/secured-data-postgres.sql has a new last block that adds
the two columns to the seven tables: nullable, defaulting to the current
time, with the rows that were already there given the row's own time. No
CREATE TABLE statement is edited. An existing database runs that block
alone, before this release is deployed. The block rewrites no table, can be
run while the release before this one is running (its inserts name neither
column and get both from the default) and can be run again. This release
does not run without the columns. README: "Upgrading an existing database".

Unchanged. The dates have no classification, policy or assistant exposure of
their own: they are CONFIDENTIAL with their table and get the tier of its
other fields. Nothing signed or verified covers them: a wrapped data key is
bound to its table, field and record id, and the fingerprints of a log row
are made from search values. A changed policy or classification writes the
same core audit, field by field, and the same POLICY_CHANGE or
CLASSIFICATION_CHANGE row.

Tests. SecuredDataStandardDatesTest: every table the producer declares has
the two dates (the tables are taken from the instance, so a table added
later without them fails); the dates resolve to the tier of the other fields
of their table for five kinds of session; every writer sets both and only a
change moves the modify date (access-log writer, policy, classification,
legal hold, reveal, break-glass start, end and expiry on the memory backend;
audit key, wipe run, wipe marker and retention rule in the shipped schema);
the access-log writer runs exactly one insert per row; a changed policy and
classification write the audit and log rows they wrote before; rows written
before the columns existed are unchanged by the upgrade block, their wrapped
keys unwrap to the same data keys and their audit token verifies the same
value and no other. SecuredDataDdlTest: the shipped DDL gives every declared
table the two columns, the upgrade block adds them where they were missing,
an insert that names neither succeeds, and the block can be run twice. Seven
of the eight new tests fail without the change; the eighth is the record of
what a changed policy wrote before and passes on both sides.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-20 09:01:39 -06:00

227 lines
13 KiB
Java

/*
* 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.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.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;
import com.kingsrook.qqq.backend.core.model.actions.tables.insert.InsertInput;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QueryInput;
import com.kingsrook.qqq.backend.core.model.actions.values.SearchPossibleValueSourceInput;
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;
import static com.kingsrook.qbits.secureddata.SecuredDataTestSupport.channelUser;
import static com.kingsrook.qbits.secureddata.SecuredDataTestSupport.classification;
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.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;
/*******************************************************************************
** Secured data qbit producer test.
*******************************************************************************/
class SecuredDataQBitProducerTest
{
/*******************************************************************************
** Cleanup.
*******************************************************************************/
@AfterEach
void cleanup()
{
close();
}
/*******************************************************************************
** Produces complete metadata.
*******************************************************************************/
@Test
void producesCompleteMetadata() throws Exception
{
QInstance instance = setup();
assertThat(instance.getTables().keySet()).containsAll(SecuredDataTables.ALL);
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);
// 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);
assertThat(ClientChannelsMetaData.ofOrWithNew(instance).getDeniedPatterns().get("assistant")).contains("secured_data_*");
assertThat(TableFeaturePermissionsMetaData.ofOrWithNew(instance).getPermissions()).extracting("suffix").contains("secured_data_full", "secured_data_reveal");
assertThat(instance.getTable(SecuredDataTables.ACCESS_LOG).getDisabledCapabilities()).contains(Capability.TABLE_UPDATE, Capability.TABLE_DELETE);
assertThat(instance.getJoin(SecuredDataTables.REVEALS_JOIN)).isNotNull();
assertThat(instance.getWidget(SecuredDataTables.REVEALS_WIDGET)).isNotNull();
assertThat(instance.getApp("secured_data").getChildren()).hasSize(5);
}
/*******************************************************************************
** Config and producer contract.
*******************************************************************************/
@Test
void configAndProducerContract() throws Exception
{
SecuredDataQBitConfig config = new SecuredDataQBitConfig().withBackendName("memory")
.withDefaultTier(DataClassification.PHI, FieldAccessTier.HIDDEN).withDefaultTierByClassification(Map.of("PHI", "FULL"))
.withNameHeuristics(true).withTableMetaDataCustomizer((instance, table) -> table);
assertThat(config.defaultTier(DataClassification.PHI)).isEqualTo(FieldAccessTier.FULL);
assertThat(config.defaultTier(DataClassification.PII)).isEqualTo(FieldAccessTier.MASKED);
SecuredDataQBitProducer producer = new SecuredDataQBitProducer().withQBitConfig(config).withNamespace("test");
assertThat(producer.getNamespace()).isEqualTo("test");
assertThat(producer.getQBitConfig()).isSameAs(config);
assertThat(producer.isEnabled()).isTrue();
assertThat(new SecuredDataQBitProducer().isEnabled()).isFalse();
assertThatThrownBy(() -> new SecuredDataQBitConfig().withAccessLogQueueCapacity(0).validate()).isInstanceOf(IllegalArgumentException.class);
setup();
assertThatThrownBy(() -> new SecuredDataQBitProducer().withQBitConfig(config).produce(QContext.getQInstance())).isInstanceOf(IllegalStateException.class);
}
/*******************************************************************************
** Admin can read but cannot forge activity and assistant cannot read.
*******************************************************************************/
@Test
void adminCanReadButCannotForgeActivityAndAssistantCannotRead() throws Exception
{
QInstance instance = setup();
QContext.setQSession(user("admin", "secured_data.admin"));
assertThat(new QueryAction().execute(new QueryInput(SecuredDataTables.POLICY)).getRecords()).isEmpty();
for(String table : SecuredDataTables.SYSTEM_WRITTEN)
{
assertThatThrownBy(() -> new InsertAction().execute(new InsertInput(table).withRecord(new QRecord()))).hasMessageContaining("Permission denied");
}
QContext.setQSession(channelUser("assistant/t1", "secured_data.admin"));
for(String table : SecuredDataTables.ALL)
{
assertThatThrownBy(() -> new QueryAction().execute(new QueryInput(table))).hasMessageContaining("Permission denied");
}
QContext.setQSession(user("ordinary"));
assertThatThrownBy(() -> new QueryAction().execute(new QueryInput(SecuredDataTables.CLASSIFICATION))).hasMessageContaining("Permission denied");
}
/*******************************************************************************
** Fields picker and classification uniqueness.
*******************************************************************************/
@Test
void fieldsPickerAndClassificationUniqueness() throws Exception
{
setup();
FieldsOfTablePossibleValueSource picker = new FieldsOfTablePossibleValueSource();
assertThat(picker.search(new SearchPossibleValueSourceInput().withOtherValues(Map.of("table_name", "person")))).hasSize(4);
assertThat(picker.search(new SearchPossibleValueSourceInput())).isEmpty();
assertThat(picker.getPossibleValue("email").getId()).isEqualTo("email");
assertThat(picker.getPossibleValue(null)).isNull();
classification(null, "CONFIDENTIAL");
assertThatThrownBy(() -> classification(null, "PHI")).hasMessageContaining("system insert failed");
assertThatThrownBy(() -> classification("no_such_field", "PHI")).hasMessageContaining("system insert failed");
assertThatThrownBy(() -> insert(SecuredDataTables.POLICY, policyRow("x", "PII", "FULL").withValue("reveal_minutes", 61))).hasMessageContaining("system insert failed");
}
/*******************************************************************************
** System cannot update or delete an access log.
*******************************************************************************/
@Test
void systemCannotUpdateOrDeleteAnAccessLog() throws Exception
{
setup();
QRecord row = insert(SecuredDataTables.ACCESS_LOG, new QRecord().withValue("event_type", "VIEW").withValue("table_name", "person").withValue("created_at", NOW));
assertThatThrownBy(() -> update(SecuredDataTables.ACCESS_LOG, new QRecord().withValue("id", row.getValue("id")).withValue("outcome", "DENIED"))).isInstanceOf(Exception.class);
assertThatThrownBy(() -> delete(SecuredDataTables.ACCESS_LOG, row)).isInstanceOf(Exception.class);
assertThat(logs()).hasSize(1);
}
/*******************************************************************************
** Versions invalidate after commit and never for rollback.
*******************************************************************************/
@Test
void versionsInvalidateAfterCommitAndNeverForRollback() throws Exception
{
setup();
var runtime = SecuredDataRuntime.current();
var customizer = new com.kingsrook.qbits.secureddata.metadata.SecuredDataTableCustomizers();
var transaction = new com.kingsrook.qqq.backend.core.actions.QBackendTransaction();
var input = new InsertInput(SecuredDataTables.CLASSIFICATION).withTransaction(transaction);
long before = runtime.classificationVersion();
customizer.postInsert(input, List.of(new QRecord().withValue("id", 42)));
assertThat(runtime.classificationVersion()).isEqualTo(before);
transaction.rollback();
assertThat(runtime.classificationVersion()).isEqualTo(before);
customizer.postInsert(input, List.of(new QRecord().withValue("id", 43)));
transaction.commit();
assertThat(runtime.classificationVersion()).isGreaterThan(before);
}
/*******************************************************************************
** Code heuristics are opt in and preserve explicit classifications.
*******************************************************************************/
@Test
void codeHeuristicsAreOptInAndPreserveExplicitClassifications() throws Exception
{
QInstance instance = 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));
QTableMetaData table = person("memory");
table.withField(new com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldMetaData("diagnosis_code", com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldType.STRING));
instance.addTable(table);
new SecuredDataQBitProducer().withQBitConfig(new SecuredDataQBitConfig().withNameHeuristics(true)).produce(instance);
QContext.init(instance, user("u1"));
RUNTIMES.add(SecuredDataRuntime.current());
assertThat(SecuredDataClassifications.effective(table, "diagnosis_code")).isEqualTo(DataClassification.PHI);
assertThat(SecuredDataClassifications.effective(table, "email")).isEqualTo(DataClassification.PII);
}
}