From 80d79de5f4e7384e1a38c980de1699fe95c9dd11 Mon Sep 17 00:00:00 2001 From: Michael Hoennig Date: Mon, 16 Sep 2024 10:00:41 +0200 Subject: [PATCH 1/4] import-legacy-ids-of-booking-items-and-hosting-assets (#101) Co-authored-by: Michael Hoennig Reviewed-on: https://dev.hostsharing.net/hostsharing/hs.hsadmin.ng/pulls/101 Reviewed-by: Marc Sandlus --- ...king-item.sql => 6300-hs-booking-item.sql} | 0 ...sql => 6308-hs-booking-item-test-data.sql} | 0 .../7016-hs-hosting-asset-migration.sql | 96 ++++++++++ .../db/changelog/db.changelog-master.yaml | 6 +- .../hs/migration/BaseOfficeDataImport.java | 21 +-- .../hsadminng/hs/migration/CsvDataImport.java | 18 ++ .../hs/migration/ImportHostingAssets.java | 167 +++++++++++++++++- 7 files changed, 284 insertions(+), 24 deletions(-) rename src/main/resources/db/changelog/6-hs-booking/630-booking-item/{6200-hs-booking-item.sql => 6300-hs-booking-item.sql} (100%) rename src/main/resources/db/changelog/6-hs-booking/630-booking-item/{6208-hs-booking-item-test-data.sql => 6308-hs-booking-item-test-data.sql} (100%) create mode 100644 src/main/resources/db/changelog/7-hs-hosting/701-hosting-asset/7016-hs-hosting-asset-migration.sql diff --git a/src/main/resources/db/changelog/6-hs-booking/630-booking-item/6200-hs-booking-item.sql b/src/main/resources/db/changelog/6-hs-booking/630-booking-item/6300-hs-booking-item.sql similarity index 100% rename from src/main/resources/db/changelog/6-hs-booking/630-booking-item/6200-hs-booking-item.sql rename to src/main/resources/db/changelog/6-hs-booking/630-booking-item/6300-hs-booking-item.sql diff --git a/src/main/resources/db/changelog/6-hs-booking/630-booking-item/6208-hs-booking-item-test-data.sql b/src/main/resources/db/changelog/6-hs-booking/630-booking-item/6308-hs-booking-item-test-data.sql similarity index 100% rename from src/main/resources/db/changelog/6-hs-booking/630-booking-item/6208-hs-booking-item-test-data.sql rename to src/main/resources/db/changelog/6-hs-booking/630-booking-item/6308-hs-booking-item-test-data.sql diff --git a/src/main/resources/db/changelog/7-hs-hosting/701-hosting-asset/7016-hs-hosting-asset-migration.sql b/src/main/resources/db/changelog/7-hs-hosting/701-hosting-asset/7016-hs-hosting-asset-migration.sql new file mode 100644 index 00000000..0cff5fbe --- /dev/null +++ b/src/main/resources/db/changelog/7-hs-hosting/701-hosting-asset/7016-hs-hosting-asset-migration.sql @@ -0,0 +1,96 @@ +--liquibase formatted sql + +-- TODO: These changesets are just for the external remote views to simulate the legacy tables. +-- Once we don't need the external remote views anymore, create revert changesets. + +-- ============================================================================ +--changeset hs-hosting-asset-MIGRATION-mapping:1 endDelimiter:--// +-- ---------------------------------------------------------------------------- + +CREATE TABLE hs_hosting_asset_legacy_id +( + uuid uuid NOT NULL REFERENCES hs_hosting_asset(uuid), + legacy_id integer NOT NULL +); +--// + + +-- ============================================================================ +--changeset hs-hosting-asset-MIGRATION-sequence:1 endDelimiter:--// +-- ---------------------------------------------------------------------------- + +CREATE SEQUENCE IF NOT EXISTS hs_hosting_asset_legacy_id_seq + AS integer + START 1000000000 + OWNED BY hs_hosting_asset_legacy_id.legacy_id; +--// + + +-- ============================================================================ +--changeset hs-hosting-asset-MIGRATION-default:1 endDelimiter:--// +-- ---------------------------------------------------------------------------- + +ALTER TABLE hs_hosting_asset_legacy_id + ALTER COLUMN legacy_id + SET DEFAULT nextVal('hs_hosting_asset_legacy_id_seq'); +--/ + + +-- ============================================================================ +--changeset hs-hosting-asset-MIGRATION-insert:1 endDelimiter:--// +-- ---------------------------------------------------------------------------- + +CALL defineContext('schema-migration'); +INSERT INTO hs_hosting_asset_legacy_id(uuid, legacy_id) + SELECT uuid, nextVal('hs_hosting_asset_legacy_id_seq') FROM hs_hosting_asset; +--/ + + +-- ============================================================================ +--changeset hs-hosting-asset-MIGRATION-insert-trigger:1 endDelimiter:--// +-- ---------------------------------------------------------------------------- +create or replace function insertassetLegacyIdMapping() + returns trigger + language plpgsql + strict as $$ +begin + if TG_OP <> 'INSERT' then + raise exception 'invalid usage of trigger'; + end if; + + INSERT INTO hs_hosting_asset_legacy_id VALUES + (NEW.uuid, nextVal('hs_hosting_asset_legacy_id_seq')); + + return NEW; +end; $$; + +create trigger createassetLegacyIdMapping + after insert on hs_hosting_asset + for each row + execute procedure insertassetLegacyIdMapping(); +--/ + + +-- ============================================================================ +--changeset hs-hosting-asset-MIGRATION-delete-trigger:1 endDelimiter:--// +-- ---------------------------------------------------------------------------- +create or replace function deleteassetLegacyIdMapping_tf() + returns trigger + language plpgsql + strict as $$ +begin + if TG_OP <> 'DELETE' then + raise exception 'invalid usage of trigger'; + end if; + + DELETE FROM hs_hosting_asset_legacy_id + WHERE uuid = OLD.uuid; + + return OLD; +end; $$; + +create trigger deleteassetLegacyIdMapping_tg + before delete on hs_hosting_asset + for each row + execute procedure deleteassetLegacyIdMapping_tf(); +--/ diff --git a/src/main/resources/db/changelog/db.changelog-master.yaml b/src/main/resources/db/changelog/db.changelog-master.yaml index 17d4d40a..72fe5519 100644 --- a/src/main/resources/db/changelog/db.changelog-master.yaml +++ b/src/main/resources/db/changelog/db.changelog-master.yaml @@ -142,15 +142,17 @@ databaseChangeLog: - include: file: db/changelog/6-hs-booking/620-booking-project/6208-hs-booking-project-test-data.sql - include: - file: db/changelog/6-hs-booking/630-booking-item/6200-hs-booking-item.sql + file: db/changelog/6-hs-booking/630-booking-item/6300-hs-booking-item.sql - include: file: db/changelog/6-hs-booking/630-booking-item/6203-hs-booking-item-rbac.sql - include: - file: db/changelog/6-hs-booking/630-booking-item/6208-hs-booking-item-test-data.sql + file: db/changelog/6-hs-booking/630-booking-item/6308-hs-booking-item-test-data.sql - include: file: db/changelog/7-hs-hosting/701-hosting-asset/7010-hs-hosting-asset.sql - include: file: db/changelog/7-hs-hosting/701-hosting-asset/7013-hs-hosting-asset-rbac.sql + - include: + file: db/changelog/7-hs-hosting/701-hosting-asset/7016-hs-hosting-asset-migration.sql - include: file: db/changelog/7-hs-hosting/701-hosting-asset/7018-hs-hosting-asset-test-data.sql - include: diff --git a/src/test/java/net/hostsharing/hsadminng/hs/migration/BaseOfficeDataImport.java b/src/test/java/net/hostsharing/hsadminng/hs/migration/BaseOfficeDataImport.java index f00d57dd..c8f107f1 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/migration/BaseOfficeDataImport.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/migration/BaseOfficeDataImport.java @@ -17,7 +17,6 @@ import net.hostsharing.hsadminng.hs.office.relation.HsOfficeRelation; import net.hostsharing.hsadminng.hs.office.relation.HsOfficeRelationRealEntity; import net.hostsharing.hsadminng.hs.office.relation.HsOfficeRelationType; import net.hostsharing.hsadminng.hs.office.sepamandate.HsOfficeSepaMandateEntity; -import net.hostsharing.hsadminng.rbac.rbacobject.BaseEntity; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import org.junit.jupiter.api.BeforeAll; @@ -615,7 +614,7 @@ public abstract class BaseOfficeDataImport extends CsvDataImport { jpaAttempt.transacted(() -> { context(rbacSuperuser); contacts.forEach(this::persist); - updateLegacyIds(contacts, "hs_office_contact_legacy_id", "contact_id"); + updateLegacyIds(contacts, "hs_office_contact_legacy_id", "contact_id"); }).assertSuccessful(); jpaAttempt.transacted(() -> { @@ -699,24 +698,6 @@ public abstract class BaseOfficeDataImport extends CsvDataImport { assumeThat(partners.size()).isLessThanOrEqualTo(MAX_NUMBER_OF_TEST_DATA_PARTNERS); } - private void updateLegacyIds( - Map entities, - final String legacyIdTable, - final String legacyIdColumn) { - em.flush(); - entities.forEach((id, entity) -> em.createNativeQuery(""" - UPDATE ${legacyIdTable} - SET ${legacyIdColumn} = :legacyId - WHERE uuid = :uuid - """ - .replace("${legacyIdTable}", legacyIdTable) - .replace("${legacyIdColumn}", legacyIdColumn)) - .setParameter("legacyId", id) - .setParameter("uuid", entity.getUuid()) - .executeUpdate() - ); - } - @Test @Order(9999) @ContinueOnFailure diff --git a/src/test/java/net/hostsharing/hsadminng/hs/migration/CsvDataImport.java b/src/test/java/net/hostsharing/hsadminng/hs/migration/CsvDataImport.java index d10f3577..f279e31d 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/migration/CsvDataImport.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/migration/CsvDataImport.java @@ -334,6 +334,24 @@ public class CsvDataImport extends ContextBasedTest { errors.clear(); assertThat(errorsToLog).isEmpty(); } + + protected void updateLegacyIds( + Map entities, + final String legacyIdTable, + final String legacyIdColumn) { + em.flush(); + entities.forEach((id, entity) -> em.createNativeQuery(""" + UPDATE ${legacyIdTable} + SET ${legacyIdColumn} = :legacyId + WHERE uuid = :uuid + """ + .replace("${legacyIdTable}", legacyIdTable) + .replace("${legacyIdColumn}", legacyIdColumn)) + .setParameter("legacyId", id) + .setParameter("uuid", entity.getUuid()) + .executeUpdate() + ); + } } class Columns { diff --git a/src/test/java/net/hostsharing/hsadminng/hs/migration/ImportHostingAssets.java b/src/test/java/net/hostsharing/hsadminng/hs/migration/ImportHostingAssets.java index d3ed3407..e8d510d9 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/migration/ImportHostingAssets.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/migration/ImportHostingAssets.java @@ -47,12 +47,12 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; import java.util.regex.Pattern; -import java.util.stream.Collectors; import static java.util.Arrays.stream; import static java.util.Map.entry; import static java.util.Map.ofEntries; import static java.util.Optional.ofNullable; +import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toMap; import static java.util.stream.Collectors.toSet; import static net.hostsharing.hsadminng.hs.hosting.asset.HsHostingAssetType.CLOUD_SERVER; @@ -938,6 +938,132 @@ public class ImportHostingAssets extends BaseOfficeDataImport { @Test @Order(19930) + void verifyCloudServerLegacyIds() { + assumeThatWeAreImportingControlledTestData(); + assertThat(fetchHosingAssetLegacyIds(CLOUD_SERVER)).isEqualTo(""" + 23611 + """.trim()); + assertThat(missingHostingAsstLegacyIds(CLOUD_SERVER)).isEmpty(); + } + + @Test + @Order(19931) + void verifyManagedServerLegacyIds() { + assumeThatWeAreImportingControlledTestData(); + assertThat(fetchHosingAssetLegacyIds(MANAGED_SERVER)).isEqualTo(""" + 10968 + 10978 + 11061 + 11447 + """.trim()); + assertThat(missingHostingAsstLegacyIds(MANAGED_SERVER)).isEmpty(); + } + + @Test + @Order(19932) + void verifyManagedWebspaceLegacyIds() { + assumeThatWeAreImportingControlledTestData(); + assertThat(fetchHosingAssetLegacyIds(MANAGED_WEBSPACE)).isEqualTo(""" + 10630 + 11094 + 11111 + 11112 + 19959 + """.trim()); + assertThat(missingHostingAsstLegacyIds(MANAGED_WEBSPACE)).isEmpty(); + } + + @Test + @Order(19933) + void verifyUnixUserLegacyIds() { + assumeThatWeAreImportingControlledTestData(); + assertThat(fetchHosingAssetLegacyIds(UNIX_USER)).isEqualTo(""" + 5803 + 5805 + 5809 + 5811 + 5813 + 5835 + 5961 + 5964 + 5966 + 5990 + 6705 + 6824 + 7846 + 9546 + 9596 + """.trim()); + assertThat(missingHostingAsstLegacyIds(UNIX_USER)).isEmpty(); + } + + @Test + @Order(19934) + void verifyPgSqlDbLegacyIds() { + assumeThatWeAreImportingControlledTestData(); + assertThat(fetchHosingAssetLegacyIds(PGSQL_DATABASE)).isEqualTo(""" + 1077 + 1858 + 1860 + 4931 + 4932 + 7522 + 7523 + 7605 + """.trim()); + assertThat(missingHostingAsstLegacyIds(PGSQL_DATABASE)).isEmpty(); + } + + @Test + @Order(19934) + void verifyPgSqlUserLegacyIds() { + assumeThatWeAreImportingControlledTestData(); + assertThat(fetchHosingAssetLegacyIds(PGSQL_USER)).isEqualTo(""" + 1857 + 1859 + 1860 + 1861 + 4931 + 7522 + 7605 + """.trim()); + assertThat(missingHostingAsstLegacyIds(PGSQL_USER)).isEmpty(); + } + + @Test + @Order(19935) + void verifyMariaDbLegacyIds() { + assumeThatWeAreImportingControlledTestData(); + assertThat(fetchHosingAssetLegacyIds(MARIADB_DATABASE)).isEqualTo(""" + 1786 + 1805 + 4908 + 4941 + 4942 + 7520 + 7521 + 7604 + """.trim()); + assertThat(missingHostingAsstLegacyIds(MARIADB_DATABASE)).isEmpty(); + } + + @Test + @Order(19936) + void verifyMariaDbUserLegacyIds() { + assumeThatWeAreImportingControlledTestData(); + assertThat(fetchHosingAssetLegacyIds(MARIADB_USER)).isEqualTo(""" + 1858 + 4908 + 4909 + 4932 + 7520 + 7604 + """.trim()); + assertThat(missingHostingAsstLegacyIds(MARIADB_USER)).isEmpty(); + } + + @Test + @Order(19940) void verifyProjectAgentsCanViewEmailAddresses() { assumeThatWeAreImportingControlledTestData(); @@ -949,6 +1075,7 @@ public class ImportHostingAssets extends BaseOfficeDataImport { assertThat(haCount).isEqualTo(68); } + // ============================================================================================ @Test @@ -1006,6 +1133,11 @@ public class ImportHostingAssets extends BaseOfficeDataImport { } ).assertSuccessful() ); + + jpaAttempt.transacted(() -> { + context(rbacSuperuser); + updateLegacyIds(assets, "hs_hosting_asset_legacy_id", "legacy_id"); + }).assertSuccessful(); } private void verifyActuallyPersistedHostingAssetCount( @@ -1610,7 +1742,7 @@ public class ImportHostingAssets extends BaseOfficeDataImport { //noinspection unchecked zoneData.put("user-RR", ((ArrayList>) zoneData.get("user-RR")).stream() - .map(userRR -> userRR.stream().map(Object::toString).collect(Collectors.joining(" "))) + .map(userRR -> userRR.stream().map(Object::toString).collect(joining(" "))) .toArray(String[]::new) ); domainDnsSetupAsset.getConfig().putAll(zoneData); @@ -1758,4 +1890,35 @@ public class ImportHostingAssets extends BaseOfficeDataImport { protected static void assumeThatWeAreImportingControlledTestData() { assumeThat(isImportingControlledTestData()).isTrue(); } + + private String fetchHosingAssetLegacyIds(final HsHostingAssetType type) { + //noinspection unchecked + return ((List>) em.createNativeQuery( + """ + SELECT li.* FROM hs_hosting_asset_legacy_id li + JOIN hs_hosting_asset ha ON ha.uuid=li.uuid + WHERE CAST(ha.type AS text)=:type + ORDER BY legacy_id + """, + List.class) + .setParameter("type", type.name()) + .getResultList() + ).stream().map(row -> row.get(1).toString()).collect(joining("\n")); + } + + private String missingHostingAsstLegacyIds(final HsHostingAssetType type) { + //noinspection unchecked + return ((List>) em.createNativeQuery( + """ + SELECT ha.uuid, ha.type, ha.identifier FROM hs_hosting_asset ha + JOIN hs_hosting_asset_legacy_id li ON li.uuid=ha.uuid + WHERE li.legacy_id is null AND CAST(ha.type AS text)=:type + ORDER BY li.legacy_id + """, + List.class) + .setParameter("type", type.name()) + .getResultList()).stream() + .map(row -> row.stream().map(Object::toString).collect(joining(", "))) + .collect(joining("\n")); + } } From 1eed0e9b211b348ac1a22a88839bee10810bbc78 Mon Sep 17 00:00:00 2001 From: Michael Hoennig Date: Mon, 16 Sep 2024 15:36:37 +0200 Subject: [PATCH 2/4] introduce separate database-schemas base+rbac (#103) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Michael Hoennig Co-authored-by: Michael Hönnig Reviewed-on: https://dev.hostsharing.net/hostsharing/hs.hsadmin.ng/pulls/103 Reviewed-by: Marc Sandlus --- README.md | 6 +- bin/git-pull-and-if-origin-changed-run-tests | 36 ++ ...2022-07-18.row-level-security-mechanism.md | 18 +- doc/rbac-performance-analysis.md | 18 +- doc/rbac.md | 56 +-- sql/historization.sql | 6 +- sql/rbac-tests.sql | 32 +- sql/rbac-view-option-experiments.sql | 42 +- ...e-cte-experiments-for-accessible-uuids.sql | 4 +- .../hsadminng/context/Context.java | 34 +- .../hs/booking/item/HsBookingItem.java | 2 +- .../booking/item/HsBookingItemController.java | 20 +- .../booking/item/HsBookingItemRbacEntity.java | 37 +- .../hs/booking/project/HsBookingProject.java | 31 +- .../project/HsBookingProjectController.java | 20 +- .../project/HsBookingProjectRbacEntity.java | 41 +- .../hs/hosting/asset/HsHostingAsset.java | 2 +- .../asset/HsHostingAssetController.java | 20 +- .../asset/HsHostingAssetRbacEntity.java | 42 +- .../HsOfficeBankAccountController.java | 16 +- .../HsOfficeBankAccountEntity.java | 14 +- .../hs/office/contact/HsOfficeContact.java | 2 +- .../contact/HsOfficeContactController.java | 20 +- .../contact/HsOfficeContactRbacEntity.java | 14 +- ...OfficeCoopAssetsTransactionController.java | 12 +- .../HsOfficeCoopAssetsTransactionEntity.java | 24 +- ...OfficeCoopSharesTransactionController.java | 12 +- .../HsOfficeCoopSharesTransactionEntity.java | 26 +- .../debitor/HsOfficeDebitorController.java | 22 +- .../office/debitor/HsOfficeDebitorEntity.java | 29 +- .../HsOfficeMembershipController.java | 20 +- .../membership/HsOfficeMembershipEntity.java | 37 +- .../partner/HsOfficePartnerController.java | 22 +- .../partner/HsOfficePartnerDetailsEntity.java | 15 +- .../office/partner/HsOfficePartnerEntity.java | 23 +- .../person/HsOfficePersonController.java | 20 +- .../office/person/HsOfficePersonEntity.java | 18 +- .../hs/office/relation/HsOfficeRelation.java | 2 +- .../relation/HsOfficeRelationController.java | 20 +- .../relation/HsOfficeRelationRbacEntity.java | 40 +- .../HsOfficeSepaMandateController.java | 20 +- .../HsOfficeSepaMandateEntity.java | 24 +- .../InsertTriggerGenerator.java | 82 ++-- .../PostgresTriggerReference.java | 2 +- .../RbacIdentityViewGenerator.java | 12 +- .../RbacObjectGenerator.java | 12 +- .../RbacRestrictedViewGenerator.java | 12 +- .../RbacRoleDescriptorsGenerator.java | 10 +- .../rbac/{rbacdef => generator}/RbacView.java | 82 ++-- .../RbacViewMermaidFlowchartGenerator.java | 6 +- .../RbacViewPostgresGenerator.java | 8 +- .../RolesGrantsAndPermissionsGenerator.java | 70 +-- .../{rbacdef => generator}/StringWriter.java | 2 +- .../{rbacdef => generator}/package-info.java | 2 +- .../RawRbacGrantEntity.java | 4 +- .../RawRbacGrantRepository.java | 2 +- .../RbacGrantController.java | 40 +- .../{rbacgrant => grant}/RbacGrantEntity.java | 16 +- .../{rbacgrant => grant}/RbacGrantId.java | 4 +- .../RbacGrantRepository.java | 6 +- .../RbacGrantsDiagramService.java | 12 +- .../{rbacobject => object}/BaseEntity.java | 2 +- .../rbac/rbacuser/RbacUserRepository.java | 46 -- .../RbacRoleController.java | 6 +- .../{rbacrole => role}/RbacRoleEntity.java | 4 +- .../RbacRoleRepository.java | 2 +- .../rbac/{rbacrole => role}/RbacRoleType.java | 2 +- .../RbacSubjectController.java} | 64 +-- .../RbacSubjectEntity.java} | 6 +- .../RbacSubjectPermission.java} | 4 +- .../rbac/subject/RbacSubjectRepository.java | 46 ++ .../test/cust/TestCustomerController.java | 8 +- .../rbac/test/cust/TestCustomerEntity.java | 18 +- .../rbac/test/dom/TestDomainEntity.java | 20 +- .../rbac/test/pac/TestPackageController.java | 8 +- .../rbac/test/pac/TestPackageEntity.java | 20 +- src/main/resources/api-definition/auth.yaml | 8 +- .../api-definition/error-responses.yaml | 4 +- .../api-definition/hs-booking/auth.yaml | 8 +- .../hs-booking/error-responses.yaml | 4 +- .../hs-booking-items-with-uuid.yaml | 6 +- .../hs-booking/hs-booking-items.yaml | 6 +- .../hs-booking-projects-with-uuid.yaml | 6 +- .../hs-booking/hs-booking-projects.yaml | 6 +- .../api-definition/hs-hosting/auth.yaml | 8 +- .../hs-hosting/error-responses.yaml | 4 +- .../hs-hosting-assets-with-uuid.yaml | 6 +- .../hs-hosting/hs-hosting-assets.yaml | 6 +- .../hs-office-bankaccounts-with-uuid.yaml | 4 +- .../hs-office/hs-office-bankaccounts.yaml | 6 +- .../hs-office-contacts-with-uuid.yaml | 6 +- .../hs-office/hs-office-contacts.yaml | 6 +- .../hs-office-coopassets-with-uuid.yaml | 2 +- .../hs-office/hs-office-coopassets.yaml | 6 +- .../hs-office-coopshares-with-uuid.yaml | 2 +- .../hs-office/hs-office-coopshares.yaml | 6 +- .../hs-office-debitors-with-uuid.yaml | 6 +- .../hs-office/hs-office-debitors.yaml | 6 +- .../hs-office-memberships-with-uuid.yaml | 6 +- .../hs-office/hs-office-memberships.yaml | 6 +- .../hs-office-partners-with-uuid.yaml | 6 +- .../hs-office/hs-office-partners.yaml | 6 +- .../hs-office-persons-with-uuid.yaml | 6 +- .../hs-office/hs-office-persons.yaml | 6 +- .../hs-office-relations-with-uuid.yaml | 6 +- .../hs-office/hs-office-relations.yaml | 6 +- .../hs-office-sepamandates-with-uuid.yaml | 6 +- .../hs-office/hs-office-sepamandates.yaml | 6 +- .../rbac/rbac-grant-schemas.yaml | 6 +- .../rbac/rbac-grants-with-id.yaml | 14 +- .../api-definition/rbac/rbac-grants.yaml | 8 +- .../api-definition/rbac/rbac-roles.yaml | 2 +- ...schemas.yaml => rbac-subject-schemas.yaml} | 4 +- ...=> rbac-subjects-with-id-permissions.yaml} | 12 +- ...uuid.yaml => rbac-subjects-with-uuid.yaml} | 22 +- .../{rbac-users.yaml => rbac-subjects.yaml} | 20 +- .../resources/api-definition/rbac/rbac.yaml | 14 +- .../api-definition/test/test-customers.yaml | 6 +- .../test/test-packages-uuid.yaml | 2 +- .../api-definition/test/test-packages.yaml | 2 +- .../000-base-schema.sql} | 8 +- .../001-last-row-count.sql | 6 +- .../{0-basis => 0-base}/002-int-to-var.sql | 10 +- .../003-random-in-range.sql | 6 +- .../004-jsonb-changes-delta.sql | 16 +- .../005-uuid-ossp-extension.sql | 2 +- .../006-numeric-hash-functions.sql | 4 +- .../{0-basis => 0-base}/007-table-columns.sql | 4 +- .../008-raise-functions.sql | 8 +- .../009-check-environment.sql | 2 +- .../{0-basis => 0-base}/010-context.sql | 74 +-- .../{0-basis => 0-base}/020-audit-log.sql | 71 +-- .../{0-basis => 0-base}/030-historization.sql | 45 +- .../090-log-slow-queries-extensions.sql | 2 +- .../db/changelog/1-rbac/1000-rbac-schema.sql | 8 + .../db/changelog/1-rbac/1050-rbac-base.sql | 431 +++++++++--------- .../1-rbac/1051-rbac-subject-grant.sql | 125 +++++ .../changelog/1-rbac/1051-rbac-user-grant.sql | 125 ----- .../db/changelog/1-rbac/1054-rbac-context.sql | 110 ++--- .../db/changelog/1-rbac/1055-rbac-views.sql | 273 ++++++----- .../1-rbac/1056-rbac-trigger-context.sql | 14 +- .../1-rbac/1057-rbac-role-builder.sql | 47 +- .../changelog/1-rbac/1058-rbac-generators.sql | 82 ++-- .../changelog/1-rbac/1059-rbac-statistics.sql | 16 +- .../db/changelog/1-rbac/1080-rbac-global.sql | 114 ++--- .../201-test-customer/2010-test-customer.sql | 4 +- .../2013-test-customer-rbac.md | 4 +- .../2013-test-customer-rbac.sql | 72 +-- .../2018-test-customer-test-data.sql | 16 +- .../202-test-package/2020-test-package.sql | 4 +- .../2023-test-package-rbac.md | 2 +- .../2023-test-package-rbac.sql | 62 +-- .../2028-test-package-test-data.sql | 14 +- .../203-test-domain/2030-test-domain.sql | 4 +- .../203-test-domain/2033-test-domain-rbac.md | 2 +- .../203-test-domain/2033-test-domain-rbac.sql | 64 +-- .../2038-test-domain-test-data.sql | 8 +- .../501-contact/5010-hs-office-contact.sql | 8 +- .../5013-hs-office-contact-rbac.md | 4 +- .../5013-hs-office-contact-rbac.sql | 32 +- .../5016-hs-office-contact-migration.sql | 14 +- .../5018-hs-office-contact-test-data.sql | 14 +- .../502-person/5020-hs-office-person.sql | 8 +- .../502-person/5023-hs-office-person-rbac.md | 4 +- .../502-person/5023-hs-office-person-rbac.sql | 32 +- .../5028-hs-office-person-test-data.sql | 14 +- .../503-relation/5030-hs-office-relation.sql | 8 +- ...-hs-office-relation-rbac-REPRESENTATIVE.md | 8 +- .../5033-hs-office-relation-rbac.md | 8 +- .../5033-hs-office-relation-rbac.sql | 66 +-- .../5038-hs-office-relation-test-data.sql | 12 +- .../504-partner/5040-hs-office-partner.sql | 18 +- .../5043-hs-office-partner-rbac.md | 10 +- .../5043-hs-office-partner-rbac.sql | 104 ++--- .../5044-hs-office-partner-details-rbac.md | 2 +- .../5044-hs-office-partner-details-rbac.sql | 62 +-- .../5046-hs-office-partner-migration.sql | 14 +- .../5048-hs-office-partner-test-data.sql | 8 +- .../5050-hs-office-bankaccount.sql | 8 +- .../5053-hs-office-bankaccount-rbac.md | 4 +- .../5053-hs-office-bankaccount-rbac.sql | 32 +- .../5058-hs-office-bankaccount-test-data.sql | 12 +- .../506-debitor/5060-hs-office-debitor.sql | 10 +- .../5063-hs-office-debitor-rbac.md | 20 +- .../5063-hs-office-debitor-rbac.sql | 82 ++-- .../5068-hs-office-debitor-test-data.sql | 8 +- .../5070-hs-office-sepamandate.sql | 8 +- .../5073-hs-office-sepamandate-rbac.md | 12 +- .../5073-hs-office-sepamandate-rbac.sql | 58 +-- .../5076-hs-office-sepamandate-migration.sql | 14 +- .../5078-hs-office-sepamandate-test-data.sql | 6 +- .../5100-hs-office-membership.sql | 8 +- .../5103-hs-office-membership-rbac.md | 10 +- .../5103-hs-office-membership-rbac.sql | 70 +-- .../5108-hs-office-membership-test-data.sql | 6 +- .../5110-hs-office-coopshares.sql | 12 +- .../5113-hs-office-coopshares-rbac.md | 8 +- .../5113-hs-office-coopshares-rbac.sql | 50 +- .../5116-hs-office-coopshares-migration.sql | 14 +- .../5118-hs-office-coopshares-test-data.sql | 6 +- .../5120-hs-office-coopassets.sql | 12 +- .../5123-hs-office-coopassets-rbac.md | 8 +- .../5123-hs-office-coopassets-rbac.sql | 50 +- .../5126-hs-office-coopassets-migration.sql | 14 +- .../5128-hs-office-coopassets-test-data.sql | 6 +- .../6100-hs-booking-debitor.sql | 2 +- .../6200-hs-booking-project.sql | 12 +- .../6203-hs-booking-project-rbac.md | 4 +- .../6203-hs-booking-project-rbac.sql | 54 +-- .../6208-hs-booking-project-test-data.sql | 6 +- .../6203-hs-booking-item-rbac.md | 63 --- .../6203-hs-booking-item-rbac.sql | 277 ----------- .../630-booking-item/6300-hs-booking-item.sql | 12 +- .../6303-hs-booking-item-rbac.md | 4 +- .../6303-hs-booking-item-rbac.sql | 82 ++-- .../6308-hs-booking-item-test-data.sql | 6 +- .../7010-hs-hosting-asset.sql | 20 +- .../7013-hs-hosting-asset-rbac.md | 8 +- .../7013-hs-hosting-asset-rbac.sql | 38 +- .../7016-hs-hosting-asset-migration.sql | 2 +- .../7018-hs-hosting-asset-test-data.sql | 38 +- .../changelog/9-hs-global/9000-statistics.sql | 8 +- .../db/changelog/db.changelog-master.yaml | 36 +- .../hsadminng/arch/ArchitectureTest.java | 14 +- ...HsBookingItemControllerAcceptanceTest.java | 20 +- .../item/HsBookingItemControllerRestTest.java | 4 +- ...sBookingItemRepositoryIntegrationTest.java | 14 +- ...ookingProjectControllerAcceptanceTest.java | 20 +- ...okingProjectRepositoryIntegrationTest.java | 14 +- ...sHostingAssetControllerAcceptanceTest.java | 32 +- .../HsHostingAssetControllerRestTest.java | 4 +- ...HostingAssetRepositoryIntegrationTest.java | 16 +- .../hsadminng/hs/migration/CsvDataImport.java | 8 +- ...ceBankAccountControllerAcceptanceTest.java | 22 +- ...HsOfficeBankAccountControllerRestTest.java | 4 +- ...eBankAccountRepositoryIntegrationTest.java | 12 +- ...OfficeContactControllerAcceptanceTest.java | 24 +- ...eContactRbacRepositoryIntegrationTest.java | 12 +- ...tsTransactionControllerAcceptanceTest.java | 18 +- ...opAssetsTransactionControllerRestTest.java | 2 +- ...sTransactionRepositoryIntegrationTest.java | 10 +- ...esTransactionControllerAcceptanceTest.java | 18 +- ...opSharesTransactionControllerRestTest.java | 2 +- ...sTransactionRepositoryIntegrationTest.java | 10 +- ...OfficeDebitorControllerAcceptanceTest.java | 36 +- ...fficeDebitorRepositoryIntegrationTest.java | 20 +- ...iceMembershipControllerAcceptanceTest.java | 30 +- .../HsOfficeMembershipControllerRestTest.java | 6 +- ...ceMembershipRepositoryIntegrationTest.java | 10 +- ...OfficePartnerControllerAcceptanceTest.java | 30 +- .../HsOfficePartnerControllerRestTest.java | 6 +- ...fficePartnerRepositoryIntegrationTest.java | 18 +- ...sOfficePersonControllerAcceptanceTest.java | 24 +- ...OfficePersonRepositoryIntegrationTest.java | 12 +- ...fficeRelationControllerAcceptanceTest.java | 28 +- ...ficeRelationRepositoryIntegrationTest.java | 14 +- ...ceSepaMandateControllerAcceptanceTest.java | 32 +- ...eSepaMandateRepositoryIntegrationTest.java | 12 +- .../rbac/context/ContextBasedTest.java | 12 +- .../rbac/context/ContextIntegrationTests.java | 34 +- .../rbac/context/ContextUnitTest.java | 24 +- .../RbacGrantControllerAcceptanceTest.java | 150 +++--- .../RbacGrantEntityUnitTest.java | 10 +- .../RbacGrantRepositoryIntegrationTest.java | 48 +- ...acGrantsDiagramServiceIntegrationTest.java | 24 +- .../hsadminng/rbac/rbacuser/TestRbacUser.java | 14 - .../RawRbacObjectEntity.java | 4 +- .../RawRbacObjectRepository.java | 2 +- .../{rbacrole => role}/RawRbacRoleEntity.java | 4 +- .../RawRbacRoleRepository.java | 2 +- .../RbacRoleControllerAcceptanceTest.java | 14 +- .../RbacRoleControllerRestTest.java | 8 +- .../RbacRoleRepositoryIntegrationTest.java | 12 +- .../rbac/{rbacrole => role}/TestRbacRole.java | 4 +- .../RbacSubjectControllerAcceptanceTest.java} | 120 ++--- .../RbacSubjectControllerRestTest.java} | 20 +- .../RbacSubjectEntityUnitTest.java} | 6 +- ...RbacSubjectRepositoryIntegrationTest.java} | 104 ++--- .../rbac/subject/TestRbacSubject.java | 14 + .../test/ContextBasedTestWithCleanup.java | 20 +- .../hsadminng/rbac/test/EntityList.java | 2 +- .../rbac/test/PatchUnitTestBase.java | 2 +- .../TestCustomerControllerAcceptanceTest.java | 20 +- .../test/cust/TestCustomerEntityUnitTest.java | 14 +- .../TestPackageControllerAcceptanceTest.java | 12 +- .../test/pac/TestPackageEntityUnitTest.java | 4 +- .../TestPackageRepositoryIntegrationTest.java | 4 +- 287 files changed, 3194 insertions(+), 3454 deletions(-) create mode 100755 bin/git-pull-and-if-origin-changed-run-tests rename src/main/java/net/hostsharing/hsadminng/rbac/{rbacdef => generator}/InsertTriggerGenerator.java (79%) rename src/main/java/net/hostsharing/hsadminng/rbac/{rbacdef => generator}/PostgresTriggerReference.java (52%) rename src/main/java/net/hostsharing/hsadminng/rbac/{rbacdef => generator}/RbacIdentityViewGenerator.java (79%) rename src/main/java/net/hostsharing/hsadminng/rbac/{rbacdef => generator}/RbacObjectGenerator.java (70%) rename src/main/java/net/hostsharing/hsadminng/rbac/{rbacdef => generator}/RbacRestrictedViewGenerator.java (76%) rename src/main/java/net/hostsharing/hsadminng/rbac/{rbacdef => generator}/RbacRoleDescriptorsGenerator.java (72%) rename src/main/java/net/hostsharing/hsadminng/rbac/{rbacdef => generator}/RbacView.java (93%) rename src/main/java/net/hostsharing/hsadminng/rbac/{rbacdef => generator}/RbacViewMermaidFlowchartGenerator.java (97%) rename src/main/java/net/hostsharing/hsadminng/rbac/{rbacdef => generator}/RbacViewPostgresGenerator.java (88%) rename src/main/java/net/hostsharing/hsadminng/rbac/{rbacdef => generator}/RolesGrantsAndPermissionsGenerator.java (90%) rename src/main/java/net/hostsharing/hsadminng/rbac/{rbacdef => generator}/StringWriter.java (98%) rename src/main/java/net/hostsharing/hsadminng/rbac/{rbacdef => generator}/package-info.java (81%) rename src/main/java/net/hostsharing/hsadminng/rbac/{rbacgrant => grant}/RawRbacGrantEntity.java (95%) rename src/main/java/net/hostsharing/hsadminng/rbac/{rbacgrant => grant}/RawRbacGrantRepository.java (88%) rename src/main/java/net/hostsharing/hsadminng/rbac/{rbacgrant => grant}/RbacGrantController.java (72%) rename src/main/java/net/hostsharing/hsadminng/rbac/{rbacgrant => grant}/RbacGrantEntity.java (80%) rename src/main/java/net/hostsharing/hsadminng/rbac/{rbacgrant => grant}/RbacGrantId.java (79%) rename src/main/java/net/hostsharing/hsadminng/rbac/{rbacgrant => grant}/RbacGrantRepository.java (80%) rename src/main/java/net/hostsharing/hsadminng/rbac/{rbacgrant => grant}/RbacGrantsDiagramService.java (95%) rename src/main/java/net/hostsharing/hsadminng/rbac/{rbacobject => object}/BaseEntity.java (88%) delete mode 100644 src/main/java/net/hostsharing/hsadminng/rbac/rbacuser/RbacUserRepository.java rename src/main/java/net/hostsharing/hsadminng/rbac/{rbacrole => role}/RbacRoleController.java (88%) rename src/main/java/net/hostsharing/hsadminng/rbac/{rbacrole => role}/RbacRoleEntity.java (89%) rename src/main/java/net/hostsharing/hsadminng/rbac/{rbacrole => role}/RbacRoleRepository.java (91%) rename src/main/java/net/hostsharing/hsadminng/rbac/{rbacrole => role}/RbacRoleType.java (61%) rename src/main/java/net/hostsharing/hsadminng/rbac/{rbacuser/RbacUserController.java => subject/RbacSubjectController.java} (50%) rename src/main/java/net/hostsharing/hsadminng/rbac/{rbacuser/RbacUserEntity.java => subject/RbacSubjectEntity.java} (92%) rename src/main/java/net/hostsharing/hsadminng/rbac/{rbacuser/RbacUserPermission.java => subject/RbacSubjectPermission.java} (73%) create mode 100644 src/main/java/net/hostsharing/hsadminng/rbac/subject/RbacSubjectRepository.java rename src/main/resources/api-definition/rbac/{rbac-user-schemas.yaml => rbac-subject-schemas.yaml} (93%) rename src/main/resources/api-definition/rbac/{rbac-users-with-id-permissions.yaml => rbac-subjects-with-id-permissions.yaml} (70%) rename src/main/resources/api-definition/rbac/{rbac-users-with-uuid.yaml => rbac-subjects-with-uuid.yaml} (66%) rename src/main/resources/api-definition/rbac/{rbac-users.yaml => rbac-subjects.yaml} (62%) rename src/main/resources/db/changelog/{0-basis/000-template.sql => 0-base/000-base-schema.sql} (71%) rename src/main/resources/db/changelog/{0-basis => 0-base}/001-last-row-count.sql (75%) rename src/main/resources/db/changelog/{0-basis => 0-base}/002-int-to-var.sql (66%) rename src/main/resources/db/changelog/{0-basis => 0-base}/003-random-in-range.sql (70%) rename src/main/resources/db/changelog/{0-basis => 0-base}/004-jsonb-changes-delta.sql (85%) rename src/main/resources/db/changelog/{0-basis => 0-base}/005-uuid-ossp-extension.sql (82%) rename src/main/resources/db/changelog/{0-basis => 0-base}/006-numeric-hash-functions.sql (69%) rename src/main/resources/db/changelog/{0-basis => 0-base}/007-table-columns.sql (79%) rename src/main/resources/db/changelog/{0-basis => 0-base}/008-raise-functions.sql (74%) rename src/main/resources/db/changelog/{0-basis => 0-base}/009-check-environment.sql (92%) rename src/main/resources/db/changelog/{0-basis => 0-base}/010-context.sql (70%) rename src/main/resources/db/changelog/{0-basis => 0-base}/020-audit-log.sql (58%) rename src/main/resources/db/changelog/{0-basis => 0-base}/030-historization.sql (74%) rename src/main/resources/db/changelog/{0-basis => 0-base}/090-log-slow-queries-extensions.sql (76%) create mode 100644 src/main/resources/db/changelog/1-rbac/1000-rbac-schema.sql create mode 100644 src/main/resources/db/changelog/1-rbac/1051-rbac-subject-grant.sql delete mode 100644 src/main/resources/db/changelog/1-rbac/1051-rbac-user-grant.sql delete mode 100644 src/main/resources/db/changelog/6-hs-booking/630-booking-item/6203-hs-booking-item-rbac.md delete mode 100644 src/main/resources/db/changelog/6-hs-booking/630-booking-item/6203-hs-booking-item-rbac.sql rename src/test/java/net/hostsharing/hsadminng/rbac/{rbacgrant => grant}/RbacGrantControllerAcceptanceTest.java (74%) rename src/test/java/net/hostsharing/hsadminng/rbac/{rbacgrant => grant}/RbacGrantEntityUnitTest.java (84%) rename src/test/java/net/hostsharing/hsadminng/rbac/{rbacgrant => grant}/RbacGrantRepositoryIntegrationTest.java (86%) rename src/test/java/net/hostsharing/hsadminng/rbac/{rbacgrant => grant}/RbacGrantsDiagramServiceIntegrationTest.java (77%) delete mode 100644 src/test/java/net/hostsharing/hsadminng/rbac/rbacuser/TestRbacUser.java rename src/test/java/net/hostsharing/hsadminng/rbac/{rbacrole => role}/RawRbacObjectEntity.java (82%) rename src/test/java/net/hostsharing/hsadminng/rbac/{rbacrole => role}/RawRbacObjectRepository.java (82%) rename src/test/java/net/hostsharing/hsadminng/rbac/{rbacrole => role}/RawRbacRoleEntity.java (92%) rename src/test/java/net/hostsharing/hsadminng/rbac/{rbacrole => role}/RawRbacRoleRepository.java (82%) rename src/test/java/net/hostsharing/hsadminng/rbac/{rbacrole => role}/RbacRoleControllerAcceptanceTest.java (90%) rename src/test/java/net/hostsharing/hsadminng/rbac/{rbacrole => role}/RbacRoleControllerRestTest.java (91%) rename src/test/java/net/hostsharing/hsadminng/rbac/{rbacrole => role}/RbacRoleRepositoryIntegrationTest.java (94%) rename src/test/java/net/hostsharing/hsadminng/rbac/{rbacrole => role}/TestRbacRole.java (87%) rename src/test/java/net/hostsharing/hsadminng/rbac/{rbacuser/RbacUserControllerAcceptanceTest.java => subject/RbacSubjectControllerAcceptanceTest.java} (74%) rename src/test/java/net/hostsharing/hsadminng/rbac/{rbacuser/RbacUserControllerRestTest.java => subject/RbacSubjectControllerRestTest.java} (83%) rename src/test/java/net/hostsharing/hsadminng/rbac/{rbacuser/RbacUserEntityUnitTest.java => subject/RbacSubjectEntityUnitTest.java} (91%) rename src/test/java/net/hostsharing/hsadminng/rbac/{rbacuser/RbacUserRepositoryIntegrationTest.java => subject/RbacSubjectRepositoryIntegrationTest.java} (80%) create mode 100644 src/test/java/net/hostsharing/hsadminng/rbac/subject/TestRbacSubject.java diff --git a/README.md b/README.md index 4d03a6d3..9cca4fc4 100644 --- a/README.md +++ b/README.md @@ -77,17 +77,17 @@ If you have at least Docker and the Java JDK installed in appropriate versions a # the following command should return a JSON array with just all customers: curl \ - -H 'current-user: superuser-alex@hostsharing.net' \ + -H 'current-subject: superuser-alex@hostsharing.net' \ http://localhost:8080/api/test/customers # the following command should return a JSON array with just all packages visible for the admin of the customer yyy: curl \ - -H 'current-user: superuser-alex@hostsharing.net' -H 'assumed-roles: test_customer#yyy:ADMIN' \ + -H 'current-subject: superuser-alex@hostsharing.net' -H 'assumed-roles: test_customer#yyy:ADMIN' \ http://localhost:8080/api/test/packages # add a new customer curl \ - -H 'current-user: superuser-alex@hostsharing.net' -H "Content-Type: application/json" \ + -H 'current-subject: superuser-alex@hostsharing.net' -H "Content-Type: application/json" \ -d '{ "prefix":"ttt", "reference":80001, "adminUserName":"admin@ttt.example.com" }' \ -X POST http://localhost:8080/api/test/customers diff --git a/bin/git-pull-and-if-origin-changed-run-tests b/bin/git-pull-and-if-origin-changed-run-tests new file mode 100755 index 00000000..f955323d --- /dev/null +++ b/bin/git-pull-and-if-origin-changed-run-tests @@ -0,0 +1,36 @@ +#!/bin/bash + +# get the current branch name +BRANCH=$(git rev-parse --abbrev-ref HEAD) + +while true; do + + # get the latest commit hashes from origin and local + git fetch origin + LOCAL=$(git rev-parse HEAD) + REMOTE=$(git rev-parse origin/$BRANCH) + + # check if the local branch differs from the remote branch + if [ "$LOCAL" != "$REMOTE" ]; then + echo "local $LOCAL differs from remote $REMOTE => pulling changes from origin" + git pull origin $BRANCH + + # run the command + echo "Running ./gradlew test" + source .aliases # only variables, aliases are not expanded in scripts + ./gradlew test + fi + + # wait 10s with a little animation + echo -e -n " waiting for changes (/) ..." + sleep 2 + echo -e -n "\r\033[K waiting for changes (-) ..." + sleep 2 + echo -e -n "\r\033[K waiting for changes (\) ..." + sleep 2 + echo -e -n "\r\033[K waiting for changes (|) ..." + sleep 2 + echo -e -n "\r\033[K waiting for changes ( ) ... " + sleep 2 + echo -e -n "\r\033[K" +done diff --git a/doc/adr/2022-07-18.row-level-security-mechanism.md b/doc/adr/2022-07-18.row-level-security-mechanism.md index 6276bd4d..b37e8932 100644 --- a/doc/adr/2022-07-18.row-level-security-mechanism.md +++ b/doc/adr/2022-07-18.row-level-security-mechanism.md @@ -14,9 +14,9 @@ The core problem here is, that in our RBAC system, determining the permissions o ### Technical Background -The session variable `hsadminng.currentUser` contains the accessing (domain-level) user, which is unrelated to the PostgreSQL user). +The session variable `hsadminng.currentSubject` contains the accessing (domain-level) user, which is unrelated to the PostgreSQL user). -Given is a stored function `isPermissionGrantedToSubject` which detects if the accessing user has a given permission (e.g. 'view'). +Given is a stored function `isPermissionGrantedToSubject` which detects if the accessing subject has a given permission (e.g. 'view'). Given is also a stored function `queryAllPermissionsOfSubjectId` which returns the flattened view to all permissions assigned to the given accessing user. @@ -38,7 +38,7 @@ In this solution, the database ignores row level visibility and returns all rows Very flexible access, programmatic, rules could be implemented. -The role-hierarchy and permissions for currently logged-in users user could be cached in the backend. +The role-hierarchy and permissions for current subjects (e.g. logged-in users) could be cached in the backend. The access logic can be tested in pure Java unit tests. @@ -74,11 +74,11 @@ For restricted DB-users, which are used by the backend, access to rows is filter FOR SELECT TO restricted USING ( - isPermissionGrantedToSubject(findEffectivePermissionId('customer', id, 'view'), currentUserUuid()) + rbac.isPermissionGrantedToSubject(rbac.findEffectivePermissionId('customer', id, 'view'), currentSubjectUuid()) ); SET SESSION AUTHORIZATION restricted; - SET hsadminng.currentUser TO 'alex@example.com'; + SET hsadminng.currentSubject TO 'alex@example.com'; SELECT * from customer; -- will only return visible rows #### Advantages @@ -101,10 +101,10 @@ We are bound to PostgreSQL, including integration tests and testing the RBAC sys CREATE OR REPLACE RULE "_RETURN" AS ON SELECT TO cust_view DO INSTEAD - SELECT * FROM customer WHERE isPermissionGrantedToSubject(findEffectivePermissionId('customer', id, 'view'), currentUserUuid()); + SELECT * FROM customer WHERE rbac.isPermissionGrantedToSubject(rbac.findEffectivePermissionId('customer', id, 'view'), currentSubjectUuid()); SET SESSION AUTHORIZATION restricted; - SET hsadminng.currentUser TO 'alex@example.com'; + SET hsadminng.currentSubject TO 'alex@example.com'; SELECT * from customer; -- will only return visible rows #### Advantages @@ -130,12 +130,12 @@ We do not access the tables directly from the backend, but via views which join CREATE OR REPLACE VIEW cust_view AS SELECT c.id, c.reference, c.prefix FROM customer AS c - JOIN queryAllPermissionsOfSubjectId(currentUserUuid()) AS p + JOIN queryAllPermissionsOfSubjectId(currentSubjectUuid()) AS p ON p.tableName='customer' AND p.rowId=c.id AND p.op='view'; GRANT ALL PRIVILEGES ON cust_view TO restricted; SET SESSION SESSION AUTHORIZATION restricted; - SET hsadminng.currentUser TO 'alex@example.com'; + SET hsadminng.currentSubject TO 'alex@example.com'; SELECT * from cust_view; -- will only return visible rows Alternatively the JOIN could also be applied in a "ON SELECT DO INSTEAD"-RULE, if there is any advantage for later features. diff --git a/doc/rbac-performance-analysis.md b/doc/rbac-performance-analysis.md index fa80dde4..6cfcdf47 100644 --- a/doc/rbac-performance-analysis.md +++ b/doc/rbac-performance-analysis.md @@ -239,7 +239,7 @@ This did not improve the performance. We were suspicious about the sequential scan over all `rbacpermission` rows which was done by PostgreSQL to execute a HashJoin strategy. Turning off that strategy by ```SQL -ALTER FUNCTION queryAccessibleObjectUuidsOfSubjectIds SET enable_hashjoin = off; +ALTER FUNCTION rbac.queryAccessibleObjectUuidsOfSubjectIds SET enable_hashjoin = off; ``` did not improve the performance though. The HashJoin was actually still applied, but no full table scan anymore: @@ -273,9 +273,9 @@ At this point, the import took 21mins with these statistics: | select hore1_0.uuid,a1_0.uuid,a1_0.familyname,a1_0.givenname,a1_0.persontype,a1_0.salutation,a1_0.title,a1_0.tradename,a1_0.version,c1_0.uuid,c1_0.caption,c1_0.emailaddresses,c1_0.phonenumbers,c1_0.postaladdress, c1_0.version,h1_0.uuid,h1_0.familyname,h1_0.givenname,h1_0.persontype,h1_0.salutation,h1_0.title,h1_0.tradename,h1_0.version,hore1_0.mark,hore1_0.type,hore1_0.version from public.hs_office_relation_rv hore1_0 left join public.hs_office_person_rv a1_0 on a1_0.uuid=hore1_0.anchoruuid left join public.hs_office_contact_rv c1_0 on c1_0.uuid=hore1_0.contactuuid left join public.hs_office_person_rv h1_0 on h1_0.uuid=hore1_0.holderuuid where hore1_0.uuid=$1 | 517 | 11 | 1282 | | select hope1_0.uuid,hope1_0.familyname,hope1_0.givenname,hope1_0.persontype,hope1_0.salutation,hope1_0.title,hope1_0.tradename,hope1_0.version from public.hs_office_person_rv hope1_0 where hope1_0.uuid=$1 | 973 | 4 | 254 | | select hoce1_0.uuid,hoce1_0.caption,hoce1_0.emailaddresses,hoce1_0.phonenumbers,hoce1_0.postaladdress,hoce1_0.version from public.hs_office_contact_rv hoce1_0 where hoce1_0.uuid=$1 | 973 | 4 | 253 | -| call grantRoleToRole(roleUuid, superRoleUuid, superRoleDesc.assumed) | 31316 | 0 | 1 | +| call rbac.grantRoleToRole(roleUuid, superRoleUuid, superRoleDesc.assumed) | 31316 | 0 | 1 | | call buildRbacSystemForHsHostingAsset(NEW) | 2258 | 0 | 7 | -| select * from isGranted(array[granteeId], grantedId) | 44613 | 0 | 0 | +| select * from rbac.isGranted(array[granteeId], grantedId) | 44613 | 0 | 0 | | insert into public.hs_hosting_asset_rv (alarmcontactuuid,assignedtoassetuuid,bookingitemuuid,caption,config,identifier,parentassetuuid,type,version,uuid) values ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10) | 2207 | 0 | 7 | | insert into hs_hosting_asset (alarmcontactuuid, version, bookingitemuuid, type, parentassetuuid, assignedtoassetuuid, config, uuid, identifier, caption) values (new.alarmcontactuuid, new. version, new. bookingitemuuid, new. type, new. parentassetuuid, new. assignedtoassetuuid, new. config, new. uuid, new. identifier, new. caption) returning * | 2207 | 0 | 7 | | insert into public.hs_office_relation_rv (anchoruuid,contactuuid,holderuuid,mark,type,version,uuid) values ($1,$2,$3,$4,$5,$6,$7) | 1261 | 0 | 9 | @@ -297,8 +297,8 @@ We changed these mappings from `EAGER` (default) to `LAZY` to `@ManyToOne(fetch | select hope1_0.uuid,hope1_0.familyname,hope1_0.givenname,hope1_0.persontype,hope1_0.salutation,hope1_0.title,hope1_0.tradename,hope1_0.version from public.hs_office_person_rv hope1_0 where hope1_0.uuid=$1 | 1015 | 4 | 238 | | select hore1_0.uuid,hore1_0.anchoruuid,hore1_0.contactuuid,hore1_0.holderuuid,hore1_0.mark,hore1_0.type,hore1_0.version from public.hs_office_relation_rv hore1_0 where hore1_0.uuid=$1 | 517 | 4 | 439 | | select hoce1_0.uuid,hoce1_0.caption,hoce1_0.emailaddresses,hoce1_0.phonenumbers,hoce1_0.postaladdress,hoce1_0.version from public.hs_office_contact_rv hoce1_0 where hoce1_0.uuid=$1 | 497 | 2 | 213 | -| call grantRoleToRole(roleUuid, superRoleUuid, superRoleDesc.assumed) | 31316 | 0 | 1 | -| select * from isGranted(array[granteeId], grantedId) | 44613 | 0 | 0 | +| call rbac.grantRoleToRole(roleUuid, superRoleUuid, superRoleDesc.assumed) | 31316 | 0 | 1 | +| select * from rbac.isGranted(array[granteeId], grantedId) | 44613 | 0 | 0 | | call buildRbacSystemForHsHostingAsset(NEW) | 2258 | 0 | 7 | | insert into public.hs_hosting_asset_rv (alarmcontactuuid,assignedtoassetuuid,bookingitemuuid,caption,config,identifier,parentassetuuid,type,version,uuid) values ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10) | 2207 | 0 | 7 | | insert into hs_hosting_asset (alarmcontactuuid, version, bookingitemuuid, type, parentassetuuid, assignedtoassetuuid, config, uuid, identifier, caption) values (new.alarmcontactuuid, new. version, new. bookingitemuuid, new. type, new. parentassetuuid, new. assignedtoassetuuid, new. config, new. uuid, new. identifier, new. caption) returning * | 2207 | 0 | 7 | @@ -333,8 +333,8 @@ Now, the longest running queries are these: | 1 | 13.093 | 4 | 21 | insert into hs_hosting_asset( uuid, type, bookingitemuuid, parentassetuuid, assignedtoassetuuid, alarmcontactuuid, identifier, caption, config, version) values ( $1, $2, $3, $4, $5, $6, $7, $8, cast($9 as jsonb), $10) | | 2 | 517 | 4 | 502 | select hore1_0.uuid,hore1_0.anchoruuid,hore1_0.contactuuid,hore1_0.holderuuid,hore1_0.mark,hore1_0.type,hore1_0.version from public.hs_office_relation_rv hore1_0 where hore1_0.uuid=$1 | | 3 | 13.144 | 4 | 21 | call buildRbacSystemForHsHostingAsset(NEW) | -| 4 | 96.632 | 3 | 2 | call grantRoleToRole(roleUuid, superRoleUuid, superRoleDesc.assumed) | -| 5 | 120.815 | 3 | 2 | select * from isGranted(array[granteeId], grantedId) | +| 4 | 96.632 | 3 | 2 | call rbac.grantRoleToRole(roleUuid, superRoleUuid, superRoleDesc.assumed) | +| 5 | 120.815 | 3 | 2 | select * from rbac.isGranted(array[granteeId], grantedId) | | 6 | 123.740 | 3 | 2 | with recursive grants as ( select descendantUuid, ascendantUuid from RbacGrants where descendantUuid = grantedId union all select "grant".descendantUuid, "grant".ascendantUuid from RbacGrants "grant" inner join grants recur on recur.ascendantUuid = "grant".descendantUuid ) select exists ( select $3 from grants where ascendantUuid = any(granteeIds) ) or grantedId = any(granteeIds) | | 7 | 497 | 2 | 259 | select hoce1_0.uuid,hoce1_0.caption,hoce1_0.emailaddresses,hoce1_0.phonenumbers,hoce1_0.postaladdress,hoce1_0.version from public.hs_office_contact_rv hoce1_0 where hoce1_0.uuid=$1 | | 8 | 497 | 2 | 255 | select hope1_0.uuid,hope1_0.familyname,hope1_0.givenname,hope1_0.persontype,hope1_0.salutation,hope1_0.title,hope1_0.tradename,hope1_0.version from public.hs_office_person_rv hope1_0 where hope1_0.uuid=$1 | @@ -392,9 +392,9 @@ We found some solution approaches: 3. Inverting the recursion of the CTE-query, combined with the type condition. - Instead of starting the recursion with `currentsubjectsuuids()`, + Instead of starting the recursion with `currentSubjectOrAssumedRolesUuids()`, we could start it with the target table name and row-type, - then recurse down to the `currentsubjectsuuids()`. + then recurse down to the `currentSubjectOrAssumedRolesUuids()`. In the end, we need the object UUIDs, though. But if we start with the join of `rbacObject` with `rbacPermission`, diff --git a/doc/rbac.md b/doc/rbac.md index 662bed29..325e2841 100644 --- a/doc/rbac.md +++ b/doc/rbac.md @@ -29,7 +29,7 @@ skinparam linetype ortho package RBAC { ' forward declarations - entity RbacUser + entity RbacSubject together { @@ -37,8 +37,8 @@ package RBAC { entity RbacPermission - RbacUser -[hidden]> RbacRole - RbacRole -[hidden]> RbacUser + RbacSubject -[hidden]> RbacRole + RbacRole -[hidden]> RbacSubject } together { @@ -57,11 +57,11 @@ package RBAC { RbacGrant o-u-> RbacReference enum RbacReferenceType { - RbacUser + RbacSubject RbacRole RbacPermission } - RbacReferenceType ..> RbacUser + RbacReferenceType ..> RbacSubject RbacReferenceType ..> RbacRole RbacReferenceType ..> RbacPermission @@ -71,12 +71,12 @@ package RBAC { type : RbacReferenceType } RbacReference o--> RbacReferenceType - entity RbacUser { + entity RbacSubject { *uuid : uuid <> -- name : varchar } - RbacUser o-- RbacReference + RbacSubject o-- RbacReference entity RbacRole { *uuid : uuid(RbacReference) @@ -143,20 +143,20 @@ The primary key of the *RbacReference* and its referred object is always identic #### RbacReferenceType The enum *RbacReferenceType* describes the type of reference. -It's only needed to make it easier to find the referred object in *RbacUser*, *RbacRole* or *RbacPermission*. +It's only needed to make it easier to find the referred object in *RbacSubject*, *RbacRole* or *RbacPermission*. -#### RbacUser +#### RbacSubject -An *RbacUser* is a type of RBAC-subject which references a login account outside this system, identified by a name (usually an email-address). +An *RbacSubject* is a type of RBAC-subject which references a login account outside this system, identified by a name (usually an email-address). -*RbacUser*s can be assigned to multiple *RbacRole*s, through which they can get permissions to *RbacObject*s. +*RbacSubject*s can be assigned to multiple *RbacRole*s, through which they can get permissions to *RbacObject*s. -The primary key of the *RbacUser* is identical to its related *RbacReference*. +The primary key of the *RbacSubject* is identical to its related *RbacReference*. #### RbacRole An *RbacRole* represents a collection of directly or indirectly assigned *RbacPermission*s. -Each *RbacRole* can be assigned to *RbacUser*s or to another *RbacRole*. +Each *RbacRole* can be assigned to *RbacSubject*s or to another *RbacRole*. Both kinds of assignments are represented via *RbacGrant*. @@ -184,7 +184,7 @@ Only with this rule, the foreign key in *RbacPermission* can be defined as `NOT #### RbacGrant -The *RbacGrant* entities represent the access-rights structure from *RbacUser*s via hierarchical *RbacRoles* down to *RbacPermission*s. +The *RbacGrant* entities represent the access-rights structure from *RbacSubject*s via hierarchical *RbacRoles* down to *RbacPermission*s. The core SQL queries to determine access rights are all recursive queries on the *RbacGrant* table. @@ -284,7 +284,7 @@ hide circle ' use right-angled line routing ' skinparam linetype ortho -package RbacUsers { +package RbacSubjects { object UserMike object UserSuse object UserPaul @@ -296,7 +296,7 @@ package RbacRoles { object RoleCustXyz_Admin object RolePackXyz00_Owner } -RbacUsers -[hidden]> RbacRoles +RbacSubjects -[hidden]> RbacRoles package RbacPermissions { object PermCustXyz_SELECT @@ -364,10 +364,10 @@ This way, each user can only select the data they have 'SELECT'-permission for, ### Current User -The current use is taken from the session variable `hsadminng.currentUser` which contains the name of the user as stored in the -*RbacUser*s table. Example: +The current use is taken from the session variable `hsadminng.currentSubject` which contains the name of the user as stored in the +*RbacSubject*s table. Example: - SET LOCAL hsadminng.currentUser = 'mike@hostsharing.net'; + SET LOCAL hsadminng.currentSubject = 'mike@hostsharing.net'; That user is also used for historicization and audit log, but which is a different topic. @@ -388,7 +388,7 @@ A full example is shown here: BEGIN TRANSACTION; SET SESSION SESSION AUTHORIZATION restricted; - SET LOCAL hsadminng.currentUser = 'mike@hostsharing.net'; + SET LOCAL hsadminng.currentSubject = 'mike@hostsharing.net'; SET LOCAL hsadminng.assumedRoles = 'customer#aab:admin;customer#aac:admin'; SELECT c.prefix, p.name as "package", ema.localPart || '@' || dom.name as "email-address" @@ -605,8 +605,8 @@ Find the SQL script here: `28-hs-tests.sql`. We have tested two variants of the query for the restricted view, both utilizing a PostgreSQL function like this: - FUNCTION queryAccessibleObjectUuidsOfSubjectIds( - requiredOp RbacOp, + FUNCTION rbac.queryAccessibleObjectUuidsOfSubjectIds( + requiredOp rbac.RbacOp, forObjectTable varchar, subjectIds uuid[], maxObjects integer = 16000) @@ -623,8 +623,8 @@ Let's have a look at the two view queries: FROM customer AS target WHERE target.uuid IN ( SELECT uuid - FROM queryAccessibleObjectUuidsOfSubjectIds( - 'SELECT, 'customer', currentSubjectsUuids())); + FROM rbac.queryAccessibleObjectUuidsOfSubjectIds( + 'SELECT, 'customer', currentSubjectOrAssumedRolesUuids())); This view should be automatically updatable. Where, for updates, we actually have to check for 'UPDATE' instead of 'SELECT' operation, which makes it a bit more complicated. @@ -641,8 +641,8 @@ Looks like the query optimizer needed some statistics to find the best path. CREATE OR REPLACE VIEW customer_rv AS SELECT DISTINCT target.* FROM customer AS target - JOIN queryAccessibleObjectUuidsOfSubjectIds( - 'SELECT, 'customer', currentSubjectsUuids()) AS allowedObjId + JOIN rbac.queryAccessibleObjectUuidsOfSubjectIds( + 'SELECT, 'customer', currentSubjectOrAssumedRolesUuids()) AS allowedObjId ON target.uuid = allowedObjId; This view cannot is not updatable automatically, @@ -671,9 +671,9 @@ Access Control for business objects checked according to the assigned roles. But we decided not to create such roles and permissions for the RBAC-Objects itself. It would have overcomplicated the system and the necessary information can easily be added to the RBAC-Objects itself, mostly the `RbacGrant`s. -### RbacUser +### RbacSubject -Users can self-register, thus to create a new RbacUser entity, no login is required. +Users can self-register, thus to create a new RbacSubject entity, no login is required. But such a user has no access-rights except viewing itself. Users can view themselves. diff --git a/sql/historization.sql b/sql/historization.sql index 6f50f428..d854f394 100644 --- a/sql/historization.sql +++ b/sql/historization.sql @@ -24,13 +24,13 @@ delete from hs_hosting_asset where uuid='5aea68d2-3b55-464f-8362-b05c76c5a681':: commit; -- single version at point in time --- set hsadminng.tx_history_txid to (select max(txid) from tx_context where txtimestamp<='2024-08-27 12:13:13.450821'); +-- set hsadminng.tx_history_txid to (select max(txid) from base.tx_context where txtimestamp<='2024-08-27 12:13:13.450821'); set hsadminng.tx_history_txid to ''; set hsadminng.tx_history_timestamp to '2024-08-29 12:42'; -- all versions -select tx_history_txid(), txc.txtimestamp, txc.currentUser, txc.currentTask, haex.* +select base.tx_history_txid(), txc.txtimestamp, txc.currentSubject, txc.currentTask, haex.* from hs_hosting_asset_ex haex - join tx_context txc on haex.txid=txc.txid + join base.tx_context txc on haex.txid=txc.txid where haex.identifier = 'test@thi.example.org'; select uuid, version, type, identifier, caption from hs_hosting_asset_hv p where identifier = 'test@thi.example.org'; diff --git a/sql/rbac-tests.sql b/sql/rbac-tests.sql index 351d1509..1a95add0 100644 --- a/sql/rbac-tests.sql +++ b/sql/rbac-tests.sql @@ -3,28 +3,28 @@ -- -------------------------------------------------------- -select isGranted(findRoleId('administrators'), findRoleId('test_package#aaa00:OWNER')); -select isGranted(findRoleId('test_package#aaa00:OWNER'), findRoleId('administrators')); --- call grantRoleToRole(findRoleId('test_package#aaa00:OWNER'), findRoleId('administrators')); --- call grantRoleToRole(findRoleId('administrators'), findRoleId('test_package#aaa00:OWNER')); +select rbac.isGranted(rbac.findRoleId('administrators'), rbac.findRoleId('test.package#aaa00:OWNER')); +select rbac.isGranted(rbac.findRoleId('test.package#aaa00:OWNER'), rbac.findRoleId('administrators')); +-- call rbac.grantRoleToRole(findRoleId('test.package#aaa00:OWNER'), findRoleId('administrators')); +-- call rbac.grantRoleToRole(findRoleId('administrators'), findRoleId('test.package#aaa00:OWNER')); select count(*) -FROM queryAllPermissionsOfSubjectIdForObjectUuids(findRbacUser('superuser-fran@hostsharing.net'), - ARRAY(select uuid from customer where reference < 1100000)); +FROM rbac.queryAllPermissionsOfSubjectIdForObjectUuids(rbac.findRbacSubject('superuser-fran@hostsharing.net'), + ARRAY(select uuid from test.customer where reference < 1100000)); select count(*) -FROM queryAllPermissionsOfSubjectId(findRbacUser('superuser-fran@hostsharing.net')); +FROM rbac.queryAllPermissionsOfSubjectId(findRbacSubject('superuser-fran@hostsharing.net')); select * -FROM queryAllPermissionsOfSubjectId(findRbacUser('alex@example.com')); +FROM rbac.queryAllPermissionsOfSubjectId(findRbacSubject('alex@example.com')); select * -FROM queryAllPermissionsOfSubjectId(findRbacUser('rosa@example.com')); +FROM rbac.queryAllPermissionsOfSubjectId(findRbacSubject('rosa@example.com')); select * -FROM queryAllRbacUsersWithPermissionsFor(findEffectivePermissionId('customer', - (SELECT uuid FROM RbacObject WHERE objectTable = 'customer' LIMIT 1), +FROM rbac.queryAllRbacSubjectsWithPermissionsFor(rbac.findEffectivePermissionId('customer', + (SELECT uuid FROM rbac.RbacObject WHERE objectTable = 'customer' LIMIT 1), 'add-package')); select * -FROM queryAllRbacUsersWithPermissionsFor(findEffectivePermissionId('package', - (SELECT uuid FROM RbacObject WHERE objectTable = 'package' LIMIT 1), +FROM rbac.queryAllRbacSubjectsWithPermissionsFor(rbac.findEffectivePermissionId('package', + (SELECT uuid FROM rbac.RbacObject WHERE objectTable = 'package' LIMIT 1), 'DELETE')); DO LANGUAGE plpgsql @@ -33,13 +33,13 @@ $$ userId uuid; result bool; BEGIN - userId = findRbacUser('superuser-alex@hostsharing.net'); - result = (SELECT * FROM isPermissionGrantedToSubject(findPermissionId('package', 94928, 'add-package'), userId)); + userId = rbac.findRbacSubject('superuser-alex@hostsharing.net'); + result = (SELECT * FROM rbac.isPermissionGrantedToSubject(rbac.findPermissionId('package', 94928, 'add-package'), userId)); IF (result) THEN RAISE EXCEPTION 'expected permission NOT to be granted, but it is'; end if; - result = (SELECT * FROM isPermissionGrantedToSubject(findPermissionId('package', 94928, 'SELECT'), userId)); + result = (SELECT * FROM rbac.isPermissionGrantedToSubject(rbac.findPermissionId('package', 94928, 'SELECT'), userId)); IF (NOT result) THEN RAISE EXCEPTION 'expected permission to be granted, but it is NOT'; end if; diff --git a/sql/rbac-view-option-experiments.sql b/sql/rbac-view-option-experiments.sql index c5c04487..75668d76 100644 --- a/sql/rbac-view-option-experiments.sql +++ b/sql/rbac-view-option-experiments.sql @@ -20,43 +20,43 @@ CREATE POLICY customer_policy ON customer TO restricted USING ( -- id=1000 - isPermissionGrantedToSubject(findEffectivePermissionId('test_customer', id, 'SELECT'), currentUserUuid()) + rbac.isPermissionGrantedToSubject(rbac.findEffectivePermissionId('test.customer', id, 'SELECT'), rbac.currentSubjectUuid()) ); SET SESSION AUTHORIZATION restricted; -SET hsadminng.currentUser TO 'alex@example.com'; +SET hsadminng.currentSubject TO 'alex@example.com'; SELECT * from customer; -- access control via view-rule and isPermissionGrantedToSubject - way too slow (35 s 580 ms for 1 million rows) SET SESSION SESSION AUTHORIZATION DEFAULT; DROP VIEW cust_view; CREATE VIEW cust_view AS -SELECT * FROM customer; +SELECT * FROM test.customer; CREATE OR REPLACE RULE "_RETURN" AS ON SELECT TO cust_view DO INSTEAD - SELECT * FROM customer WHERE isPermissionGrantedToSubject(findEffectivePermissionId('test_customer', id, 'SELECT'), currentUserUuid()); + SELECT * FROM test.customer WHERE rbac.isPermissionGrantedToSubject(rbac.findEffectivePermissionId('test.customer', id, 'SELECT'), rbac.currentSubjectUuid()); SELECT * from cust_view LIMIT 10; -select queryAllPermissionsOfSubjectId(findRbacUser('superuser-alex@hostsharing.net')); +select rbac.queryAllPermissionsOfSubjectId(findRbacSubject('superuser-alex@hostsharing.net')); -- access control via view-rule with join to recursive permissions - really fast (38ms for 1 million rows) SET SESSION SESSION AUTHORIZATION DEFAULT; -ALTER TABLE customer ENABLE ROW LEVEL SECURITY; +ALTER TABLE test.customer ENABLE ROW LEVEL SECURITY; DROP VIEW IF EXISTS cust_view; CREATE OR REPLACE VIEW cust_view AS SELECT * -FROM customer; +FROM test.customer; CREATE OR REPLACE RULE "_RETURN" AS ON SELECT TO cust_view DO INSTEAD - SELECT c.uuid, c.reference, c.prefix FROM customer AS c - JOIN queryAllPermissionsOfSubjectId(currentUserUuid()) AS p - ON p.objectTable='test_customer' AND p.objectUuid=c.uuid; + SELECT c.uuid, c.reference, c.prefix FROM test.customer AS c + JOIN rbac.queryAllPermissionsOfSubjectId(rbac.currentSubjectUuid()) AS p + ON p.objectTable='test.customer' AND p.objectUuid=c.uuid; GRANT ALL PRIVILEGES ON cust_view TO restricted; SET SESSION SESSION AUTHORIZATION restricted; -SET hsadminng.currentUser TO 'alex@example.com'; +SET hsadminng.currentSubject TO 'alex@example.com'; SELECT * from cust_view; @@ -67,23 +67,23 @@ DROP VIEW IF EXISTS cust_view; CREATE OR REPLACE VIEW cust_view AS SELECT c.uuid, c.reference, c.prefix FROM customer AS c - JOIN queryAllPermissionsOfSubjectId(currentUserUuid()) AS p + JOIN queryAllPermissionsOfSubjectId(rbac.currentSubjectUuid()) AS p ON p.objectUuid=c.uuid; GRANT ALL PRIVILEGES ON cust_view TO restricted; SET SESSION SESSION AUTHORIZATION restricted; --- SET hsadminng.currentUser TO 'alex@example.com'; -SET hsadminng.currentUser TO 'superuser-alex@hostsharing.net'; --- SET hsadminng.currentUser TO 'aaaaouq@example.com'; +-- SET hsadminng.currentSubject TO 'alex@example.com'; +SET hsadminng.currentSubject TO 'superuser-alex@hostsharing.net'; +-- SET hsadminng.currentSubject TO 'aaaaouq@example.com'; SELECT * from cust_view where reference=1144150; -select rr.uuid, rr.type from RbacGrants g - join RbacReference RR on g.ascendantUuid = RR.uuid +select rr.uuid, rr.type from rbac.RbacGrants g + join rbac.RbacReference RR on g.ascendantUuid = RR.uuid where g.descendantUuid in ( - select uuid from queryAllPermissionsOfSubjectId(findRbacUser('alex@example.com')) - where objectTable='test_customer'); + select uuid from rbac.queryAllPermissionsOfSubjectId(findRbacSubject('alex@example.com')) + where objectTable='test.customer'); -call grantRoleToUser(findRoleId('test_customer#aaa:ADMIN'), findRbacUser('aaaaouq@example.com')); +call rbac.grantRoleToUser(rbac.findRoleId('test.customer#aaa:ADMIN'), rbac.findRbacSubject('aaaaouq@example.com')); -select queryAllPermissionsOfSubjectId(findRbacUser('aaaaouq@example.com')); +select rbac.queryAllPermissionsOfSubjectId(findRbacSubject('aaaaouq@example.com')); diff --git a/sql/recursive-cte-experiments-for-accessible-uuids.sql b/sql/recursive-cte-experiments-for-accessible-uuids.sql index 5e9a7be5..84fa6e79 100644 --- a/sql/recursive-cte-experiments-for-accessible-uuids.sql +++ b/sql/recursive-cte-experiments-for-accessible-uuids.sql @@ -1,6 +1,6 @@ -- just a permanent playground to explore optimization of the central recursive CTE query for RBAC -select * from hs_statistics_view; +select * from hs_statistics_v; -- ======================================================== @@ -17,7 +17,7 @@ with recursive 1 as level, true from rbacgrants - where (rbacgrants.ascendantuuid = any (currentsubjectsuuids())) + where (rbacgrants.ascendantuuid = any (rbac.currentSubjectOrAssumedRolesUuids())) and rbacgrants.assumed union all select distinct g.descendantuuid, diff --git a/src/main/java/net/hostsharing/hsadminng/context/Context.java b/src/main/java/net/hostsharing/hsadminng/context/Context.java index b3dac96b..6ceed023 100644 --- a/src/main/java/net/hostsharing/hsadminng/context/Context.java +++ b/src/main/java/net/hostsharing/hsadminng/context/Context.java @@ -38,53 +38,53 @@ public class Context { private HttpServletRequest request; @Transactional(propagation = MANDATORY) - public void define(final String currentUser) { - define(currentUser, null); + public void define(final String currentSubject) { + define(currentSubject, null); } @Transactional(propagation = MANDATORY) - public void define(final String currentUser, final String assumedRoles) { - define(toTask(request), toCurl(request), currentUser, assumedRoles); + public void define(final String currentSubject, final String assumedRoles) { + define(toTask(request), toCurl(request), currentSubject, assumedRoles); } @Transactional(propagation = MANDATORY) public void define( final String currentTask, final String currentRequest, - final String currentUser, + final String currentSubject, final String assumedRoles) { final var query = em.createNativeQuery(""" - call defineContext( + call base.defineContext( cast(:currentTask as varchar(127)), cast(:currentRequest as text), - cast(:currentUser as varchar(63)), + cast(:currentSubject as varchar(63)), cast(:assumedRoles as varchar(1023))); """); query.setParameter("currentTask", shortenToMaxLength(currentTask, 127)); query.setParameter("currentRequest", currentRequest); - query.setParameter("currentUser", currentUser); + query.setParameter("currentSubject", currentSubject); query.setParameter("assumedRoles", assumedRoles != null ? assumedRoles : ""); query.executeUpdate(); } - public String getCurrentTask() { + public String fetchCurrentTask() { return (String) em.createNativeQuery("select current_setting('hsadminng.currentTask');").getSingleResult(); } - public String getCurrentUser() { - return String.valueOf(em.createNativeQuery("select currentUser()").getSingleResult()); + public String fetchCurrentSubject() { + return String.valueOf(em.createNativeQuery("select base.currentSubject()").getSingleResult()); } - public UUID getCurrentUserUUid() { - return (UUID) em.createNativeQuery("select currentUserUUid()", UUID.class).getSingleResult(); + public UUID fetchCurrentSubjectUuid() { + return (UUID) em.createNativeQuery("select rbac.currentSubjectUuid()", UUID.class).getSingleResult(); } - public String[] getAssumedRoles() { - return (String[]) em.createNativeQuery("select assumedRoles() as roles", String[].class).getSingleResult(); + public String[] fetchAssumedRoles() { + return (String[]) em.createNativeQuery("select base.assumedRoles() as roles", String[].class).getSingleResult(); } - public UUID[] currentSubjectsUuids() { - return (UUID[]) em.createNativeQuery("select currentSubjectsUuids() as uuids", UUID[].class).getSingleResult(); + public UUID[] fetchCurrentSubjectOrAssumedRolesUuids() { + return (UUID[]) em.createNativeQuery("select rbac.currentSubjectOrAssumedRolesUuids() as uuids", UUID[].class).getSingleResult(); } public static String getCallerMethodNameFromStackFrame(final int skipFrames) { diff --git a/src/main/java/net/hostsharing/hsadminng/hs/booking/item/HsBookingItem.java b/src/main/java/net/hostsharing/hsadminng/hs/booking/item/HsBookingItem.java index 215f7d94..7b7e2174 100644 --- a/src/main/java/net/hostsharing/hsadminng/hs/booking/item/HsBookingItem.java +++ b/src/main/java/net/hostsharing/hsadminng/hs/booking/item/HsBookingItem.java @@ -14,7 +14,7 @@ import net.hostsharing.hsadminng.hs.booking.project.HsBookingProject; import net.hostsharing.hsadminng.hs.booking.project.HsBookingProjectRealEntity; import net.hostsharing.hsadminng.hs.validation.PropertiesProvider; import net.hostsharing.hsadminng.mapper.PatchableMapWrapper; -import net.hostsharing.hsadminng.rbac.rbacobject.BaseEntity; +import net.hostsharing.hsadminng.rbac.object.BaseEntity; import net.hostsharing.hsadminng.stringify.Stringify; import net.hostsharing.hsadminng.stringify.Stringifyable; import org.hibernate.annotations.Type; diff --git a/src/main/java/net/hostsharing/hsadminng/hs/booking/item/HsBookingItemController.java b/src/main/java/net/hostsharing/hsadminng/hs/booking/item/HsBookingItemController.java index 01d2e6a5..6afd5219 100644 --- a/src/main/java/net/hostsharing/hsadminng/hs/booking/item/HsBookingItemController.java +++ b/src/main/java/net/hostsharing/hsadminng/hs/booking/item/HsBookingItemController.java @@ -41,10 +41,10 @@ public class HsBookingItemController implements HsBookingItemsApi { @Override @Transactional(readOnly = true) public ResponseEntity> listBookingItemsByProjectUuid( - final String currentUser, + final String currentSubject, final String assumedRoles, final UUID projectUuid) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var entities = bookingItemRepo.findAllByProjectUuid(projectUuid); @@ -55,11 +55,11 @@ public class HsBookingItemController implements HsBookingItemsApi { @Override @Transactional public ResponseEntity addBookingItem( - final String currentUser, + final String currentSubject, final String assumedRoles, final HsBookingItemInsertResource body) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var entityToSave = mapper.map(body, HsBookingItemRbacEntity.class, RESOURCE_TO_ENTITY_POSTMAPPER); @@ -77,11 +77,11 @@ public class HsBookingItemController implements HsBookingItemsApi { @Override @Transactional(readOnly = true) public ResponseEntity getBookingItemByUuid( - final String currentUser, + final String currentSubject, final String assumedRoles, final UUID bookingItemUuid) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var result = bookingItemRepo.findByUuid(bookingItemUuid); result.ifPresent(entity -> em.detach(entity)); // prevent further LAZY-loading @@ -94,10 +94,10 @@ public class HsBookingItemController implements HsBookingItemsApi { @Override @Transactional public ResponseEntity deleteBookingIemByUuid( - final String currentUser, + final String currentSubject, final String assumedRoles, final UUID bookingItemUuid) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var result = bookingItemRepo.deleteByUuid(bookingItemUuid); return result == 0 @@ -108,12 +108,12 @@ public class HsBookingItemController implements HsBookingItemsApi { @Override @Transactional public ResponseEntity patchBookingItem( - final String currentUser, + final String currentSubject, final String assumedRoles, final UUID bookingItemUuid, final HsBookingItemPatchResource body) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var current = bookingItemRepo.findByUuid(bookingItemUuid).orElseThrow(); diff --git a/src/main/java/net/hostsharing/hsadminng/hs/booking/item/HsBookingItemRbacEntity.java b/src/main/java/net/hostsharing/hsadminng/hs/booking/item/HsBookingItemRbacEntity.java index 5bd7b15d..b4f40cb2 100644 --- a/src/main/java/net/hostsharing/hsadminng/hs/booking/item/HsBookingItemRbacEntity.java +++ b/src/main/java/net/hostsharing/hsadminng/hs/booking/item/HsBookingItemRbacEntity.java @@ -5,8 +5,8 @@ import lombok.NoArgsConstructor; import lombok.Setter; import lombok.experimental.SuperBuilder; import net.hostsharing.hsadminng.hs.booking.project.HsBookingProject; -import net.hostsharing.hsadminng.rbac.rbacdef.RbacView; -import net.hostsharing.hsadminng.rbac.rbacdef.RbacView.SQL; +import net.hostsharing.hsadminng.rbac.generator.RbacView; +import net.hostsharing.hsadminng.rbac.generator.RbacView.SQL; import jakarta.persistence.AttributeOverride; import jakarta.persistence.AttributeOverrides; @@ -15,19 +15,20 @@ import jakarta.persistence.Entity; import jakarta.persistence.Table; import java.io.IOException; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Column.dependsOnColumn; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.ColumnValue.usingDefaultCase; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Nullable.NULLABLE; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Permission.DELETE; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Permission.INSERT; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Permission.SELECT; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Permission.UPDATE; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Role.ADMIN; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Role.AGENT; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Role.OWNER; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Role.TENANT; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.SQL.directlyFetchedByDependsOnColumn; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.rbacViewFor; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Column.dependsOnColumn; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.ColumnValue.usingDefaultCase; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.GLOBAL; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Nullable.NULLABLE; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Permission.DELETE; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Permission.INSERT; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Permission.SELECT; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Permission.UPDATE; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Role.ADMIN; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Role.AGENT; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Role.OWNER; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Role.TENANT; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.SQL.directlyFetchedByDependsOnColumn; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.rbacViewFor; @Entity @Table(name = "hs_booking_item_rv") @@ -45,8 +46,8 @@ public class HsBookingItemRbacEntity extends HsBookingItem { .withIdentityView(SQL.projection("caption")) .withRestrictedViewOrderBy(SQL.expression("validity")) .withUpdatableColumns("version", "caption", "validity", "resources") - .toRole("global", ADMIN).grantPermission(INSERT) // TODO.impl: Why is this necessary to insert test data? - .toRole("global", ADMIN).grantPermission(DELETE) + .toRole(GLOBAL, ADMIN).grantPermission(INSERT) // TODO.impl: Why is this necessary to insert test data? + .toRole(GLOBAL, ADMIN).grantPermission(DELETE) .importEntityAlias("project", HsBookingProject.class, usingDefaultCase(), dependsOnColumn("projectUuid"), @@ -74,7 +75,7 @@ public class HsBookingItemRbacEntity extends HsBookingItem { with.permission(SELECT); }) - .limitDiagramTo("bookingItem", "project", "global"); + .limitDiagramTo("bookingItem", "project", "rbac.global"); } public static void main(String[] args) throws IOException { diff --git a/src/main/java/net/hostsharing/hsadminng/hs/booking/project/HsBookingProject.java b/src/main/java/net/hostsharing/hsadminng/hs/booking/project/HsBookingProject.java index 6c109ef5..935051fe 100644 --- a/src/main/java/net/hostsharing/hsadminng/hs/booking/project/HsBookingProject.java +++ b/src/main/java/net/hostsharing/hsadminng/hs/booking/project/HsBookingProject.java @@ -5,9 +5,9 @@ import lombok.experimental.SuperBuilder; import net.hostsharing.hsadminng.hs.booking.debitor.HsBookingDebitorEntity; import net.hostsharing.hsadminng.hs.office.debitor.HsOfficeDebitorEntity; import net.hostsharing.hsadminng.hs.office.relation.HsOfficeRelationRbacEntity; -import net.hostsharing.hsadminng.rbac.rbacdef.RbacView; -import net.hostsharing.hsadminng.rbac.rbacdef.RbacView.SQL; -import net.hostsharing.hsadminng.rbac.rbacobject.BaseEntity; +import net.hostsharing.hsadminng.rbac.generator.RbacView; +import net.hostsharing.hsadminng.rbac.generator.RbacView.SQL; +import net.hostsharing.hsadminng.rbac.object.BaseEntity; import net.hostsharing.hsadminng.stringify.Stringify; import net.hostsharing.hsadminng.stringify.Stringifyable; @@ -17,15 +17,16 @@ import java.util.UUID; import static java.util.Optional.ofNullable; import static net.hostsharing.hsadminng.hs.office.relation.HsOfficeRelationType.DEBITOR; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Column.dependsOnColumn; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.ColumnValue.usingCase; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.ColumnValue.usingDefaultCase; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Nullable.NOT_NULL; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Permission.*; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Role.*; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.SQL.directlyFetchedByDependsOnColumn; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.SQL.fetchedBySql; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.rbacViewFor; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Column.dependsOnColumn; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.ColumnValue.usingCase; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.ColumnValue.usingDefaultCase; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.GLOBAL; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Nullable.NOT_NULL; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Permission.*; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Role.*; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.SQL.directlyFetchedByDependsOnColumn; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.SQL.fetchedBySql; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.rbacViewFor; import static net.hostsharing.hsadminng.stringify.Stringify.stringify; @MappedSuperclass @@ -69,7 +70,7 @@ public abstract class HsBookingProject implements Stringifyable, BaseEntity { with.incomingSuperRole("debitorRel", AGENT).unassumed(); @@ -105,7 +106,7 @@ public abstract class HsBookingProject implements Stringifyable, BaseEntity> listBookingProjectsByDebitorUuid( - final String currentUser, + final String currentSubject, final String assumedRoles, final UUID debitorUuid) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var entities = bookingProjectRepo.findAllByDebitorUuid(debitorUuid); @@ -50,11 +50,11 @@ public class HsBookingProjectController implements HsBookingProjectsApi { @Override @Transactional public ResponseEntity addBookingProject( - final String currentUser, + final String currentSubject, final String assumedRoles, final HsBookingProjectInsertResource body) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var entityToSave = mapper.map(body, HsBookingProjectRbacEntity.class, RESOURCE_TO_ENTITY_POSTMAPPER); @@ -72,11 +72,11 @@ public class HsBookingProjectController implements HsBookingProjectsApi { @Override @Transactional(readOnly = true) public ResponseEntity getBookingProjectByUuid( - final String currentUser, + final String currentSubject, final String assumedRoles, final UUID bookingProjectUuid) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var result = bookingProjectRepo.findByUuid(bookingProjectUuid); return result @@ -88,10 +88,10 @@ public class HsBookingProjectController implements HsBookingProjectsApi { @Override @Transactional public ResponseEntity deleteBookingIemByUuid( - final String currentUser, + final String currentSubject, final String assumedRoles, final UUID bookingProjectUuid) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var result = bookingProjectRepo.deleteByUuid(bookingProjectUuid); return result == 0 @@ -102,12 +102,12 @@ public class HsBookingProjectController implements HsBookingProjectsApi { @Override @Transactional public ResponseEntity patchBookingProject( - final String currentUser, + final String currentSubject, final String assumedRoles, final UUID bookingProjectUuid, final HsBookingProjectPatchResource body) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var current = bookingProjectRepo.findByUuid(bookingProjectUuid).orElseThrow(); diff --git a/src/main/java/net/hostsharing/hsadminng/hs/booking/project/HsBookingProjectRbacEntity.java b/src/main/java/net/hostsharing/hsadminng/hs/booking/project/HsBookingProjectRbacEntity.java index 50ba366a..e1fed9aa 100644 --- a/src/main/java/net/hostsharing/hsadminng/hs/booking/project/HsBookingProjectRbacEntity.java +++ b/src/main/java/net/hostsharing/hsadminng/hs/booking/project/HsBookingProjectRbacEntity.java @@ -6,29 +6,30 @@ import lombok.Setter; import lombok.experimental.SuperBuilder; import net.hostsharing.hsadminng.hs.office.debitor.HsOfficeDebitorEntity; import net.hostsharing.hsadminng.hs.office.relation.HsOfficeRelationRbacEntity; -import net.hostsharing.hsadminng.rbac.rbacdef.RbacView; -import net.hostsharing.hsadminng.rbac.rbacdef.RbacView.SQL; +import net.hostsharing.hsadminng.rbac.generator.RbacView; +import net.hostsharing.hsadminng.rbac.generator.RbacView.SQL; import jakarta.persistence.Entity; import jakarta.persistence.Table; import java.io.IOException; import static net.hostsharing.hsadminng.hs.office.relation.HsOfficeRelationType.DEBITOR; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Column.dependsOnColumn; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.ColumnValue.usingCase; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.ColumnValue.usingDefaultCase; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Nullable.NOT_NULL; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Permission.DELETE; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Permission.INSERT; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Permission.SELECT; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Permission.UPDATE; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Role.ADMIN; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Role.AGENT; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Role.OWNER; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Role.TENANT; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.SQL.directlyFetchedByDependsOnColumn; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.SQL.fetchedBySql; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.rbacViewFor; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Column.dependsOnColumn; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.ColumnValue.usingCase; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.ColumnValue.usingDefaultCase; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.GLOBAL; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Nullable.NOT_NULL; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Permission.DELETE; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Permission.INSERT; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Permission.SELECT; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Permission.UPDATE; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Role.ADMIN; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Role.AGENT; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Role.OWNER; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Role.TENANT; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.SQL.directlyFetchedByDependsOnColumn; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.SQL.fetchedBySql; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.rbacViewFor; @Entity @Table(name = "hs_booking_project_rv") @@ -41,7 +42,7 @@ public class HsBookingProjectRbacEntity extends HsBookingProject { public static RbacView rbac() { return rbacViewFor("project", HsBookingProjectRbacEntity.class) .withIdentityView(SQL.query(""" - SELECT bookingProject.uuid as uuid, debitorIV.idName || '-' || cleanIdentifier(bookingProject.caption) as idName + SELECT bookingProject.uuid as uuid, debitorIV.idName || '-' || base.cleanIdentifier(bookingProject.caption) as idName FROM hs_booking_project bookingProject JOIN hs_office_debitor_iv debitorIV ON debitorIV.uuid = bookingProject.debitorUuid """)) @@ -63,7 +64,7 @@ public class HsBookingProjectRbacEntity extends HsBookingProject { """), NOT_NULL) .toRole("debitorRel", ADMIN).grantPermission(INSERT) - .toRole("global", ADMIN).grantPermission(DELETE) + .toRole(GLOBAL, ADMIN).grantPermission(DELETE) .createRole(OWNER, (with) -> { with.incomingSuperRole("debitorRel", AGENT).unassumed(); @@ -77,7 +78,7 @@ public class HsBookingProjectRbacEntity extends HsBookingProject { with.permission(SELECT); }) - .limitDiagramTo("project", "debitorRel", "global"); + .limitDiagramTo("project", "debitorRel", "rbac.global"); } public static void main(String[] args) throws IOException { diff --git a/src/main/java/net/hostsharing/hsadminng/hs/hosting/asset/HsHostingAsset.java b/src/main/java/net/hostsharing/hsadminng/hs/hosting/asset/HsHostingAsset.java index 52e884e1..4510655c 100644 --- a/src/main/java/net/hostsharing/hsadminng/hs/hosting/asset/HsHostingAsset.java +++ b/src/main/java/net/hostsharing/hsadminng/hs/hosting/asset/HsHostingAsset.java @@ -14,7 +14,7 @@ import net.hostsharing.hsadminng.hs.booking.project.HsBookingProject; import net.hostsharing.hsadminng.hs.office.contact.HsOfficeContactRealEntity; import net.hostsharing.hsadminng.hs.validation.PropertiesProvider; import net.hostsharing.hsadminng.mapper.PatchableMapWrapper; -import net.hostsharing.hsadminng.rbac.rbacobject.BaseEntity; +import net.hostsharing.hsadminng.rbac.object.BaseEntity; import net.hostsharing.hsadminng.stringify.Stringify; import net.hostsharing.hsadminng.stringify.Stringifyable; import org.hibernate.annotations.Type; diff --git a/src/main/java/net/hostsharing/hsadminng/hs/hosting/asset/HsHostingAssetController.java b/src/main/java/net/hostsharing/hsadminng/hs/hosting/asset/HsHostingAssetController.java index 26636eb4..8973d0cc 100644 --- a/src/main/java/net/hostsharing/hsadminng/hs/hosting/asset/HsHostingAssetController.java +++ b/src/main/java/net/hostsharing/hsadminng/hs/hosting/asset/HsHostingAssetController.java @@ -49,12 +49,12 @@ public class HsHostingAssetController implements HsHostingAssetsApi { @Override @Transactional(readOnly = true) public ResponseEntity> listAssets( - final String currentUser, + final String currentSubject, final String assumedRoles, final UUID debitorUuid, final UUID parentAssetUuid, final HsHostingAssetTypeResource type) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var entities = rbacAssetRepo.findAllByCriteria(debitorUuid, parentAssetUuid, HsHostingAssetType.of(type)); @@ -66,11 +66,11 @@ public class HsHostingAssetController implements HsHostingAssetsApi { @Override @Transactional public ResponseEntity addAsset( - final String currentUser, + final String currentSubject, final String assumedRoles, final HsHostingAssetInsertResource body) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var entity = mapper.map(body, HsHostingAssetRbacEntity.class, RESOURCE_TO_ENTITY_POSTMAPPER); @@ -94,11 +94,11 @@ public class HsHostingAssetController implements HsHostingAssetsApi { @Override @Transactional(readOnly = true) public ResponseEntity getAssetByUuid( - final String currentUser, + final String currentSubject, final String assumedRoles, final UUID assetUuid) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var result = rbacAssetRepo.findByUuid(assetUuid); return result @@ -110,10 +110,10 @@ public class HsHostingAssetController implements HsHostingAssetsApi { @Override @Transactional public ResponseEntity deleteAssetUuid( - final String currentUser, + final String currentSubject, final String assumedRoles, final UUID assetUuid) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var result = rbacAssetRepo.deleteByUuid(assetUuid); return result == 0 @@ -124,12 +124,12 @@ public class HsHostingAssetController implements HsHostingAssetsApi { @Override @Transactional public ResponseEntity patchAsset( - final String currentUser, + final String currentSubject, final String assumedRoles, final UUID assetUuid, final HsHostingAssetPatchResource body) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var entity = rbacAssetRepo.findByUuid(assetUuid).orElseThrow(); diff --git a/src/main/java/net/hostsharing/hsadminng/hs/hosting/asset/HsHostingAssetRbacEntity.java b/src/main/java/net/hostsharing/hsadminng/hs/hosting/asset/HsHostingAssetRbacEntity.java index be568944..da011cdf 100644 --- a/src/main/java/net/hostsharing/hsadminng/hs/hosting/asset/HsHostingAssetRbacEntity.java +++ b/src/main/java/net/hostsharing/hsadminng/hs/hosting/asset/HsHostingAssetRbacEntity.java @@ -6,31 +6,31 @@ import lombok.Setter; import lombok.experimental.SuperBuilder; import net.hostsharing.hsadminng.hs.booking.item.HsBookingItem; import net.hostsharing.hsadminng.hs.office.contact.HsOfficeContactRbacEntity; -import net.hostsharing.hsadminng.rbac.rbacdef.RbacView; -import net.hostsharing.hsadminng.rbac.rbacdef.RbacView.SQL; +import net.hostsharing.hsadminng.rbac.generator.RbacView; +import net.hostsharing.hsadminng.rbac.generator.RbacView.SQL; import jakarta.persistence.Entity; import jakarta.persistence.Table; import java.io.IOException; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.CaseDef.inCaseOf; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Column.dependsOnColumn; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.ColumnValue.usingDefaultCase; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.GLOBAL; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Nullable.NULLABLE; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Permission.DELETE; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Permission.INSERT; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Permission.SELECT; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Permission.UPDATE; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.RbacUserReference.UserRole.CREATOR; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Role.ADMIN; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Role.AGENT; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Role.GUEST; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Role.OWNER; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Role.REFERRER; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Role.TENANT; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.SQL.directlyFetchedByDependsOnColumn; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.rbacViewFor; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.CaseDef.inCaseOf; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Column.dependsOnColumn; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.ColumnValue.usingDefaultCase; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.GLOBAL; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Nullable.NULLABLE; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Permission.DELETE; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Permission.INSERT; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Permission.SELECT; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Permission.UPDATE; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.RbacSubjectReference.UserRole.CREATOR; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Role.ADMIN; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Role.AGENT; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Role.GUEST; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Role.OWNER; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Role.REFERRER; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Role.TENANT; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.SQL.directlyFetchedByDependsOnColumn; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.rbacViewFor; @Entity @Table(name = "hs_hosting_asset_rv") @@ -106,7 +106,7 @@ public class HsHostingAssetRbacEntity extends HsHostingAsset { "parentAsset", "assignedToAsset", "alarmContact", - "global"); + "rbac.global"); } public static void main(String[] args) throws IOException { diff --git a/src/main/java/net/hostsharing/hsadminng/hs/office/bankaccount/HsOfficeBankAccountController.java b/src/main/java/net/hostsharing/hsadminng/hs/office/bankaccount/HsOfficeBankAccountController.java index 9f39767f..50183bf7 100644 --- a/src/main/java/net/hostsharing/hsadminng/hs/office/bankaccount/HsOfficeBankAccountController.java +++ b/src/main/java/net/hostsharing/hsadminng/hs/office/bankaccount/HsOfficeBankAccountController.java @@ -32,10 +32,10 @@ public class HsOfficeBankAccountController implements HsOfficeBankAccountsApi { @Override @Transactional(readOnly = true) public ResponseEntity> listBankAccounts( - final String currentUser, + final String currentSubject, final String assumedRoles, final String holder) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var entities = bankAccountRepo.findByOptionalHolderLike(holder); @@ -46,11 +46,11 @@ public class HsOfficeBankAccountController implements HsOfficeBankAccountsApi { @Override @Transactional public ResponseEntity addBankAccount( - final String currentUser, + final String currentSubject, final String assumedRoles, final HsOfficeBankAccountInsertResource body) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); IbanUtil.validate(body.getIban()); BicUtil.validate(body.getBic()); @@ -72,11 +72,11 @@ public class HsOfficeBankAccountController implements HsOfficeBankAccountsApi { @Override @Transactional(readOnly = true) public ResponseEntity getBankAccountByUuid( - final String currentUser, + final String currentSubject, final String assumedRoles, final UUID bankAccountUuid) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var result = bankAccountRepo.findByUuid(bankAccountUuid); if (result.isEmpty()) { @@ -88,10 +88,10 @@ public class HsOfficeBankAccountController implements HsOfficeBankAccountsApi { @Override @Transactional public ResponseEntity deleteBankAccountByUuid( - final String currentUser, + final String currentSubject, final String assumedRoles, final UUID BankAccountUuid) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var result = bankAccountRepo.deleteByUuid(BankAccountUuid); if (result == 0) { diff --git a/src/main/java/net/hostsharing/hsadminng/hs/office/bankaccount/HsOfficeBankAccountEntity.java b/src/main/java/net/hostsharing/hsadminng/hs/office/bankaccount/HsOfficeBankAccountEntity.java index 94fe2b16..06026420 100644 --- a/src/main/java/net/hostsharing/hsadminng/hs/office/bankaccount/HsOfficeBankAccountEntity.java +++ b/src/main/java/net/hostsharing/hsadminng/hs/office/bankaccount/HsOfficeBankAccountEntity.java @@ -3,8 +3,8 @@ package net.hostsharing.hsadminng.hs.office.bankaccount; import lombok.*; import lombok.experimental.FieldNameConstants; import net.hostsharing.hsadminng.errors.DisplayAs; -import net.hostsharing.hsadminng.rbac.rbacobject.BaseEntity; -import net.hostsharing.hsadminng.rbac.rbacdef.RbacView; +import net.hostsharing.hsadminng.rbac.object.BaseEntity; +import net.hostsharing.hsadminng.rbac.generator.RbacView; import net.hostsharing.hsadminng.stringify.Stringify; import net.hostsharing.hsadminng.stringify.Stringifyable; @@ -12,10 +12,10 @@ import jakarta.persistence.*; import java.io.IOException; import java.util.UUID; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.*; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Permission.*; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.RbacUserReference.UserRole.CREATOR; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Role.*; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.*; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Permission.*; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.RbacSubjectReference.UserRole.CREATOR; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Role.*; import static net.hostsharing.hsadminng.stringify.Stringify.stringify; @Entity @@ -62,7 +62,7 @@ public class HsOfficeBankAccountEntity implements BaseEntity { with.owningUser(CREATOR); diff --git a/src/main/java/net/hostsharing/hsadminng/hs/office/contact/HsOfficeContact.java b/src/main/java/net/hostsharing/hsadminng/hs/office/contact/HsOfficeContact.java index 9450e331..196e2d40 100644 --- a/src/main/java/net/hostsharing/hsadminng/hs/office/contact/HsOfficeContact.java +++ b/src/main/java/net/hostsharing/hsadminng/hs/office/contact/HsOfficeContact.java @@ -11,7 +11,7 @@ import lombok.experimental.FieldNameConstants; import lombok.experimental.SuperBuilder; import net.hostsharing.hsadminng.errors.DisplayAs; import net.hostsharing.hsadminng.mapper.PatchableMapWrapper; -import net.hostsharing.hsadminng.rbac.rbacobject.BaseEntity; +import net.hostsharing.hsadminng.rbac.object.BaseEntity; import net.hostsharing.hsadminng.stringify.Stringify; import net.hostsharing.hsadminng.stringify.Stringifyable; import org.hibernate.annotations.GenericGenerator; diff --git a/src/main/java/net/hostsharing/hsadminng/hs/office/contact/HsOfficeContactController.java b/src/main/java/net/hostsharing/hsadminng/hs/office/contact/HsOfficeContactController.java index cee7e28a..17d39b7f 100644 --- a/src/main/java/net/hostsharing/hsadminng/hs/office/contact/HsOfficeContactController.java +++ b/src/main/java/net/hostsharing/hsadminng/hs/office/contact/HsOfficeContactController.java @@ -34,10 +34,10 @@ public class HsOfficeContactController implements HsOfficeContactsApi { @Override @Transactional(readOnly = true) public ResponseEntity> listContacts( - final String currentUser, + final String currentSubject, final String assumedRoles, final String caption) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var entities = contactRepo.findContactByOptionalCaptionLike(caption); @@ -48,11 +48,11 @@ public class HsOfficeContactController implements HsOfficeContactsApi { @Override @Transactional public ResponseEntity addContact( - final String currentUser, + final String currentSubject, final String assumedRoles, final HsOfficeContactInsertResource body) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var entityToSave = mapper.map(body, HsOfficeContactRbacEntity.class, RESOURCE_TO_ENTITY_POSTMAPPER); @@ -70,11 +70,11 @@ public class HsOfficeContactController implements HsOfficeContactsApi { @Override @Transactional(readOnly = true) public ResponseEntity getContactByUuid( - final String currentUser, + final String currentSubject, final String assumedRoles, final UUID contactUuid) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var result = contactRepo.findByUuid(contactUuid); if (result.isEmpty()) { @@ -86,10 +86,10 @@ public class HsOfficeContactController implements HsOfficeContactsApi { @Override @Transactional public ResponseEntity deleteContactByUuid( - final String currentUser, + final String currentSubject, final String assumedRoles, final UUID contactUuid) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var result = contactRepo.deleteByUuid(contactUuid); if (result == 0) { @@ -102,12 +102,12 @@ public class HsOfficeContactController implements HsOfficeContactsApi { @Override @Transactional public ResponseEntity patchContact( - final String currentUser, + final String currentSubject, final String assumedRoles, final UUID contactUuid, final HsOfficeContactPatchResource body) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var current = contactRepo.findByUuid(contactUuid).orElseThrow(); diff --git a/src/main/java/net/hostsharing/hsadminng/hs/office/contact/HsOfficeContactRbacEntity.java b/src/main/java/net/hostsharing/hsadminng/hs/office/contact/HsOfficeContactRbacEntity.java index c4e934cc..39b51d0d 100644 --- a/src/main/java/net/hostsharing/hsadminng/hs/office/contact/HsOfficeContactRbacEntity.java +++ b/src/main/java/net/hostsharing/hsadminng/hs/office/contact/HsOfficeContactRbacEntity.java @@ -3,17 +3,17 @@ package net.hostsharing.hsadminng.hs.office.contact; import lombok.*; import lombok.experimental.SuperBuilder; import net.hostsharing.hsadminng.errors.DisplayAs; -import net.hostsharing.hsadminng.rbac.rbacdef.RbacView; -import net.hostsharing.hsadminng.rbac.rbacdef.RbacView.SQL; +import net.hostsharing.hsadminng.rbac.generator.RbacView; +import net.hostsharing.hsadminng.rbac.generator.RbacView.SQL; import jakarta.persistence.*; import java.io.IOException; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.GLOBAL; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Permission.*; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.RbacUserReference.UserRole.CREATOR; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Role.*; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.rbacViewFor; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.GLOBAL; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Permission.*; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.RbacSubjectReference.UserRole.CREATOR; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Role.*; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.rbacViewFor; @Entity @Table(name = "hs_office_contact_rv") diff --git a/src/main/java/net/hostsharing/hsadminng/hs/office/coopassets/HsOfficeCoopAssetsTransactionController.java b/src/main/java/net/hostsharing/hsadminng/hs/office/coopassets/HsOfficeCoopAssetsTransactionController.java index 8ec1d956..f4cb28a3 100644 --- a/src/main/java/net/hostsharing/hsadminng/hs/office/coopassets/HsOfficeCoopAssetsTransactionController.java +++ b/src/main/java/net/hostsharing/hsadminng/hs/office/coopassets/HsOfficeCoopAssetsTransactionController.java @@ -37,12 +37,12 @@ public class HsOfficeCoopAssetsTransactionController implements HsOfficeCoopAsse @Override @Transactional(readOnly = true) public ResponseEntity> listCoopAssets( - final String currentUser, + final String currentSubject, final String assumedRoles, final UUID membershipUuid, final @DateTimeFormat(iso = ISO.DATE) LocalDate fromValueDate, final @DateTimeFormat(iso = ISO.DATE) LocalDate toValueDate) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var entities = coopAssetsTransactionRepo.findCoopAssetsTransactionByOptionalMembershipUuidAndDateRange( membershipUuid, @@ -56,11 +56,11 @@ public class HsOfficeCoopAssetsTransactionController implements HsOfficeCoopAsse @Override @Transactional public ResponseEntity addCoopAssetsTransaction( - final String currentUser, + final String currentSubject, final String assumedRoles, final HsOfficeCoopAssetsTransactionInsertResource requestBody) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); validate(requestBody); final var entityToSave = mapper.map(requestBody, HsOfficeCoopAssetsTransactionEntity.class, RESOURCE_TO_ENTITY_POSTMAPPER); @@ -79,9 +79,9 @@ public class HsOfficeCoopAssetsTransactionController implements HsOfficeCoopAsse @Transactional(readOnly = true) public ResponseEntity getCoopAssetTransactionByUuid( - final String currentUser, final String assumedRoles, final UUID assetTransactionUuid) { + final String currentSubject, final String assumedRoles, final UUID assetTransactionUuid) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var result = coopAssetsTransactionRepo.findByUuid(assetTransactionUuid); if (result.isEmpty()) { diff --git a/src/main/java/net/hostsharing/hsadminng/hs/office/coopassets/HsOfficeCoopAssetsTransactionEntity.java b/src/main/java/net/hostsharing/hsadminng/hs/office/coopassets/HsOfficeCoopAssetsTransactionEntity.java index 49487cd8..aecafaba 100644 --- a/src/main/java/net/hostsharing/hsadminng/hs/office/coopassets/HsOfficeCoopAssetsTransactionEntity.java +++ b/src/main/java/net/hostsharing/hsadminng/hs/office/coopassets/HsOfficeCoopAssetsTransactionEntity.java @@ -8,8 +8,8 @@ import lombok.NoArgsConstructor; import lombok.Setter; import net.hostsharing.hsadminng.errors.DisplayAs; import net.hostsharing.hsadminng.hs.office.membership.HsOfficeMembershipEntity; -import net.hostsharing.hsadminng.rbac.rbacobject.BaseEntity; -import net.hostsharing.hsadminng.rbac.rbacdef.RbacView; +import net.hostsharing.hsadminng.rbac.object.BaseEntity; +import net.hostsharing.hsadminng.rbac.generator.RbacView; import net.hostsharing.hsadminng.stringify.Stringify; import net.hostsharing.hsadminng.stringify.Stringifyable; import org.hibernate.annotations.GenericGenerator; @@ -21,16 +21,16 @@ import java.time.LocalDate; import java.util.UUID; import static java.util.Optional.ofNullable; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Column.dependsOnColumn; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.ColumnValue.usingDefaultCase; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Nullable.NOT_NULL; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Permission.INSERT; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Permission.SELECT; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Permission.UPDATE; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Role.ADMIN; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Role.AGENT; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.SQL.directlyFetchedByDependsOnColumn; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.rbacViewFor; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Column.dependsOnColumn; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.ColumnValue.usingDefaultCase; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Nullable.NOT_NULL; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Permission.INSERT; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Permission.SELECT; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Permission.UPDATE; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Role.ADMIN; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Role.AGENT; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.SQL.directlyFetchedByDependsOnColumn; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.rbacViewFor; import static net.hostsharing.hsadminng.stringify.Stringify.stringify; @Entity diff --git a/src/main/java/net/hostsharing/hsadminng/hs/office/coopshares/HsOfficeCoopSharesTransactionController.java b/src/main/java/net/hostsharing/hsadminng/hs/office/coopshares/HsOfficeCoopSharesTransactionController.java index 78b41c9f..1616568d 100644 --- a/src/main/java/net/hostsharing/hsadminng/hs/office/coopshares/HsOfficeCoopSharesTransactionController.java +++ b/src/main/java/net/hostsharing/hsadminng/hs/office/coopshares/HsOfficeCoopSharesTransactionController.java @@ -39,12 +39,12 @@ public class HsOfficeCoopSharesTransactionController implements HsOfficeCoopShar @Override @Transactional(readOnly = true) public ResponseEntity> listCoopShares( - final String currentUser, + final String currentSubject, final String assumedRoles, final UUID membershipUuid, final @DateTimeFormat(iso = ISO.DATE) LocalDate fromValueDate, final @DateTimeFormat(iso = ISO.DATE) LocalDate toValueDate) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var entities = coopSharesTransactionRepo.findCoopSharesTransactionByOptionalMembershipUuidAndDateRange( membershipUuid, @@ -58,11 +58,11 @@ public class HsOfficeCoopSharesTransactionController implements HsOfficeCoopShar @Override @Transactional public ResponseEntity addCoopSharesTransaction( - final String currentUser, + final String currentSubject, final String assumedRoles, final HsOfficeCoopSharesTransactionInsertResource requestBody) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); validate(requestBody); final var entityToSave = mapper.map(requestBody, HsOfficeCoopSharesTransactionEntity.class, RESOURCE_TO_ENTITY_POSTMAPPER); @@ -81,9 +81,9 @@ public class HsOfficeCoopSharesTransactionController implements HsOfficeCoopShar @Override @Transactional(readOnly = true) public ResponseEntity getCoopShareTransactionByUuid( - final String currentUser, final String assumedRoles, final UUID shareTransactionUuid) { + final String currentSubject, final String assumedRoles, final UUID shareTransactionUuid) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var result = coopSharesTransactionRepo.findByUuid(shareTransactionUuid); if (result.isEmpty()) { diff --git a/src/main/java/net/hostsharing/hsadminng/hs/office/coopshares/HsOfficeCoopSharesTransactionEntity.java b/src/main/java/net/hostsharing/hsadminng/hs/office/coopshares/HsOfficeCoopSharesTransactionEntity.java index aa650bd5..2d96af52 100644 --- a/src/main/java/net/hostsharing/hsadminng/hs/office/coopshares/HsOfficeCoopSharesTransactionEntity.java +++ b/src/main/java/net/hostsharing/hsadminng/hs/office/coopshares/HsOfficeCoopSharesTransactionEntity.java @@ -7,9 +7,9 @@ import lombok.NoArgsConstructor; import lombok.Setter; import net.hostsharing.hsadminng.errors.DisplayAs; import net.hostsharing.hsadminng.hs.office.membership.HsOfficeMembershipEntity; -import net.hostsharing.hsadminng.rbac.rbacdef.RbacView; -import net.hostsharing.hsadminng.rbac.rbacobject.BaseEntity; -import net.hostsharing.hsadminng.rbac.rbacdef.RbacView.SQL; +import net.hostsharing.hsadminng.rbac.generator.RbacView; +import net.hostsharing.hsadminng.rbac.object.BaseEntity; +import net.hostsharing.hsadminng.rbac.generator.RbacView.SQL; import net.hostsharing.hsadminng.stringify.Stringify; import net.hostsharing.hsadminng.stringify.Stringifyable; @@ -19,16 +19,16 @@ import java.time.LocalDate; import java.util.UUID; import static java.util.Optional.ofNullable; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Column.dependsOnColumn; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.ColumnValue.usingDefaultCase; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Nullable.NOT_NULL; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Permission.INSERT; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Permission.SELECT; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Permission.UPDATE; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Role.ADMIN; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Role.AGENT; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.SQL.directlyFetchedByDependsOnColumn; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.rbacViewFor; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Column.dependsOnColumn; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.ColumnValue.usingDefaultCase; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Nullable.NOT_NULL; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Permission.INSERT; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Permission.SELECT; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Permission.UPDATE; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Role.ADMIN; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Role.AGENT; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.SQL.directlyFetchedByDependsOnColumn; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.rbacViewFor; import static net.hostsharing.hsadminng.stringify.Stringify.stringify; @Entity diff --git a/src/main/java/net/hostsharing/hsadminng/hs/office/debitor/HsOfficeDebitorController.java b/src/main/java/net/hostsharing/hsadminng/hs/office/debitor/HsOfficeDebitorController.java index 73fe78af..fd8412c8 100644 --- a/src/main/java/net/hostsharing/hsadminng/hs/office/debitor/HsOfficeDebitorController.java +++ b/src/main/java/net/hostsharing/hsadminng/hs/office/debitor/HsOfficeDebitorController.java @@ -8,7 +8,7 @@ import net.hostsharing.hsadminng.hs.office.generated.api.v1.model.HsOfficeDebito import net.hostsharing.hsadminng.hs.office.relation.HsOfficeRelationRealEntity; import net.hostsharing.hsadminng.hs.office.relation.HsOfficeRelationRealRepository; import net.hostsharing.hsadminng.mapper.Mapper; -import net.hostsharing.hsadminng.rbac.rbacobject.BaseEntity; +import net.hostsharing.hsadminng.rbac.object.BaseEntity; import org.apache.commons.lang3.Validate; import org.hibernate.Hibernate; import org.springframework.beans.factory.annotation.Autowired; @@ -48,11 +48,11 @@ public class HsOfficeDebitorController implements HsOfficeDebitorsApi { @Override @Transactional(readOnly = true) public ResponseEntity> listDebitors( - final String currentUser, + final String currentSubject, final String assumedRoles, final String name, final Integer debitorNumber) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var entities = debitorNumber != null ? debitorRepo.findDebitorByDebitorNumber(debitorNumber) @@ -65,11 +65,11 @@ public class HsOfficeDebitorController implements HsOfficeDebitorsApi { @Override @Transactional public ResponseEntity addDebitor( - String currentUser, + String currentSubject, String assumedRoles, HsOfficeDebitorInsertResource body) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); Validate.isTrue(body.getDebitorRel() == null || body.getDebitorRelUuid() == null, "ERROR: [400] exactly one of debitorRel and debitorRelUuid must be supplied, but found both"); @@ -112,11 +112,11 @@ public class HsOfficeDebitorController implements HsOfficeDebitorsApi { @Override @Transactional(readOnly = true) public ResponseEntity getDebitorByUuid( - final String currentUser, + final String currentSubject, final String assumedRoles, final UUID debitorUuid) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var result = debitorRepo.findByUuid(debitorUuid); if (result.isEmpty()) { @@ -128,10 +128,10 @@ public class HsOfficeDebitorController implements HsOfficeDebitorsApi { @Override @Transactional public ResponseEntity deleteDebitorByUuid( - final String currentUser, + final String currentSubject, final String assumedRoles, final UUID debitorUuid) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var result = debitorRepo.deleteByUuid(debitorUuid); if (result == 0) { @@ -144,12 +144,12 @@ public class HsOfficeDebitorController implements HsOfficeDebitorsApi { @Override @Transactional public ResponseEntity patchDebitor( - final String currentUser, + final String currentSubject, final String assumedRoles, final UUID debitorUuid, final HsOfficeDebitorPatchResource body) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var current = debitorRepo.findByUuid(debitorUuid).orElseThrow(); diff --git a/src/main/java/net/hostsharing/hsadminng/hs/office/debitor/HsOfficeDebitorEntity.java b/src/main/java/net/hostsharing/hsadminng/hs/office/debitor/HsOfficeDebitorEntity.java index 192f3f2e..e0d9493e 100644 --- a/src/main/java/net/hostsharing/hsadminng/hs/office/debitor/HsOfficeDebitorEntity.java +++ b/src/main/java/net/hostsharing/hsadminng/hs/office/debitor/HsOfficeDebitorEntity.java @@ -11,9 +11,9 @@ import net.hostsharing.hsadminng.hs.office.partner.HsOfficePartnerEntity; import net.hostsharing.hsadminng.hs.office.relation.HsOfficeRelation; import net.hostsharing.hsadminng.hs.office.relation.HsOfficeRelationRealEntity; import net.hostsharing.hsadminng.hs.office.relation.HsOfficeRelationRbacEntity; -import net.hostsharing.hsadminng.rbac.rbacobject.BaseEntity; -import net.hostsharing.hsadminng.rbac.rbacdef.RbacView; -import net.hostsharing.hsadminng.rbac.rbacdef.RbacView.SQL; +import net.hostsharing.hsadminng.rbac.object.BaseEntity; +import net.hostsharing.hsadminng.rbac.generator.RbacView; +import net.hostsharing.hsadminng.rbac.generator.RbacView.SQL; import net.hostsharing.hsadminng.stringify.Stringify; import net.hostsharing.hsadminng.stringify.Stringifyable; import org.hibernate.annotations.GenericGenerator; @@ -40,16 +40,17 @@ import static jakarta.persistence.CascadeType.PERSIST; import static jakarta.persistence.CascadeType.REFRESH; import static java.util.Optional.ofNullable; import static net.hostsharing.hsadminng.hs.office.relation.HsOfficeRelationType.DEBITOR; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Column.dependsOnColumn; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.ColumnValue.usingCase; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.ColumnValue.usingDefaultCase; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Nullable.NOT_NULL; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Nullable.NULLABLE; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Permission.*; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Role.*; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.SQL.directlyFetchedByDependsOnColumn; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.SQL.fetchedBySql; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.rbacViewFor; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Column.dependsOnColumn; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.ColumnValue.usingCase; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.ColumnValue.usingDefaultCase; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.GLOBAL; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Nullable.NOT_NULL; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Nullable.NULLABLE; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Permission.*; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Role.*; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.SQL.directlyFetchedByDependsOnColumn; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.SQL.fetchedBySql; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.rbacViewFor; import static net.hostsharing.hsadminng.stringify.Stringify.stringify; @Entity @@ -188,7 +189,7 @@ public class HsOfficeDebitorEntity implements BaseEntity, "vatBusiness", "vatReverseCharge", "defaultPrefix") - .toRole("global", ADMIN).grantPermission(INSERT) + .toRole(GLOBAL, ADMIN).grantPermission(INSERT) .importRootEntityAliasProxy("debitorRel", HsOfficeRelationRbacEntity.class, usingCase(DEBITOR), directlyFetchedByDependsOnColumn(), diff --git a/src/main/java/net/hostsharing/hsadminng/hs/office/membership/HsOfficeMembershipController.java b/src/main/java/net/hostsharing/hsadminng/hs/office/membership/HsOfficeMembershipController.java index 3c783aae..8c87e5fa 100644 --- a/src/main/java/net/hostsharing/hsadminng/hs/office/membership/HsOfficeMembershipController.java +++ b/src/main/java/net/hostsharing/hsadminng/hs/office/membership/HsOfficeMembershipController.java @@ -32,11 +32,11 @@ public class HsOfficeMembershipController implements HsOfficeMembershipsApi { @Override @Transactional(readOnly = true) public ResponseEntity> listMemberships( - final String currentUser, + final String currentSubject, final String assumedRoles, UUID partnerUuid, Integer memberNumber) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var entities = ( memberNumber != null) ? List.of(membershipRepo.findMembershipByMemberNumber(memberNumber)) @@ -50,11 +50,11 @@ public class HsOfficeMembershipController implements HsOfficeMembershipsApi { @Override @Transactional public ResponseEntity addMembership( - final String currentUser, + final String currentSubject, final String assumedRoles, final HsOfficeMembershipInsertResource body) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var entityToSave = mapper.map(body, HsOfficeMembershipEntity.class); @@ -73,11 +73,11 @@ public class HsOfficeMembershipController implements HsOfficeMembershipsApi { @Override @Transactional(readOnly = true) public ResponseEntity getMembershipByUuid( - final String currentUser, + final String currentSubject, final String assumedRoles, final UUID membershipUuid) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var result = membershipRepo.findByUuid(membershipUuid); if (result.isEmpty()) { @@ -90,10 +90,10 @@ public class HsOfficeMembershipController implements HsOfficeMembershipsApi { @Override @Transactional public ResponseEntity deleteMembershipByUuid( - final String currentUser, + final String currentSubject, final String assumedRoles, final UUID membershipUuid) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var result = membershipRepo.deleteByUuid(membershipUuid); if (result == 0) { @@ -106,12 +106,12 @@ public class HsOfficeMembershipController implements HsOfficeMembershipsApi { @Override @Transactional public ResponseEntity patchMembership( - final String currentUser, + final String currentSubject, final String assumedRoles, final UUID membershipUuid, final HsOfficeMembershipPatchResource body) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var current = membershipRepo.findByUuid(membershipUuid).orElseThrow(); diff --git a/src/main/java/net/hostsharing/hsadminng/hs/office/membership/HsOfficeMembershipEntity.java b/src/main/java/net/hostsharing/hsadminng/hs/office/membership/HsOfficeMembershipEntity.java index 9d05f5f9..dae389f8 100644 --- a/src/main/java/net/hostsharing/hsadminng/hs/office/membership/HsOfficeMembershipEntity.java +++ b/src/main/java/net/hostsharing/hsadminng/hs/office/membership/HsOfficeMembershipEntity.java @@ -9,10 +9,10 @@ import lombok.NoArgsConstructor; import lombok.Setter; import net.hostsharing.hsadminng.errors.DisplayAs; import net.hostsharing.hsadminng.hs.office.relation.HsOfficeRelationRbacEntity; -import net.hostsharing.hsadminng.rbac.rbacobject.BaseEntity; +import net.hostsharing.hsadminng.rbac.object.BaseEntity; import net.hostsharing.hsadminng.hs.office.partner.HsOfficePartnerEntity; -import net.hostsharing.hsadminng.rbac.rbacdef.RbacView; -import net.hostsharing.hsadminng.rbac.rbacdef.RbacView.SQL; +import net.hostsharing.hsadminng.rbac.generator.RbacView; +import net.hostsharing.hsadminng.rbac.generator.RbacView.SQL; import net.hostsharing.hsadminng.stringify.Stringify; import net.hostsharing.hsadminng.stringify.Stringifyable; import org.hibernate.annotations.Type; @@ -38,20 +38,21 @@ import static io.hypersistence.utils.hibernate.type.range.Range.emptyRange; import static net.hostsharing.hsadminng.mapper.PostgresDateRange.lowerInclusiveFromPostgresDateRange; import static net.hostsharing.hsadminng.mapper.PostgresDateRange.toPostgresDateRange; import static net.hostsharing.hsadminng.mapper.PostgresDateRange.upperInclusiveFromPostgresDateRange; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Column.dependsOnColumn; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.ColumnValue.usingDefaultCase; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Nullable.NOT_NULL; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Permission.DELETE; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Permission.INSERT; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Permission.SELECT; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Permission.UPDATE; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.RbacUserReference.UserRole.CREATOR; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Role.ADMIN; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Role.AGENT; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Role.OWNER; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Role.TENANT; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.SQL.fetchedBySql; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.rbacViewFor; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Column.dependsOnColumn; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.ColumnValue.usingDefaultCase; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.GLOBAL; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Nullable.NOT_NULL; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Permission.DELETE; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Permission.INSERT; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Permission.SELECT; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Permission.UPDATE; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.RbacSubjectReference.UserRole.CREATOR; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Role.ADMIN; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Role.AGENT; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Role.OWNER; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Role.TENANT; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.SQL.fetchedBySql; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.rbacViewFor; import static net.hostsharing.hsadminng.stringify.Stringify.stringify; @Entity @@ -174,7 +175,7 @@ public class HsOfficeMembershipEntity implements BaseEntity { with.owningUser(CREATOR); diff --git a/src/main/java/net/hostsharing/hsadminng/hs/office/partner/HsOfficePartnerController.java b/src/main/java/net/hostsharing/hsadminng/hs/office/partner/HsOfficePartnerController.java index 5965d990..b4b8bd75 100644 --- a/src/main/java/net/hostsharing/hsadminng/hs/office/partner/HsOfficePartnerController.java +++ b/src/main/java/net/hostsharing/hsadminng/hs/office/partner/HsOfficePartnerController.java @@ -13,7 +13,7 @@ import net.hostsharing.hsadminng.hs.office.relation.HsOfficeRelationRealEntity; import net.hostsharing.hsadminng.hs.office.relation.HsOfficeRelationRealRepository; import net.hostsharing.hsadminng.hs.office.relation.HsOfficeRelationType; import net.hostsharing.hsadminng.mapper.Mapper; -import net.hostsharing.hsadminng.rbac.rbacobject.BaseEntity; +import net.hostsharing.hsadminng.rbac.object.BaseEntity; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -50,10 +50,10 @@ public class HsOfficePartnerController implements HsOfficePartnersApi { @Override @Transactional(readOnly = true) public ResponseEntity> listPartners( - final String currentUser, + final String currentSubject, final String assumedRoles, final String name) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var entities = partnerRepo.findPartnerByOptionalNameLike(name); @@ -64,11 +64,11 @@ public class HsOfficePartnerController implements HsOfficePartnersApi { @Override @Transactional public ResponseEntity addPartner( - final String currentUser, + final String currentSubject, final String assumedRoles, final HsOfficePartnerInsertResource body) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var entityToSave = createPartnerEntity(body); @@ -86,11 +86,11 @@ public class HsOfficePartnerController implements HsOfficePartnersApi { @Override @Transactional(readOnly = true) public ResponseEntity getPartnerByUuid( - final String currentUser, + final String currentSubject, final String assumedRoles, final UUID partnerUuid) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var result = partnerRepo.findByUuid(partnerUuid); if (result.isEmpty()) { @@ -102,10 +102,10 @@ public class HsOfficePartnerController implements HsOfficePartnersApi { @Override @Transactional public ResponseEntity deletePartnerByUuid( - final String currentUser, + final String currentSubject, final String assumedRoles, final UUID partnerUuid) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var partnerToDelete = partnerRepo.findByUuid(partnerUuid); if (partnerToDelete.isEmpty()) { @@ -122,12 +122,12 @@ public class HsOfficePartnerController implements HsOfficePartnersApi { @Override @Transactional public ResponseEntity patchPartner( - final String currentUser, + final String currentSubject, final String assumedRoles, final UUID partnerUuid, final HsOfficePartnerPatchResource body) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var current = partnerRepo.findByUuid(partnerUuid).orElseThrow(); final var previousPartnerRel = current.getPartnerRel(); diff --git a/src/main/java/net/hostsharing/hsadminng/hs/office/partner/HsOfficePartnerDetailsEntity.java b/src/main/java/net/hostsharing/hsadminng/hs/office/partner/HsOfficePartnerDetailsEntity.java index 1ef8cb8f..0da0323d 100644 --- a/src/main/java/net/hostsharing/hsadminng/hs/office/partner/HsOfficePartnerDetailsEntity.java +++ b/src/main/java/net/hostsharing/hsadminng/hs/office/partner/HsOfficePartnerDetailsEntity.java @@ -2,9 +2,9 @@ package net.hostsharing.hsadminng.hs.office.partner; import lombok.*; import net.hostsharing.hsadminng.errors.DisplayAs; -import net.hostsharing.hsadminng.rbac.rbacobject.BaseEntity; -import net.hostsharing.hsadminng.rbac.rbacdef.RbacView; -import net.hostsharing.hsadminng.rbac.rbacdef.RbacView.SQL; +import net.hostsharing.hsadminng.rbac.object.BaseEntity; +import net.hostsharing.hsadminng.rbac.generator.RbacView; +import net.hostsharing.hsadminng.rbac.generator.RbacView.SQL; import net.hostsharing.hsadminng.stringify.Stringify; import net.hostsharing.hsadminng.stringify.Stringifyable; @@ -13,9 +13,10 @@ import java.io.IOException; import java.time.LocalDate; import java.util.UUID; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Permission.*; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Role.*; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.rbacViewFor; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.GLOBAL; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Permission.*; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Role.*; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.rbacViewFor; import static net.hostsharing.hsadminng.stringify.Stringify.stringify; @Entity @@ -82,7 +83,7 @@ public class HsOfficePartnerDetailsEntity implements BaseEntity> listPersons( - final String currentUser, + final String currentSubject, final String assumedRoles, final String caption) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var entities = personRepo.findPersonByOptionalNameLike(caption); @@ -45,11 +45,11 @@ public class HsOfficePersonController implements HsOfficePersonsApi { @Override @Transactional public ResponseEntity addPerson( - final String currentUser, + final String currentSubject, final String assumedRoles, final HsOfficePersonInsertResource body) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var entityToSave = mapper.map(body, HsOfficePersonEntity.class); @@ -67,11 +67,11 @@ public class HsOfficePersonController implements HsOfficePersonsApi { @Override @Transactional(readOnly = true) public ResponseEntity getPersonByUuid( - final String currentUser, + final String currentSubject, final String assumedRoles, final UUID personUuid) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var result = personRepo.findByUuid(personUuid); if (result.isEmpty()) { @@ -83,10 +83,10 @@ public class HsOfficePersonController implements HsOfficePersonsApi { @Override @Transactional public ResponseEntity deletePersonByUuid( - final String currentUser, + final String currentSubject, final String assumedRoles, final UUID personUuid) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var result = personRepo.deleteByUuid(personUuid); if (result == 0) { @@ -99,12 +99,12 @@ public class HsOfficePersonController implements HsOfficePersonsApi { @Override @Transactional public ResponseEntity patchPerson( - final String currentUser, + final String currentSubject, final String assumedRoles, final UUID personUuid, final HsOfficePersonPatchResource body) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var current = personRepo.findByUuid(personUuid).orElseThrow(); diff --git a/src/main/java/net/hostsharing/hsadminng/hs/office/person/HsOfficePersonEntity.java b/src/main/java/net/hostsharing/hsadminng/hs/office/person/HsOfficePersonEntity.java index dd21a5c3..9f50d56e 100644 --- a/src/main/java/net/hostsharing/hsadminng/hs/office/person/HsOfficePersonEntity.java +++ b/src/main/java/net/hostsharing/hsadminng/hs/office/person/HsOfficePersonEntity.java @@ -3,9 +3,9 @@ package net.hostsharing.hsadminng.hs.office.person; import lombok.*; import lombok.experimental.FieldNameConstants; import net.hostsharing.hsadminng.errors.DisplayAs; -import net.hostsharing.hsadminng.rbac.rbacobject.BaseEntity; -import net.hostsharing.hsadminng.rbac.rbacdef.RbacView; -import net.hostsharing.hsadminng.rbac.rbacdef.RbacView.SQL; +import net.hostsharing.hsadminng.rbac.object.BaseEntity; +import net.hostsharing.hsadminng.rbac.generator.RbacView; +import net.hostsharing.hsadminng.rbac.generator.RbacView.SQL; import net.hostsharing.hsadminng.stringify.Stringify; import net.hostsharing.hsadminng.stringify.Stringifyable; import org.apache.commons.lang3.StringUtils; @@ -14,11 +14,11 @@ import jakarta.persistence.*; import java.io.IOException; import java.util.UUID; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.GLOBAL; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Permission.*; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.RbacUserReference.UserRole.CREATOR; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Role.*; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.rbacViewFor; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.GLOBAL; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Permission.*; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.RbacSubjectReference.UserRole.CREATOR; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Role.*; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.rbacViewFor; import static net.hostsharing.hsadminng.stringify.Stringify.stringify; @Entity @@ -80,7 +80,7 @@ public class HsOfficePersonEntity implements BaseEntity, S return rbacViewFor("person", HsOfficePersonEntity.class) .withIdentityView(SQL.projection("concat(tradeName, familyName, givenName)")) .withUpdatableColumns("personType", "title", "salutation", "tradeName", "givenName", "familyName") - .toRole("global", GUEST).grantPermission(INSERT) + .toRole(GLOBAL, GUEST).grantPermission(INSERT) .createRole(OWNER, (with) -> { with.permission(DELETE); diff --git a/src/main/java/net/hostsharing/hsadminng/hs/office/relation/HsOfficeRelation.java b/src/main/java/net/hostsharing/hsadminng/hs/office/relation/HsOfficeRelation.java index c0f13f56..66e954a4 100644 --- a/src/main/java/net/hostsharing/hsadminng/hs/office/relation/HsOfficeRelation.java +++ b/src/main/java/net/hostsharing/hsadminng/hs/office/relation/HsOfficeRelation.java @@ -5,7 +5,7 @@ import lombok.experimental.FieldNameConstants; import lombok.experimental.SuperBuilder; import net.hostsharing.hsadminng.hs.office.contact.HsOfficeContactRealEntity; import net.hostsharing.hsadminng.hs.office.person.HsOfficePersonEntity; -import net.hostsharing.hsadminng.rbac.rbacobject.BaseEntity; +import net.hostsharing.hsadminng.rbac.object.BaseEntity; import net.hostsharing.hsadminng.stringify.Stringify; import net.hostsharing.hsadminng.stringify.Stringifyable; diff --git a/src/main/java/net/hostsharing/hsadminng/hs/office/relation/HsOfficeRelationController.java b/src/main/java/net/hostsharing/hsadminng/hs/office/relation/HsOfficeRelationController.java index a3f4d136..f054e563 100644 --- a/src/main/java/net/hostsharing/hsadminng/hs/office/relation/HsOfficeRelationController.java +++ b/src/main/java/net/hostsharing/hsadminng/hs/office/relation/HsOfficeRelationController.java @@ -45,11 +45,11 @@ public class HsOfficeRelationController implements HsOfficeRelationsApi { @Override @Transactional(readOnly = true) public ResponseEntity> listRelations( - final String currentUser, + final String currentSubject, final String assumedRoles, final UUID personUuid, final HsOfficeRelationTypeResource relationType) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var entities = relationRbacRepo.findRelationRelatedToPersonUuidAndRelationType(personUuid, mapper.map(relationType, HsOfficeRelationType.class)); @@ -62,11 +62,11 @@ public class HsOfficeRelationController implements HsOfficeRelationsApi { @Override @Transactional public ResponseEntity addRelation( - final String currentUser, + final String currentSubject, final String assumedRoles, final HsOfficeRelationInsertResource body) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var entityToSave = new HsOfficeRelationRbacEntity(); entityToSave.setType(HsOfficeRelationType.valueOf(body.getType())); @@ -96,11 +96,11 @@ public class HsOfficeRelationController implements HsOfficeRelationsApi { @Override @Transactional(readOnly = true) public ResponseEntity getRelationByUuid( - final String currentUser, + final String currentSubject, final String assumedRoles, final UUID relationUuid) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var result = relationRbacRepo.findByUuid(relationUuid); if (result.isEmpty()) { @@ -112,10 +112,10 @@ public class HsOfficeRelationController implements HsOfficeRelationsApi { @Override @Transactional public ResponseEntity deleteRelationByUuid( - final String currentUser, + final String currentSubject, final String assumedRoles, final UUID relationUuid) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var result = relationRbacRepo.deleteByUuid(relationUuid); if (result == 0) { @@ -128,12 +128,12 @@ public class HsOfficeRelationController implements HsOfficeRelationsApi { @Override @Transactional public ResponseEntity patchRelation( - final String currentUser, + final String currentSubject, final String assumedRoles, final UUID relationUuid, final HsOfficeRelationPatchResource body) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var current = relationRbacRepo.findByUuid(relationUuid).orElseThrow(); diff --git a/src/main/java/net/hostsharing/hsadminng/hs/office/relation/HsOfficeRelationRbacEntity.java b/src/main/java/net/hostsharing/hsadminng/hs/office/relation/HsOfficeRelationRbacEntity.java index f081404e..f47fc105 100644 --- a/src/main/java/net/hostsharing/hsadminng/hs/office/relation/HsOfficeRelationRbacEntity.java +++ b/src/main/java/net/hostsharing/hsadminng/hs/office/relation/HsOfficeRelationRbacEntity.java @@ -7,31 +7,31 @@ import lombok.experimental.SuperBuilder; import net.hostsharing.hsadminng.errors.DisplayAs; import net.hostsharing.hsadminng.hs.office.contact.HsOfficeContactRbacEntity; import net.hostsharing.hsadminng.hs.office.person.HsOfficePersonEntity; -import net.hostsharing.hsadminng.rbac.rbacdef.RbacView; -import net.hostsharing.hsadminng.rbac.rbacdef.RbacView.SQL; +import net.hostsharing.hsadminng.rbac.generator.RbacView; +import net.hostsharing.hsadminng.rbac.generator.RbacView.SQL; import jakarta.persistence.Entity; import jakarta.persistence.Table; import java.io.IOException; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.CaseDef.inCaseOf; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.CaseDef.inOtherCases; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Column.dependsOnColumn; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.ColumnValue.usingDefaultCase; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.GLOBAL; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Nullable.NOT_NULL; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Permission.DELETE; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Permission.INSERT; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Permission.SELECT; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Permission.UPDATE; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.RbacUserReference.UserRole.CREATOR; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Role.ADMIN; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Role.AGENT; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Role.OWNER; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Role.REFERRER; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Role.TENANT; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.SQL.directlyFetchedByDependsOnColumn; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.rbacViewFor; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.CaseDef.inCaseOf; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.CaseDef.inOtherCases; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Column.dependsOnColumn; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.ColumnValue.usingDefaultCase; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.GLOBAL; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Nullable.NOT_NULL; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Permission.DELETE; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Permission.INSERT; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Permission.SELECT; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Permission.UPDATE; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.RbacSubjectReference.UserRole.CREATOR; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Role.ADMIN; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Role.AGENT; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Role.OWNER; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Role.REFERRER; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Role.TENANT; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.SQL.directlyFetchedByDependsOnColumn; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.rbacViewFor; @Entity @Table(name = "hs_office_relation_rv") diff --git a/src/main/java/net/hostsharing/hsadminng/hs/office/sepamandate/HsOfficeSepaMandateController.java b/src/main/java/net/hostsharing/hsadminng/hs/office/sepamandate/HsOfficeSepaMandateController.java index 115b8948..9511bdd6 100644 --- a/src/main/java/net/hostsharing/hsadminng/hs/office/sepamandate/HsOfficeSepaMandateController.java +++ b/src/main/java/net/hostsharing/hsadminng/hs/office/sepamandate/HsOfficeSepaMandateController.java @@ -39,10 +39,10 @@ public class HsOfficeSepaMandateController implements HsOfficeSepaMandatesApi { @Override @Transactional(readOnly = true) public ResponseEntity> listSepaMandatesByIban( - final String currentUser, + final String currentSubject, final String assumedRoles, final String iban) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var entities = sepaMandateRepo.findSepaMandateByOptionalIban(iban); @@ -54,11 +54,11 @@ public class HsOfficeSepaMandateController implements HsOfficeSepaMandatesApi { @Override @Transactional public ResponseEntity addSepaMandate( - final String currentUser, + final String currentSubject, final String assumedRoles, final HsOfficeSepaMandateInsertResource body) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var entityToSave = mapper.map(body, HsOfficeSepaMandateEntity.class, SEPA_MANDATE_RESOURCE_TO_ENTITY_POSTMAPPER); @@ -77,11 +77,11 @@ public class HsOfficeSepaMandateController implements HsOfficeSepaMandatesApi { @Override @Transactional(readOnly = true) public ResponseEntity getSepaMandateByUuid( - final String currentUser, + final String currentSubject, final String assumedRoles, final UUID sepaMandateUuid) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var result = sepaMandateRepo.findByUuid(sepaMandateUuid); if (result.isEmpty()) { @@ -94,10 +94,10 @@ public class HsOfficeSepaMandateController implements HsOfficeSepaMandatesApi { @Override @Transactional public ResponseEntity deleteSepaMandateByUuid( - final String currentUser, + final String currentSubject, final String assumedRoles, final UUID sepaMandateUuid) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var result = sepaMandateRepo.deleteByUuid(sepaMandateUuid); if (result == 0) { @@ -110,12 +110,12 @@ public class HsOfficeSepaMandateController implements HsOfficeSepaMandatesApi { @Override @Transactional public ResponseEntity patchSepaMandate( - final String currentUser, + final String currentSubject, final String assumedRoles, final UUID sepaMandateUuid, final HsOfficeSepaMandatePatchResource body) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var current = sepaMandateRepo.findByUuid(sepaMandateUuid).orElseThrow(); diff --git a/src/main/java/net/hostsharing/hsadminng/hs/office/sepamandate/HsOfficeSepaMandateEntity.java b/src/main/java/net/hostsharing/hsadminng/hs/office/sepamandate/HsOfficeSepaMandateEntity.java index a57ee32a..e984ce3b 100644 --- a/src/main/java/net/hostsharing/hsadminng/hs/office/sepamandate/HsOfficeSepaMandateEntity.java +++ b/src/main/java/net/hostsharing/hsadminng/hs/office/sepamandate/HsOfficeSepaMandateEntity.java @@ -7,8 +7,8 @@ import net.hostsharing.hsadminng.errors.DisplayAs; import net.hostsharing.hsadminng.hs.office.bankaccount.HsOfficeBankAccountEntity; import net.hostsharing.hsadminng.hs.office.debitor.HsOfficeDebitorEntity; import net.hostsharing.hsadminng.hs.office.relation.HsOfficeRelationRbacEntity; -import net.hostsharing.hsadminng.rbac.rbacobject.BaseEntity; -import net.hostsharing.hsadminng.rbac.rbacdef.RbacView; +import net.hostsharing.hsadminng.rbac.object.BaseEntity; +import net.hostsharing.hsadminng.rbac.generator.RbacView; import net.hostsharing.hsadminng.stringify.Stringify; import net.hostsharing.hsadminng.stringify.Stringifyable; import org.hibernate.annotations.Type; @@ -20,16 +20,16 @@ import java.util.UUID; import static net.hostsharing.hsadminng.hs.office.relation.HsOfficeRelationType.DEBITOR; import static net.hostsharing.hsadminng.mapper.PostgresDateRange.*; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Column.dependsOnColumn; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.ColumnValue.usingCase; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.ColumnValue.usingDefaultCase; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.GLOBAL; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Nullable.NOT_NULL; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Permission.*; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.RbacUserReference.UserRole.CREATOR; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Role.*; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.SQL.*; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.rbacViewFor; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Column.dependsOnColumn; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.ColumnValue.usingCase; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.ColumnValue.usingDefaultCase; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.GLOBAL; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Nullable.NOT_NULL; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Permission.*; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.RbacSubjectReference.UserRole.CREATOR; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Role.*; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.SQL.*; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.rbacViewFor; import static net.hostsharing.hsadminng.stringify.Stringify.stringify; @Entity diff --git a/src/main/java/net/hostsharing/hsadminng/rbac/rbacdef/InsertTriggerGenerator.java b/src/main/java/net/hostsharing/hsadminng/rbac/generator/InsertTriggerGenerator.java similarity index 79% rename from src/main/java/net/hostsharing/hsadminng/rbac/rbacdef/InsertTriggerGenerator.java rename to src/main/java/net/hostsharing/hsadminng/rbac/generator/InsertTriggerGenerator.java index 7c8b08ea..eb489038 100644 --- a/src/main/java/net/hostsharing/hsadminng/rbac/rbacdef/InsertTriggerGenerator.java +++ b/src/main/java/net/hostsharing/hsadminng/rbac/generator/InsertTriggerGenerator.java @@ -1,4 +1,4 @@ -package net.hostsharing.hsadminng.rbac.rbacdef; +package net.hostsharing.hsadminng.rbac.generator; import java.util.Optional; import java.util.Set; @@ -6,12 +6,12 @@ import java.util.function.BinaryOperator; import java.util.stream.Stream; import static java.util.stream.Collectors.joining; -import static net.hostsharing.hsadminng.rbac.rbacdef.PostgresTriggerReference.NEW; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Permission.INSERT; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.RbacGrantDefinition.GrantType.PERM_TO_ROLE; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Role.ADMIN; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Role.GUEST; -import static net.hostsharing.hsadminng.rbac.rbacdef.StringWriter.with; +import static net.hostsharing.hsadminng.rbac.generator.PostgresTriggerReference.NEW; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Permission.INSERT; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.RbacGrantDefinition.GrantType.PERM_TO_ROLE; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Role.ADMIN; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Role.GUEST; +import static net.hostsharing.hsadminng.rbac.generator.StringWriter.with; import static org.apache.commons.lang3.StringUtils.capitalize; import static org.apache.commons.lang3.StringUtils.uncapitalize; @@ -46,7 +46,7 @@ public class InsertTriggerGenerator { private void generateInsertPermissionGrants(final StringWriter plPgSql) { plPgSql.writeLn(""" -- ============================================================================ - --changeset ${liquibaseTagPrefix}-rbac-GRANTING-INSERT-PERMISSION:1 endDelimiter:--// + --changeset InsertTriggerGenerator:${liquibaseTagPrefix}-rbac-GRANTING-INSERT-PERMISSION endDelimiter:--// -- ---------------------------------------------------------------------------- """, with("liquibaseTagPrefix", liquibaseTagPrefix)); @@ -55,7 +55,7 @@ public class InsertTriggerGenerator { plPgSql.writeLn(""" -- granting INSERT permission to ${rawSubTable} ---------------------------- """, - with("rawSubTable", g.getSuperRoleDef().getEntityAlias().getRawTableName())); + with("rawSubTable", g.getSuperRoleDef().getEntityAlias().getRawTableNameWithSchema())); if (isGrantToADifferentTable(g)) { plPgSql.writeLn( @@ -67,13 +67,13 @@ public class InsertTriggerGenerator { declare row ${rawSuperTable}; begin - call defineContext('create INSERT INTO ${rawSubTable} permissions for pre-exising ${rawSuperTable} rows'); + call base.defineContext('create INSERT INTO ${rawSubTable} permissions for pre-exising ${rawSuperTable} rows'); FOR row IN SELECT * FROM ${rawSuperTable} ${whenCondition} LOOP - call grantPermissionToRole( - createPermission(row.uuid, 'INSERT', '${rawSubTable}'), + call rbac.grantPermissionToRole( + rbac.createPermission(row.uuid, 'INSERT', '${rawSubTable}'), ${superRoleRef}); END LOOP; end; @@ -84,40 +84,40 @@ public class InsertTriggerGenerator { ? "WHERE type = '${value}'" .replace("${value}", g.getSuperRoleDef().getEntityAlias().usingCase().value) : "-- unconditional for all rows in that table"), - with("rawSuperTable", g.getSuperRoleDef().getEntityAlias().getRawTableName()), - with("rawSubTable", g.getPermDef().getEntityAlias().getRawTableName()), + with("rawSuperTable", g.getSuperRoleDef().getEntityAlias().getRawTableNameWithSchema()), + with("rawSubTable", g.getPermDef().getEntityAlias().getRawTableNameWithSchema()), with("superRoleRef", toRoleDescriptor(g.getSuperRoleDef(), "row"))); } else { plPgSql.writeLn(""" -- Granting INSERT INTO hs_hosting_asset permissions to specified role of pre-existing hs_hosting_asset rows slipped, -- because there cannot yet be any pre-existing rows in the same table yet. """, - with("rawSuperTable", g.getSuperRoleDef().getEntityAlias().getRawTableName()), - with("rawSubTable", g.getPermDef().getEntityAlias().getRawTableName())); + with("rawSuperTable", g.getSuperRoleDef().getEntityAlias().getRawTableNameWithSchema()), + with("rawSubTable", g.getPermDef().getEntityAlias().getRawTableNameWithSchema())); } plPgSql.writeLn(""" /** Grants ${rawSubTable} INSERT permission to specified role of new ${rawSuperTable} rows. */ - create or replace function new_${rawSubTable}_grants_insert_to_${rawSuperTable}_tf() + create or replace function ${rawSuperTableSchemaName}new_${rawSubTableShortName}_grants_insert_to_${rawSuperTableShortName}_tf() returns trigger language plpgsql strict as $$ begin ${ifConditionThen} - call grantPermissionToRole( - createPermission(NEW.uuid, 'INSERT', '${rawSubTable}'), + call rbac.grantPermissionToRole( + rbac.createPermission(NEW.uuid, 'INSERT', '${rawSubTable}'), ${superRoleRef}); ${ifConditionEnd} return NEW; end; $$; - + -- z_... is to put it at the end of after insert triggers, to make sure the roles exist - create trigger z_new_${rawSubTable}_grants_insert_to_${rawSuperTable}_tg - after insert on ${rawSuperTable} + create trigger z_new_${rawSubTable}_grants_after_insert_tg + after insert on ${rawSuperTableWithSchema} for each row - execute procedure new_${rawSubTable}_grants_insert_to_${rawSuperTable}_tf(); + execute procedure ${rawSuperTableSchemaName}new_${rawSubTableShortName}_grants_insert_to_${rawSuperTableShortName}_tf(); """, with("ifConditionThen", g.getSuperRoleDef().getEntityAlias().isCaseDependent() // TODO.impl: .type needs to be dynamically generated @@ -127,8 +127,12 @@ public class InsertTriggerGenerator { ? "end if;" : "-- end."), with("superRoleRef", toRoleDescriptor(g.getSuperRoleDef(), NEW.name())), + with("rawSuperTableWithSchema", g.getSuperRoleDef().getEntityAlias().getRawTableNameWithSchema()), + with("rawSuperTableShortName", g.getSuperRoleDef().getEntityAlias().getRawTableShortName()), with("rawSuperTable", g.getSuperRoleDef().getEntityAlias().getRawTableName()), - with("rawSubTable", g.getPermDef().getEntityAlias().getRawTableName())); + with("rawSuperTableSchemaName", g.getSuperRoleDef().getEntityAlias().getRawTableSchemaPrefix()), + with("rawSubTable", g.getPermDef().getEntityAlias().getRawTableNameWithSchema()), + with("rawSubTableShortName", g.getPermDef().getEntityAlias().getRawTableShortName())); }); } @@ -136,7 +140,7 @@ public class InsertTriggerGenerator { private void generateInsertPermissionTriggerAlwaysDisallow(final StringWriter plPgSql) { plPgSql.writeLn(""" -- ============================================================================ - --changeset ${liquibaseTagPrefix}-rbac-ALWAYS-DISALLOW-INSERT:1 endDelimiter:--// + --changeset InsertTriggerGenerator:${liquibaseTagPrefix}-rbac-ALWAYS-DISALLOW-INSERT endDelimiter:--// -- ---------------------------------------------------------------------------- """, with("liquibaseTagPrefix", liquibaseTagPrefix)); @@ -152,13 +156,13 @@ public class InsertTriggerGenerator { begin raise exception '[403] insert into ${rawSubTable} values(%) not allowed regardless of current subject, no insert permissions granted at all', NEW; end; $$; - + create trigger ${rawSubTable}_insert_permission_check_tg before insert on ${rawSubTable} for each row execute procedure ${rawSubTable}_insert_permission_missing_tf(); """, - with("rawSubTable", rbacDef.getRootEntityAlias().getRawTableName())); + with("rawSubTable", rbacDef.getRootEntityAlias().getRawTableNameWithSchema())); plPgSql.writeLn("--//"); } @@ -179,7 +183,7 @@ public class InsertTriggerGenerator { private void generateInsertPermissionsCheckHeader(final StringWriter plPgSql) { plPgSql.writeLn(""" -- ============================================================================ - --changeset ${rawSubTable}-rbac-CHECKING-INSERT-PERMISSION:1 endDelimiter:--// + --changeset InsertTriggerGenerator:${rawSubTable}-rbac-CHECKING-INSERT-PERMISSION endDelimiter:--// -- ---------------------------------------------------------------------------- /** @@ -192,7 +196,7 @@ public class InsertTriggerGenerator { superObjectUuid uuid; begin """, - with("rawSubTable", rbacDef.getRootEntityAlias().getRawTableName())); + with("rawSubTable", rbacDef.getRootEntityAlias().getRawTableNameWithSchema())); plPgSql.chopEmptyLines(); } @@ -206,7 +210,7 @@ public class InsertTriggerGenerator { if (g.getSuperRoleDef().isGlobal(GUEST)) { plPgSql.writeLn( """ - -- check INSERT INSERT permission for global anyone + -- check INSERT INSERT permission for rbac.global anyone if ${caseCondition}true then return NEW; end if; @@ -215,8 +219,8 @@ public class InsertTriggerGenerator { } else if (g.getSuperRoleDef().isGlobal(ADMIN)) { plPgSql.writeLn( """ - -- check INSERT INSERT if global ADMIN - if ${caseCondition}isGlobalAdmin() then + -- check INSERT INSERT if rbac.global ADMIN + if ${caseCondition}rbac.isGlobalAdmin() then return NEW; end if; """, @@ -225,25 +229,25 @@ public class InsertTriggerGenerator { plPgSql.writeLn( """ -- check INSERT permission via direct foreign key: NEW.${refColumn} - if ${caseCondition}hasInsertPermission(NEW.${refColumn}, '${rawSubTable}') then + if ${caseCondition}rbac.hasInsertPermission(NEW.${refColumn}, '${rawSubTable}') then return NEW; end if; """, with("caseCondition", caseCondition), with("refColumn", superRoleEntityAlias.dependsOnColumName()), - with("rawSubTable", rbacDef.getRootEntityAlias().getRawTableName())); + with("rawSubTable", rbacDef.getRootEntityAlias().getRawTableNameWithSchema())); } else { plPgSql.writeLn( """ -- check INSERT permission via indirect foreign key: NEW.${refColumn} superObjectUuid := (${fetchSql}); assert superObjectUuid is not null, 'object uuid fetched depending on ${rawSubTable}.${refColumn} must not be null, also check fetchSql in RBAC DSL'; - if ${caseCondition}hasInsertPermission(superObjectUuid, '${rawSubTable}') then + if ${caseCondition}rbac.hasInsertPermission(superObjectUuid, '${rawSubTable}') then return NEW; end if; """, with("caseCondition", caseCondition), - with("rawSubTable", rbacDef.getRootEntityAlias().getRawTableName()), + with("rawSubTable", rbacDef.getRootEntityAlias().getRawTableNameWithSchema()), with("refColumn", superRoleEntityAlias.dependsOnColumName()), with("fetchSql", g.getSuperRoleDef().getEntityAlias().fetchSql().sql), with("columns", g.getSuperRoleDef().getEntityAlias().aliasName() + ".uuid"), @@ -255,7 +259,7 @@ public class InsertTriggerGenerator { plPgSql.writeLn(); plPgSql.writeLn(""" raise exception '[403] insert into ${rawSubTable} values(%) not allowed for current subjects % (%)', - NEW, currentSubjects(), currentSubjectsUuids(); + NEW, base.currentSubjects(), rbac.currentSubjectOrAssumedRolesUuids(); end; $$; create trigger ${rawSubTable}_insert_permission_check_tg @@ -264,7 +268,7 @@ public class InsertTriggerGenerator { execute procedure ${rawSubTable}_insert_permission_check_tf(); --// """, - with("rawSubTable", rbacDef.getRootEntityAlias().getRawTableName())); + with("rawSubTable", rbacDef.getRootEntityAlias().getRawTableNameWithSchema())); } private String toStringList(final Set cases) { @@ -272,7 +276,7 @@ public class InsertTriggerGenerator { } private boolean isGrantToADifferentTable(final RbacView.RbacGrantDefinition g) { - return !rbacDef.getRootEntityAlias().getRawTableName().equals(g.getSuperRoleDef().getEntityAlias().getRawTableName()); + return !rbacDef.getRootEntityAlias().getRawTableNameWithSchema().equals(g.getSuperRoleDef().getEntityAlias().getRawTableNameWithSchema()); } private Stream getInsertGrants() { diff --git a/src/main/java/net/hostsharing/hsadminng/rbac/rbacdef/PostgresTriggerReference.java b/src/main/java/net/hostsharing/hsadminng/rbac/generator/PostgresTriggerReference.java similarity index 52% rename from src/main/java/net/hostsharing/hsadminng/rbac/rbacdef/PostgresTriggerReference.java rename to src/main/java/net/hostsharing/hsadminng/rbac/generator/PostgresTriggerReference.java index 4fb5cb61..f987eecd 100644 --- a/src/main/java/net/hostsharing/hsadminng/rbac/rbacdef/PostgresTriggerReference.java +++ b/src/main/java/net/hostsharing/hsadminng/rbac/generator/PostgresTriggerReference.java @@ -1,4 +1,4 @@ -package net.hostsharing.hsadminng.rbac.rbacdef; +package net.hostsharing.hsadminng.rbac.generator; public enum PostgresTriggerReference { NEW, OLD diff --git a/src/main/java/net/hostsharing/hsadminng/rbac/rbacdef/RbacIdentityViewGenerator.java b/src/main/java/net/hostsharing/hsadminng/rbac/generator/RbacIdentityViewGenerator.java similarity index 79% rename from src/main/java/net/hostsharing/hsadminng/rbac/rbacdef/RbacIdentityViewGenerator.java rename to src/main/java/net/hostsharing/hsadminng/rbac/generator/RbacIdentityViewGenerator.java index 50b404eb..473cc394 100644 --- a/src/main/java/net/hostsharing/hsadminng/rbac/rbacdef/RbacIdentityViewGenerator.java +++ b/src/main/java/net/hostsharing/hsadminng/rbac/generator/RbacIdentityViewGenerator.java @@ -1,6 +1,6 @@ -package net.hostsharing.hsadminng.rbac.rbacdef; +package net.hostsharing.hsadminng.rbac.generator; -import static net.hostsharing.hsadminng.rbac.rbacdef.StringWriter.with; +import static net.hostsharing.hsadminng.rbac.generator.StringWriter.with; public class RbacIdentityViewGenerator { private final RbacView rbacDef; @@ -12,13 +12,13 @@ public class RbacIdentityViewGenerator { this.rbacDef = rbacDef; this.liquibaseTagPrefix = liquibaseTagPrefix; this.simpleEntityVarName = rbacDef.getRootEntityAlias().simpleName(); - this.rawTableName = rbacDef.getRootEntityAlias().getRawTableName(); + this.rawTableName = rbacDef.getRootEntityAlias().getRawTableNameWithSchema(); } void generateTo(final StringWriter plPgSql) { plPgSql.writeLn(""" -- ============================================================================ - --changeset ${liquibaseTagPrefix}-rbac-IDENTITY-VIEW:1 endDelimiter:--// + --changeset RbacIdentityViewGenerator:${liquibaseTagPrefix}-rbac-IDENTITY-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- """, with("liquibaseTagPrefix", liquibaseTagPrefix)); @@ -26,13 +26,13 @@ public class RbacIdentityViewGenerator { plPgSql.writeLn( switch (rbacDef.getIdentityViewSqlQuery().part) { case SQL_PROJECTION -> """ - call generateRbacIdentityViewFromProjection('${rawTableName}', + call rbac.generateRbacIdentityViewFromProjection('${rawTableName}', $idName$ ${identityViewSqlPart} $idName$); """; case SQL_QUERY -> """ - call generateRbacIdentityViewFromQuery('${rawTableName}', + call rbac.generateRbacIdentityViewFromQuery('${rawTableName}', $idName$ ${identityViewSqlPart} $idName$); diff --git a/src/main/java/net/hostsharing/hsadminng/rbac/rbacdef/RbacObjectGenerator.java b/src/main/java/net/hostsharing/hsadminng/rbac/generator/RbacObjectGenerator.java similarity index 70% rename from src/main/java/net/hostsharing/hsadminng/rbac/rbacdef/RbacObjectGenerator.java rename to src/main/java/net/hostsharing/hsadminng/rbac/generator/RbacObjectGenerator.java index a7377301..f641ad99 100644 --- a/src/main/java/net/hostsharing/hsadminng/rbac/rbacdef/RbacObjectGenerator.java +++ b/src/main/java/net/hostsharing/hsadminng/rbac/generator/RbacObjectGenerator.java @@ -1,6 +1,6 @@ -package net.hostsharing.hsadminng.rbac.rbacdef; +package net.hostsharing.hsadminng.rbac.generator; -import static net.hostsharing.hsadminng.rbac.rbacdef.StringWriter.with; +import static net.hostsharing.hsadminng.rbac.generator.StringWriter.with; public class RbacObjectGenerator { @@ -9,17 +9,17 @@ public class RbacObjectGenerator { public RbacObjectGenerator(final RbacView rbacDef, final String liquibaseTagPrefix) { this.liquibaseTagPrefix = liquibaseTagPrefix; - this.rawTableName = rbacDef.getRootEntityAlias().getRawTableName(); + this.rawTableName = rbacDef.getRootEntityAlias().getRawTableNameWithSchema(); } void generateTo(final StringWriter plPgSql) { plPgSql.writeLn(""" -- ============================================================================ - --changeset ${liquibaseTagPrefix}-rbac-OBJECT:1 endDelimiter:--// + --changeset RbacObjectGenerator:${liquibaseTagPrefix}-rbac-OBJECT endDelimiter:--// -- ---------------------------------------------------------------------------- - call generateRelatedRbacObject('${rawTableName}'); + call rbac.generateRelatedRbacObject('${rawTableName}'); --// - + """, with("liquibaseTagPrefix", liquibaseTagPrefix), with("rawTableName", rawTableName)); diff --git a/src/main/java/net/hostsharing/hsadminng/rbac/rbacdef/RbacRestrictedViewGenerator.java b/src/main/java/net/hostsharing/hsadminng/rbac/generator/RbacRestrictedViewGenerator.java similarity index 76% rename from src/main/java/net/hostsharing/hsadminng/rbac/rbacdef/RbacRestrictedViewGenerator.java rename to src/main/java/net/hostsharing/hsadminng/rbac/generator/RbacRestrictedViewGenerator.java index b5757865..f493d382 100644 --- a/src/main/java/net/hostsharing/hsadminng/rbac/rbacdef/RbacRestrictedViewGenerator.java +++ b/src/main/java/net/hostsharing/hsadminng/rbac/generator/RbacRestrictedViewGenerator.java @@ -1,9 +1,9 @@ -package net.hostsharing.hsadminng.rbac.rbacdef; +package net.hostsharing.hsadminng.rbac.generator; import static java.util.stream.Collectors.joining; -import static net.hostsharing.hsadminng.rbac.rbacdef.StringWriter.indented; -import static net.hostsharing.hsadminng.rbac.rbacdef.StringWriter.with; +import static net.hostsharing.hsadminng.rbac.generator.StringWriter.indented; +import static net.hostsharing.hsadminng.rbac.generator.StringWriter.with; public class RbacRestrictedViewGenerator { private final RbacView rbacDef; @@ -13,15 +13,15 @@ public class RbacRestrictedViewGenerator { public RbacRestrictedViewGenerator(final RbacView rbacDef, final String liquibaseTagPrefix) { this.rbacDef = rbacDef; this.liquibaseTagPrefix = liquibaseTagPrefix; - this.rawTableName = rbacDef.getRootEntityAlias().getRawTableName(); + this.rawTableName = rbacDef.getRootEntityAlias().getRawTableNameWithSchema(); } void generateTo(final StringWriter plPgSql) { plPgSql.writeLn(""" -- ============================================================================ - --changeset ${liquibaseTagPrefix}-rbac-RESTRICTED-VIEW:1 endDelimiter:--// + --changeset RbacRestrictedViewGenerator:${liquibaseTagPrefix}-rbac-RESTRICTED-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- - call generateRbacRestrictedView('${rawTableName}', + call rbac.generateRbacRestrictedView('${rawTableName}', $orderBy$ ${orderBy} $orderBy$, diff --git a/src/main/java/net/hostsharing/hsadminng/rbac/rbacdef/RbacRoleDescriptorsGenerator.java b/src/main/java/net/hostsharing/hsadminng/rbac/generator/RbacRoleDescriptorsGenerator.java similarity index 72% rename from src/main/java/net/hostsharing/hsadminng/rbac/rbacdef/RbacRoleDescriptorsGenerator.java rename to src/main/java/net/hostsharing/hsadminng/rbac/generator/RbacRoleDescriptorsGenerator.java index dab3ab01..098ebf81 100644 --- a/src/main/java/net/hostsharing/hsadminng/rbac/rbacdef/RbacRoleDescriptorsGenerator.java +++ b/src/main/java/net/hostsharing/hsadminng/rbac/generator/RbacRoleDescriptorsGenerator.java @@ -1,6 +1,6 @@ -package net.hostsharing.hsadminng.rbac.rbacdef; +package net.hostsharing.hsadminng.rbac.generator; -import static net.hostsharing.hsadminng.rbac.rbacdef.StringWriter.with; +import static net.hostsharing.hsadminng.rbac.generator.StringWriter.with; public class RbacRoleDescriptorsGenerator { @@ -11,15 +11,15 @@ public class RbacRoleDescriptorsGenerator { public RbacRoleDescriptorsGenerator(final RbacView rbacDef, final String liquibaseTagPrefix) { this.liquibaseTagPrefix = liquibaseTagPrefix; this.simpleEntityVarName = rbacDef.getRootEntityAlias().simpleName(); - this.rawTableName = rbacDef.getRootEntityAlias().getRawTableName(); + this.rawTableName = rbacDef.getRootEntityAlias().getRawTableNameWithSchema(); } void generateTo(final StringWriter plPgSql) { plPgSql.writeLn(""" -- ============================================================================ - --changeset ${liquibaseTagPrefix}-rbac-ROLE-DESCRIPTORS:1 endDelimiter:--// + --changeset RbacRoleDescriptorsGenerator:${liquibaseTagPrefix}-rbac-ROLE-DESCRIPTORS endDelimiter:--// -- ---------------------------------------------------------------------------- - call generateRbacRoleDescriptors('${simpleEntityVarName}', '${rawTableName}'); + call rbac.generateRbacRoleDescriptors('${simpleEntityVarName}', '${rawTableName}'); --// """, diff --git a/src/main/java/net/hostsharing/hsadminng/rbac/rbacdef/RbacView.java b/src/main/java/net/hostsharing/hsadminng/rbac/generator/RbacView.java similarity index 93% rename from src/main/java/net/hostsharing/hsadminng/rbac/rbacdef/RbacView.java rename to src/main/java/net/hostsharing/hsadminng/rbac/generator/RbacView.java index ed3a1486..634d4c33 100644 --- a/src/main/java/net/hostsharing/hsadminng/rbac/rbacdef/RbacView.java +++ b/src/main/java/net/hostsharing/hsadminng/rbac/generator/RbacView.java @@ -1,8 +1,8 @@ -package net.hostsharing.hsadminng.rbac.rbacdef; +package net.hostsharing.hsadminng.rbac.generator; import lombok.EqualsAndHashCode; import lombok.Getter; -import net.hostsharing.hsadminng.rbac.rbacobject.BaseEntity; +import net.hostsharing.hsadminng.rbac.object.BaseEntity; import org.reflections.Reflections; import org.reflections.scanners.TypeAnnotationsScanner; @@ -23,12 +23,12 @@ import static java.util.Arrays.asList; import static java.util.Arrays.stream; import static java.util.Collections.max; import static java.util.Optional.ofNullable; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.ColumnValue.usingDefaultCase; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Nullable.NOT_NULL; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.RbacGrantDefinition.GrantType.PERM_TO_ROLE; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.RbacGrantDefinition.GrantType.ROLE_TO_ROLE; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.RbacUserReference.UserRole.CREATOR; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.SQL.Part.AUTO_FETCH; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.ColumnValue.usingDefaultCase; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Nullable.NOT_NULL; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.RbacGrantDefinition.GrantType.PERM_TO_ROLE; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.RbacGrantDefinition.GrantType.ROLE_TO_ROLE; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.RbacSubjectReference.UserRole.CREATOR; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.SQL.Part.AUTO_FETCH; import static org.apache.commons.collections4.SetUtils.hashSet; import static org.apache.commons.lang3.StringUtils.uncapitalize; @@ -36,12 +36,12 @@ import static org.apache.commons.lang3.StringUtils.uncapitalize; // TODO.refa: rename to RbacDSL public class RbacView { - public static final String GLOBAL = "global"; + public static final String GLOBAL = "rbac.global"; public static final String OUTPUT_BASEDIR = "src/main/resources/db/changelog"; private final EntityAlias rootEntityAlias; - private final Set userDefs = new LinkedHashSet<>(); + private final Set userDefs = new LinkedHashSet<>(); private final Set roleDefs = new LinkedHashSet<>(); private final Set permDefs = new LinkedHashSet<>(); private final Map entityAliases = new HashMap<>() { @@ -97,8 +97,8 @@ public class RbacView { RbacView(final String alias, final Class entityClass) { rootEntityAlias = new EntityAlias(alias, entityClass); entityAliases.put(alias, rootEntityAlias); - new RbacUserReference(CREATOR); - entityAliases.put("global", new EntityAlias("global")); + new RbacSubjectReference(CREATOR); + entityAliases.put("rbac.global", new EntityAlias("rbac.global")); } /** @@ -467,7 +467,7 @@ public class RbacView { return new RbacExampleRole(entityAlias, role); } - private RbacGrantDefinition grantRoleToUser(final RbacRoleDefinition roleDefinition, final RbacUserReference user) { + private RbacGrantDefinition grantRoleToSubject(final RbacRoleDefinition roleDefinition, final RbacSubjectReference user) { return findOrCreateGrantDef(roleDefinition, user).toCreate(); } @@ -548,7 +548,7 @@ public class RbacView { } public RbacView grantPermission(final Permission perm) { - final var forTable = rootEntityAlias.getRawTableName(); + final var forTable = rootEntityAlias.getRawTableNameWithSchema(); findOrCreateGrantDef(findRbacPerm(rootEntityAlias, perm, forTable), superRoleDef).toCreate(); return RbacView.this; } @@ -564,7 +564,7 @@ public class RbacView { @EqualsAndHashCode public class RbacGrantDefinition { - private final RbacUserReference userDef; + private final RbacSubjectReference userDef; private final RbacRoleDefinition superRoleDef; private final RbacRoleDefinition subRoleDef; private final RbacPermissionDefinition permDef; @@ -605,7 +605,7 @@ public class RbacView { register(this); } - public RbacGrantDefinition(final RbacRoleDefinition roleDef, final RbacUserReference userDef) { + public RbacGrantDefinition(final RbacRoleDefinition roleDef, final RbacSubjectReference userDef) { this.userDef = userDef; this.subRoleDef = roleDef; this.superRoleDef = null; @@ -770,8 +770,8 @@ public class RbacView { * @return * The grant definition for further chained calls. */ - public RbacGrantDefinition owningUser(final RbacUserReference.UserRole userRole) { - return grantRoleToUser(this, findUserRef(userRole)); + public RbacGrantDefinition owningUser(final RbacSubjectReference.UserRole userRole) { + return grantRoleToSubject(this, findUserRef(userRole)); } /** @@ -833,12 +833,12 @@ public class RbacView { } } - public RbacUserReference findUserRef(final RbacUserReference.UserRole userRole) { + public RbacSubjectReference findUserRef(final RbacSubjectReference.UserRole userRole) { return userDefs.stream().filter(u -> u.role == userRole).findFirst().orElseThrow(); } @EqualsAndHashCode - public class RbacUserReference { + public class RbacSubjectReference { public enum UserRole { GLOBAL_ADMIN, @@ -847,7 +847,7 @@ public class RbacView { final UserRole role; - public RbacUserReference(final UserRole creator) { + public RbacSubjectReference(final UserRole creator) { this.role = creator; userDefs.add(this); } @@ -885,7 +885,7 @@ public class RbacView { .orElseGet(() -> new RbacPermissionDefinition(entityAlias, perm, tableName, true)); // TODO: true => toCreate } - private RbacGrantDefinition findOrCreateGrantDef(final RbacRoleDefinition roleDefinition, final RbacUserReference user) { + private RbacGrantDefinition findOrCreateGrantDef(final RbacRoleDefinition roleDefinition, final RbacSubjectReference user) { return grantDefs.stream() .filter(g -> g.subRoleDef == roleDefinition && g.userDef == user) .findFirst() @@ -922,7 +922,7 @@ public class RbacView { } boolean isGlobal() { - return aliasName().equals("global"); + return aliasName().equals("rbac.global"); } boolean isPlaceholder() { @@ -937,7 +937,7 @@ public class RbacView { return switch (fetchSql.part) { case SQL_QUERY -> fetchSql; case AUTO_FETCH -> - SQL.query("SELECT * FROM " + getRawTableName() + " WHERE uuid = ${ref}." + dependsOnColum.column); + SQL.query("SELECT * FROM " + getRawTableNameWithSchema() + " WHERE uuid = ${ref}." + dependsOnColum.column); default -> throw new IllegalStateException("unexpected SQL definition: " + fetchSql); }; } @@ -960,13 +960,39 @@ public class RbacView { : uncapitalize(withoutEntitySuffix(entityClass.getSimpleName())); } - String getRawTableName() { - if ( aliasName.equals("global")) { - return "global"; // TODO: maybe we should introduce a GlobalEntity class? + String getRawTableNameWithSchema() { + if ( aliasName.equals("rbac.global")) { + return "rbac.global"; // TODO: maybe we should introduce a GlobalEntity class? } return withoutRvSuffix(entityClass.getAnnotation(Table.class).name()); } + String getRawTableSchemaPrefix() { + final var rawTableNameWithSchema = getRawTableNameWithSchema(); + final var parts = rawTableNameWithSchema.split("\\."); + final var rawTableSchemaPrefix = parts.length > 1 ? parts[0] + "." : ""; + return rawTableSchemaPrefix; + } + + String getRawTableName() { + final var rawTableNameWithSchema = getRawTableNameWithSchema(); + final var parts = rawTableNameWithSchema.split("\\."); + final var rawTableName = parts.length > 1 ? parts[1] : rawTableNameWithSchema; + return rawTableName; + } + + String getRawTableShortName() { + // TODO.impl: some combined function and trigger names are too long + // maybe we should shorten the table name e.g. hs_office_coopsharestransaction -> hsof.coopsharetx + // this is just a workaround: + return getRawTableName() + .replace("hs_office_", "hsof_") + .replace("hs_booking_", "hsbk_") + .replace("hs_hosting_", "hsho_") + .replace("coopsharestransaction", "coopsharetx") + .replace("coopassetstransaction", "coopassettx"); + } + String dependsOnColumName() { if (dependsOnColum == null) { throw new IllegalStateException( @@ -1166,7 +1192,7 @@ public class RbacView { } String map(final String originalAliasName) { - if (outerAliasNames.contains(originalAliasName) || originalAliasName.equals("global")) { + if (outerAliasNames.contains(originalAliasName) || originalAliasName.equals("rbac.global")) { return originalAliasName; } if (originalAliasName.equals(importedRbacView.rootEntityAlias.aliasName)) { diff --git a/src/main/java/net/hostsharing/hsadminng/rbac/rbacdef/RbacViewMermaidFlowchartGenerator.java b/src/main/java/net/hostsharing/hsadminng/rbac/generator/RbacViewMermaidFlowchartGenerator.java similarity index 97% rename from src/main/java/net/hostsharing/hsadminng/rbac/rbacdef/RbacViewMermaidFlowchartGenerator.java rename to src/main/java/net/hostsharing/hsadminng/rbac/generator/RbacViewMermaidFlowchartGenerator.java index a820ad6a..6a457310 100644 --- a/src/main/java/net/hostsharing/hsadminng/rbac/rbacdef/RbacViewMermaidFlowchartGenerator.java +++ b/src/main/java/net/hostsharing/hsadminng/rbac/generator/RbacViewMermaidFlowchartGenerator.java @@ -1,7 +1,7 @@ -package net.hostsharing.hsadminng.rbac.rbacdef; +package net.hostsharing.hsadminng.rbac.generator; import lombok.SneakyThrows; -import net.hostsharing.hsadminng.rbac.rbacdef.RbacView.CaseDef; +import net.hostsharing.hsadminng.rbac.generator.RbacView.CaseDef; import org.apache.commons.lang3.StringUtils; import java.nio.file.*; @@ -12,7 +12,7 @@ import java.util.stream.Stream; import static java.util.Comparator.comparing; import static java.util.stream.Collectors.joining; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.RbacGrantDefinition.GrantType.*; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.RbacGrantDefinition.GrantType.*; public class RbacViewMermaidFlowchartGenerator { diff --git a/src/main/java/net/hostsharing/hsadminng/rbac/rbacdef/RbacViewPostgresGenerator.java b/src/main/java/net/hostsharing/hsadminng/rbac/generator/RbacViewPostgresGenerator.java similarity index 88% rename from src/main/java/net/hostsharing/hsadminng/rbac/rbacdef/RbacViewPostgresGenerator.java rename to src/main/java/net/hostsharing/hsadminng/rbac/generator/RbacViewPostgresGenerator.java index 5a3b2be8..b4c6dfb4 100644 --- a/src/main/java/net/hostsharing/hsadminng/rbac/rbacdef/RbacViewPostgresGenerator.java +++ b/src/main/java/net/hostsharing/hsadminng/rbac/generator/RbacViewPostgresGenerator.java @@ -1,4 +1,4 @@ -package net.hostsharing.hsadminng.rbac.rbacdef; +package net.hostsharing.hsadminng.rbac.generator; import lombok.SneakyThrows; @@ -6,8 +6,8 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; -import static net.hostsharing.hsadminng.rbac.rbacdef.PostgresTriggerReference.NEW; -import static net.hostsharing.hsadminng.rbac.rbacdef.StringWriter.with; +import static net.hostsharing.hsadminng.rbac.generator.PostgresTriggerReference.NEW; +import static net.hostsharing.hsadminng.rbac.generator.StringWriter.with; public class RbacViewPostgresGenerator { @@ -17,7 +17,7 @@ public class RbacViewPostgresGenerator { public RbacViewPostgresGenerator(final RbacView forRbacDef) { rbacDef = forRbacDef; - liqibaseTagPrefix = rbacDef.getRootEntityAlias().getRawTableName().replace("_", "-"); + liqibaseTagPrefix = rbacDef.getRootEntityAlias().getRawTableNameWithSchema().replace("_", "-"); plPgSql.writeLn(""" --liquibase formatted sql -- This code generated was by ${generator}, do not amend manually. diff --git a/src/main/java/net/hostsharing/hsadminng/rbac/rbacdef/RolesGrantsAndPermissionsGenerator.java b/src/main/java/net/hostsharing/hsadminng/rbac/generator/RolesGrantsAndPermissionsGenerator.java similarity index 90% rename from src/main/java/net/hostsharing/hsadminng/rbac/rbacdef/RolesGrantsAndPermissionsGenerator.java rename to src/main/java/net/hostsharing/hsadminng/rbac/generator/RolesGrantsAndPermissionsGenerator.java index 2089d4d9..caa46eaf 100644 --- a/src/main/java/net/hostsharing/hsadminng/rbac/rbacdef/RolesGrantsAndPermissionsGenerator.java +++ b/src/main/java/net/hostsharing/hsadminng/rbac/generator/RolesGrantsAndPermissionsGenerator.java @@ -1,8 +1,8 @@ -package net.hostsharing.hsadminng.rbac.rbacdef; +package net.hostsharing.hsadminng.rbac.generator; -import net.hostsharing.hsadminng.rbac.rbacdef.RbacView.CaseDef; -import net.hostsharing.hsadminng.rbac.rbacdef.RbacView.RbacGrantDefinition; -import net.hostsharing.hsadminng.rbac.rbacdef.RbacView.RbacPermissionDefinition; +import net.hostsharing.hsadminng.rbac.generator.RbacView.CaseDef; +import net.hostsharing.hsadminng.rbac.generator.RbacView.RbacGrantDefinition; +import net.hostsharing.hsadminng.rbac.generator.RbacView.RbacPermissionDefinition; import java.util.HashSet; import java.util.List; @@ -13,12 +13,12 @@ import java.util.stream.Stream; import static java.util.Optional.ofNullable; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toSet; -import static net.hostsharing.hsadminng.rbac.rbacdef.PostgresTriggerReference.NEW; -import static net.hostsharing.hsadminng.rbac.rbacdef.PostgresTriggerReference.OLD; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Permission.INSERT; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.RbacGrantDefinition.GrantType.*; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Role.*; -import static net.hostsharing.hsadminng.rbac.rbacdef.StringWriter.with; +import static net.hostsharing.hsadminng.rbac.generator.PostgresTriggerReference.NEW; +import static net.hostsharing.hsadminng.rbac.generator.PostgresTriggerReference.OLD; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Permission.INSERT; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.RbacGrantDefinition.GrantType.*; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Role.*; +import static net.hostsharing.hsadminng.rbac.generator.StringWriter.with; import static org.apache.commons.lang3.StringUtils.capitalize; import static org.apache.commons.lang3.StringUtils.uncapitalize; @@ -40,7 +40,7 @@ class RolesGrantsAndPermissionsGenerator { simpleEntityVarName = rbacDef.getRootEntityAlias().simpleName(); simpleEntityName = capitalize(simpleEntityVarName); - rawTableName = rbacDef.getRootEntityAlias().getRawTableName(); + rawTableName = rbacDef.getRootEntityAlias().getRawTableNameWithSchema(); } void generateTo(final StringWriter plPgSql) { @@ -53,7 +53,7 @@ class RolesGrantsAndPermissionsGenerator { private void generateHeader(final StringWriter plPgSql, final String triggerType) { plPgSql.writeLn(""" -- ============================================================================ - --changeset ${liquibaseTagPrefix}-rbac-${triggerType}-trigger:1 endDelimiter:--// + --changeset RolesGrantsAndPermissionsGenerator:${liquibaseTagPrefix}-rbac-${triggerType}-trigger endDelimiter:--// -- ---------------------------------------------------------------------------- """, with("liquibaseTagPrefix", liquibaseTagPrefix), @@ -77,17 +77,17 @@ class RolesGrantsAndPermissionsGenerator { plPgSql.writeLn("declare"); plPgSql.indented(() -> { referencedEntityAliases() - .forEach((ea) -> plPgSql.writeLn(entityRefVar(NEW, ea) + " " + ea.getRawTableName() + ";")); + .forEach((ea) -> plPgSql.writeLn(entityRefVar(NEW, ea) + " " + ea.getRawTableNameWithSchema() + ";")); }); plPgSql.writeLn(); plPgSql.writeLn("begin"); plPgSql.indented(() -> { - plPgSql.writeLn("call enterTriggerForObjectUuid(NEW.uuid);"); + plPgSql.writeLn("call rbac.enterTriggerForObjectUuid(NEW.uuid);"); plPgSql.writeLn(); generateCreateRolesAndGrantsAfterInsert(plPgSql); plPgSql.ensureSingleEmptyLine(); - plPgSql.writeLn("call leaveTriggerForObjectUuid(NEW.uuid);"); + plPgSql.writeLn("call rbac.leaveTriggerForObjectUuid(NEW.uuid);"); }); plPgSql.writeLn("end; $$;"); plPgSql.writeLn(); @@ -114,7 +114,7 @@ class RolesGrantsAndPermissionsGenerator { begin if ${updateConditions} then - delete from rbacgrants g where g.grantedbytriggerof = OLD.uuid; + delete from rbac.grants g where g.grantedbytriggerof = OLD.uuid; call buildRbacSystemFor${simpleEntityName}(NEW); end if; end; $$; @@ -145,19 +145,19 @@ class RolesGrantsAndPermissionsGenerator { plPgSql.indented(() -> { referencedEntityAliases() .forEach((ea) -> { - plPgSql.writeLn(entityRefVar(OLD, ea) + " " + ea.getRawTableName() + ";"); - plPgSql.writeLn(entityRefVar(NEW, ea) + " " + ea.getRawTableName() + ";"); + plPgSql.writeLn(entityRefVar(OLD, ea) + " " + ea.getRawTableNameWithSchema() + ";"); + plPgSql.writeLn(entityRefVar(NEW, ea) + " " + ea.getRawTableNameWithSchema() + ";"); }); }); plPgSql.writeLn(); plPgSql.writeLn("begin"); plPgSql.indented(() -> { - plPgSql.writeLn("call enterTriggerForObjectUuid(NEW.uuid);"); + plPgSql.writeLn("call rbac.enterTriggerForObjectUuid(NEW.uuid);"); plPgSql.writeLn(); generateUpdateRolesAndGrantsAfterUpdate(plPgSql); plPgSql.ensureSingleEmptyLine(); - plPgSql.writeLn("call leaveTriggerForObjectUuid(NEW.uuid);"); + plPgSql.writeLn("call rbac.leaveTriggerForObjectUuid(NEW.uuid);"); }); plPgSql.writeLn("end; $$;"); plPgSql.writeLn(); @@ -309,10 +309,10 @@ class RolesGrantsAndPermissionsGenerator { private String generateRevoke(RbacGrantDefinition grantDef) { return switch (grantDef.grantType()) { case ROLE_TO_USER -> throw new IllegalArgumentException("unexpected grant"); - case ROLE_TO_ROLE -> "call revokeRoleFromRole(${subRoleRef}, ${superRoleRef});" + case ROLE_TO_ROLE -> "call rbac.revokeRoleFromRole(${subRoleRef}, ${superRoleRef});" .replace("${subRoleRef}", roleRef(OLD, grantDef.getSubRoleDef())) .replace("${superRoleRef}", roleRef(OLD, grantDef.getSuperRoleDef())); - case PERM_TO_ROLE -> "call revokePermissionFromRole(${permRef}, ${superRoleRef});" + case PERM_TO_ROLE -> "call rbac.revokePermissionFromRole(${permRef}, ${superRoleRef});" .replace("${permRef}", getPerm(OLD, grantDef.getPermDef())) .replace("${superRoleRef}", roleRef(OLD, grantDef.getSuperRoleDef())); }; @@ -321,13 +321,13 @@ class RolesGrantsAndPermissionsGenerator { private String generateGrant(RbacGrantDefinition grantDef) { final var grantSql = switch (grantDef.grantType()) { case ROLE_TO_USER -> throw new IllegalArgumentException("unexpected grant"); - case ROLE_TO_ROLE -> "call grantRoleToRole(${subRoleRef}, ${superRoleRef}${assumed});" - .replace("${assumed}", grantDef.isAssumed() ? "" : ", unassumed()") + case ROLE_TO_ROLE -> "call rbac.grantRoleToRole(${subRoleRef}, ${superRoleRef}${assumed});" + .replace("${assumed}", grantDef.isAssumed() ? "" : ", rbac.unassumed()") .replace("${subRoleRef}", roleRef(NEW, grantDef.getSubRoleDef())) .replace("${superRoleRef}", roleRef(NEW, grantDef.getSuperRoleDef())); case PERM_TO_ROLE -> grantDef.getPermDef().getPermission() == INSERT ? "" - : "call grantPermissionToRole(${permRef}, ${superRoleRef});" + : "call rbac.grantPermissionToRole(${permRef}, ${superRoleRef});" .replace("${permRef}", createPerm(NEW, grantDef.getPermDef())) .replace("${superRoleRef}", roleRef(NEW, grantDef.getSuperRoleDef())); }; @@ -335,15 +335,15 @@ class RolesGrantsAndPermissionsGenerator { } private String findPerm(final PostgresTriggerReference ref, final RbacPermissionDefinition permDef) { - return permRef("findPermissionId", ref, permDef); + return permRef("rbac.findPermissionId", ref, permDef); } private String getPerm(final PostgresTriggerReference ref, final RbacPermissionDefinition permDef) { - return permRef("getPermissionId", ref, permDef); + return permRef("rbac.getPermissionId", ref, permDef); } private String createPerm(final PostgresTriggerReference ref, final RbacPermissionDefinition permDef) { - return permRef("createPermission", ref, permDef); + return permRef("rbac.createPermission", ref, permDef); } private String permRef(final String functionName, final PostgresTriggerReference ref, final RbacPermissionDefinition permDef) { @@ -364,7 +364,7 @@ class RolesGrantsAndPermissionsGenerator { System.out.println("null"); } if (roleDef.getEntityAlias().isGlobal()) { - return "globalAdmin()"; + return "rbac.globalAdmin()"; } final String entityRefVar = entityRefVar(rootRefVar, roleDef.getEntityAlias()); return roleDef.getEntityAlias().simpleName() + capitalize(roleDef.getRole().name()) @@ -389,7 +389,7 @@ class RolesGrantsAndPermissionsGenerator { } plPgSql.writeLn(); - plPgSql.writeLn("perform createRoleWithGrants("); + plPgSql.writeLn("perform rbac.defineRoleWithGrants("); plPgSql.indented(() -> { plPgSql.writeLn("${simpleVarName)${roleSuffix}(NEW)," .replace("${simpleVarName)", simpleEntityVarName) @@ -415,7 +415,7 @@ class RolesGrantsAndPermissionsGenerator { .map(this::toPlPgSqlReference) .toList(); plPgSql.indented(() -> - plPgSql.writeLn("userUuids => array[" + joinArrayElements(arrayElements, 2) + "],\n")); + plPgSql.writeLn("subjectUuids => array[" + joinArrayElements(arrayElements, 2) + "],\n")); rbacGrants.removeAll(grantsToUsers); } } @@ -578,9 +578,9 @@ class RolesGrantsAndPermissionsGenerator { plPgSql.writeLn(); } - private String toPlPgSqlReference(final RbacView.RbacUserReference userRef) { + private String toPlPgSqlReference(final RbacView.RbacSubjectReference userRef) { return switch (userRef.role) { - case CREATOR -> "currentUserUuid()"; + case CREATOR -> "rbac.currentSubjectUuid()"; default -> throw new IllegalArgumentException("unknown user role: " + userRef); }; } @@ -589,9 +589,9 @@ class RolesGrantsAndPermissionsGenerator { final PostgresTriggerReference triggerRef, final RbacView.RbacRoleDefinition roleDef, final boolean assumed) { - final var assumedArg = assumed ? "" : ", unassumed()"; + final var assumedArg = assumed ? "" : ", rbac.unassumed()"; return toRoleRef(roleDef) + - (roleDef.getEntityAlias().isGlobal() ? ( assumed ? "()" : "(unassumed())") + (roleDef.getEntityAlias().isGlobal() ? ( assumed ? "()" : "(rbac.unassumed())") : rbacDef.isRootEntityAlias(roleDef.getEntityAlias()) ? ("(" + triggerRef.name() + ")") : "(" + toTriggerReference(triggerRef, roleDef.getEntityAlias()) + assumedArg + ")"); } diff --git a/src/main/java/net/hostsharing/hsadminng/rbac/rbacdef/StringWriter.java b/src/main/java/net/hostsharing/hsadminng/rbac/generator/StringWriter.java similarity index 98% rename from src/main/java/net/hostsharing/hsadminng/rbac/rbacdef/StringWriter.java rename to src/main/java/net/hostsharing/hsadminng/rbac/generator/StringWriter.java index d78e9a3b..346b8e4d 100644 --- a/src/main/java/net/hostsharing/hsadminng/rbac/rbacdef/StringWriter.java +++ b/src/main/java/net/hostsharing/hsadminng/rbac/generator/StringWriter.java @@ -1,4 +1,4 @@ -package net.hostsharing.hsadminng.rbac.rbacdef; +package net.hostsharing.hsadminng.rbac.generator; import org.apache.commons.lang3.StringUtils; diff --git a/src/main/java/net/hostsharing/hsadminng/rbac/rbacdef/package-info.java b/src/main/java/net/hostsharing/hsadminng/rbac/generator/package-info.java similarity index 81% rename from src/main/java/net/hostsharing/hsadminng/rbac/rbacdef/package-info.java rename to src/main/java/net/hostsharing/hsadminng/rbac/generator/package-info.java index 2a193f2f..8f78c10c 100644 --- a/src/main/java/net/hostsharing/hsadminng/rbac/rbacdef/package-info.java +++ b/src/main/java/net/hostsharing/hsadminng/rbac/generator/package-info.java @@ -1,4 +1,4 @@ -package net.hostsharing.hsadminng.rbac.rbacdef; +package net.hostsharing.hsadminng.rbac.generator; // TODO: The whole code in this package is more like a quick hack to solve an urgent problem. // It should be re-written in PostgreSQL pl/pgsql, diff --git a/src/main/java/net/hostsharing/hsadminng/rbac/rbacgrant/RawRbacGrantEntity.java b/src/main/java/net/hostsharing/hsadminng/rbac/grant/RawRbacGrantEntity.java similarity index 95% rename from src/main/java/net/hostsharing/hsadminng/rbac/rbacgrant/RawRbacGrantEntity.java rename to src/main/java/net/hostsharing/hsadminng/rbac/grant/RawRbacGrantEntity.java index f7b3cdf4..f166bbe0 100644 --- a/src/main/java/net/hostsharing/hsadminng/rbac/rbacgrant/RawRbacGrantEntity.java +++ b/src/main/java/net/hostsharing/hsadminng/rbac/grant/RawRbacGrantEntity.java @@ -1,4 +1,4 @@ -package net.hostsharing.hsadminng.rbac.rbacgrant; +package net.hostsharing.hsadminng.rbac.grant; import lombok.*; import org.springframework.data.annotation.Immutable; @@ -12,7 +12,7 @@ import java.util.List; import java.util.UUID; @Entity -@Table(name = "rbacgrants_ev") +@Table(schema = "rbac", name = "grants_ev") @Getter @Setter @Builder diff --git a/src/main/java/net/hostsharing/hsadminng/rbac/rbacgrant/RawRbacGrantRepository.java b/src/main/java/net/hostsharing/hsadminng/rbac/grant/RawRbacGrantRepository.java similarity index 88% rename from src/main/java/net/hostsharing/hsadminng/rbac/rbacgrant/RawRbacGrantRepository.java rename to src/main/java/net/hostsharing/hsadminng/rbac/grant/RawRbacGrantRepository.java index 37828bdf..1d0ba3a1 100644 --- a/src/main/java/net/hostsharing/hsadminng/rbac/rbacgrant/RawRbacGrantRepository.java +++ b/src/main/java/net/hostsharing/hsadminng/rbac/grant/RawRbacGrantRepository.java @@ -1,4 +1,4 @@ -package net.hostsharing.hsadminng.rbac.rbacgrant; +package net.hostsharing.hsadminng.rbac.grant; import org.springframework.data.repository.Repository; diff --git a/src/main/java/net/hostsharing/hsadminng/rbac/rbacgrant/RbacGrantController.java b/src/main/java/net/hostsharing/hsadminng/rbac/grant/RbacGrantController.java similarity index 72% rename from src/main/java/net/hostsharing/hsadminng/rbac/rbacgrant/RbacGrantController.java rename to src/main/java/net/hostsharing/hsadminng/rbac/grant/RbacGrantController.java index 9dfaea74..4ca538b9 100644 --- a/src/main/java/net/hostsharing/hsadminng/rbac/rbacgrant/RbacGrantController.java +++ b/src/main/java/net/hostsharing/hsadminng/rbac/grant/RbacGrantController.java @@ -1,4 +1,4 @@ -package net.hostsharing.hsadminng.rbac.rbacgrant; +package net.hostsharing.hsadminng.rbac.grant; import net.hostsharing.hsadminng.context.Context; import net.hostsharing.hsadminng.mapper.Mapper; @@ -33,14 +33,14 @@ public class RbacGrantController implements RbacGrantsApi { @Override @Transactional(readOnly = true) public ResponseEntity getGrantById( - final String currentUser, + final String currentSubject, final String assumedRoles, final UUID grantedRoleUuid, - final UUID granteeUserUuid) { + final UUID granteeSubjectUuid) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); - final var id = new RbacGrantId(granteeUserUuid, grantedRoleUuid); + final var id = new RbacGrantId(granteeSubjectUuid, grantedRoleUuid); final var result = rbacGrantRepository.findById(id); if (result == null) { return ResponseEntity.notFound().build(); @@ -50,23 +50,23 @@ public class RbacGrantController implements RbacGrantsApi { @Override @Transactional(readOnly = true) - public ResponseEntity> listUserGrants( - final String currentUser, + public ResponseEntity> listSubjectGrants( + final String currentSubject, final String assumedRoles) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); return ResponseEntity.ok(mapper.mapList(rbacGrantRepository.findAll(), RbacGrantResource.class)); } @Override @Transactional - public ResponseEntity grantRoleToUser( - final String currentUser, + public ResponseEntity grantRoleToSubject( + final String currentSubject, final String assumedRoles, final RbacGrantResource body) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var granted = rbacGrantRepository.save(mapper.map(body, RbacGrantEntity.class)); em.flush(); @@ -82,28 +82,28 @@ public class RbacGrantController implements RbacGrantsApi { @Override @Transactional - public ResponseEntity revokeRoleFromUser( - final String currentUser, + public ResponseEntity revokeRoleFromSubject( + final String currentSubject, final String assumedRoles, final UUID grantedRoleUuid, - final UUID granteeUserUuid) { + final UUID granteeSubjectUuid) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); - rbacGrantRepository.deleteByRbacGrantId(new RbacGrantId(granteeUserUuid, grantedRoleUuid)); + rbacGrantRepository.deleteByRbacGrantId(new RbacGrantId(granteeSubjectUuid, grantedRoleUuid)); return ResponseEntity.noContent().build(); } -// TODO: implement an endpoint to create a Mermaid flowchart with all grants of a given user +// TODO.feat: implement an endpoint to create a Mermaid flowchart with all grants of a given user // @GetMapping( -// path = "/api/rbac/users/{userUuid}/grants", +// path = "/api/rbac/subjects/{subjectUuid}/grants", // produces = {"text/vnd.mermaid"}) // @Transactional(readOnly = true) // public ResponseEntity allGrantsOfUserAsMermaid( -// @RequestHeader(name = "current-user") String currentUser, +// @RequestHeader(name = "current-subject") String currentSubject, // @RequestHeader(name = "assumed-roles", required = false) String assumedRoles) { -// final var graph = RbacGrantsDiagramService.allGrantsToUser(currentUser); +// final var graph = RbacGrantsDiagramService.allGrantsToUser(currentSubject); // return ResponseEntity.ok(graph); // } diff --git a/src/main/java/net/hostsharing/hsadminng/rbac/rbacgrant/RbacGrantEntity.java b/src/main/java/net/hostsharing/hsadminng/rbac/grant/RbacGrantEntity.java similarity index 80% rename from src/main/java/net/hostsharing/hsadminng/rbac/rbacgrant/RbacGrantEntity.java rename to src/main/java/net/hostsharing/hsadminng/rbac/grant/RbacGrantEntity.java index c2f2d524..68152e59 100644 --- a/src/main/java/net/hostsharing/hsadminng/rbac/rbacgrant/RbacGrantEntity.java +++ b/src/main/java/net/hostsharing/hsadminng/rbac/grant/RbacGrantEntity.java @@ -1,14 +1,14 @@ -package net.hostsharing.hsadminng.rbac.rbacgrant; +package net.hostsharing.hsadminng.rbac.grant; import lombok.*; -import net.hostsharing.hsadminng.rbac.rbacrole.RbacRoleType; +import net.hostsharing.hsadminng.rbac.role.RbacRoleType; import org.springframework.data.annotation.Immutable; import jakarta.persistence.*; import java.util.UUID; @Entity -@Table(name = "rbacgrants_rv") +@Table(schema = "rbac", name = "grants_rv") @IdClass(RbacGrantId.class) @Getter @Setter @@ -33,11 +33,11 @@ public class RbacGrantEntity { private UUID grantedRoleUuid; @Column(name = "username", updatable = false, insertable = false) - private String granteeUserName; + private String granteeSubjectName; @Id - @Column(name = "useruuid") - private UUID granteeUserUuid; + @Column(name = "subjectuuid") + private UUID granteeSubjectUuid; private boolean assumed; @@ -55,12 +55,12 @@ public class RbacGrantEntity { private RbacRoleType grantedRoleType; RbacGrantId getRbacGrantId() { - return new RbacGrantId(granteeUserUuid, grantedRoleUuid); + return new RbacGrantId(granteeSubjectUuid, grantedRoleUuid); } public String toDisplay() { return "{ grant role:" + grantedRoleIdName + - " to user:" + granteeUserName + + " to user:" + granteeSubjectName + " by role:" + grantedByRoleIdName + (assumed ? " and assume" : "") + " }"; diff --git a/src/main/java/net/hostsharing/hsadminng/rbac/rbacgrant/RbacGrantId.java b/src/main/java/net/hostsharing/hsadminng/rbac/grant/RbacGrantId.java similarity index 79% rename from src/main/java/net/hostsharing/hsadminng/rbac/rbacgrant/RbacGrantId.java rename to src/main/java/net/hostsharing/hsadminng/rbac/grant/RbacGrantId.java index 4c3449e7..86182c14 100644 --- a/src/main/java/net/hostsharing/hsadminng/rbac/rbacgrant/RbacGrantId.java +++ b/src/main/java/net/hostsharing/hsadminng/rbac/grant/RbacGrantId.java @@ -1,4 +1,4 @@ -package net.hostsharing.hsadminng.rbac.rbacgrant; +package net.hostsharing.hsadminng.rbac.grant; import lombok.AllArgsConstructor; import lombok.EqualsAndHashCode; @@ -14,6 +14,6 @@ import java.util.UUID; @AllArgsConstructor public class RbacGrantId implements Serializable { - private UUID granteeUserUuid; + private UUID granteeSubjectUuid; private UUID grantedRoleUuid; } diff --git a/src/main/java/net/hostsharing/hsadminng/rbac/rbacgrant/RbacGrantRepository.java b/src/main/java/net/hostsharing/hsadminng/rbac/grant/RbacGrantRepository.java similarity index 80% rename from src/main/java/net/hostsharing/hsadminng/rbac/rbacgrant/RbacGrantRepository.java rename to src/main/java/net/hostsharing/hsadminng/rbac/grant/RbacGrantRepository.java index 90cf0e58..9621e1f4 100644 --- a/src/main/java/net/hostsharing/hsadminng/rbac/rbacgrant/RbacGrantRepository.java +++ b/src/main/java/net/hostsharing/hsadminng/rbac/grant/RbacGrantRepository.java @@ -1,4 +1,4 @@ -package net.hostsharing.hsadminng.rbac.rbacgrant; +package net.hostsharing.hsadminng.rbac.grant; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; @@ -11,7 +11,7 @@ public interface RbacGrantRepository extends Repository> descendantsByUuid = new HashMap<>(); - public String allGrantsToCurrentUser(final EnumSet includes) { + public String allGrantsTocurrentSubject(final EnumSet includes) { final var graph = new LimitedHashSet(); - for ( UUID subjectUuid: context.currentSubjectsUuids() ) { + for ( UUID subjectUuid: context.fetchCurrentSubjectOrAssumedRolesUuids() ) { traverseGrantsTo(graph, subjectUuid, includes); } return toMermaidFlowchart(graph, includes); @@ -78,7 +78,7 @@ public class RbacGrantsDiagramService { if (!includes.contains(PERMISSIONS) && g.getDescendantIdName().startsWith("perm:")) { return; } - if ( !g.getDescendantIdName().startsWith("role:global")) { + if ( !g.getDescendantIdName().startsWith("role:rbac.global")) { if (!includes.contains(TEST_ENTITIES) && g.getDescendantIdName().contains(":test_")) { return; } @@ -94,7 +94,7 @@ public class RbacGrantsDiagramService { } public String allGrantsFrom(final UUID targetObject, final String op, final EnumSet includes) { - final var refUuid = (UUID) em.createNativeQuery("SELECT uuid FROM rbacpermission WHERE objectuuid=:targetObject AND op=:op") + final var refUuid = (UUID) em.createNativeQuery("SELECT uuid FROM rbac.permission WHERE objectuuid=:targetObject AND op=:op") .setParameter("targetObject", targetObject) .setParameter("op", op) .getSingleResult(); diff --git a/src/main/java/net/hostsharing/hsadminng/rbac/rbacobject/BaseEntity.java b/src/main/java/net/hostsharing/hsadminng/rbac/object/BaseEntity.java similarity index 88% rename from src/main/java/net/hostsharing/hsadminng/rbac/rbacobject/BaseEntity.java rename to src/main/java/net/hostsharing/hsadminng/rbac/object/BaseEntity.java index d0e7605f..1d0211bb 100644 --- a/src/main/java/net/hostsharing/hsadminng/rbac/rbacobject/BaseEntity.java +++ b/src/main/java/net/hostsharing/hsadminng/rbac/object/BaseEntity.java @@ -1,4 +1,4 @@ -package net.hostsharing.hsadminng.rbac.rbacobject; +package net.hostsharing.hsadminng.rbac.object; import org.hibernate.Hibernate; diff --git a/src/main/java/net/hostsharing/hsadminng/rbac/rbacuser/RbacUserRepository.java b/src/main/java/net/hostsharing/hsadminng/rbac/rbacuser/RbacUserRepository.java deleted file mode 100644 index 0c1a168b..00000000 --- a/src/main/java/net/hostsharing/hsadminng/rbac/rbacuser/RbacUserRepository.java +++ /dev/null @@ -1,46 +0,0 @@ -package net.hostsharing.hsadminng.rbac.rbacuser; - -import org.springframework.data.jpa.repository.Modifying; -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.repository.Repository; - -import java.util.List; -import java.util.UUID; - -public interface RbacUserRepository extends Repository { - - @Query(""" - select u from RbacUserEntity u - where :userName is null or u.name like concat(cast(:userName as text), '%') - order by u.name - """) - List findByOptionalNameLike(String userName); - - // bypasses the restricted view, to be able to grant rights to arbitrary user - @Query(value = "select * from rbacuser where name=:userName", nativeQuery = true) - RbacUserEntity findByName(String userName); - - RbacUserEntity findByUuid(UUID uuid); - - @Query(value = "select * from grantedPermissions(:userUuid)", nativeQuery = true) - List findPermissionsOfUserByUuid(UUID userUuid); - - /* - Can't use save/saveAndFlush from SpringData because the uuid is not generated on the entity level, - but explicitly, and then SpringData check's if it exists using an SQL SELECT. - And SQL SELECT needs a currentUser which we don't yet have in the case of self registration. - */ - @Modifying - @Query(value = "insert into RBacUser_RV (uuid, name) values( :#{#newUser.uuid}, :#{#newUser.name})", nativeQuery = true) - void insert(final RbacUserEntity newUser); - - default RbacUserEntity create(final RbacUserEntity rbacUserEntity) { - if (rbacUserEntity.getUuid() == null) { - rbacUserEntity.setUuid(UUID.randomUUID()); - } - insert(rbacUserEntity); - return rbacUserEntity; - } - - void deleteByUuid(UUID userUuid); -} diff --git a/src/main/java/net/hostsharing/hsadminng/rbac/rbacrole/RbacRoleController.java b/src/main/java/net/hostsharing/hsadminng/rbac/role/RbacRoleController.java similarity index 88% rename from src/main/java/net/hostsharing/hsadminng/rbac/rbacrole/RbacRoleController.java rename to src/main/java/net/hostsharing/hsadminng/rbac/role/RbacRoleController.java index 0405fee2..5da97292 100644 --- a/src/main/java/net/hostsharing/hsadminng/rbac/rbacrole/RbacRoleController.java +++ b/src/main/java/net/hostsharing/hsadminng/rbac/role/RbacRoleController.java @@ -1,4 +1,4 @@ -package net.hostsharing.hsadminng.rbac.rbacrole; +package net.hostsharing.hsadminng.rbac.role; import net.hostsharing.hsadminng.context.Context; import net.hostsharing.hsadminng.mapper.Mapper; @@ -26,10 +26,10 @@ public class RbacRoleController implements RbacRolesApi { @Override @Transactional(readOnly = true) public ResponseEntity> listRoles( - final String currentUser, + final String currentSubject, final String assumedRoles) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final List result = rbacRoleRepository.findAll(); diff --git a/src/main/java/net/hostsharing/hsadminng/rbac/rbacrole/RbacRoleEntity.java b/src/main/java/net/hostsharing/hsadminng/rbac/role/RbacRoleEntity.java similarity index 89% rename from src/main/java/net/hostsharing/hsadminng/rbac/rbacrole/RbacRoleEntity.java rename to src/main/java/net/hostsharing/hsadminng/rbac/role/RbacRoleEntity.java index fa21785a..b3c801be 100644 --- a/src/main/java/net/hostsharing/hsadminng/rbac/rbacrole/RbacRoleEntity.java +++ b/src/main/java/net/hostsharing/hsadminng/rbac/role/RbacRoleEntity.java @@ -1,4 +1,4 @@ -package net.hostsharing.hsadminng.rbac.rbacrole; +package net.hostsharing.hsadminng.rbac.role; import lombok.*; import org.hibernate.annotations.Formula; @@ -8,7 +8,7 @@ import jakarta.persistence.*; import java.util.UUID; @Entity -@Table(name = "rbacrole_rv") +@Table(schema = "rbac", name = "role_rv") @Getter @Setter @ToString diff --git a/src/main/java/net/hostsharing/hsadminng/rbac/rbacrole/RbacRoleRepository.java b/src/main/java/net/hostsharing/hsadminng/rbac/role/RbacRoleRepository.java similarity index 91% rename from src/main/java/net/hostsharing/hsadminng/rbac/rbacrole/RbacRoleRepository.java rename to src/main/java/net/hostsharing/hsadminng/rbac/role/RbacRoleRepository.java index 94633d7c..50a2e8b4 100644 --- a/src/main/java/net/hostsharing/hsadminng/rbac/rbacrole/RbacRoleRepository.java +++ b/src/main/java/net/hostsharing/hsadminng/rbac/role/RbacRoleRepository.java @@ -1,4 +1,4 @@ -package net.hostsharing.hsadminng.rbac.rbacrole; +package net.hostsharing.hsadminng.rbac.role; import org.springframework.data.repository.Repository; diff --git a/src/main/java/net/hostsharing/hsadminng/rbac/rbacrole/RbacRoleType.java b/src/main/java/net/hostsharing/hsadminng/rbac/role/RbacRoleType.java similarity index 61% rename from src/main/java/net/hostsharing/hsadminng/rbac/rbacrole/RbacRoleType.java rename to src/main/java/net/hostsharing/hsadminng/rbac/role/RbacRoleType.java index e78e8836..3fad2ff4 100644 --- a/src/main/java/net/hostsharing/hsadminng/rbac/rbacrole/RbacRoleType.java +++ b/src/main/java/net/hostsharing/hsadminng/rbac/role/RbacRoleType.java @@ -1,4 +1,4 @@ -package net.hostsharing.hsadminng.rbac.rbacrole; +package net.hostsharing.hsadminng.rbac.role; public enum RbacRoleType { OWNER, ADMIN, AGENT, TENANT, GUEST, REFERRER diff --git a/src/main/java/net/hostsharing/hsadminng/rbac/rbacuser/RbacUserController.java b/src/main/java/net/hostsharing/hsadminng/rbac/subject/RbacSubjectController.java similarity index 50% rename from src/main/java/net/hostsharing/hsadminng/rbac/rbacuser/RbacUserController.java rename to src/main/java/net/hostsharing/hsadminng/rbac/subject/RbacSubjectController.java index bcc7844b..52c0649b 100644 --- a/src/main/java/net/hostsharing/hsadminng/rbac/rbacuser/RbacUserController.java +++ b/src/main/java/net/hostsharing/hsadminng/rbac/subject/RbacSubjectController.java @@ -1,10 +1,10 @@ -package net.hostsharing.hsadminng.rbac.rbacuser; +package net.hostsharing.hsadminng.rbac.subject; import net.hostsharing.hsadminng.context.Context; import net.hostsharing.hsadminng.mapper.Mapper; -import net.hostsharing.hsadminng.rbac.generated.api.v1.api.RbacUsersApi; -import net.hostsharing.hsadminng.rbac.generated.api.v1.model.RbacUserPermissionResource; -import net.hostsharing.hsadminng.rbac.generated.api.v1.model.RbacUserResource; +import net.hostsharing.hsadminng.rbac.generated.api.v1.api.RbacSubjectsApi; +import net.hostsharing.hsadminng.rbac.generated.api.v1.model.RbacSubjectPermissionResource; +import net.hostsharing.hsadminng.rbac.generated.api.v1.model.RbacSubjectResource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.transaction.annotation.Transactional; @@ -15,7 +15,7 @@ import java.util.List; import java.util.UUID; @RestController -public class RbacUserController implements RbacUsersApi { +public class RbacSubjectController implements RbacSubjectsApi { @Autowired private Context context; @@ -24,81 +24,81 @@ public class RbacUserController implements RbacUsersApi { private Mapper mapper; @Autowired - private RbacUserRepository rbacUserRepository; + private RbacSubjectRepository rbacSubjectRepository; @Override @Transactional - public ResponseEntity createUser( - final RbacUserResource body + public ResponseEntity createSubject( + final RbacSubjectResource body ) { context.define(null); if (body.getUuid() == null) { body.setUuid(UUID.randomUUID()); } - final var saved = mapper.map(body, RbacUserEntity.class); - rbacUserRepository.create(saved); + final var saved = mapper.map(body, RbacSubjectEntity.class); + rbacSubjectRepository.create(saved); final var uri = MvcUriComponentsBuilder.fromController(getClass()) .path("/api/rbac.yaml/users/{id}") .buildAndExpand(saved.getUuid()) .toUri(); - return ResponseEntity.created(uri).body(mapper.map(saved, RbacUserResource.class)); + return ResponseEntity.created(uri).body(mapper.map(saved, RbacSubjectResource.class)); } @Override @Transactional - public ResponseEntity deleteUserByUuid( - final String currentUser, + public ResponseEntity deleteSubjectByUuid( + final String currentSubject, final String assumedRoles, - final UUID userUuid + final UUID subjectUuid ) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); - rbacUserRepository.deleteByUuid(userUuid); + rbacSubjectRepository.deleteByUuid(subjectUuid); return ResponseEntity.noContent().build(); } @Override @Transactional(readOnly = true) - public ResponseEntity getUserById( - final String currentUser, + public ResponseEntity getSubjectById( + final String currentSubject, final String assumedRoles, - final UUID userUuid) { + final UUID subjectUuid) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); - final var result = rbacUserRepository.findByUuid(userUuid); + final var result = rbacSubjectRepository.findByUuid(subjectUuid); if (result == null) { return ResponseEntity.notFound().build(); } - return ResponseEntity.ok(mapper.map(result, RbacUserResource.class)); + return ResponseEntity.ok(mapper.map(result, RbacSubjectResource.class)); } @Override @Transactional(readOnly = true) - public ResponseEntity> listUsers( - final String currentUser, + public ResponseEntity> listSubjects( + final String currentSubject, final String assumedRoles, final String userName ) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); - return ResponseEntity.ok(mapper.mapList(rbacUserRepository.findByOptionalNameLike(userName), RbacUserResource.class)); + return ResponseEntity.ok(mapper.mapList(rbacSubjectRepository.findByOptionalNameLike(userName), RbacSubjectResource.class)); } @Override @Transactional(readOnly = true) - public ResponseEntity> listUserPermissions( - final String currentUser, + public ResponseEntity> listSubjectPermissions( + final String currentSubject, final String assumedRoles, - final UUID userUuid + final UUID subjectUuid ) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); return ResponseEntity.ok(mapper.mapList( - rbacUserRepository.findPermissionsOfUserByUuid(userUuid), - RbacUserPermissionResource.class)); + rbacSubjectRepository.findPermissionsOfUserByUuid(subjectUuid), + RbacSubjectPermissionResource.class)); } } diff --git a/src/main/java/net/hostsharing/hsadminng/rbac/rbacuser/RbacUserEntity.java b/src/main/java/net/hostsharing/hsadminng/rbac/subject/RbacSubjectEntity.java similarity index 92% rename from src/main/java/net/hostsharing/hsadminng/rbac/rbacuser/RbacUserEntity.java rename to src/main/java/net/hostsharing/hsadminng/rbac/subject/RbacSubjectEntity.java index 8da64357..3ff2c81d 100644 --- a/src/main/java/net/hostsharing/hsadminng/rbac/rbacuser/RbacUserEntity.java +++ b/src/main/java/net/hostsharing/hsadminng/rbac/subject/RbacSubjectEntity.java @@ -1,4 +1,4 @@ -package net.hostsharing.hsadminng.rbac.rbacuser; +package net.hostsharing.hsadminng.rbac.subject; import lombok.*; import org.springframework.data.annotation.Immutable; @@ -13,14 +13,14 @@ import java.time.temporal.ChronoUnit; import java.util.UUID; @Entity -@Table(name = "rbacuser_rv") +@Table(schema = "rbac", name = "subject_rv") @Getter @Setter @ToString @Immutable @NoArgsConstructor @AllArgsConstructor -public class RbacUserEntity { +public class RbacSubjectEntity { private static final int MAX_VALIDITY_DAYS = 21; private static DateTimeFormatter DATE_FORMAT_WITH_FULLHOUR = DateTimeFormatter.ofPattern("MM-dd-yyyy HH"); diff --git a/src/main/java/net/hostsharing/hsadminng/rbac/rbacuser/RbacUserPermission.java b/src/main/java/net/hostsharing/hsadminng/rbac/subject/RbacSubjectPermission.java similarity index 73% rename from src/main/java/net/hostsharing/hsadminng/rbac/rbacuser/RbacUserPermission.java rename to src/main/java/net/hostsharing/hsadminng/rbac/subject/RbacSubjectPermission.java index f29503c3..9a82ad2d 100644 --- a/src/main/java/net/hostsharing/hsadminng/rbac/rbacuser/RbacUserPermission.java +++ b/src/main/java/net/hostsharing/hsadminng/rbac/subject/RbacSubjectPermission.java @@ -1,8 +1,8 @@ -package net.hostsharing.hsadminng.rbac.rbacuser; +package net.hostsharing.hsadminng.rbac.subject; import java.util.UUID; -public interface RbacUserPermission { +public interface RbacSubjectPermission { UUID getRoleUuid(); String getRoleName(); diff --git a/src/main/java/net/hostsharing/hsadminng/rbac/subject/RbacSubjectRepository.java b/src/main/java/net/hostsharing/hsadminng/rbac/subject/RbacSubjectRepository.java new file mode 100644 index 00000000..16a13962 --- /dev/null +++ b/src/main/java/net/hostsharing/hsadminng/rbac/subject/RbacSubjectRepository.java @@ -0,0 +1,46 @@ +package net.hostsharing.hsadminng.rbac.subject; + +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.Repository; + +import java.util.List; +import java.util.UUID; + +public interface RbacSubjectRepository extends Repository { + + @Query(""" + select u from RbacSubjectEntity u + where :userName is null or u.name like concat(cast(:userName as text), '%') + order by u.name + """) + List findByOptionalNameLike(String userName); + + // bypasses the restricted view, to be able to grant rights to arbitrary user + @Query(value = "select * from rbac.subject where name=:userName", nativeQuery = true) + RbacSubjectEntity findByName(String userName); + + RbacSubjectEntity findByUuid(UUID uuid); + + @Query(value = "select * from rbac.grantedPermissions(:subjectUuid)", nativeQuery = true) + List findPermissionsOfUserByUuid(UUID subjectUuid); + + /* + Can't use save/saveAndFlush from SpringData because the uuid is not generated on the entity level, + but explicitly, and then SpringData check's if it exists using an SQL SELECT. + And SQL SELECT needs a currentSubject which we don't yet have in the case of self registration. + */ + @Modifying + @Query(value = "insert into rbac.subject_rv (uuid, name) values( :#{#newUser.uuid}, :#{#newUser.name})", nativeQuery = true) + void insert(final RbacSubjectEntity newUser); + + default RbacSubjectEntity create(final RbacSubjectEntity rbacSubjectEntity) { + if (rbacSubjectEntity.getUuid() == null) { + rbacSubjectEntity.setUuid(UUID.randomUUID()); + } + insert(rbacSubjectEntity); + return rbacSubjectEntity; + } + + void deleteByUuid(UUID subjectUuid); +} diff --git a/src/main/java/net/hostsharing/hsadminng/rbac/test/cust/TestCustomerController.java b/src/main/java/net/hostsharing/hsadminng/rbac/test/cust/TestCustomerController.java index d0ab74bf..c6bbc115 100644 --- a/src/main/java/net/hostsharing/hsadminng/rbac/test/cust/TestCustomerController.java +++ b/src/main/java/net/hostsharing/hsadminng/rbac/test/cust/TestCustomerController.java @@ -32,11 +32,11 @@ public class TestCustomerController implements TestCustomersApi { @Override @Transactional(readOnly = true) public ResponseEntity> listCustomers( - String currentUser, + String currentSubject, String assumedRoles, String prefix ) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var result = testCustomerRepository.findCustomerByOptionalPrefixLike(prefix); @@ -46,11 +46,11 @@ public class TestCustomerController implements TestCustomersApi { @Override @Transactional public ResponseEntity addCustomer( - final String currentUser, + final String currentSubject, final String assumedRoles, final TestCustomerResource customer) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var saved = testCustomerRepository.save(mapper.map(customer, TestCustomerEntity.class)); final var uri = diff --git a/src/main/java/net/hostsharing/hsadminng/rbac/test/cust/TestCustomerEntity.java b/src/main/java/net/hostsharing/hsadminng/rbac/test/cust/TestCustomerEntity.java index 72df9c48..f60fd11d 100644 --- a/src/main/java/net/hostsharing/hsadminng/rbac/test/cust/TestCustomerEntity.java +++ b/src/main/java/net/hostsharing/hsadminng/rbac/test/cust/TestCustomerEntity.java @@ -5,19 +5,19 @@ import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; -import net.hostsharing.hsadminng.rbac.rbacobject.BaseEntity; -import net.hostsharing.hsadminng.rbac.rbacdef.RbacView; -import net.hostsharing.hsadminng.rbac.rbacdef.RbacView.SQL; +import net.hostsharing.hsadminng.rbac.object.BaseEntity; +import net.hostsharing.hsadminng.rbac.generator.RbacView; +import net.hostsharing.hsadminng.rbac.generator.RbacView.SQL; import jakarta.persistence.*; import java.io.IOException; import java.util.UUID; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.GLOBAL; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Permission.*; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.RbacUserReference.UserRole.CREATOR; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Role.*; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.rbacViewFor; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.GLOBAL; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Permission.*; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.RbacSubjectReference.UserRole.CREATOR; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Role.*; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.rbacViewFor; @Entity @Table(name = "test_customer_rv") @@ -46,7 +46,7 @@ public class TestCustomerEntity implements BaseEntity { .withIdentityView(SQL.projection("prefix")) .withRestrictedViewOrderBy(SQL.expression("reference")) .withUpdatableColumns("reference", "prefix", "adminUserName") - .toRole("global", ADMIN).grantPermission(INSERT) + .toRole("rbac.global", ADMIN).grantPermission(INSERT) .createRole(OWNER, (with) -> { with.owningUser(CREATOR).unassumed(); diff --git a/src/main/java/net/hostsharing/hsadminng/rbac/test/dom/TestDomainEntity.java b/src/main/java/net/hostsharing/hsadminng/rbac/test/dom/TestDomainEntity.java index 5d1369ca..3af8bd66 100644 --- a/src/main/java/net/hostsharing/hsadminng/rbac/test/dom/TestDomainEntity.java +++ b/src/main/java/net/hostsharing/hsadminng/rbac/test/dom/TestDomainEntity.java @@ -4,22 +4,22 @@ import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; -import net.hostsharing.hsadminng.rbac.rbacobject.BaseEntity; -import net.hostsharing.hsadminng.rbac.rbacdef.RbacView; -import net.hostsharing.hsadminng.rbac.rbacdef.RbacView.SQL; +import net.hostsharing.hsadminng.rbac.object.BaseEntity; +import net.hostsharing.hsadminng.rbac.generator.RbacView; +import net.hostsharing.hsadminng.rbac.generator.RbacView.SQL; import net.hostsharing.hsadminng.rbac.test.pac.TestPackageEntity; import jakarta.persistence.*; import java.io.IOException; import java.util.UUID; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Column.dependsOnColumn; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.ColumnValue.usingDefaultCase; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Nullable.NOT_NULL; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Permission.*; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Role.*; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.SQL.directlyFetchedByDependsOnColumn; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.rbacViewFor; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Column.dependsOnColumn; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.ColumnValue.usingDefaultCase; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Nullable.NOT_NULL; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Permission.*; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Role.*; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.SQL.directlyFetchedByDependsOnColumn; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.rbacViewFor; @Entity @Table(name = "test_domain_rv") diff --git a/src/main/java/net/hostsharing/hsadminng/rbac/test/pac/TestPackageController.java b/src/main/java/net/hostsharing/hsadminng/rbac/test/pac/TestPackageController.java index 8bb94971..c6ecc7e0 100644 --- a/src/main/java/net/hostsharing/hsadminng/rbac/test/pac/TestPackageController.java +++ b/src/main/java/net/hostsharing/hsadminng/rbac/test/pac/TestPackageController.java @@ -29,11 +29,11 @@ public class TestPackageController implements TestPackagesApi { @Override @Transactional(readOnly = true) public ResponseEntity> listPackages( - String currentUser, + String currentSubject, String assumedRoles, String name ) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var result = testPackageRepository.findAllByOptionalNameLike(name); return ResponseEntity.ok(mapper.mapList(result, TestPackageResource.class)); @@ -42,12 +42,12 @@ public class TestPackageController implements TestPackagesApi { @Override @Transactional public ResponseEntity updatePackage( - final String currentUser, + final String currentSubject, final String assumedRoles, final UUID packageUuid, final TestPackageUpdateResource body) { - context.define(currentUser, assumedRoles); + context.define(currentSubject, assumedRoles); final var current = testPackageRepository.findByUuid(packageUuid); OptionalFromJson.of(body.getDescription()).ifPresent(current::setDescription); diff --git a/src/main/java/net/hostsharing/hsadminng/rbac/test/pac/TestPackageEntity.java b/src/main/java/net/hostsharing/hsadminng/rbac/test/pac/TestPackageEntity.java index 8f4541d5..19e58733 100644 --- a/src/main/java/net/hostsharing/hsadminng/rbac/test/pac/TestPackageEntity.java +++ b/src/main/java/net/hostsharing/hsadminng/rbac/test/pac/TestPackageEntity.java @@ -4,22 +4,22 @@ import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; -import net.hostsharing.hsadminng.rbac.rbacobject.BaseEntity; -import net.hostsharing.hsadminng.rbac.rbacdef.RbacView; -import net.hostsharing.hsadminng.rbac.rbacdef.RbacView.SQL; +import net.hostsharing.hsadminng.rbac.object.BaseEntity; +import net.hostsharing.hsadminng.rbac.generator.RbacView; +import net.hostsharing.hsadminng.rbac.generator.RbacView.SQL; import net.hostsharing.hsadminng.rbac.test.cust.TestCustomerEntity; import jakarta.persistence.*; import java.io.IOException; import java.util.UUID; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Column.dependsOnColumn; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.ColumnValue.usingDefaultCase; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Nullable.NOT_NULL; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Permission.*; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.Role.*; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.SQL.*; -import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.rbacViewFor; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Column.dependsOnColumn; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.ColumnValue.usingDefaultCase; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Nullable.NOT_NULL; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Permission.*; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.Role.*; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.SQL.*; +import static net.hostsharing.hsadminng.rbac.generator.RbacView.rbacViewFor; @Entity @Table(name = "test_package_rv") diff --git a/src/main/resources/api-definition/auth.yaml b/src/main/resources/api-definition/auth.yaml index 65d491fb..138c5eaa 100644 --- a/src/main/resources/api-definition/auth.yaml +++ b/src/main/resources/api-definition/auth.yaml @@ -3,13 +3,13 @@ components: parameters: - currentUser: - name: current-user + currentSubject: + name: current-subject in: header required: true schema: type: string - description: Identifying name of the currently logged in user. + description: Identifying name of the current subject (e.g. user). assumedRoles: name: assumed-roles @@ -17,4 +17,4 @@ components: required: false schema: type: string - description: Semicolon-separated list of roles to assume. The current user needs to have the right to assume these roles. + description: Semicolon-separated list of roles to assume. The current subject needs to have the right to assume these roles. diff --git a/src/main/resources/api-definition/error-responses.yaml b/src/main/resources/api-definition/error-responses.yaml index 83ca3dfb..d7999f91 100644 --- a/src/main/resources/api-definition/error-responses.yaml +++ b/src/main/resources/api-definition/error-responses.yaml @@ -8,13 +8,13 @@ components: schema: $ref: '#/components/schemas/Error' Unauthorized: - description: The current user is unknown or not authorized. + description: The current subject is unknown or not authorized. content: application/json: schema: $ref: '#/components/schemas/Error' Forbidden: - description: The current user or none of the assumed or roles is granted access to the resource. + description: The current subject or none of the assumed or roles is granted access to the resource. content: application/json: schema: diff --git a/src/main/resources/api-definition/hs-booking/auth.yaml b/src/main/resources/api-definition/hs-booking/auth.yaml index 65d491fb..0aa48bf5 100644 --- a/src/main/resources/api-definition/hs-booking/auth.yaml +++ b/src/main/resources/api-definition/hs-booking/auth.yaml @@ -3,13 +3,13 @@ components: parameters: - currentUser: - name: current-user + currentSubject: + name: current-subject in: header required: true schema: type: string - description: Identifying name of the currently logged in user. + description: Identifying name of the currently logged in subject. assumedRoles: name: assumed-roles @@ -17,4 +17,4 @@ components: required: false schema: type: string - description: Semicolon-separated list of roles to assume. The current user needs to have the right to assume these roles. + description: Semicolon-separated list of roles to assume. The current subject needs to have the right to assume these roles. diff --git a/src/main/resources/api-definition/hs-booking/error-responses.yaml b/src/main/resources/api-definition/hs-booking/error-responses.yaml index 83ca3dfb..d7999f91 100644 --- a/src/main/resources/api-definition/hs-booking/error-responses.yaml +++ b/src/main/resources/api-definition/hs-booking/error-responses.yaml @@ -8,13 +8,13 @@ components: schema: $ref: '#/components/schemas/Error' Unauthorized: - description: The current user is unknown or not authorized. + description: The current subject is unknown or not authorized. content: application/json: schema: $ref: '#/components/schemas/Error' Forbidden: - description: The current user or none of the assumed or roles is granted access to the resource. + description: The current subject or none of the assumed or roles is granted access to the resource. content: application/json: schema: diff --git a/src/main/resources/api-definition/hs-booking/hs-booking-items-with-uuid.yaml b/src/main/resources/api-definition/hs-booking/hs-booking-items-with-uuid.yaml index 3d7567c8..e93cb7b6 100644 --- a/src/main/resources/api-definition/hs-booking/hs-booking-items-with-uuid.yaml +++ b/src/main/resources/api-definition/hs-booking/hs-booking-items-with-uuid.yaml @@ -4,7 +4,7 @@ get: description: 'Fetch a single booking item its uuid, if visible for the current subject.' operationId: getBookingItemByUuid parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' - name: bookingItemUuid in: path @@ -32,7 +32,7 @@ patch: description: 'Updates a single booking item identified by its uuid, if permitted for the current subject.' operationId: patchBookingItem parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' - name: bookingItemUuid in: path @@ -63,7 +63,7 @@ delete: description: 'Delete a single booking item identified by its uuid, if permitted for the current subject.' operationId: deleteBookingIemByUuid parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' - name: bookingItemUuid in: path diff --git a/src/main/resources/api-definition/hs-booking/hs-booking-items.yaml b/src/main/resources/api-definition/hs-booking/hs-booking-items.yaml index 40a3d010..e18e4926 100644 --- a/src/main/resources/api-definition/hs-booking/hs-booking-items.yaml +++ b/src/main/resources/api-definition/hs-booking/hs-booking-items.yaml @@ -1,11 +1,11 @@ get: summary: Returns a list of all booking items for a specified project. - description: Returns the list of all booking items for a specified project which are visible to the current user or any of it's assumed roles. + description: Returns the list of all booking items for a specified project which are visible to the current subject or any of it's assumed roles. tags: - hs-booking-items operationId: listBookingItemsByProjectUuid parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' - name: projectUuid in: query @@ -34,7 +34,7 @@ post: - hs-booking-items operationId: addBookingItem parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' requestBody: description: A JSON object describing the new booking item. diff --git a/src/main/resources/api-definition/hs-booking/hs-booking-projects-with-uuid.yaml b/src/main/resources/api-definition/hs-booking/hs-booking-projects-with-uuid.yaml index 085205a7..4c41d51c 100644 --- a/src/main/resources/api-definition/hs-booking/hs-booking-projects-with-uuid.yaml +++ b/src/main/resources/api-definition/hs-booking/hs-booking-projects-with-uuid.yaml @@ -4,7 +4,7 @@ get: description: 'Fetch a single booking project its uuid, if visible for the current subject.' operationId: getBookingProjectByUuid parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' - name: bookingProjectUuid in: path @@ -32,7 +32,7 @@ patch: description: 'Updates a single booking project identified by its uuid, if permitted for the current subject.' operationId: patchBookingProject parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' - name: bookingProjectUuid in: path @@ -63,7 +63,7 @@ delete: description: 'Delete a single booking project identified by its uuid, if permitted for the current subject.' operationId: deleteBookingIemByUuid parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' - name: bookingProjectUuid in: path diff --git a/src/main/resources/api-definition/hs-booking/hs-booking-projects.yaml b/src/main/resources/api-definition/hs-booking/hs-booking-projects.yaml index bccb7443..3b567346 100644 --- a/src/main/resources/api-definition/hs-booking/hs-booking-projects.yaml +++ b/src/main/resources/api-definition/hs-booking/hs-booking-projects.yaml @@ -1,11 +1,11 @@ get: summary: Returns a list of all booking projects for a specified debitor. - description: Returns the list of all booking projects for a specified debitor which are visible to the current user or any of it's assumed roles. + description: Returns the list of all booking projects for a specified debitor which are visible to the current subject or any of it's assumed roles. tags: - hs-booking-projects operationId: listBookingProjectsByDebitorUuid parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' - name: debitorUuid in: query @@ -34,7 +34,7 @@ post: - hs-booking-projects operationId: addBookingProject parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' requestBody: description: A JSON object describing the new booking project. diff --git a/src/main/resources/api-definition/hs-hosting/auth.yaml b/src/main/resources/api-definition/hs-hosting/auth.yaml index 65d491fb..0aa48bf5 100644 --- a/src/main/resources/api-definition/hs-hosting/auth.yaml +++ b/src/main/resources/api-definition/hs-hosting/auth.yaml @@ -3,13 +3,13 @@ components: parameters: - currentUser: - name: current-user + currentSubject: + name: current-subject in: header required: true schema: type: string - description: Identifying name of the currently logged in user. + description: Identifying name of the currently logged in subject. assumedRoles: name: assumed-roles @@ -17,4 +17,4 @@ components: required: false schema: type: string - description: Semicolon-separated list of roles to assume. The current user needs to have the right to assume these roles. + description: Semicolon-separated list of roles to assume. The current subject needs to have the right to assume these roles. diff --git a/src/main/resources/api-definition/hs-hosting/error-responses.yaml b/src/main/resources/api-definition/hs-hosting/error-responses.yaml index 83ca3dfb..d7999f91 100644 --- a/src/main/resources/api-definition/hs-hosting/error-responses.yaml +++ b/src/main/resources/api-definition/hs-hosting/error-responses.yaml @@ -8,13 +8,13 @@ components: schema: $ref: '#/components/schemas/Error' Unauthorized: - description: The current user is unknown or not authorized. + description: The current subject is unknown or not authorized. content: application/json: schema: $ref: '#/components/schemas/Error' Forbidden: - description: The current user or none of the assumed or roles is granted access to the resource. + description: The current subject or none of the assumed or roles is granted access to the resource. content: application/json: schema: diff --git a/src/main/resources/api-definition/hs-hosting/hs-hosting-assets-with-uuid.yaml b/src/main/resources/api-definition/hs-hosting/hs-hosting-assets-with-uuid.yaml index 6630d245..625afdd0 100644 --- a/src/main/resources/api-definition/hs-hosting/hs-hosting-assets-with-uuid.yaml +++ b/src/main/resources/api-definition/hs-hosting/hs-hosting-assets-with-uuid.yaml @@ -4,7 +4,7 @@ get: description: 'Fetch a single managed asset by its uuid, if visible for the current subject.' operationId: getAssetByUuid parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' - name: assetUuid in: path @@ -32,7 +32,7 @@ patch: description: 'Updates a single hosting asset identified by its uuid, if permitted for the current subject.' operationId: patchAsset parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' - name: assetUuid in: path @@ -63,7 +63,7 @@ delete: description: 'Delete a single hosting asset identified by its uuid, if permitted for the current subject.' operationId: deleteAssetUuid parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' - name: assetUuid in: path diff --git a/src/main/resources/api-definition/hs-hosting/hs-hosting-assets.yaml b/src/main/resources/api-definition/hs-hosting/hs-hosting-assets.yaml index 8a208c68..8aae49a8 100644 --- a/src/main/resources/api-definition/hs-hosting/hs-hosting-assets.yaml +++ b/src/main/resources/api-definition/hs-hosting/hs-hosting-assets.yaml @@ -1,11 +1,11 @@ get: summary: Returns a filtered list of all hosting assets. - description: Returns the list of all hosting assets which match the given filters and are visible to the current user or any of it's assumed roles. + description: Returns the list of all hosting assets which match the given filters and are visible to the current subject or any of it's assumed roles. tags: - hs-hosting-assets operationId: listAssets parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' - name: projectUuid in: query @@ -47,7 +47,7 @@ post: - hs-hosting-assets operationId: addAsset parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' requestBody: description: A JSON object describing the new hosting asset. diff --git a/src/main/resources/api-definition/hs-office/hs-office-bankaccounts-with-uuid.yaml b/src/main/resources/api-definition/hs-office/hs-office-bankaccounts-with-uuid.yaml index 44f89fa1..cdef972a 100644 --- a/src/main/resources/api-definition/hs-office/hs-office-bankaccounts-with-uuid.yaml +++ b/src/main/resources/api-definition/hs-office/hs-office-bankaccounts-with-uuid.yaml @@ -4,7 +4,7 @@ get: description: 'Fetch a single bank account by its uuid, if visible for the current subject.' operationId: getBankAccountByUuid parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' - name: bankAccountUUID in: path @@ -31,7 +31,7 @@ delete: description: 'Delete a single bank account by its uuid, if permitted for the current subject.' operationId: deleteBankAccountByUuid parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' - name: bankAccountUUID in: path diff --git a/src/main/resources/api-definition/hs-office/hs-office-bankaccounts.yaml b/src/main/resources/api-definition/hs-office/hs-office-bankaccounts.yaml index 75380d5d..316fc250 100644 --- a/src/main/resources/api-definition/hs-office/hs-office-bankaccounts.yaml +++ b/src/main/resources/api-definition/hs-office/hs-office-bankaccounts.yaml @@ -1,11 +1,11 @@ get: summary: Returns a list of (optionally filtered) bankaccounts. - description: Returns the list of (optionally filtered) bankaccounts which are visible to the current user or any of it's assumed roles. + description: Returns the list of (optionally filtered) bankaccounts which are visible to the current subject or any of it's assumed roles. tags: - hs-office-bank-accounts operationId: listBankAccounts parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' - name: holder in: query @@ -33,7 +33,7 @@ post: - hs-office-bank-accounts operationId: addBankAccount parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' requestBody: content: diff --git a/src/main/resources/api-definition/hs-office/hs-office-contacts-with-uuid.yaml b/src/main/resources/api-definition/hs-office/hs-office-contacts-with-uuid.yaml index 13e96f39..a6561e8d 100644 --- a/src/main/resources/api-definition/hs-office/hs-office-contacts-with-uuid.yaml +++ b/src/main/resources/api-definition/hs-office/hs-office-contacts-with-uuid.yaml @@ -4,7 +4,7 @@ get: description: 'Fetch a single business contact by its uuid, if visible for the current subject.' operationId: getContactByUuid parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' - name: contactUUID in: path @@ -32,7 +32,7 @@ patch: description: 'Updates a single contact by its uuid, if permitted for the current subject.' operationId: patchContact parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' - name: contactUUID in: path @@ -63,7 +63,7 @@ delete: description: 'Delete a single business contact by its uuid, if permitted for the current subject.' operationId: deleteContactByUuid parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' - name: contactUUID in: path diff --git a/src/main/resources/api-definition/hs-office/hs-office-contacts.yaml b/src/main/resources/api-definition/hs-office/hs-office-contacts.yaml index 52d54a87..cc3f56af 100644 --- a/src/main/resources/api-definition/hs-office/hs-office-contacts.yaml +++ b/src/main/resources/api-definition/hs-office/hs-office-contacts.yaml @@ -1,11 +1,11 @@ get: summary: Returns a list of (optionally filtered) contacts. - description: Returns the list of (optionally filtered) contacts which are visible to the current user or any of it's assumed roles. + description: Returns the list of (optionally filtered) contacts which are visible to the current subject or any of it's assumed roles. tags: - hs-office-contacts operationId: listContacts parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' - name: name in: query @@ -33,7 +33,7 @@ post: - hs-office-contacts operationId: addContact parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' requestBody: content: diff --git a/src/main/resources/api-definition/hs-office/hs-office-coopassets-with-uuid.yaml b/src/main/resources/api-definition/hs-office/hs-office-coopassets-with-uuid.yaml index 7fd6d243..51d51c2c 100644 --- a/src/main/resources/api-definition/hs-office/hs-office-coopassets-with-uuid.yaml +++ b/src/main/resources/api-definition/hs-office/hs-office-coopassets-with-uuid.yaml @@ -4,7 +4,7 @@ get: description: 'Fetch a single asset transaction by its uuid, if visible for the current subject.' operationId: getCoopAssetTransactionByUuid parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' - name: assetTransactionUUID in: path diff --git a/src/main/resources/api-definition/hs-office/hs-office-coopassets.yaml b/src/main/resources/api-definition/hs-office/hs-office-coopassets.yaml index aa0ae953..bff3e1d5 100644 --- a/src/main/resources/api-definition/hs-office/hs-office-coopassets.yaml +++ b/src/main/resources/api-definition/hs-office/hs-office-coopassets.yaml @@ -1,11 +1,11 @@ get: summary: Returns a list of (optionally filtered) cooperative asset transactions. - description: Returns the list of (optionally filtered) cooperative asset transactions which are visible to the current user or any of it's assumed roles. + description: Returns the list of (optionally filtered) cooperative asset transactions which are visible to the current subject or any of it's assumed roles. tags: - hs-office-coopAssets operationId: listCoopAssets parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' - name: membershipUuid in: query @@ -48,7 +48,7 @@ post: - hs-office-coopAssets operationId: addCoopAssetsTransaction parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' requestBody: description: A JSON object describing the new cooperative assets transaction. diff --git a/src/main/resources/api-definition/hs-office/hs-office-coopshares-with-uuid.yaml b/src/main/resources/api-definition/hs-office/hs-office-coopshares-with-uuid.yaml index cd7ff827..a37dbf7e 100644 --- a/src/main/resources/api-definition/hs-office/hs-office-coopshares-with-uuid.yaml +++ b/src/main/resources/api-definition/hs-office/hs-office-coopshares-with-uuid.yaml @@ -4,7 +4,7 @@ get: description: 'Fetch a single share transaction by its uuid, if visible for the current subject.' operationId: getCoopShareTransactionByUuid parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' - name: shareTransactionUUID in: path diff --git a/src/main/resources/api-definition/hs-office/hs-office-coopshares.yaml b/src/main/resources/api-definition/hs-office/hs-office-coopshares.yaml index 338018ad..215df97e 100644 --- a/src/main/resources/api-definition/hs-office/hs-office-coopshares.yaml +++ b/src/main/resources/api-definition/hs-office/hs-office-coopshares.yaml @@ -1,11 +1,11 @@ get: summary: Returns a list of (optionally filtered) cooperative share transactions. - description: Returns the list of (optionally filtered) cooperative share transactions which are visible to the current user or any of it's assumed roles. + description: Returns the list of (optionally filtered) cooperative share transactions which are visible to the current subject or any of it's assumed roles. tags: - hs-office-coopShares operationId: listCoopShares parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' - name: membershipUuid in: query @@ -48,7 +48,7 @@ post: - hs-office-coopShares operationId: addCoopSharesTransaction parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' requestBody: description: A JSON object describing the new cooperative shares transaction. diff --git a/src/main/resources/api-definition/hs-office/hs-office-debitors-with-uuid.yaml b/src/main/resources/api-definition/hs-office/hs-office-debitors-with-uuid.yaml index 09c6d42d..feb8e473 100644 --- a/src/main/resources/api-definition/hs-office/hs-office-debitors-with-uuid.yaml +++ b/src/main/resources/api-definition/hs-office/hs-office-debitors-with-uuid.yaml @@ -4,7 +4,7 @@ get: description: 'Fetch a single debitor by its uuid, if visible for the current subject.' operationId: getDebitorByUuid parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' - name: debitorUUID in: path @@ -32,7 +32,7 @@ patch: description: 'Updates a single debitor by its uuid, if permitted for the current subject.' operationId: patchDebitor parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' - name: debitorUUID in: path @@ -63,7 +63,7 @@ delete: description: 'Delete a single debitor by its uuid, if permitted for the current subject.' operationId: deleteDebitorByUuid parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' - name: debitorUUID in: path diff --git a/src/main/resources/api-definition/hs-office/hs-office-debitors.yaml b/src/main/resources/api-definition/hs-office/hs-office-debitors.yaml index 5936198b..16554531 100644 --- a/src/main/resources/api-definition/hs-office/hs-office-debitors.yaml +++ b/src/main/resources/api-definition/hs-office/hs-office-debitors.yaml @@ -1,11 +1,11 @@ get: summary: Returns a list of (optionally filtered) debitors. - description: Returns the list of (optionally filtered) debitors which are visible to the current user or any of it's assumed roles. + description: Returns the list of (optionally filtered) debitors which are visible to the current subject or any of it's assumed roles. tags: - hs-office-debitors operationId: listDebitors parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' - name: name in: query @@ -39,7 +39,7 @@ post: - hs-office-debitors operationId: addDebitor parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' requestBody: content: diff --git a/src/main/resources/api-definition/hs-office/hs-office-memberships-with-uuid.yaml b/src/main/resources/api-definition/hs-office/hs-office-memberships-with-uuid.yaml index 4bd1b3fb..1511e09f 100644 --- a/src/main/resources/api-definition/hs-office/hs-office-memberships-with-uuid.yaml +++ b/src/main/resources/api-definition/hs-office/hs-office-memberships-with-uuid.yaml @@ -4,7 +4,7 @@ get: description: 'Fetch a single membership by its uuid, if visible for the current subject.' operationId: getMembershipByUuid parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' - name: membershipUUID in: path @@ -32,7 +32,7 @@ patch: description: 'Updates a single membership by its uuid, if permitted for the current subject.' operationId: patchMembership parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' - name: membershipUUID in: path @@ -63,7 +63,7 @@ delete: description: 'Delete a single membership by its uuid, if permitted for the current subject.' operationId: deleteMembershipByUuid parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' - name: membershipUUID in: path diff --git a/src/main/resources/api-definition/hs-office/hs-office-memberships.yaml b/src/main/resources/api-definition/hs-office/hs-office-memberships.yaml index 260dee51..8436134b 100644 --- a/src/main/resources/api-definition/hs-office/hs-office-memberships.yaml +++ b/src/main/resources/api-definition/hs-office/hs-office-memberships.yaml @@ -1,12 +1,12 @@ get: summary: Returns a list of (optionally filtered) memberships. - description: Returns the list of memberships which are visible to the current user or any of it's assumed roles. + description: Returns the list of memberships which are visible to the current subject or any of it's assumed roles. The list can optionally be filtered by either the `partnerUuid` or the `memberNumber` - not both at the same time. tags: - hs-office-memberships operationId: listMemberships parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' - name: partnerUuid in: query @@ -41,7 +41,7 @@ post: - hs-office-memberships operationId: addMembership parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' requestBody: description: A JSON object describing the new membership. diff --git a/src/main/resources/api-definition/hs-office/hs-office-partners-with-uuid.yaml b/src/main/resources/api-definition/hs-office/hs-office-partners-with-uuid.yaml index 914df66b..e19e6cd2 100644 --- a/src/main/resources/api-definition/hs-office/hs-office-partners-with-uuid.yaml +++ b/src/main/resources/api-definition/hs-office/hs-office-partners-with-uuid.yaml @@ -4,7 +4,7 @@ get: description: 'Fetch a single business partner by its uuid, if visible for the current subject.' operationId: getPartnerByUuid parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' - name: partnerUUID in: path @@ -32,7 +32,7 @@ patch: description: 'Updates a single business partner by its uuid, if permitted for the current subject.' operationId: patchPartner parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' - name: partnerUUID in: path @@ -63,7 +63,7 @@ delete: description: 'Delete a single business partner by its uuid, if permitted for the current subject.' operationId: deletePartnerByUuid parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' - name: partnerUUID in: path diff --git a/src/main/resources/api-definition/hs-office/hs-office-partners.yaml b/src/main/resources/api-definition/hs-office/hs-office-partners.yaml index 1f6ee36e..9e97a91d 100644 --- a/src/main/resources/api-definition/hs-office/hs-office-partners.yaml +++ b/src/main/resources/api-definition/hs-office/hs-office-partners.yaml @@ -1,11 +1,11 @@ get: summary: Returns a list of (optionally filtered) business partners. - description: Returns the list of (optionally filtered) business partners which are visible to the current user or any of it's assumed roles. + description: Returns the list of (optionally filtered) business partners which are visible to the current subject or any of it's assumed roles. tags: - hs-office-partners operationId: listPartners parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' - name: name in: query @@ -33,7 +33,7 @@ post: - hs-office-partners operationId: addPartner parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' requestBody: content: diff --git a/src/main/resources/api-definition/hs-office/hs-office-persons-with-uuid.yaml b/src/main/resources/api-definition/hs-office/hs-office-persons-with-uuid.yaml index 1b90c777..fe63c509 100644 --- a/src/main/resources/api-definition/hs-office/hs-office-persons-with-uuid.yaml +++ b/src/main/resources/api-definition/hs-office/hs-office-persons-with-uuid.yaml @@ -4,7 +4,7 @@ get: description: 'Fetch a single business person by its uuid, if visible for the current subject.' operationId: getPersonByUuid parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' - name: personUUID in: path @@ -32,7 +32,7 @@ patch: description: 'Updates a single person by its uuid, if permitted for the current subject.' operationId: patchPerson parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' - name: personUUID in: path @@ -63,7 +63,7 @@ delete: description: 'Delete a single business person by its uuid, if permitted for the current subject.' operationId: deletePersonByUuid parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' - name: personUUID in: path diff --git a/src/main/resources/api-definition/hs-office/hs-office-persons.yaml b/src/main/resources/api-definition/hs-office/hs-office-persons.yaml index f7cba51a..e761957c 100644 --- a/src/main/resources/api-definition/hs-office/hs-office-persons.yaml +++ b/src/main/resources/api-definition/hs-office/hs-office-persons.yaml @@ -1,11 +1,11 @@ get: summary: Returns a list of (optionally filtered) persons. - description: Returns the list of (optionally filtered) persons which are visible to the current user or any of it's assumed roles. + description: Returns the list of (optionally filtered) persons which are visible to the current subject or any of it's assumed roles. tags: - hs-office-persons operationId: listPersons parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' - name: name in: query @@ -33,7 +33,7 @@ post: - hs-office-persons operationId: addPerson parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' requestBody: content: diff --git a/src/main/resources/api-definition/hs-office/hs-office-relations-with-uuid.yaml b/src/main/resources/api-definition/hs-office/hs-office-relations-with-uuid.yaml index 4e8010e7..3dbe1391 100644 --- a/src/main/resources/api-definition/hs-office/hs-office-relations-with-uuid.yaml +++ b/src/main/resources/api-definition/hs-office/hs-office-relations-with-uuid.yaml @@ -4,7 +4,7 @@ get: description: 'Fetch a single person relation by its uuid, if visible for the current subject.' operationId: getRelationByUuid parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' - name: relationUUID in: path @@ -32,7 +32,7 @@ patch: description: 'Updates a single person relation by its uuid, if permitted for the current subject.' operationId: patchRelation parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' - name: relationUUID in: path @@ -63,7 +63,7 @@ delete: description: 'Delete a single person relation by its uuid, if permitted for the current subject.' operationId: deleteRelationByUuid parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' - name: relationUUID in: path diff --git a/src/main/resources/api-definition/hs-office/hs-office-relations.yaml b/src/main/resources/api-definition/hs-office/hs-office-relations.yaml index 94131df5..ce7a865b 100644 --- a/src/main/resources/api-definition/hs-office/hs-office-relations.yaml +++ b/src/main/resources/api-definition/hs-office/hs-office-relations.yaml @@ -1,11 +1,11 @@ get: summary: Returns a list of (optionally filtered) person relations for a given person. - description: Returns the list of (optionally filtered) person relations of a given person and which are visible to the current user or any of it's assumed roles. + description: Returns the list of (optionally filtered) person relations of a given person and which are visible to the current subject or any of it's assumed roles. tags: - hs-office-relations operationId: listRelations parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' - name: personUuid in: query @@ -40,7 +40,7 @@ post: - hs-office-relations operationId: addRelation parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' requestBody: content: diff --git a/src/main/resources/api-definition/hs-office/hs-office-sepamandates-with-uuid.yaml b/src/main/resources/api-definition/hs-office/hs-office-sepamandates-with-uuid.yaml index 52d050ee..1e14a235 100644 --- a/src/main/resources/api-definition/hs-office/hs-office-sepamandates-with-uuid.yaml +++ b/src/main/resources/api-definition/hs-office/hs-office-sepamandates-with-uuid.yaml @@ -4,7 +4,7 @@ get: description: 'Fetch a single SEPA Mandate by its uuid, if visible for the current subject.' operationId: getSepaMandateByUuid parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' - name: sepaMandateUUID in: path @@ -32,7 +32,7 @@ patch: description: 'Updates a single SEPA Mandate by its uuid, if permitted for the current subject.' operationId: patchSepaMandate parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' - name: sepaMandateUUID in: path @@ -63,7 +63,7 @@ delete: description: 'Delete a single SEPA Mandate by its uuid, if permitted for the current subject.' operationId: deleteSepaMandateByUuid parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' - name: sepaMandateUUID in: path diff --git a/src/main/resources/api-definition/hs-office/hs-office-sepamandates.yaml b/src/main/resources/api-definition/hs-office/hs-office-sepamandates.yaml index 82f8f154..3050ab79 100644 --- a/src/main/resources/api-definition/hs-office/hs-office-sepamandates.yaml +++ b/src/main/resources/api-definition/hs-office/hs-office-sepamandates.yaml @@ -1,11 +1,11 @@ get: summary: Returns a list of (optionally filtered) SEPA Mandates. - description: Returns the list of (optionally filtered) SEPA Mandates which are visible to the current user or any of it's assumed roles. + description: Returns the list of (optionally filtered) SEPA Mandates which are visible to the current subject or any of it's assumed roles. tags: - hs-office-sepaMandates operationId: listSepaMandatesByIBAN parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' - name: name in: query @@ -33,7 +33,7 @@ post: - hs-office-sepaMandates operationId: addSepaMandate parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' requestBody: description: A JSON object describing the new SEPA-Mandate. diff --git a/src/main/resources/api-definition/rbac/rbac-grant-schemas.yaml b/src/main/resources/api-definition/rbac/rbac-grant-schemas.yaml index 12a2cbbd..90700354 100644 --- a/src/main/resources/api-definition/rbac/rbac-grant-schemas.yaml +++ b/src/main/resources/api-definition/rbac/rbac-grant-schemas.yaml @@ -18,11 +18,11 @@ components: grantedRoleUuid: type: string format: uuid - granteeUserName: + granteeSubjectName: type: string - granteeUserUuid: + granteeSubjectUuid: type: string format: uuid required: - grantedRoleUuid - - granteeUserUuid + - granteeSubjectUuid diff --git a/src/main/resources/api-definition/rbac/rbac-grants-with-id.yaml b/src/main/resources/api-definition/rbac/rbac-grants-with-id.yaml index b45ebb4e..ddda4510 100644 --- a/src/main/resources/api-definition/rbac/rbac-grants-with-id.yaml +++ b/src/main/resources/api-definition/rbac/rbac-grants-with-id.yaml @@ -3,7 +3,7 @@ get: - rbac-grants operationId: getGrantById parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' - name: grantedRoleUuid in: path @@ -12,13 +12,13 @@ get: type: string format: uuid description: UUID of the granted role. - - name: granteeUserUuid + - name: granteeSubjectUuid in: path required: true schema: type: string format: uuid - description: UUID of the user to whom the role was granted. + description: UUID of the subject to who the role was granted. responses: "200": description: OK @@ -36,9 +36,9 @@ get: delete: tags: - rbac-grants - operationId: revokeRoleFromUser + operationId: revokeRoleFromSubject parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' - name: grantedRoleUuid in: path @@ -47,13 +47,13 @@ delete: type: string format: uuid description: UUID of the granted role. - - name: granteeUserUuid + - name: granteeSubjectUuid in: path required: true schema: type: string format: uuid - description: UUID of the user to whom the role was granted. + description: UUID of the subject to which the role was granted. responses: "204": description: No Content diff --git a/src/main/resources/api-definition/rbac/rbac-grants.yaml b/src/main/resources/api-definition/rbac/rbac-grants.yaml index 16011bcd..7c5392cd 100644 --- a/src/main/resources/api-definition/rbac/rbac-grants.yaml +++ b/src/main/resources/api-definition/rbac/rbac-grants.yaml @@ -1,9 +1,9 @@ get: tags: - rbac-grants - operationId: listUserGrants + operationId: listSubjectGrants parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' responses: "200": @@ -18,9 +18,9 @@ get: post: tags: - rbac-grants - operationId: grantRoleToUser + operationId: grantRoleToSubject parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' requestBody: required: true diff --git a/src/main/resources/api-definition/rbac/rbac-roles.yaml b/src/main/resources/api-definition/rbac/rbac-roles.yaml index b97aa387..e35ee44e 100644 --- a/src/main/resources/api-definition/rbac/rbac-roles.yaml +++ b/src/main/resources/api-definition/rbac/rbac-roles.yaml @@ -3,7 +3,7 @@ get: - rbac-roles operationId: listRoles parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' responses: "200": diff --git a/src/main/resources/api-definition/rbac/rbac-user-schemas.yaml b/src/main/resources/api-definition/rbac/rbac-subject-schemas.yaml similarity index 93% rename from src/main/resources/api-definition/rbac/rbac-user-schemas.yaml rename to src/main/resources/api-definition/rbac/rbac-subject-schemas.yaml index c7ca49c0..9cb8ec0f 100644 --- a/src/main/resources/api-definition/rbac/rbac-user-schemas.yaml +++ b/src/main/resources/api-definition/rbac/rbac-subject-schemas.yaml @@ -3,7 +3,7 @@ components: schemas: - RbacUser: + RbacSubject: type: object properties: uuid: @@ -11,7 +11,7 @@ components: format: uuid name: type: string - RbacUserPermission: + RbacSubjectPermission: type: object properties: objectUuid: diff --git a/src/main/resources/api-definition/rbac/rbac-users-with-id-permissions.yaml b/src/main/resources/api-definition/rbac/rbac-subjects-with-id-permissions.yaml similarity index 70% rename from src/main/resources/api-definition/rbac/rbac-users-with-id-permissions.yaml rename to src/main/resources/api-definition/rbac/rbac-subjects-with-id-permissions.yaml index ba6eb3fe..a92407db 100644 --- a/src/main/resources/api-definition/rbac/rbac-users-with-id-permissions.yaml +++ b/src/main/resources/api-definition/rbac/rbac-subjects-with-id-permissions.yaml @@ -1,12 +1,12 @@ get: tags: - - rbac-users - description: 'List all visible permissions granted to the given user; reduced ' - operationId: listUserPermissions + - rbac-subjects + description: 'List all visible permissions granted to the given subject; reduced ' + operationId: listSubjectPermissions parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' - - name: userUuid + - name: subjectUuid in: path required: true schema: @@ -20,7 +20,7 @@ get: schema: type: array items: - $ref: 'rbac-user-schemas.yaml#/components/schemas/RbacUserPermission' + $ref: 'rbac-subject-schemas.yaml#/components/schemas/RbacSubjectPermission' "401": $ref: 'error-responses.yaml#/components/responses/Unauthorized' diff --git a/src/main/resources/api-definition/rbac/rbac-users-with-uuid.yaml b/src/main/resources/api-definition/rbac/rbac-subjects-with-uuid.yaml similarity index 66% rename from src/main/resources/api-definition/rbac/rbac-users-with-uuid.yaml rename to src/main/resources/api-definition/rbac/rbac-subjects-with-uuid.yaml index 058fc5cd..67e0ac6d 100644 --- a/src/main/resources/api-definition/rbac/rbac-users-with-uuid.yaml +++ b/src/main/resources/api-definition/rbac/rbac-subjects-with-uuid.yaml @@ -1,12 +1,12 @@ get: tags: - - rbac-users - description: 'Fetch a single user by its id, if visible for the current subject.' - operationId: getUserById + - rbac-subjects + description: 'Fetch a single subject by its id, if visible for the current subject.' + operationId: getSubjectById parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' - - name: userUuid + - name: subjectUuid in: path required: true schema: @@ -18,7 +18,7 @@ get: content: 'application/json': schema: - $ref: 'rbac-user-schemas.yaml#/components/schemas/RbacUser' + $ref: 'rbac-subject-schemas.yaml#/components/schemas/RbacSubject' "401": $ref: 'error-responses.yaml#/components/responses/Unauthorized' @@ -28,18 +28,18 @@ get: delete: tags: - - rbac-users - operationId: deleteUserByUuid + - rbac-subjects + operationId: deleteSubjectByUuid parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' - - name: userUuid + - name: subjectUuid in: path required: true schema: type: string format: uuid - description: UUID of the user to delete. + description: UUID of the subject to delete. responses: "204": description: No Content diff --git a/src/main/resources/api-definition/rbac/rbac-users.yaml b/src/main/resources/api-definition/rbac/rbac-subjects.yaml similarity index 62% rename from src/main/resources/api-definition/rbac/rbac-users.yaml rename to src/main/resources/api-definition/rbac/rbac-subjects.yaml index 4acb729e..0877163e 100644 --- a/src/main/resources/api-definition/rbac/rbac-users.yaml +++ b/src/main/resources/api-definition/rbac/rbac-subjects.yaml @@ -1,10 +1,10 @@ get: tags: - - rbac-users - description: List accessible RBAC users with optional filter by name. - operationId: listUsers + - rbac-subjects + description: List accessible RBAC subjects with optional filter by name. + operationId: listSubjects parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' - name: name in: query @@ -19,7 +19,7 @@ get: schema: type: array items: - $ref: 'rbac-user-schemas.yaml#/components/schemas/RbacUser' + $ref: 'rbac-subject-schemas.yaml#/components/schemas/RbacSubject' '401': $ref: 'error-responses.yaml#/components/responses/Unauthorized' '403': @@ -27,22 +27,22 @@ get: post: tags: - - rbac-users - description: Create a new RBAC user. - operationId: createUser + - rbac-subjects + description: Create a new RBAC subject (e.g. user). + operationId: createSubject requestBody: required: true content: application/json: schema: - $ref: 'rbac-user-schemas.yaml#/components/schemas/RbacUser' + $ref: 'rbac-subject-schemas.yaml#/components/schemas/RbacSubject' responses: '201': description: Created content: 'application/json': schema: - $ref: 'rbac-user-schemas.yaml#/components/schemas/RbacUser' + $ref: 'rbac-subject-schemas.yaml#/components/schemas/RbacSubject' '409': $ref: 'error-responses.yaml#/components/responses/Conflict' diff --git a/src/main/resources/api-definition/rbac/rbac.yaml b/src/main/resources/api-definition/rbac/rbac.yaml index ad6dfca4..463692d0 100644 --- a/src/main/resources/api-definition/rbac/rbac.yaml +++ b/src/main/resources/api-definition/rbac/rbac.yaml @@ -8,14 +8,14 @@ servers: paths: - /api/rbac/users: - $ref: 'rbac-users.yaml' + /api/rbac/subjects: + $ref: 'rbac-subjects.yaml' - /api/rbac/users/{userUuid}/permissions: - $ref: 'rbac-users-with-id-permissions.yaml' + /api/rbac/subjects/{subjectUuid}/permissions: + $ref: 'rbac-subjects-with-id-permissions.yaml' - /api/rbac/users/{userUuid}: - $ref: 'rbac-users-with-uuid.yaml' + /api/rbac/subjects/{subjectUuid}: + $ref: 'rbac-subjects-with-uuid.yaml' /api/rbac/roles: $ref: 'rbac-roles.yaml' @@ -23,6 +23,6 @@ paths: /api/rbac/grants: $ref: 'rbac-grants.yaml' - /api/rbac/grants/{grantedRoleUuid}/{granteeUserUuid}: + /api/rbac/grants/{grantedRoleUuid}/{granteeSubjectUuid}: $ref: 'rbac-grants-with-id.yaml' diff --git a/src/main/resources/api-definition/test/test-customers.yaml b/src/main/resources/api-definition/test/test-customers.yaml index 89a8fb6b..8e81426a 100644 --- a/src/main/resources/api-definition/test/test-customers.yaml +++ b/src/main/resources/api-definition/test/test-customers.yaml @@ -1,11 +1,11 @@ get: summary: Returns a list of (optionally filtered) customers. - description: Returns the list of (optionally filtered) customers which are visible to the current user or any of it's assumed roles. + description: Returns the list of (optionally filtered) customers which are visible to the current subject or any of it's assumed roles. tags: - testCustomers operationId: listCustomers parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' - name: prefix in: query @@ -33,7 +33,7 @@ post: - testCustomers operationId: addCustomer parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' requestBody: content: diff --git a/src/main/resources/api-definition/test/test-packages-uuid.yaml b/src/main/resources/api-definition/test/test-packages-uuid.yaml index 4fc8ef80..994810df 100644 --- a/src/main/resources/api-definition/test/test-packages-uuid.yaml +++ b/src/main/resources/api-definition/test/test-packages-uuid.yaml @@ -3,7 +3,7 @@ patch: - testPackages operationId: updatePackage parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' - name: packageUUID in: path diff --git a/src/main/resources/api-definition/test/test-packages.yaml b/src/main/resources/api-definition/test/test-packages.yaml index 6a3e0e7f..98190e30 100644 --- a/src/main/resources/api-definition/test/test-packages.yaml +++ b/src/main/resources/api-definition/test/test-packages.yaml @@ -3,7 +3,7 @@ get: - testPackages operationId: listPackages parameters: - - $ref: 'auth.yaml#/components/parameters/currentUser' + - $ref: 'auth.yaml#/components/parameters/currentSubject' - $ref: 'auth.yaml#/components/parameters/assumedRoles' - name: name in: query diff --git a/src/main/resources/db/changelog/0-basis/000-template.sql b/src/main/resources/db/changelog/0-base/000-base-schema.sql similarity index 71% rename from src/main/resources/db/changelog/0-basis/000-template.sql rename to src/main/resources/db/changelog/0-base/000-base-schema.sql index 1dc12f42..921be5fa 100644 --- a/src/main/resources/db/changelog/0-basis/000-template.sql +++ b/src/main/resources/db/changelog/0-base/000-base-schema.sql @@ -2,11 +2,7 @@ -- ============================================================================ ---changeset prefix-TEMPLATE:1 endDelimiter:--// +--changeset michael.hoennig:base-SCHEMA endDelimiter:--// -- ---------------------------------------------------------------------------- - -/* - - */ - +CREATE SCHEMA base; --// diff --git a/src/main/resources/db/changelog/0-basis/001-last-row-count.sql b/src/main/resources/db/changelog/0-base/001-last-row-count.sql similarity index 75% rename from src/main/resources/db/changelog/0-basis/001-last-row-count.sql rename to src/main/resources/db/changelog/0-base/001-last-row-count.sql index c1f3fe05..1c76d02c 100644 --- a/src/main/resources/db/changelog/0-basis/001-last-row-count.sql +++ b/src/main/resources/db/changelog/0-base/001-last-row-count.sql @@ -2,19 +2,19 @@ -- ============================================================================ -- LAST-ROW-COUNT ---changeset last-row-count:1 endDelimiter:--// +--changeset michael.hoennig:last-row-count endDelimiter:--// -- ---------------------------------------------------------------------------- /* Returns the row count from the result of the previous query. Other than the native statement it's usable in an expression. */ -create or replace function lastRowCount() +create or replace function base.lastRowCount() returns bigint language plpgsql as $$ declare lastRowCount bigint; begin - get diagnostics lastrowCount = row_count; + get diagnostics lastRowCount = row_count; return lastRowCount; end; $$; --// diff --git a/src/main/resources/db/changelog/0-basis/002-int-to-var.sql b/src/main/resources/db/changelog/0-base/002-int-to-var.sql similarity index 66% rename from src/main/resources/db/changelog/0-basis/002-int-to-var.sql rename to src/main/resources/db/changelog/0-base/002-int-to-var.sql index eb3212e3..fea9028f 100644 --- a/src/main/resources/db/changelog/0-basis/002-int-to-var.sql +++ b/src/main/resources/db/changelog/0-base/002-int-to-var.sql @@ -2,16 +2,16 @@ -- ============================================================================ -- INT-TO-VAR ---changeset int-to-var:1 endDelimiter:--// +--changeset michael.hoennig:int-to-var endDelimiter:--// -- ---------------------------------------------------------------------------- /* Returns a textual representation of an integer number to be used as generated test data. Examples : - intToVarChar(0, 3) => 'aaa' - intToVarChar(1, 3) => 'aab' + base.intToVarChar(0, 3) => 'aaa' + base.intToVarChar(1, 3) => 'aab' */ -create or replace function intToVarChar(i integer, len integer) +create or replace function base.intToVarChar(i integer, len integer) returns varchar language plpgsql as $$ declare @@ -19,7 +19,7 @@ declare begin select chr(ascii('a') + i % 26) into partial; if len > 1 then - return intToVarChar(i / 26, len - 1) || partial; + return base.intToVarChar(i / 26, len - 1) || partial; else return partial; end if; diff --git a/src/main/resources/db/changelog/0-basis/003-random-in-range.sql b/src/main/resources/db/changelog/0-base/003-random-in-range.sql similarity index 70% rename from src/main/resources/db/changelog/0-basis/003-random-in-range.sql rename to src/main/resources/db/changelog/0-base/003-random-in-range.sql index 8ed0112d..7d102de8 100644 --- a/src/main/resources/db/changelog/0-basis/003-random-in-range.sql +++ b/src/main/resources/db/changelog/0-base/003-random-in-range.sql @@ -3,16 +3,16 @@ -- ============================================================================ -- RANDOM-IN-RANGE ---changeset random-in-range:1 endDelimiter:--// +--changeset michael.hoennig:random-in-range endDelimiter:--// -- ---------------------------------------------------------------------------- /* Returns a random integer in the given range (both included), to be used for test data generation. Example: - randomInRange(0, 4) might return any of 0, 1, 2, 3, 4 + base.randomInRange(0, 4) might return any of 0, 1, 2, 3, 4 */ -create or replace function randomInRange(min integer, max integer) +create or replace function base.randomInRange(min integer, max integer) returns integer returns null on null input language 'plpgsql' as $$ diff --git a/src/main/resources/db/changelog/0-basis/004-jsonb-changes-delta.sql b/src/main/resources/db/changelog/0-base/004-jsonb-changes-delta.sql similarity index 85% rename from src/main/resources/db/changelog/0-basis/004-jsonb-changes-delta.sql rename to src/main/resources/db/changelog/0-base/004-jsonb-changes-delta.sql index d6cdd7d3..79acc2ca 100644 --- a/src/main/resources/db/changelog/0-basis/004-jsonb-changes-delta.sql +++ b/src/main/resources/db/changelog/0-base/004-jsonb-changes-delta.sql @@ -2,14 +2,14 @@ -- ============================================================================ ---changeset JSONB-CHANGES-DELTA:1 endDelimiter:--// +--changeset michael.hoennig:JSONB-CHANGES-DELTA endDelimiter:--// -- ---------------------------------------------------------------------------- /* Recursively compares two jsonb values and returns what has changed. This is a kind of right sided json diff. */ -create or replace function jsonb_changes_delta(oldJson jsonb, newJson jsonb) +create or replace function base.jsonb_changes_delta(oldJson jsonb, newJson jsonb) returns jsonb called on null input language plpgsql as $$ @@ -31,7 +31,7 @@ begin if jsonb_typeof(newJson -> (oldJsonElement.key)) = 'object' then diffJson = diffJson || jsonb_build_object(oldJsonElement.key, - jsonb_changes_delta(oldJsonElement.value, newJson -> (oldJsonElement.key))); + base.jsonb_changes_delta(oldJsonElement.value, newJson -> (oldJsonElement.key))); end if; else diffJson = diffJson || jsonb_build_object(oldJsonElement.key, null); @@ -49,30 +49,30 @@ do language plpgsql $$ actual text; begin - select jsonb_changes_delta(null::jsonb, null::jsonb) into actual; + select base.jsonb_changes_delta(null::jsonb, null::jsonb) into actual; if actual is not null then raise exception 'jsonb_diff #1 failed:% expected: %,% actually: %', E'\n', expected, E'\n', actual; end if; - select jsonb_changes_delta(null::jsonb, '{"a": "new"}'::jsonb) into actual; + select base.jsonb_changes_delta(null::jsonb, '{"a": "new"}'::jsonb) into actual; expected := '{"a": "new"}'::jsonb; if actual <> expected then raise exception 'jsonb_diff #2 failed:% expected: %,% actual: %', E'\n', expected, E'\n', actual; end if; - select jsonb_changes_delta('{"a": "old"}'::jsonb, '{"a": "new"}'::jsonb) into actual; + select base.jsonb_changes_delta('{"a": "old"}'::jsonb, '{"a": "new"}'::jsonb) into actual; expected := '{"a": "new"}'::jsonb; if actual <> expected then raise exception 'jsonb_diff #3 failed:% expected: %,% actual: %', E'\n', expected, E'\n', actual; end if; - select jsonb_changes_delta('{"a": "old"}'::jsonb, '{"a": "old"}'::jsonb) into actual; + select base.jsonb_changes_delta('{"a": "old"}'::jsonb, '{"a": "old"}'::jsonb) into actual; expected := '{}'::jsonb; if actual <> expected then raise exception 'jsonb_diff #4 failed:% expected: %,% actual: %', E'\n', expected, E'\n', actual; end if; - select jsonb_changes_delta( + select base.jsonb_changes_delta( $json${ "a": "same", "b": "old", diff --git a/src/main/resources/db/changelog/0-basis/005-uuid-ossp-extension.sql b/src/main/resources/db/changelog/0-base/005-uuid-ossp-extension.sql similarity index 82% rename from src/main/resources/db/changelog/0-basis/005-uuid-ossp-extension.sql rename to src/main/resources/db/changelog/0-base/005-uuid-ossp-extension.sql index f156af69..d3c32082 100644 --- a/src/main/resources/db/changelog/0-basis/005-uuid-ossp-extension.sql +++ b/src/main/resources/db/changelog/0-base/005-uuid-ossp-extension.sql @@ -3,7 +3,7 @@ -- ============================================================================ -- UUID-OSSP-EXTENSION ---changeset uuid-ossp-extension:1 endDelimiter:--// +--changeset michael.hoennig:uuid-ossp-extension endDelimiter:--// -- ---------------------------------------------------------------------------- /* Makes improved uuid generation available. diff --git a/src/main/resources/db/changelog/0-basis/006-numeric-hash-functions.sql b/src/main/resources/db/changelog/0-base/006-numeric-hash-functions.sql similarity index 69% rename from src/main/resources/db/changelog/0-basis/006-numeric-hash-functions.sql rename to src/main/resources/db/changelog/0-base/006-numeric-hash-functions.sql index 13d31931..5ad2395a 100644 --- a/src/main/resources/db/changelog/0-basis/006-numeric-hash-functions.sql +++ b/src/main/resources/db/changelog/0-base/006-numeric-hash-functions.sql @@ -3,10 +3,10 @@ -- ============================================================================ -- NUMERIC-HASH-FUNCTIONS ---changeset numeric-hash-functions:1 endDelimiter:--// +--changeset michael.hoennig:numeric-hash-functions endDelimiter:--// -- ---------------------------------------------------------------------------- -create function bigIntHash(text) returns bigint as $$ +create function base.bigIntHash(text) returns bigint as $$ select ('x'||substr(md5($1),1,16))::bit(64)::bigint; $$ language sql; --// diff --git a/src/main/resources/db/changelog/0-basis/007-table-columns.sql b/src/main/resources/db/changelog/0-base/007-table-columns.sql similarity index 79% rename from src/main/resources/db/changelog/0-basis/007-table-columns.sql rename to src/main/resources/db/changelog/0-base/007-table-columns.sql index 588defba..55c744bd 100644 --- a/src/main/resources/db/changelog/0-basis/007-table-columns.sql +++ b/src/main/resources/db/changelog/0-base/007-table-columns.sql @@ -3,10 +3,10 @@ -- ============================================================================ -- TABLE-COLUMNS-FUNCTION ---changeset table-columns-function:1 endDelimiter:--// +--changeset michael.hoennig:table-columns-function endDelimiter:--// -- ---------------------------------------------------------------------------- -create or replace function columnsNames( tableName text ) +create or replace function base.tableColumnNames( tableName text ) returns text stable language 'plpgsql' as $$ diff --git a/src/main/resources/db/changelog/0-basis/008-raise-functions.sql b/src/main/resources/db/changelog/0-base/008-raise-functions.sql similarity index 74% rename from src/main/resources/db/changelog/0-basis/008-raise-functions.sql rename to src/main/resources/db/changelog/0-base/008-raise-functions.sql index ad298dc9..97364f1d 100644 --- a/src/main/resources/db/changelog/0-basis/008-raise-functions.sql +++ b/src/main/resources/db/changelog/0-base/008-raise-functions.sql @@ -1,12 +1,12 @@ --liquibase formatted sql -- ============================================================================ ---changeset RAISE-FUNCTIONS:1 endDelimiter:--// +--changeset michael.hoennig:RAISE-FUNCTIONS endDelimiter:--// -- ---------------------------------------------------------------------------- /* Like `RAISE EXCEPTION` ... just as an expression instead of a statement. */ -create or replace function raiseException(msg text) +create or replace function base.raiseException(msg text) returns varchar language plpgsql as $$ begin @@ -16,12 +16,12 @@ end; $$; -- ============================================================================ ---changeset ASSERT-FUNCTIONS:1 endDelimiter:--// +--changeset michael.hoennig:ASSERT-FUNCTIONS endDelimiter:--// -- ---------------------------------------------------------------------------- /* Like `ASSERT` but as an expression instead of a statement. */ -create or replace function assertTrue(expectedTrue boolean, msg text) +create or replace function base.assertTrue(expectedTrue boolean, msg text) returns boolean language plpgsql as $$ begin diff --git a/src/main/resources/db/changelog/0-basis/009-check-environment.sql b/src/main/resources/db/changelog/0-base/009-check-environment.sql similarity index 92% rename from src/main/resources/db/changelog/0-basis/009-check-environment.sql rename to src/main/resources/db/changelog/0-base/009-check-environment.sql index 0bad2670..d4a2f867 100644 --- a/src/main/resources/db/changelog/0-basis/009-check-environment.sql +++ b/src/main/resources/db/changelog/0-base/009-check-environment.sql @@ -3,7 +3,7 @@ -- ============================================================================ -- NUMERIC-HASH-FUNCTIONS ---changeset hash:1 endDelimiter:--// +--changeset michael.hoennig:hash endDelimiter:--// -- ---------------------------------------------------------------------------- do $$ diff --git a/src/main/resources/db/changelog/0-basis/010-context.sql b/src/main/resources/db/changelog/0-base/010-context.sql similarity index 70% rename from src/main/resources/db/changelog/0-basis/010-context.sql rename to src/main/resources/db/changelog/0-base/010-context.sql index 25c6c48c..95318e9a 100644 --- a/src/main/resources/db/changelog/0-basis/010-context.sql +++ b/src/main/resources/db/changelog/0-base/010-context.sql @@ -2,17 +2,17 @@ -- ============================================================================ ---changeset context-DEFINE:1 endDelimiter:--// +--changeset michael.hoennig:context-DEFINE endDelimiter:--// -- ---------------------------------------------------------------------------- /* Callback which is called after the context has been (re-) defined. This function will be overwritten by later changesets. */ -create procedure contextDefined( +create procedure base.contextDefined( currentTask varchar(127), currentRequest text, - currentUser varchar(63), + currentSubject varchar(63), assumedRoles varchar(1023) ) language plpgsql as $$ @@ -22,10 +22,10 @@ end; $$; /* Defines the transaction context. */ -create or replace procedure defineContext( +create or replace procedure base.defineContext( currentTask varchar(127), currentRequest text = null, - currentUser varchar(63) = null, + currentSubject varchar(63) = null, assumedRoles varchar(1023) = null ) language plpgsql as $$ @@ -38,27 +38,27 @@ begin currentRequest := coalesce(currentRequest, ''); execute format('set local hsadminng.currentRequest to %L', currentRequest); - currentUser := coalesce(currentUser, ''); - assert length(currentUser) <= 63, FORMAT('currentUser must not be longer than 63 characters: "%s"', currentUser); - execute format('set local hsadminng.currentUser to %L', currentUser); + currentSubject := coalesce(currentSubject, ''); + assert length(currentSubject) <= 63, FORMAT('currentSubject must not be longer than 63 characters: "%s"', currentSubject); + execute format('set local hsadminng.currentSubject to %L', currentSubject); assumedRoles := coalesce(assumedRoles, ''); assert length(assumedRoles) <= 1023, FORMAT('assumedRoles must not be longer than 1023 characters: "%s"', assumedRoles); execute format('set local hsadminng.assumedRoles to %L', assumedRoles); - call contextDefined(currentTask, currentRequest, currentUser, assumedRoles); + call base.contextDefined(currentTask, currentRequest, currentSubject, assumedRoles); end; $$; --// -- ============================================================================ ---changeset context-CURRENT-TASK:1 endDelimiter:--// +--changeset michael.hoennig:context-CURRENT-TASK endDelimiter:--// -- ---------------------------------------------------------------------------- /* Returns the current task as set by `hsadminng.currentTask`. Raises exception if not set. */ -create or replace function currentTask() +create or replace function base.currentTask() returns varchar(127) stable -- leakproof language plpgsql as $$ @@ -72,7 +72,7 @@ begin currentTask := null; end; if (currentTask is null or currentTask = '') then - raise exception '[401] currentTask must be defined, please call `defineContext(...)`'; + raise exception '[401] currentTask must be defined, please call `base.defineContext(...)`'; end if; return currentTask; end; $$; @@ -80,13 +80,13 @@ end; $$; -- ============================================================================ ---changeset context-CURRENT-REQUEST:1 endDelimiter:--// +--changeset michael.hoennig:context-CURRENT-REQUEST endDelimiter:--// -- ---------------------------------------------------------------------------- /* - Returns the current http request as set via `defineContext(...)`. + Returns the current http request as set via `base.defineContext(...)`. Raises exception if not set. */ -create or replace function currentRequest() +create or replace function base.currentRequest() returns text stable -- leakproof language plpgsql as $$ @@ -105,36 +105,36 @@ end; $$; -- ============================================================================ ---changeset context-CURRENT-USER:1 endDelimiter:--// +--changeset michael.hoennig:context-current-subject endDelimiter:--// -- ---------------------------------------------------------------------------- /* - Returns the current user as defined by `defineContext(...)`. + Returns the current user as defined by `base.defineContext(...)`. */ -create or replace function currentUser() +create or replace function base.currentSubject() returns varchar(63) stable -- leakproof language plpgsql as $$ declare - currentUser varchar(63); + currentSubject varchar(63); begin begin - currentUser := current_setting('hsadminng.currentUser'); + currentSubject := current_setting('hsadminng.currentSubject'); exception when others then - currentUser := null; + currentSubject := null; end; - return currentUser; + return currentSubject; end; $$; --// -- ============================================================================ ---changeset context-ASSUMED-ROLES:1 endDelimiter:--// +--changeset michael.hoennig:context-base.ASSUMED-ROLES endDelimiter:--// -- ---------------------------------------------------------------------------- /* Returns assumed role names as set in `hsadminng.assumedRoles` or empty array, if not set. */ -create or replace function assumedRoles() +create or replace function base.assumedRoles() returns varchar(1023)[] stable -- leakproof language plpgsql as $$ @@ -142,7 +142,7 @@ begin return string_to_array(current_setting('hsadminng.assumedRoles', true), ';'); end; $$; -create or replace function cleanIdentifier(rawIdentifier varchar) +create or replace function base.cleanIdentifier(rawIdentifier varchar) returns varchar returns null on null input language plpgsql as $$ @@ -153,21 +153,21 @@ begin return cleanIdentifier; end; $$; -create or replace function pureIdentifier(rawIdentifier varchar) +create or replace function base.pureIdentifier(rawIdentifier varchar) returns varchar returns null on null input language plpgsql as $$ declare cleanIdentifier varchar; begin - cleanIdentifier := cleanIdentifier(rawIdentifier); + cleanIdentifier := base.cleanIdentifier(rawIdentifier); if cleanIdentifier != rawIdentifier then raise exception 'identifier "%" contains invalid characters, maybe use "%"', rawIdentifier, cleanIdentifier; end if; return cleanIdentifier; end; $$; -create or replace function findObjectUuidByIdName(objectTable varchar, objectIdName varchar) +create or replace function base.findObjectUuidByIdName(objectTable varchar, objectIdName varchar) returns uuid returns null on null input language plpgsql as $$ @@ -175,8 +175,8 @@ declare sql varchar; uuid uuid; begin - objectTable := pureIdentifier(objectTable); - objectIdName := pureIdentifier(objectIdName); + objectTable := base.pureIdentifier(objectTable); + objectIdName := base.pureIdentifier(objectIdName); sql := format('select * from %sUuidByIdName(%L);', objectTable, objectIdName); begin execute sql into uuid; @@ -187,7 +187,7 @@ begin return uuid; end ; $$; -create or replace function findIdNameByObjectUuid(objectTable varchar, objectUuid uuid) +create or replace function base.findIdNameByObjectUuid(objectTable varchar, objectUuid uuid) returns varchar returns null on null input language plpgsql as $$ @@ -195,7 +195,7 @@ declare sql varchar; idName varchar; begin - objectTable := pureIdentifier(objectTable); + objectTable := base.pureIdentifier(objectTable); sql := format('select * from %sIdNameByUuid(%L::uuid);', objectTable, objectUuid); begin execute sql into idName; @@ -206,27 +206,27 @@ begin return idName; end ; $$; -create or replace function currentSubjects() +create or replace function base.currentSubjects() returns varchar(1023)[] stable -- leakproof language plpgsql as $$ declare assumedRoles varchar(1023)[]; begin - assumedRoles := assumedRoles(); + assumedRoles := base.assumedRoles(); if array_length(assumedRoles, 1) > 0 then return assumedRoles; else - return array [currentUser()]::varchar(1023)[]; + return array [base.currentSubject()]::varchar(1023)[]; end if; end; $$; -create or replace function hasAssumedRole() +create or replace function base.hasAssumedRole() returns boolean stable -- leakproof language plpgsql as $$ begin - return array_length(assumedRoles(), 1) > 0; + return array_length(base.assumedRoles(), 1) > 0; end; $$; --// diff --git a/src/main/resources/db/changelog/0-basis/020-audit-log.sql b/src/main/resources/db/changelog/0-base/020-audit-log.sql similarity index 58% rename from src/main/resources/db/changelog/0-basis/020-audit-log.sql rename to src/main/resources/db/changelog/0-base/020-audit-log.sql index c231814c..cdf5b42c 100644 --- a/src/main/resources/db/changelog/0-basis/020-audit-log.sql +++ b/src/main/resources/db/changelog/0-base/020-audit-log.sql @@ -1,107 +1,107 @@ --liquibase formatted sql -- ============================================================================ ---changeset audit-OPERATION-TYPE:1 endDelimiter:--// +--changeset michael.hoennig:audit-OPERATION-TYPE endDelimiter:--// -- ---------------------------------------------------------------------------- /* A type representing a DML operation. */ do $$ begin - if not exists(select 1 from pg_type where typname = 'operation') then - create type "operation" as enum ('INSERT', 'UPDATE', 'DELETE', 'TRUNCATE'); + if not exists(select 1 from pg_type where typname = 'base.tx_operation') then + create type base.tx_operation as enum ('INSERT', 'UPDATE', 'DELETE', 'TRUNCATE'); end if; --more types here... end $$; --// -- ============================================================================ ---changeset audit-TX-CONTEXT-TABLE:1 endDelimiter:--// +--changeset michael.hoennig:audit-TX-CONTEXT-TABLE endDelimiter:--// -- ---------------------------------------------------------------------------- /* A table storing transactions with context data. */ -create table tx_context +create table base.tx_context ( txId xid8 primary key not null, txTimestamp timestamp not null, - currentUser varchar(63) not null, -- not the uuid, because users can be deleted + currentSubject varchar(63) not null, -- not the uuid, because users can be deleted assumedRoles varchar(1023) not null, -- not the uuids, because roles can be deleted currentTask varchar(127) not null, currentRequest text not null ); -create index on tx_context using brin (txTimestamp); +create index on base.tx_context using brin (txTimestamp); --// -- ============================================================================ ---changeset audit-TX-JOURNAL-TABLE:1 endDelimiter:--// +--changeset michael.hoennig:audit-TX-JOURNAL-TABLE endDelimiter:--// -- ---------------------------------------------------------------------------- /* A table storing the transaction audit journal for all target tables it's configured for. */ -create table tx_journal +create table base.tx_journal ( - txId xid8 not null references tx_context (txId), - targetTable text not null, - targetUuid uuid not null, -- Assumes that all audited tables have a uuid column. - targetOp operation not null, + txId xid8 not null references base.tx_context (txId), + targetTable text not null, + targetUuid uuid not null, -- Assumes that all audited tables have a uuid column. + targetOp base.tx_operation not null, targetDelta jsonb ); -create index on tx_journal (targetTable, targetUuid); +create index on base.tx_journal (targetTable, targetUuid); --// -- ============================================================================ ---changeset audit-TX-JOURNAL-VIEW:1 endDelimiter:--// +--changeset michael.hoennig:audit-TX-JOURNAL-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- /* - A view combining tx_journal with tx_context. + A view combining base.tx_journal with base.tx_context. */ -create view tx_journal_v as +create view base.tx_journal_v as select txc.*, txj.targettable, txj.targetop, txj.targetuuid, txj.targetdelta - from tx_journal txj - left join tx_context txc using (txId) + from base.tx_journal txj + left join base.tx_context txc using (txId) order by txc.txtimestamp; --// -- ============================================================================ ---changeset audit-TX-JOURNAL-TRIGGER:1 endDelimiter:--// +--changeset michael.hoennig:audit-TX-JOURNAL-TRIGGER endDelimiter:--// -- ---------------------------------------------------------------------------- /* Trigger function for transaction audit journal. */ -create or replace function tx_journal_trigger() +create or replace function base.tx_journal_trigger() returns trigger language plpgsql as $$ declare curTask text; curTxId xid8; begin - curTask := currentTask(); + curTask := base.currentTask(); curTxId := pg_current_xact_id(); insert - into tx_context (txId, txTimestamp, currentUser, assumedRoles, currentTask, currentRequest) + into base.tx_context (txId, txTimestamp, currentSubject, assumedRoles, currentTask, currentRequest) values ( curTxId, now(), - currentUser(), assumedRoles(), curTask, currentRequest()) + base.currentSubject(), base.assumedRoles(), curTask, base.currentRequest()) on conflict do nothing; case tg_op when 'INSERT' then insert - into tx_journal + into base.tx_journal values (curTxId, - tg_table_name, new.uuid, tg_op::operation, + tg_table_name, new.uuid, tg_op::base.tx_operation, to_jsonb(new)); when 'UPDATE' then insert - into tx_journal + into base.tx_journal values (curTxId, - tg_table_name, old.uuid, tg_op::operation, - jsonb_changes_delta(to_jsonb(old), to_jsonb(new))); + tg_table_name, old.uuid, tg_op::base.tx_operation, + base.jsonb_changes_delta(to_jsonb(old), to_jsonb(new))); when 'DELETE' then insert - into tx_journal + into base.tx_journal values (curTxId, - tg_table_name, old.uuid, 'DELETE'::operation, + tg_table_name, old.uuid, 'DELETE'::base.tx_operation, null::jsonb); else raise exception 'Trigger op % not supported for %.', tg_op, tg_table_name; end case; @@ -110,22 +110,23 @@ end; $$; --// -- ============================================================================ ---changeset audit-CREATE-JOURNAL-LOG:1 endDelimiter:--// +--changeset michael.hoennig:audit-CREATE-JOURNAL-LOG endDelimiter:--// -- ---------------------------------------------------------------------------- /* Trigger function for transaction audit journal. */ -create or replace procedure create_journal(targetTable varchar) +create or replace procedure base.create_journal(targetTable varchar) language plpgsql as $$ declare createTriggerSQL varchar; begin targetTable := lower(targetTable); - createTriggerSQL = 'CREATE TRIGGER ' || targetTable || '_journal' || + -- "-0-" to put the trigger execution before any alphabetically greater tx-triggers + createTriggerSQL = 'CREATE TRIGGER tx_0_journal_tg' || ' AFTER INSERT OR UPDATE OR DELETE ON ' || targetTable || - ' FOR EACH ROW EXECUTE PROCEDURE tx_journal_trigger()'; + ' FOR EACH ROW EXECUTE PROCEDURE base.tx_journal_trigger()'; execute createTriggerSQL; end; $$; --// diff --git a/src/main/resources/db/changelog/0-basis/030-historization.sql b/src/main/resources/db/changelog/0-base/030-historization.sql similarity index 74% rename from src/main/resources/db/changelog/0-basis/030-historization.sql rename to src/main/resources/db/changelog/0-base/030-historization.sql index 709cb9c8..888f5be9 100644 --- a/src/main/resources/db/changelog/0-basis/030-historization.sql +++ b/src/main/resources/db/changelog/0-base/030-historization.sql @@ -1,9 +1,9 @@ --liquibase formatted sql -- ============================================================================ ---changeset hs-global-historization-tx-history-txid:1 endDelimiter:--// +--changeset michael.hoennig:hs-global-historization-tx-history-txid endDelimiter:--// -- ---------------------------------------------------------------------------- -create or replace function tx_history_txid() +create or replace function base.tx_history_txid() returns xid8 stable language plpgsql as $$ declare @@ -23,11 +23,11 @@ begin historicalTxIdSetting, historicalTimestampSetting; end if; -- just for debugging / making sure the function is only called once per query - -- raise notice 'tx_history_txid() called with: (%, %)', historicalTxIdSetting, historicalTimestampSetting; + -- raise notice 'base.tx_history_txid() called with: (%, %)', historicalTxIdSetting, historicalTimestampSetting; if historicalTxIdSetting is null or historicalTxIdSetting = '' then select historicalTimestampSetting::timestamp into historicalTimestamp; - select max(txc.txid) from tx_context txc where txc.txtimestamp <= historicalTimestamp into historicalTxId; + select max(txc.txid) from base.tx_context txc where txc.txtimestamp <= historicalTimestamp into historicalTxId; else historicalTxId = historicalTxIdSetting::xid8; end if; @@ -37,17 +37,17 @@ end; $$; -- ============================================================================ ---changeset hs-global-historization-tx-historicize-tf:1 endDelimiter:--// +--changeset michael.hoennig:hs-global-historization-tx-historicize-tf endDelimiter:--// -- ---------------------------------------------------------------------------- -create type "tx_operation" as enum ('INSERT', 'UPDATE', 'DELETE', 'TRUNCATE'); +-- create type base.tx_operation as enum ('INSERT', 'UPDATE', 'DELETE', 'TRUNCATE'); -create or replace function tx_historicize_tf() +create or replace function base.tx_historicize_tf() returns trigger language plpgsql strict as $$ declare - currentUser varchar(63); + currentSubject varchar(63); currentTask varchar(127); "row" record; "alive" boolean; @@ -55,15 +55,15 @@ declare begin -- determine user_id begin - currentUser := current_setting('hsadminng.currentUser'); + currentSubject := current_setting('hsadminng.currentSubject'); exception when others then - currentUser := null; + currentSubject := null; end; - if (currentUser is null or currentUser = '') then - raise exception 'hsadminng.currentUser must be defined, please use "SET LOCAL ...;"'; + if (currentSubject is null or currentSubject = '') then + raise exception 'hsadminng.currentSubject must be defined, please use "SET LOCAL ...;"'; end if; - raise notice 'currentUser: %', currentUser; + raise notice 'currentSubject: %', currentSubject; -- determine task currentTask = current_setting('hsadminng.currentTask'); @@ -91,11 +91,11 @@ end; $$; -- ============================================================================ ---changeset hs-global-historization-tx-create-historicization:1 endDelimiter:--// +--changeset michael.hoennig:hs-global-historization-tx-create-historicization endDelimiter:--// -- ---------------------------------------------------------------------------- -create or replace procedure tx_create_historicization(baseTable varchar) +create or replace procedure base.tx_create_historicization(baseTable varchar) language plpgsql as $$ declare createHistTableSql varchar; @@ -110,8 +110,8 @@ begin createHistTableSql = '' || 'CREATE TABLE ' || baseTable || '_ex (' || ' version_id serial PRIMARY KEY,' || - ' txid xid8 NOT NULL REFERENCES tx_context(txid),' || - ' trigger_op tx_operation NOT NULL,' || + ' txid xid8 NOT NULL REFERENCES base.tx_context(txid),' || + ' trigger_op base.tx_operation NOT NULL,' || ' alive boolean not null,' || ' LIKE ' || baseTable || ' EXCLUDING CONSTRAINTS' || @@ -131,8 +131,8 @@ begin createViewSQL = format( 'CREATE OR REPLACE VIEW %1$s AS' || '(' || - -- make sure the function is only called once, not for every matching row in tx_context - ' WITH txh AS (SELECT tx_history_txid() AS txid) ' || + -- make sure the function is only called once, not for every matching row in base.tx_context + ' WITH txh AS (SELECT base.tx_history_txid() AS txid) ' || ' SELECT %2$s' || ' FROM %3$s' || ' WHERE alive = TRUE' || @@ -140,7 +140,7 @@ begin ' (' || ' SELECT max(ex.version_id) AS history_id' || ' FROM %3$s AS ex' || - ' JOIN tx_context as txc ON ex.txid = txc.txid' || + ' JOIN base.tx_context as txc ON ex.txid = txc.txid' || ' WHERE txc.txid <= (SELECT txid FROM txh)' || ' GROUP BY uuid' || ' )' || @@ -150,9 +150,10 @@ begin raise notice 'sql: %', createViewSQL; execute createViewSQL; - createTriggerSQL = 'CREATE TRIGGER ' || baseTable || '_tx_historicize_tg' || + -- "-9-" to put the trigger execution after any alphabetically lesser tx-triggers + createTriggerSQL = 'CREATE TRIGGER tx_9_historicize_tg' || ' AFTER INSERT OR DELETE OR UPDATE ON ' || baseTable || - ' FOR EACH ROW EXECUTE PROCEDURE tx_historicize_tf()'; + ' FOR EACH ROW EXECUTE PROCEDURE base.tx_historicize_tf()'; raise notice 'sql: %', createTriggerSQL; execute createTriggerSQL; diff --git a/src/main/resources/db/changelog/0-basis/090-log-slow-queries-extensions.sql b/src/main/resources/db/changelog/0-base/090-log-slow-queries-extensions.sql similarity index 76% rename from src/main/resources/db/changelog/0-basis/090-log-slow-queries-extensions.sql rename to src/main/resources/db/changelog/0-base/090-log-slow-queries-extensions.sql index 953004db..d4d89ac0 100644 --- a/src/main/resources/db/changelog/0-basis/090-log-slow-queries-extensions.sql +++ b/src/main/resources/db/changelog/0-base/090-log-slow-queries-extensions.sql @@ -3,7 +3,7 @@ -- ============================================================================ -- PG-STAT-STATEMENTS-EXTENSION ---changeset pg-stat-statements-extension:1 context:pg_stat_statements endDelimiter:--// +--changeset michael.hoennig:pg-stat-statements-extension context:pg_stat_statements endDelimiter:--// -- ---------------------------------------------------------------------------- /* Makes improved uuid generation available. diff --git a/src/main/resources/db/changelog/1-rbac/1000-rbac-schema.sql b/src/main/resources/db/changelog/1-rbac/1000-rbac-schema.sql new file mode 100644 index 00000000..a28b0935 --- /dev/null +++ b/src/main/resources/db/changelog/1-rbac/1000-rbac-schema.sql @@ -0,0 +1,8 @@ +--liquibase formatted sql + + +-- ============================================================================ +--changeset michael.hoennig:rbac-SCHEMA endDelimiter:--// +-- ---------------------------------------------------------------------------- +CREATE SCHEMA rbac; +--// diff --git a/src/main/resources/db/changelog/1-rbac/1050-rbac-base.sql b/src/main/resources/db/changelog/1-rbac/1050-rbac-base.sql index 6199abcd..77ced6ad 100644 --- a/src/main/resources/db/changelog/1-rbac/1050-rbac-base.sql +++ b/src/main/resources/db/changelog/1-rbac/1050-rbac-base.sql @@ -1,30 +1,30 @@ --liquibase formatted sql -- ============================================================================ ---changeset rbac-base-REFERENCE:1 endDelimiter:--// +--changeset michael.hoennig:rbac-base-REFERENCE endDelimiter:--// -- ---------------------------------------------------------------------------- /* */ -create type ReferenceType as enum ('RbacUser', 'RbacRole', 'RbacPermission'); +create type rbac.ReferenceType as enum ('rbac.subject', 'rbac.role', 'rbac.permission'); -create table RbacReference +create table rbac.reference ( uuid uuid unique default uuid_generate_v4(), - type ReferenceType not null + type rbac.ReferenceType not null ); -create or replace function assertReferenceType(argument varchar, referenceId uuid, expectedType ReferenceType) - returns ReferenceType +create or replace function rbac.assertReferenceType(argument varchar, referenceId uuid, expectedType rbac.ReferenceType) + returns rbac.ReferenceType language plpgsql as $$ declare - actualType ReferenceType; + actualType rbac.ReferenceType; begin if referenceId is null then raise exception '% must be a % and not null', argument, expectedType; end if; - actualType = (select type from RbacReference where uuid = referenceId); + actualType = (select type from rbac.reference where uuid = referenceId); if (actualType <> expectedType) then raise exception '% must reference a %, but got a %', argument, expectedType, actualType; end if; @@ -33,20 +33,20 @@ end; $$; --// -- ============================================================================ ---changeset rbac-base-USER:1 endDelimiter:--// +--changeset michael.hoennig:rbac-base-SUBJECT endDelimiter:--// -- ---------------------------------------------------------------------------- /* */ -create table RbacUser +create table rbac.subject ( - uuid uuid primary key references RbacReference (uuid) on delete cascade, + uuid uuid primary key references rbac.reference (uuid) on delete cascade, name varchar(63) not null unique ); -call create_journal('RbacUser'); +call base.create_journal('rbac.subject'); -create or replace function createRbacUser(userName varchar) +create or replace function rbac.create_subject(subjectName varchar) returns uuid returns null on null input language plpgsql as $$ @@ -54,47 +54,47 @@ declare objectId uuid; begin insert - into RbacReference (type) - values ('RbacUser') + into rbac.reference (type) + values ('rbac.subject') returning uuid into objectId; insert - into RbacUser (uuid, name) - values (objectid, userName); + into rbac.subject (uuid, name) + values (objectid, subjectName); return objectId; end; $$; -create or replace function createRbacUser(refUuid uuid, userName varchar) +create or replace function rbac.create_subject(refUuid uuid, subjectName varchar) returns uuid called on null input language plpgsql as $$ begin insert - into RbacReference as r (uuid, type) - values (coalesce(refUuid, uuid_generate_v4()), 'RbacUser') + into rbac.reference as r (uuid, type) + values (coalesce(refUuid, uuid_generate_v4()), 'rbac.subject') returning r.uuid into refUuid; insert - into RbacUser (uuid, name) - values (refUuid, userName); + into rbac.subject (uuid, name) + values (refUuid, subjectName); return refUuid; end; $$; -create or replace function findRbacUserId(userName varchar) +create or replace function rbac.find_subject_id(subjectName varchar) returns uuid returns null on null input language sql as $$ -select uuid from RbacUser where name = userName +select uuid from rbac.subject where name = subjectName $$; --// -- ============================================================================ ---changeset rbac-base-OBJECT:1 endDelimiter:--// +--changeset michael.hoennig:rbac-base-OBJECT endDelimiter:--// -- ---------------------------------------------------------------------------- /* */ -create table RbacObject +create table rbac.object ( uuid uuid primary key default uuid_generate_v4(), serialId serial, -- TODO.perf: only needed for reverse deletion of temp test data @@ -102,19 +102,19 @@ create table RbacObject unique (objectTable, uuid) ); -call create_journal('RbacObject'); +call base.create_journal('rbac.object'); --// -- ============================================================================ ---changeset rbac-base-GENERATE-RELATED-OBJECT:1 endDelimiter:--// +--changeset michael.hoennig:rbac-base-GENERATE-RELATED-OBJECT endDelimiter:--// -- ---------------------------------------------------------------------------- /* - Inserts related RbacObject for use in the BEFORE ONSERT TRIGGERs on the business objects. + Inserts related rbac.object for use in the BEFORE INSERT TRIGGERs on the business objects. */ -create or replace function insertRelatedRbacObject() +create or replace function rbac.insert_related_object() returns trigger language plpgsql strict as $$ @@ -124,13 +124,13 @@ begin if TG_OP = 'INSERT' then if NEW.uuid is null then insert - into RbacObject (objectTable) + into rbac.object (objectTable) values (TG_TABLE_NAME) returning uuid into objectUuid; NEW.uuid = objectUuid; else insert - into RbacObject (uuid, objectTable) + into rbac.object (uuid, objectTable) values (NEW.uuid, TG_TABLE_NAME) returning uuid into objectUuid; end if; @@ -141,75 +141,79 @@ begin end; $$; /* - Deletes related RbacObject for use in the BEFORE DELETE TRIGGERs on the business objects. + Deletes related rbac.object for use in the BEFORE DELETE TRIGGERs on the business objects. + Through cascades all related rbac roles and grants are going to be deleted as well. */ -create or replace function deleteRelatedRbacObject() +create or replace function rbac.delete_related_rbac_rules_tf() returns trigger language plpgsql strict as $$ begin if TG_OP = 'DELETE' then - delete from RbacObject where rbacobject.uuid = old.uuid; + delete from rbac.object where rbac.object.uuid = old.uuid; else raise exception 'invalid usage of TRIGGER BEFORE DELETE'; end if; return old; end; $$; +--// -- ============================================================================ ---changeset rbac-base-ROLE:1 endDelimiter:--// +--changeset michael.hoennig:rbac-base-ROLE endDelimiter:--// -- ---------------------------------------------------------------------------- -/* - */ +create type rbac.RoleType as enum ('OWNER', 'ADMIN', 'AGENT', 'TENANT', 'GUEST', 'REFERRER'); -create type RbacRoleType as enum ('OWNER', 'ADMIN', 'AGENT', 'TENANT', 'GUEST', 'REFERRER'); - -create table RbacRole +create table rbac.role ( - uuid uuid primary key references RbacReference (uuid) on delete cascade initially deferred, -- initially deferred - objectUuid uuid not null references RbacObject (uuid) initially deferred, - roleType RbacRoleType not null, + uuid uuid primary key references rbac.reference (uuid) on delete cascade initially deferred, -- initially deferred + objectUuid uuid not null references rbac.object (uuid) initially deferred, + roleType rbac.RoleType not null, unique (objectUuid, roleType) ); -call create_journal('RbacRole'); +call base.create_journal('rbac.role'); +--// -create type RbacRoleDescriptor as + +-- ============================================================================ +--changeset michael.hoennig:rbac-base-ROLE-DESCRIPTOR endDelimiter:--// +-- ---------------------------------------------------------------------------- + +create type rbac.RoleDescriptor as ( objectTable varchar(63), -- for human readability and easier debugging objectUuid uuid, - roleType RbacRoleType, + roleType rbac.RoleType, assumed boolean ); -create or replace function assumed() +create or replace function rbac.assumed() returns boolean stable -- leakproof language sql as $$ select true; $$; -create or replace function unassumed() +create or replace function rbac.unassumed() returns boolean stable -- leakproof language sql as $$ select false; $$; - -create or replace function roleDescriptor( - objectTable varchar(63), objectUuid uuid, roleType RbacRoleType, +create or replace function rbac.roleDescriptorOf( + objectTable varchar(63), objectUuid uuid, roleType rbac.RoleType, assumed boolean = true) -- just for DSL readability, belongs actually to the grant - returns RbacRoleDescriptor + returns rbac.RoleDescriptor returns null on null input stable -- leakproof language sql as $$ - select objectTable, objectUuid, roleType::RbacRoleType, assumed; + select objectTable, objectUuid, roleType::rbac.RoleType, assumed; $$; -create or replace function createRole(roleDescriptor RbacRoleDescriptor) +create or replace function rbac.createRole(roleDescriptor rbac.RoleDescriptor) returns uuid returns null on null input language plpgsql as $$ @@ -217,60 +221,65 @@ declare referenceId uuid; begin insert - into RbacReference (type) - values ('RbacRole') + into rbac.reference (type) + values ('rbac.role') returning uuid into referenceId; insert - into RbacRole (uuid, objectUuid, roleType) + into rbac.role (uuid, objectUuid, roleType) values (referenceId, roleDescriptor.objectUuid, roleDescriptor.roleType); return referenceId; end; $$; +--// -create or replace procedure deleteRole(roleUUid uuid) +-- ============================================================================ +--changeset michael.hoennig:rbac-base-ROLE-FUNCTIONS endDelimiter:--// +-- ---------------------------------------------------------------------------- + +create or replace procedure rbac.deleteRole(roleUUid uuid) language plpgsql as $$ begin - --raise exception '% deleting role uuid %', currentsubjectsuuids(), roleUUid; - delete from RbacRole where uuid = roleUUid; + --raise exception '% deleting role uuid %', rbac.currentSubjectOrAssumedRolesUuids(), roleUUid; + delete from rbac.role where uuid = roleUUid; end; $$; -create or replace function findRoleId(roleIdName varchar) +create or replace function rbac.findRoleId(roleIdName varchar) returns uuid returns null on null input language plpgsql as $$ declare roleParts text; - roleTypeFromRoleIdName RbacRoleType; + roleTypeFromRoleIdName rbac.RoleType; objectNameFromRoleIdName text; objectTableFromRoleIdName text; objectUuidOfRole uuid; roleUuid uuid; begin - -- TODO.refa: extract function toRbacRoleDescriptor(roleIdName varchar) + find other occurrences + -- TODO.refa: extract function rbac.toRoleDescriptor(roleIdName varchar) + find other occurrences roleParts = overlay(roleIdName placing '#' from length(roleIdName) + 1 - strpos(reverse(roleIdName), ':')); objectTableFromRoleIdName = split_part(roleParts, '#', 1); objectNameFromRoleIdName = split_part(roleParts, '#', 2); roleTypeFromRoleIdName = split_part(roleParts, '#', 3); - objectUuidOfRole = findObjectUuidByIdName(objectTableFromRoleIdName, objectNameFromRoleIdName); + objectUuidOfRole = base.findObjectUuidByIdName(objectTableFromRoleIdName, objectNameFromRoleIdName); select uuid - from RbacRole + from rbac.role where objectUuid = objectUuidOfRole and roleType = roleTypeFromRoleIdName into roleUuid; return roleUuid; end; $$; -create or replace function findRoleId(roleDescriptor RbacRoleDescriptor) +create or replace function rbac.findRoleId(roleDescriptor rbac.RoleDescriptor) returns uuid returns null on null input language sql as $$ -select uuid from RbacRole where objectUuid = roleDescriptor.objectUuid and roleType = roleDescriptor.roleType; +select uuid from rbac.role where objectUuid = roleDescriptor.objectUuid and roleType = roleDescriptor.roleType; $$; -create or replace function getRoleId(roleDescriptor RbacRoleDescriptor) +create or replace function rbac.getRoleId(roleDescriptor rbac.RoleDescriptor) returns uuid language plpgsql as $$ declare @@ -278,29 +287,30 @@ declare begin assert roleDescriptor is not null, 'roleDescriptor must not be null'; - roleUuid := findRoleId(roleDescriptor); + roleUuid := rbac.findRoleId(roleDescriptor); if (roleUuid is null) then - raise exception 'RbacRole "%#%.%" not found', roleDescriptor.objectTable, roleDescriptor.objectUuid, roleDescriptor.roleType; + raise exception 'rbac.role "%#%.%" not found', roleDescriptor.objectTable, roleDescriptor.objectUuid, roleDescriptor.roleType; end if; return roleUuid; end; $$; +--// -- ============================================================================ ---changeset rbac-base-BEFORE-DELETE-ROLE-TRIGGER:1 endDelimiter:--// +--changeset michael.hoennig:rbac-base-BEFORE-DELETE-ROLE-TRIGGER endDelimiter:--// -- ---------------------------------------------------------------------------- /* - RbacRole BEFORE DELETE TRIGGER function which deletes all related roles. + rbac.role BEFORE DELETE TRIGGER function which deletes all related roles. */ -create or replace function deleteRbacGrantsOfRbacRole() +create or replace function rbac.delete_grants_of_role_tf() returns trigger language plpgsql strict as $$ begin if TG_OP = 'DELETE' then - delete from RbacGrants g where old.uuid in (g.grantedbyroleuuid, g.ascendantuuid, g.descendantuuid); + delete from rbac.grants g where old.uuid in (g.grantedbyroleuuid, g.ascendantuuid, g.descendantuuid); else raise exception 'invalid usage of TRIGGER BEFORE DELETE'; end if; @@ -308,31 +318,31 @@ begin end; $$; /* - Installs the RbacRole BEFORE DELETE TRIGGER. + Installs the rbac.role BEFORE DELETE TRIGGER. */ -create trigger deleteRbacGrantsOfRbacRole_Trigger +create trigger delete_grants_of_role_tg before delete - on RbacRole + on rbac.role for each row -execute procedure deleteRbacGrantsOfRbacRole(); +execute procedure rbac.delete_grants_of_role_tf(); --// -- ============================================================================ ---changeset rbac-base-BEFORE-DELETE-OBJECT-TRIGGER:1 endDelimiter:--// +--changeset michael.hoennig:rbac-base-BEFORE-DELETE-OBJECT-TRIGGER endDelimiter:--// -- ---------------------------------------------------------------------------- /* - RbacObject BEFORE DELETE TRIGGER function which deletes all related roles. + rbac.object BEFORE DELETE TRIGGER function which deletes all related roles. */ -create or replace function deleteRbacRolesOfRbacObject() +create or replace function rbac.delete_roles_of_object_tf() returns trigger language plpgsql strict as $$ begin if TG_OP = 'DELETE' then - delete from RbacPermission p where p.objectuuid = old.uuid; - delete from RbacRole r where r.objectUuid = old.uuid; + delete from rbac.permission p where p.objectuuid = old.uuid; + delete from rbac.role r where r.objectUuid = old.uuid; else raise exception 'invalid usage of TRIGGER BEFORE DELETE'; end if; @@ -340,23 +350,20 @@ begin end; $$; /* - Installs the RbacRole BEFORE DELETE TRIGGER. + Installs the rbac.role BEFORE DELETE TRIGGER. */ -create trigger deleteRbacRolesOfRbacObject_Trigger +create trigger delete_roles_of_object_tg before delete - on RbacObject + on rbac.object for each row - execute procedure deleteRbacRolesOfRbacObject(); + execute procedure rbac.delete_roles_of_object_tf(); --// -- ============================================================================ ---changeset rbac-base-PERMISSION:1 endDelimiter:--// +--changeset michael.hoennig:rbac-base-PERMISSION endDelimiter:--// -- ---------------------------------------------------------------------------- -/* - - */ -create domain RbacOp as varchar(6) +create domain rbac.RbacOp as varchar(6) check ( VALUE = 'DELETE' or VALUE = 'UPDATE' @@ -365,23 +372,23 @@ create domain RbacOp as varchar(6) or VALUE = 'ASSUME' ); -create table RbacPermission +create table rbac.permission ( - uuid uuid primary key references RbacReference (uuid) on delete cascade, - objectUuid uuid not null references RbacObject, - op RbacOp not null, + uuid uuid primary key references rbac.reference (uuid) on delete cascade, + objectUuid uuid not null references rbac.object, + op rbac.RbacOp not null, opTableName varchar(60) ); -- TODO.perf: check if these indexes are really useful -create index on RbacPermission (objectUuid, op); -create index on RbacPermission (opTableName, op); +create index on rbac.permission (objectUuid, op); +create index on rbac.permission (opTableName, op); -ALTER TABLE RbacPermission +ALTER TABLE rbac.permission ADD CONSTRAINT RbacPermission_uc UNIQUE NULLS NOT DISTINCT (objectUuid, op, opTableName); -call create_journal('RbacPermission'); +call base.create_journal('rbac.permission'); -create or replace function createPermission(forObjectUuid uuid, forOp RbacOp, forOpTableName text = null) +create or replace function rbac.createPermission(forObjectUuid uuid, forOp rbac.RbacOp, forOpTableName text = null) returns uuid language plpgsql as $$ declare @@ -398,50 +405,50 @@ begin end if; permissionUuid := ( - select uuid from RbacPermission + select uuid from rbac.permission where objectUuid = forObjectUuid and op = forOp and opTableName is not distinct from forOpTableName); if (permissionUuid is null) then - insert into RbacReference ("type") - values ('RbacPermission') + insert into rbac.reference ("type") + values ('rbac.permission') returning uuid into permissionUuid; begin - insert into RbacPermission (uuid, objectUuid, op, opTableName) + insert into rbac.permission (uuid, objectUuid, op, opTableName) values (permissionUuid, forObjectUuid, forOp, forOpTableName); exception when others then - raise exception 'insert into RbacPermission (uuid, objectUuid, op, opTableName) + raise exception 'insert into rbac.permission (uuid, objectUuid, op, opTableName) values (%, %, %, %);', permissionUuid, forObjectUuid, forOp, forOpTableName; end; end if; return permissionUuid; end; $$; -create or replace function findEffectivePermissionId(forObjectUuid uuid, forOp RbacOp, forOpTableName text = null) +create or replace function rbac.findEffectivePermissionId(forObjectUuid uuid, forOp rbac.RbacOp, forOpTableName text = null) returns uuid returns null on null input stable -- leakproof language sql as $$ select uuid - from RbacPermission p + from rbac.permission p where p.objectUuid = forObjectUuid - and (forOp = 'SELECT' or p.op = forOp) -- all other RbacOp include 'SELECT' + and (forOp = 'SELECT' or p.op = forOp) -- all other rbac.RbacOp include 'SELECT' and p.opTableName = forOpTableName $$; -create or replace function findPermissionId(forObjectUuid uuid, forOp RbacOp, forOpTableName text = null) +create or replace function rbac.findPermissionId(forObjectUuid uuid, forOp rbac.RbacOp, forOpTableName text = null) returns uuid returns null on null input stable -- leakproof language sql as $$ select uuid - from RbacPermission p + from rbac.permission p where p.objectUuid = forObjectUuid and p.op = forOp and p.opTableName = forOpTableName $$; -create or replace function getPermissionId(forObjectUuid uuid, forOp RbacOp, forOpTableName text = null) +create or replace function rbac.getPermissionId(forObjectUuid uuid, forOp rbac.RbacOp, forOpTableName text = null) returns uuid stable -- leakproof language plpgsql as $$ @@ -449,7 +456,7 @@ declare permissionUuid uuid; begin select uuid into permissionUuid - from RbacPermission p + from rbac.permission p where p.objectUuid = forObjectUuid and p.op = forOp and forOpTableName is null or p.opTableName = forOpTableName; @@ -461,17 +468,17 @@ end; $$; -- ============================================================================ ---changeset rbac-base-duplicate-role-grant-exception:1 endDelimiter:--// +--changeset michael.hoennig:rbac-base-duplicate-role-grant-exception endDelimiter:--// -- ---------------------------------------------------------------------------- -create or replace procedure raiseDuplicateRoleGrantException(subRoleId uuid, superRoleId uuid) +create or replace procedure rbac.raiseDuplicateRoleGrantException(subRoleId uuid, superRoleId uuid) language plpgsql as $$ declare subRoleIdName text; superRoleIdName text; begin - select roleIdName from rbacRole_ev where uuid=subRoleId into subRoleIdName; - select roleIdName from rbacRole_ev where uuid=superRoleId into superRoleIdName; + select roleIdName from rbac.role_ev where uuid=subRoleId into subRoleIdName; + select roleIdName from rbac.role_ev where uuid=superRoleId into superRoleIdName; raise exception '[400] Duplicate role grant detected: role % (%) already granted to % (%)', subRoleId, subRoleIdName, superRoleId, superRoleIdName; end; $$; @@ -479,54 +486,54 @@ $$; -- ============================================================================ ---changeset rbac-base-GRANTS:1 endDelimiter:--// +--changeset michael.hoennig:rbac-base-GRANTS endDelimiter:--// -- ---------------------------------------------------------------------------- /* - Table to store grants / role- or permission assignments to users or roles. + Table to store grants / role- or permission assignments to subjects or roles. */ -create table RbacGrants +create table rbac.grants ( uuid uuid primary key default uuid_generate_v4(), - grantedByTriggerOf uuid references RbacObject (uuid) on delete cascade initially deferred , - grantedByRoleUuid uuid references RbacRole (uuid), - ascendantUuid uuid references RbacReference (uuid), - descendantUuid uuid references RbacReference (uuid), + grantedByTriggerOf uuid references rbac.object (uuid) on delete cascade initially deferred , + grantedByRoleUuid uuid references rbac.role (uuid), + ascendantUuid uuid references rbac.reference (uuid), + descendantUuid uuid references rbac.reference (uuid), assumed boolean not null default true, -- auto assumed (true) vs. needs assumeRoles (false) unique (ascendantUuid, descendantUuid), constraint rbacGrant_createdBy check ( grantedByRoleUuid is null or grantedByTriggerOf is null) ); -create index on RbacGrants (ascendantUuid); -create index on RbacGrants (descendantUuid); +create index on rbac.grants (ascendantUuid); +create index on rbac.grants (descendantUuid); -call create_journal('RbacGrants'); -create or replace function findGrantees(grantedId uuid) - returns setof RbacReference +call base.create_journal('rbac.grants'); +create or replace function rbac.findGrantees(grantedId uuid) + returns setof rbac.reference returns null on null input language sql as $$ with recursive grants as ( select descendantUuid, ascendantUuid - from RbacGrants + from rbac.grants where descendantUuid = grantedId union all select g.descendantUuid, g.ascendantUuid - from RbacGrants g + from rbac.grants g inner join grants on grants.ascendantUuid = g.descendantUuid ) select ref.* from grants - join RbacReference ref on ref.uuid = grants.ascendantUuid; + join rbac.reference ref on ref.uuid = grants.ascendantUuid; $$; -create or replace function isGranted(granteeIds uuid[], grantedId uuid) +create or replace function rbac.isGranted(granteeIds uuid[], grantedId uuid) returns bool returns null on null input language sql as $$ with recursive grants as ( select descendantUuid, ascendantUuid - from RbacGrants + from rbac.grants where descendantUuid = grantedId union all select "grant".descendantUuid, "grant".ascendantUuid - from RbacGrants "grant" + from rbac.grants "grant" inner join grants recur on recur.ascendantUuid = "grant".descendantUuid ) select exists ( @@ -536,23 +543,23 @@ select exists ( ) or grantedId = any(granteeIds); $$; -create or replace function isGranted(granteeId uuid, grantedId uuid) +create or replace function rbac.isGranted(granteeId uuid, grantedId uuid) returns bool returns null on null input language sql as $$ -select * from isGranted(array[granteeId], grantedId); +select * from rbac.isGranted(array[granteeId], grantedId); $$; -create or replace function isPermissionGrantedToSubject(permissionId uuid, subjectId uuid) +create or replace function rbac.isPermissionGrantedToSubject(permissionId uuid, subjectId uuid) returns BOOL stable -- leakproof language sql as $$ with recursive grants as ( select descendantUuid, ascendantUuid - from RbacGrants + from rbac.grants where descendantUuid = permissionId union all select g.descendantUuid, g.ascendantUuid - from RbacGrants g + from rbac.grants g inner join grants on grants.ascendantUuid = g.descendantUuid ) select exists( @@ -562,117 +569,117 @@ select exists( ); $$; -create or replace function hasInsertPermission(objectUuid uuid, tableName text ) +create or replace function rbac.hasInsertPermission(objectUuid uuid, tableName text ) returns BOOL stable -- leakproof language plpgsql as $$ declare permissionUuid uuid; begin - permissionUuid = findPermissionId(objectUuid, 'INSERT'::RbacOp, tableName); + permissionUuid = rbac.findPermissionId(objectUuid, 'INSERT'::rbac.RbacOp, tableName); return permissionUuid is not null; end; $$; -create or replace function hasGlobalRoleGranted(userUuid uuid) +create or replace function rbac.hasGlobalRoleGranted(forAscendantUuid uuid) returns bool stable -- leakproof language sql as $$ select exists( select r.uuid - from RbacGrants as g - join RbacRole as r on r.uuid = g.descendantuuid - join RbacObject as o on o.uuid = r.objectuuid - where g.ascendantuuid = userUuid - and o.objecttable = 'global' + from rbac.grants as g + join rbac.role as r on r.uuid = g.descendantuuid + join rbac.object as o on o.uuid = r.objectuuid + where g.ascendantuuid = forAscendantUuid + and o.objecttable = 'rbac.global' ); $$; -create or replace procedure grantPermissionToRole(permissionUuid uuid, roleUuid uuid) +create or replace procedure rbac.grantPermissionToRole(permissionUuid uuid, roleUuid uuid) language plpgsql as $$ begin - perform assertReferenceType('roleId (ascendant)', roleUuid, 'RbacRole'); - perform assertReferenceType('permissionId (descendant)', permissionUuid, 'RbacPermission'); + perform rbac.assertReferenceType('roleId (ascendant)', roleUuid, 'rbac.role'); + perform rbac.assertReferenceType('permissionId (descendant)', permissionUuid, 'rbac.permission'); insert - into RbacGrants (grantedByTriggerOf, ascendantUuid, descendantUuid, assumed) - values (currentTriggerObjectUuid(), roleUuid, permissionUuid, true) + into rbac.grants (grantedByTriggerOf, ascendantUuid, descendantUuid, assumed) + values (rbac.currentTriggerObjectUuid(), roleUuid, permissionUuid, true) on conflict do nothing; -- allow granting multiple times end; $$; -create or replace procedure grantPermissionToRole(permissionUuid uuid, roleDesc RbacRoleDescriptor) +create or replace procedure rbac.grantPermissionToRole(permissionUuid uuid, roleDesc rbac.RoleDescriptor) language plpgsql as $$ begin - call grantPermissionToRole(permissionUuid, findRoleId(roleDesc)); + call rbac.grantPermissionToRole(permissionUuid, rbac.findRoleId(roleDesc)); end; $$; -create or replace procedure grantRoleToRole(subRoleId uuid, superRoleId uuid, doAssume bool = true) +create or replace procedure rbac.grantRoleToRole(subRoleId uuid, superRoleId uuid, doAssume bool = true) language plpgsql as $$ begin - perform assertReferenceType('superRoleId (ascendant)', superRoleId, 'RbacRole'); - perform assertReferenceType('subRoleId (descendant)', subRoleId, 'RbacRole'); + perform rbac.assertReferenceType('superRoleId (ascendant)', superRoleId, 'rbac.role'); + perform rbac.assertReferenceType('subRoleId (descendant)', subRoleId, 'rbac.role'); - if isGranted(subRoleId, superRoleId) then - call raiseDuplicateRoleGrantException(subRoleId, superRoleId); + if rbac.isGranted(subRoleId, superRoleId) then + call rbac.raiseDuplicateRoleGrantException(subRoleId, superRoleId); end if; insert - into RbacGrants (grantedByTriggerOf, ascendantuuid, descendantUuid, assumed) - values (currentTriggerObjectUuid(), superRoleId, subRoleId, doAssume) + into rbac.grants (grantedByTriggerOf, ascendantuuid, descendantUuid, assumed) + values (rbac.currentTriggerObjectUuid(), superRoleId, subRoleId, doAssume) on conflict do nothing; -- allow granting multiple times end; $$; -create or replace procedure grantRoleToRole(subRole RbacRoleDescriptor, superRole RbacRoleDescriptor, doAssume bool = true) +create or replace procedure rbac.grantRoleToRole(subRole rbac.RoleDescriptor, superRole rbac.RoleDescriptor, doAssume bool = true) language plpgsql as $$ declare superRoleId uuid; subRoleId uuid; begin - -- TODO.refa: maybe separate method grantRoleToRoleIfNotNull(...) for NULLABLE references + -- TODO.refa: maybe separate method rbac.grantRoleToRoleIfNotNull(...) for NULLABLE references if superRole.objectUuid is null or subRole.objectuuid is null then return; end if; - superRoleId := findRoleId(superRole); - subRoleId := findRoleId(subRole); + superRoleId := rbac.findRoleId(superRole); + subRoleId := rbac.findRoleId(subRole); - perform assertReferenceType('superRoleId (ascendant)', superRoleId, 'RbacRole'); - perform assertReferenceType('subRoleId (descendant)', subRoleId, 'RbacRole'); + perform rbac.assertReferenceType('superRoleId (ascendant)', superRoleId, 'rbac.role'); + perform rbac.assertReferenceType('subRoleId (descendant)', subRoleId, 'rbac.role'); - if isGranted(subRoleId, superRoleId) then - call raiseDuplicateRoleGrantException(subRoleId, superRoleId); + if rbac.isGranted(subRoleId, superRoleId) then + call rbac.raiseDuplicateRoleGrantException(subRoleId, superRoleId); end if; insert - into RbacGrants (grantedByTriggerOf, ascendantuuid, descendantUuid, assumed) - values (currentTriggerObjectUuid(), superRoleId, subRoleId, doAssume) + into rbac.grants (grantedByTriggerOf, ascendantuuid, descendantUuid, assumed) + values (rbac.currentTriggerObjectUuid(), superRoleId, subRoleId, doAssume) on conflict do nothing; -- allow granting multiple times end; $$; -create or replace procedure revokeRoleFromRole(subRole RbacRoleDescriptor, superRole RbacRoleDescriptor) +create or replace procedure rbac.revokeRoleFromRole(subRole rbac.RoleDescriptor, superRole rbac.RoleDescriptor) language plpgsql as $$ declare superRoleId uuid; subRoleId uuid; begin - superRoleId := findRoleId(superRole); - subRoleId := findRoleId(subRole); + superRoleId := rbac.findRoleId(superRole); + subRoleId := rbac.findRoleId(subRole); - perform assertReferenceType('superRoleId (ascendant)', superRoleId, 'RbacRole'); - perform assertReferenceType('subRoleId (descendant)', subRoleId, 'RbacRole'); + perform rbac.assertReferenceType('superRoleId (ascendant)', superRoleId, 'rbac.role'); + perform rbac.assertReferenceType('subRoleId (descendant)', subRoleId, 'rbac.role'); - if (isGranted(superRoleId, subRoleId)) then - delete from RbacGrants where ascendantUuid = superRoleId and descendantUuid = subRoleId; + if (rbac.isGranted(superRoleId, subRoleId)) then + delete from rbac.grants where ascendantUuid = superRoleId and descendantUuid = subRoleId; else raise exception 'cannot revoke role % (%) from % (%) because it is not granted', subRole, subRoleId, superRole, superRoleId; end if; end; $$; -create or replace procedure revokePermissionFromRole(permissionId UUID, superRole RbacRoleDescriptor) +create or replace procedure rbac.revokePermissionFromRole(permissionId UUID, superRole rbac.RoleDescriptor) language plpgsql as $$ declare superRoleId uuid; @@ -680,18 +687,18 @@ declare objectTable text; objectUuid uuid; begin - superRoleId := findRoleId(superRole); + superRoleId := rbac.findRoleId(superRole); - perform assertReferenceType('superRoleId (ascendant)', superRoleId, 'RbacRole'); - perform assertReferenceType('permission (descendant)', permissionId, 'RbacPermission'); + perform rbac.assertReferenceType('superRoleId (ascendant)', superRoleId, 'rbac.role'); + perform rbac.assertReferenceType('permission (descendant)', permissionId, 'rbac.permission'); - if (isGranted(superRoleId, permissionId)) then - delete from RbacGrants where ascendantUuid = superRoleId and descendantUuid = permissionId; + if (rbac.isGranted(superRoleId, permissionId)) then + delete from rbac.grants where ascendantUuid = superRoleId and descendantUuid = permissionId; else select p.op, o.objectTable, o.uuid - from rbacGrants g - join rbacPermission p on p.uuid=g.descendantUuid - join rbacobject o on o.uuid=p.objectUuid + from rbac.grants g + join rbac.permission p on p.uuid=g.descendantUuid + join rbac.object o on o.uuid=p.objectUuid where g.uuid=permissionId into permissionOp, objectTable, objectUuid; @@ -701,13 +708,13 @@ begin end; $$; -- ============================================================================ ---changeset rbac-base-QUERY-ACCESSIBLE-OBJECT-UUIDS:1 runOnChange=true endDelimiter:--// +--changeset michael.hoennig:rbac-base-QUERY-ACCESSIBLE-OBJECT-UUIDS runOnChange=true endDelimiter:--// -- ---------------------------------------------------------------------------- /* */ -create or replace function queryAccessibleObjectUuidsOfSubjectIds( - requiredOp RbacOp, +create or replace function rbac.queryAccessibleObjectUuidsOfSubjectIds( + requiredOp rbac.RbacOp, forObjectTable varchar, subjectIds uuid[], maxObjects integer = 8000) @@ -720,12 +727,12 @@ begin return query WITH RECURSIVE grants AS ( SELECT descendantUuid, ascendantUuid, 1 AS level - FROM RbacGrants + FROM rbac.grants WHERE assumed AND ascendantUuid = any(subjectIds) UNION ALL SELECT g.descendantUuid, g.ascendantUuid, grants.level + 1 AS level - FROM RbacGrants g + FROM rbac.grants g INNER JOIN grants ON grants.descendantUuid = g.ascendantUuid WHERE g.assumed ), @@ -735,13 +742,13 @@ begin ) SELECT DISTINCT perm.objectUuid FROM granted - JOIN RbacPermission perm ON granted.descendantUuid = perm.uuid - JOIN RbacObject obj ON obj.uuid = perm.objectUuid + JOIN rbac.permission perm ON granted.descendantUuid = perm.uuid + JOIN rbac.object obj ON obj.uuid = perm.objectUuid WHERE (requiredOp = 'SELECT' OR perm.op = requiredOp) AND obj.objectTable = forObjectTable LIMIT maxObjects+1; - foundRows = lastRowCount(); + foundRows = base.lastRowCount(); if foundRows > maxObjects then raise exception '[400] Too many accessible objects, limit is %, found %.', maxObjects, foundRows using @@ -753,26 +760,26 @@ $$; --// -- ============================================================================ ---changeset rbac-base-QUERY-GRANTED-PERMISSIONS:1 endDelimiter:--// +--changeset michael.hoennig:rbac-base-QUERY-GRANTED-PERMISSIONS endDelimiter:--// -- ---------------------------------------------------------------------------- /* - Returns all permissions accessible to the given subject UUID (user or role). + Returns all permissions accessible to the given subject UUID (subject or role). */ -create or replace function queryPermissionsGrantedToSubjectId(subjectId uuid) - returns setof RbacPermission +create or replace function rbac.queryPermissionsGrantedToSubjectId(subjectId uuid) + returns setof rbac.permission strict language sql as $$ with recursive grants as ( select descendantUuid, ascendantUuid - from RbacGrants + from rbac.grants where ascendantUuid = subjectId union all select g.descendantUuid, g.ascendantUuid - from RbacGrants g + from rbac.grants g inner join grants on grants.descendantUuid = g.ascendantUuid ) select perm.* - from RbacPermission perm + from rbac.permission perm where perm.uuid in ( select descendantUuid from grants @@ -782,27 +789,27 @@ $$; --// -- ============================================================================ ---changeset rbac-base-QUERY-USERS-WITH-PERMISSION-FOR-OBJECT:1 endDelimiter:--// +--changeset michael.hoennig:rbac-base-QUERY-SUBJECTS-WITH-PERMISSION-FOR-OBJECT endDelimiter:--// -- ---------------------------------------------------------------------------- /* - Returns all user UUIDs which have any permission for the given object UUID. + Returns all subject UUIDs which have any permission for the given object UUID. */ -create or replace function queryAllRbacUsersWithPermissionsFor(objectId uuid) - returns setof RbacUser +create or replace function rbac.queryAllRbacSubjectsWithPermissionsFor(objectId uuid) + returns setof rbac.subject returns null on null input language sql as $$ select * - from RbacUser + from rbac.subject where uuid in ( -- @formatter:off with recursive grants as ( select descendantUuid, ascendantUuid - from RbacGrants + from rbac.grants where descendantUuid = objectId union all select "grant".descendantUuid, "grant".ascendantUuid - from RbacGrants "grant" + from rbac.grants "grant" inner join grants recur on recur.ascendantUuid = "grant".descendantUuid ) -- @formatter:on @@ -813,7 +820,7 @@ $$; -- ============================================================================ ---changeset rbac-base-PGSQL-ROLES:1 context:dev,tc endDelimiter:--// +--changeset michael.hoennig:rbac-base-PGSQL-ROLES context:dev,tc endDelimiter:--// -- ---------------------------------------------------------------------------- do $$ diff --git a/src/main/resources/db/changelog/1-rbac/1051-rbac-subject-grant.sql b/src/main/resources/db/changelog/1-rbac/1051-rbac-subject-grant.sql new file mode 100644 index 00000000..99c76ccc --- /dev/null +++ b/src/main/resources/db/changelog/1-rbac/1051-rbac-subject-grant.sql @@ -0,0 +1,125 @@ +--liquibase formatted sql + +-- ============================================================================ +--changeset michael.hoennig:rbac-user-grant-GRANT-ROLE-TO-USER endDelimiter:--// +-- ---------------------------------------------------------------------------- + +create or replace function rbac.assumedRoleUuid() + returns uuid + stable -- leakproof + language plpgsql as $$ +declare + currentSubjectOrAssumedRolesUuids uuid[]; +begin + -- exactly one role must be assumed, not none not more than one + if cardinality(base.assumedRoles()) <> 1 then + raise exception '[400] Granting roles to user is only possible if exactly one role is assumed, given: %', base.assumedRoles(); + end if; + + currentSubjectOrAssumedRolesUuids := rbac.currentSubjectOrAssumedRolesUuids(); + return currentSubjectOrAssumedRolesUuids[1]; +end; $$; + +create or replace procedure rbac.grantRoleToSubjectUnchecked(grantedByRoleUuid uuid, grantedRoleUuid uuid, subjectUuid uuid, doAssume boolean = true) + language plpgsql as $$ +begin + perform rbac.assertReferenceType('grantingRoleUuid', grantedByRoleUuid, 'rbac.role'); + perform rbac.assertReferenceType('roleId (descendant)', grantedRoleUuid, 'rbac.role'); + perform rbac.assertReferenceType('subjectUuid (ascendant)', subjectUuid, 'rbac.subject'); + + insert + into rbac.grants (grantedByRoleUuid, ascendantUuid, descendantUuid, assumed) + values (grantedByRoleUuid, subjectUuid, grantedRoleUuid, doAssume) + -- TODO: check if grantedByRoleUuid+doAssume are the same, otherwise raise exception? + on conflict do nothing; -- allow granting multiple times +end; $$; + +create or replace procedure rbac.grantRoleToSubject(grantedByRoleUuid uuid, grantedRoleUuid uuid, subjectUuid uuid, doAssume boolean = true) + language plpgsql as $$ +declare + grantedByRoleIdName text; + grantedRoleIdName text; +begin + perform rbac.assertReferenceType('grantingRoleUuid', grantedByRoleUuid, 'rbac.role'); + perform rbac.assertReferenceType('grantedRoleUuid (descendant)', grantedRoleUuid, 'rbac.role'); + perform rbac.assertReferenceType('subjectUuid (ascendant)', subjectUuid, 'rbac.subject'); + + assert grantedByRoleUuid is not null, 'grantedByRoleUuid must not be null'; + assert grantedRoleUuid is not null, 'grantedRoleUuid must not be null'; + assert subjectUuid is not null, 'subjectUuid must not be null'; + + if NOT rbac.isGranted(rbac.currentSubjectOrAssumedRolesUuids(), grantedByRoleUuid) then + select roleIdName from rbac.role_ev where uuid=grantedByRoleUuid into grantedByRoleIdName; + raise exception '[403] Access to granted-by-role % (%) forbidden for % (%)', + grantedByRoleIdName, grantedByRoleUuid, base.currentSubjects(), rbac.currentSubjectOrAssumedRolesUuids(); + end if; + if NOT rbac.isGranted(grantedByRoleUuid, grantedRoleUuid) then + select roleIdName from rbac.role_ev where uuid=grantedByRoleUuid into grantedByRoleIdName; + select roleIdName from rbac.role_ev where uuid=grantedRoleUuid into grantedRoleIdName; + raise exception '[403] Access to granted role % (%) forbidden for % (%)', + grantedRoleIdName, grantedRoleUuid, grantedByRoleIdName, grantedByRoleUuid; + end if; + + insert + into rbac.grants (grantedByRoleUuid, ascendantUuid, descendantUuid, assumed) + values (grantedByRoleUuid, subjectUuid, grantedRoleUuid, doAssume); + -- TODO.impl: What should happen on multiple grants? What if options (doAssume) are not the same? + -- Most powerful or latest grant wins? What about managed? + -- on conflict do nothing; -- allow granting multiple times +end; $$; +--// + + +-- ============================================================================ +--changeset michael.hoennig:rbac-user-grant-REVOKE-ROLE-FROM-USER endDelimiter:--// +-- ---------------------------------------------------------------------------- + +create or replace procedure rbac.checkRevokeRoleFromSubjectPreconditions(grantedByRoleUuid uuid, grantedRoleUuid uuid, subjectUuid uuid) + language plpgsql as $$ +begin + perform rbac.assertReferenceType('grantedByRoleUuid', grantedByRoleUuid, 'rbac.role'); + perform rbac.assertReferenceType('grantedRoleUuid (descendant)', grantedRoleUuid, 'rbac.role'); + perform rbac.assertReferenceType('subjectUuid (ascendant)', subjectUuid, 'rbac.subject'); + + if NOT rbac.isGranted(rbac.currentSubjectOrAssumedRolesUuids(), grantedByRoleUuid) then + raise exception '[403] Revoking role created by % is forbidden for %.', grantedByRoleUuid, base.currentSubjects(); + end if; + + if NOT rbac.isGranted(grantedByRoleUuid, grantedRoleUuid) then + raise exception '[403] Revoking role % is forbidden for %.', grantedRoleUuid, base.currentSubjects(); + end if; + + --raise exception 'rbac.isGranted(%, %)', rbac.currentSubjectOrAssumedRolesUuids(), grantedByRoleUuid; + if NOT rbac.isGranted(rbac.currentSubjectOrAssumedRolesUuids(), grantedByRoleUuid) then + raise exception '[403] Revoking role granted by % is forbidden for %.', grantedByRoleUuid, base.currentSubjects(); + end if; + + if NOT rbac.isGranted(subjectUuid, grantedRoleUuid) then + raise exception '[404] No such grant found granted by % for subject % to role %.', grantedByRoleUuid, subjectUuid, grantedRoleUuid; + end if; +end; $$; + +create or replace procedure rbac.revokeRoleFromSubject(grantedByRoleUuid uuid, grantedRoleUuid uuid, subjectUuid uuid) + language plpgsql as $$ +begin + call rbac.checkRevokeRoleFromSubjectPreconditions(grantedByRoleUuid, grantedRoleUuid, subjectUuid); + + raise INFO 'delete from rbac.grants where ascendantUuid = % and descendantUuid = %', subjectUuid, grantedRoleUuid; + delete from rbac.grants as g + where g.ascendantUuid = subjectUuid and g.descendantUuid = grantedRoleUuid + and g.grantedByRoleUuid = revokeRoleFromSubject.grantedByRoleUuid; +end; $$; +--// + +-- ============================================================================ +--changeset michael.hoennig:rbac-user-grant-REVOKE-PERMISSION-FROM-ROLE endDelimiter:--// +-- ---------------------------------------------------------------------------- + +create or replace procedure rbac.revokePermissionFromRole(permissionUuid uuid, superRoleUuid uuid) + language plpgsql as $$ +begin + raise INFO 'delete from rbac.grants where ascendantUuid = % and descendantUuid = %', superRoleUuid, permissionUuid; + delete from rbac.grants as g + where g.ascendantUuid = superRoleUuid and g.descendantUuid = permissionUuid; +end; $$; +--// diff --git a/src/main/resources/db/changelog/1-rbac/1051-rbac-user-grant.sql b/src/main/resources/db/changelog/1-rbac/1051-rbac-user-grant.sql deleted file mode 100644 index fc74a6de..00000000 --- a/src/main/resources/db/changelog/1-rbac/1051-rbac-user-grant.sql +++ /dev/null @@ -1,125 +0,0 @@ ---liquibase formatted sql - --- ============================================================================ ---changeset rbac-user-grant-GRANT-ROLE-TO-USER:1 endDelimiter:--// --- ---------------------------------------------------------------------------- - -create or replace function assumedRoleUuid() - returns uuid - stable -- leakproof - language plpgsql as $$ -declare - currentSubjectsUuids uuid[]; -begin - -- exactly one role must be assumed, not none not more than one - if cardinality(assumedRoles()) <> 1 then - raise exception '[400] Granting roles to user is only possible if exactly one role is assumed, given: %', assumedRoles(); - end if; - - currentSubjectsUuids := currentSubjectsUuids(); - return currentSubjectsUuids[1]; -end; $$; - -create or replace procedure grantRoleToUserUnchecked(grantedByRoleUuid uuid, grantedRoleUuid uuid, userUuid uuid, doAssume boolean = true) - language plpgsql as $$ -begin - perform assertReferenceType('grantingRoleUuid', grantedByRoleUuid, 'RbacRole'); - perform assertReferenceType('roleId (descendant)', grantedRoleUuid, 'RbacRole'); - perform assertReferenceType('userId (ascendant)', userUuid, 'RbacUser'); - - insert - into RbacGrants (grantedByRoleUuid, ascendantUuid, descendantUuid, assumed) - values (grantedByRoleUuid, userUuid, grantedRoleUuid, doAssume) - -- TODO: check if grantedByRoleUuid+doAssume are the same, otherwise raise exception? - on conflict do nothing; -- allow granting multiple times -end; $$; - -create or replace procedure grantRoleToUser(grantedByRoleUuid uuid, grantedRoleUuid uuid, userUuid uuid, doAssume boolean = true) - language plpgsql as $$ -declare - grantedByRoleIdName text; - grantedRoleIdName text; -begin - perform assertReferenceType('grantingRoleUuid', grantedByRoleUuid, 'RbacRole'); - perform assertReferenceType('grantedRoleUuid (descendant)', grantedRoleUuid, 'RbacRole'); - perform assertReferenceType('userUuid (ascendant)', userUuid, 'RbacUser'); - - assert grantedByRoleUuid is not null, 'grantedByRoleUuid must not be null'; - assert grantedRoleUuid is not null, 'grantedRoleUuid must not be null'; - assert userUuid is not null, 'userUuid must not be null'; - - if NOT isGranted(currentSubjectsUuids(), grantedByRoleUuid) then - select roleIdName from rbacRole_ev where uuid=grantedByRoleUuid into grantedByRoleIdName; - raise exception '[403] Access to granted-by-role % (%) forbidden for % (%)', - grantedByRoleIdName, grantedByRoleUuid, currentSubjects(), currentSubjectsUuids(); - end if; - if NOT isGranted(grantedByRoleUuid, grantedRoleUuid) then - select roleIdName from rbacRole_ev where uuid=grantedByRoleUuid into grantedByRoleIdName; - select roleIdName from rbacRole_ev where uuid=grantedRoleUuid into grantedRoleIdName; - raise exception '[403] Access to granted role % (%) forbidden for % (%)', - grantedRoleIdName, grantedRoleUuid, grantedByRoleIdName, grantedByRoleUuid; - end if; - - insert - into RbacGrants (grantedByRoleUuid, ascendantUuid, descendantUuid, assumed) - values (grantedByRoleUuid, userUuid, grantedRoleUuid, doAssume); - -- TODO.impl: What should happen on mupltiple grants? What if options (doAssume) are not the same? - -- Most powerful or latest grant wins? What about managed? - -- on conflict do nothing; -- allow granting multiple times -end; $$; ---// - - --- ============================================================================ ---changeset rbac-user-grant-REVOKE-ROLE-FROM-USER:1 endDelimiter:--// --- ---------------------------------------------------------------------------- - -create or replace procedure checkRevokeRoleFromUserPreconditions(grantedByRoleUuid uuid, grantedRoleUuid uuid, userUuid uuid) - language plpgsql as $$ -begin - perform assertReferenceType('grantedByRoleUuid', grantedByRoleUuid, 'RbacRole'); - perform assertReferenceType('grantedRoleUuid (descendant)', grantedRoleUuid, 'RbacRole'); - perform assertReferenceType('userUuid (ascendant)', userUuid, 'RbacUser'); - - if NOT isGranted(currentSubjectsUuids(), grantedByRoleUuid) then - raise exception '[403] Revoking role created by % is forbidden for %.', grantedByRoleUuid, currentSubjects(); - end if; - - if NOT isGranted(grantedByRoleUuid, grantedRoleUuid) then - raise exception '[403] Revoking role % is forbidden for %.', grantedRoleUuid, currentSubjects(); - end if; - - --raise exception 'isGranted(%, %)', currentSubjectsUuids(), grantedByRoleUuid; - if NOT isGranted(currentSubjectsUuids(), grantedByRoleUuid) then - raise exception '[403] Revoking role granted by % is forbidden for %.', grantedByRoleUuid, currentSubjects(); - end if; - - if NOT isGranted(userUuid, grantedRoleUuid) then - raise exception '[404] No such grant found granted by % for user % to role %.', grantedByRoleUuid, userUuid, grantedRoleUuid; - end if; -end; $$; - -create or replace procedure revokeRoleFromUser(grantedByRoleUuid uuid, grantedRoleUuid uuid, userUuid uuid) - language plpgsql as $$ -begin - call checkRevokeRoleFromUserPreconditions(grantedByRoleUuid, grantedRoleUuid, userUuid); - - raise INFO 'delete from RbacGrants where ascendantUuid = % and descendantUuid = %', userUuid, grantedRoleUuid; - delete from RbacGrants as g - where g.ascendantUuid = userUuid and g.descendantUuid = grantedRoleUuid - and g.grantedByRoleUuid = revokeRoleFromUser.grantedByRoleUuid; -end; $$; ---// - --- ============================================================================ ---changeset rbac-user-grant-REVOKE-PERMISSION-FROM-ROLE:1 endDelimiter:--// --- ---------------------------------------------------------------------------- - -create or replace procedure revokePermissionFromRole(permissionUuid uuid, superRoleUuid uuid) - language plpgsql as $$ -begin - raise INFO 'delete from RbacGrants where ascendantUuid = % and descendantUuid = %', superRoleUuid, permissionUuid; - delete from RbacGrants as g - where g.ascendantUuid = superRoleUuid and g.descendantUuid = permissionUuid; -end; $$; ---// diff --git a/src/main/resources/db/changelog/1-rbac/1054-rbac-context.sql b/src/main/resources/db/changelog/1-rbac/1054-rbac-context.sql index ab3a9bd5..afede6ac 100644 --- a/src/main/resources/db/changelog/1-rbac/1054-rbac-context.sql +++ b/src/main/resources/db/changelog/1-rbac/1054-rbac-context.sql @@ -2,28 +2,28 @@ -- ============================================================================ ---changeset rbac-context-DETERMINE:1 endDelimiter:--// +--changeset michael.hoennig:rbac-context-DETERMINE endDelimiter:--// -- ---------------------------------------------------------------------------- -create or replace function determineCurrentUserUuid(currentUser varchar) +create or replace function rbac.determineCurrentSubjectUuid(currentSubject varchar) returns uuid stable -- leakproof language plpgsql as $$ declare - currentUserUuid uuid; + currentSubjectUuid uuid; begin - if currentUser = '' then + if currentSubject = '' then return null; end if; - select uuid from RbacUser where name = currentUser into currentUserUuid; - if currentUserUuid is null then - raise exception '[401] user % given in `defineContext(...)` does not exist', currentUser; + select uuid from rbac.subject where name = currentSubject into currentSubjectUuid; + if currentSubjectUuid is null then + raise exception '[401] subject % given in `base.defineContext(...)` does not exist', currentSubject; end if; - return currentUserUuid; + return currentSubjectUuid; end; $$; -create or replace function determineCurrentSubjectsUuids(currentUserUuid uuid, assumedRoles varchar) +create or replace function rbac.determinecurrentsubjectorassumedrolesuuids(currentSubjectOrAssumedRolesUuids uuid, assumedRoles varchar) returns uuid[] stable -- leakproof language plpgsql as $$ @@ -33,11 +33,11 @@ declare objectTableToAssume varchar(63); objectNameToAssume varchar(63); objectUuidToAssume uuid; - roleTypeToAssume RbacRoleType; + roleTypeToAssume rbac.RoleType; roleIdsToAssume uuid[]; roleUuidToAssume uuid; begin - if currentUserUuid is null then + if currentSubjectOrAssumedRolesUuids is null then if length(coalesce(assumedRoles, '')) > 0 then raise exception '[403] undefined has no permission to assume role %', assumedRoles; else @@ -45,7 +45,7 @@ begin end if; end if; if length(coalesce(assumedRoles, '')) = 0 then - return array [currentUserUuid]; + return array [currentSubjectOrAssumedRolesUuids]; end if; foreach roleName in array string_to_array(assumedRoles, ';') @@ -55,21 +55,21 @@ begin objectNameToAssume = split_part(roleNameParts, '#', 2); roleTypeToAssume = split_part(roleNameParts, '#', 3); - objectUuidToAssume = findObjectUuidByIdName(objectTableToAssume, objectNameToAssume); + objectUuidToAssume = base.findObjectUuidByIdName(objectTableToAssume, objectNameToAssume); if objectUuidToAssume is null then - raise exception '[401] object % cannot be found in table %', objectNameToAssume, objectTableToAssume; + raise exception '[401] object % cannot be found in table % (from roleNameParts=%)', objectNameToAssume, objectTableToAssume, roleNameParts; end if; select uuid - from RbacRole r + from rbac.role r where r.objectUuid = objectUuidToAssume and r.roleType = roleTypeToAssume into roleUuidToAssume; if roleUuidToAssume is null then - raise exception '[403] role % does not exist or is not accessible for user %', roleName, currentUser(); + raise exception '[403] role % does not exist or is not accessible for subject %', roleName, base.currentSubject(); end if; - if not isGranted(currentUserUuid, roleUuidToAssume) then - raise exception '[403] user % has no permission to assume role %', currentUser(), roleName; + if not rbac.isGranted(currentSubjectOrAssumedRolesUuids, roleUuidToAssume) then + raise exception '[403] subject % has no permission to assume role %', base.currentSubject(), roleName; end if; roleIdsToAssume := roleIdsToAssume || roleUuidToAssume; end loop; @@ -78,102 +78,102 @@ begin end; $$; -- ============================================================================ ---changeset rbac-context-CONTEXT-DEFINED:1 endDelimiter:--// +--changeset michael.hoennig:rbac-context-CONTEXT-DEFINED endDelimiter:--// -- ---------------------------------------------------------------------------- /* Callback which is called after the context has been (re-) defined. This function will be overwritten by later changesets. */ -create or replace procedure contextDefined( +create or replace procedure base.contextDefined( currentTask varchar(127), currentRequest text, - currentUser varchar(63), + currentSubject varchar(63), assumedRoles varchar(1023) ) language plpgsql as $$ declare - currentUserUuid uuid; + currentSubjectUuid uuid; begin execute format('set local hsadminng.currentTask to %L', currentTask); execute format('set local hsadminng.currentRequest to %L', currentRequest); - execute format('set local hsadminng.currentUser to %L', currentUser); - select determineCurrentUserUuid(currentUser) into currentUserUuid; - execute format('set local hsadminng.currentUserUuid to %L', coalesce(currentUserUuid::text, '')); + execute format('set local hsadminng.currentSubject to %L', currentSubject); + select rbac.determineCurrentSubjectUuid(currentSubject) into currentSubjectUuid; + execute format('set local hsadminng.currentSubjectUuid to %L', coalesce(currentSubjectUuid::text, '')); execute format('set local hsadminng.assumedRoles to %L', assumedRoles); - execute format('set local hsadminng.currentSubjectsUuids to %L', - (select array_to_string(determinecurrentSubjectsUuids(currentUserUuid, assumedRoles), ';'))); + execute format('set local hsadminng.currentSubjectOrAssumedRolesUuids to %L', + (select array_to_string(rbac.determinecurrentsubjectorassumedrolesuuids(currentSubjectUuid, assumedRoles), ';'))); - raise notice 'Context defined as: %, %, %, [%]', currentTask, currentRequest, currentUser, assumedRoles; + raise notice 'Context defined as: %, %, %, [%]', currentTask, currentRequest, currentSubject, assumedRoles; end; $$; -- ============================================================================ ---changeset rbac-context-CURRENT-USER-ID:1 endDelimiter:--// +--changeset michael.hoennig:rbac-context-current-subject-ID endDelimiter:--// -- ---------------------------------------------------------------------------- /* - Returns the uuid of the current user as set via `defineContext(...)`. + Returns the uuid of the current subject as set via `base.defineContext(...)`. */ -create or replace function currentUserUuid() +create or replace function rbac.currentSubjectUuid() returns uuid stable -- leakproof language plpgsql as $$ declare - currentUserUuid text; - currentUserName text; + currentSubjectUuid text; + currentSubjectName text; begin begin - currentUserUuid := current_setting('hsadminng.currentUserUuid'); + currentSubjectUuid := current_setting('hsadminng.currentSubjectUuid'); exception when others then - currentUserUuid := null; + currentSubjectUuid := null; end; - if (currentUserUuid is null or currentUserUuid = '') then - currentUserName := currentUser(); - if (length(currentUserName) > 0) then - raise exception '[401] currentUserUuid cannot be determined, unknown user name "%"', currentUserName; + if (currentSubjectUuid is null or currentSubjectUuid = '') then + currentSubjectName := base.currentSubject(); + if (length(currentSubjectName) > 0) then + raise exception '[401] currentSubjectUuid cannot be determined, unknown subject name "%"', currentSubjectName; else - raise exception '[401] currentUserUuid cannot be determined, please call `defineContext(...)` first;"'; + raise exception '[401] currentSubjectUuid cannot be determined, please call `base.defineContext(...)` first;"'; end if; end if; - return currentUserUuid::uuid; + return currentSubjectUuid::uuid; end; $$; --// -- ============================================================================ ---changeset rbac-context-CURRENT-SUBJECT-UUIDS:1 endDelimiter:--// +--changeset michael.hoennig:rbac-context-CURRENT-SUBJECT-UUIDS endDelimiter:--// -- ---------------------------------------------------------------------------- /* - Returns the uuid of the current user as set via `defineContext(...)`, - or, if any, the uuids of all assumed roles as set via `defineContext(...)` + Returns the uuid of the current subject as set via `base.defineContext(...)`, + or, if any, the uuids of all assumed roles as set via `base.defineContext(...)` or empty array, if context is not defined. */ -create or replace function currentSubjectsUuids() +create or replace function rbac.currentSubjectOrAssumedRolesUuids() returns uuid[] stable -- leakproof language plpgsql as $$ declare - currentSubjectsUuids text; - currentUserName text; + currentSubjectOrAssumedRolesUuids text; + currentSubjectName text; begin begin - currentSubjectsUuids := current_setting('hsadminng.currentSubjectsUuids'); + currentSubjectOrAssumedRolesUuids := current_setting('hsadminng.currentSubjectOrAssumedRolesUuids'); exception when others then - currentSubjectsUuids := null; + currentSubjectOrAssumedRolesUuids := null; end; - if (currentSubjectsUuids is null or length(currentSubjectsUuids) = 0 ) then - currentUserName := currentUser(); - if (length(currentUserName) > 0) then - raise exception '[401] currentSubjectsUuids (%) cannot be determined, unknown user name "%"', currentSubjectsUuids, currentUserName; + if (currentSubjectOrAssumedRolesUuids is null or length(currentSubjectOrAssumedRolesUuids) = 0 ) then + currentSubjectName := base.currentSubject(); + if (length(currentSubjectName) > 0) then + raise exception '[401] currentSubjectOrAssumedRolesUuids (%) cannot be determined, unknown subject name "%"', currentSubjectOrAssumedRolesUuids, currentSubjectName; else - raise exception '[401] currentSubjectsUuids cannot be determined, please call `defineContext(...)` with a valid user;"'; + raise exception '[401] currentSubjectOrAssumedRolesUuids cannot be determined, please call `base.defineContext(...)` with a valid subject;"'; end if; end if; - return string_to_array(currentSubjectsUuids, ';'); + return string_to_array(currentSubjectOrAssumedRolesUuids, ';'); end; $$; --// diff --git a/src/main/resources/db/changelog/1-rbac/1055-rbac-views.sql b/src/main/resources/db/changelog/1-rbac/1055-rbac-views.sql index a8570f6c..e1ea0c1e 100644 --- a/src/main/resources/db/changelog/1-rbac/1055-rbac-views.sql +++ b/src/main/resources/db/changelog/1-rbac/1055-rbac-views.sql @@ -1,63 +1,63 @@ --liquibase formatted sql -- ============================================================================ ---changeset rbac-views-ROLE-ENHANCED-VIEW:1 endDelimiter:--// +--changeset michael.hoennig:rbac-views-ROLE-ENHANCED-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- /* Creates a view to the role table with additional columns for easier human readability. */ -drop view if exists rbacrole_ev; -create or replace view rbacrole_ev as +drop view if exists rbac.role_ev; +create or replace view rbac.role_ev as select (objectTable || '#' || objectIdName || ':' || roleType) as roleIdName, * -- @formatter:off from ( select r.*, - o.objectTable, findIdNameByObjectUuid(o.objectTable, o.uuid) as objectIdName - from rbacrole as r - join rbacobject as o on o.uuid = r.objectuuid + o.objectTable, base.findIdNameByObjectUuid(o.objectTable, o.uuid) as objectIdName + from rbac.role as r + join rbac.object as o on o.uuid = r.objectuuid ) as unordered -- @formatter:on order by roleIdName; --// -- ============================================================================ ---changeset rbac-views-ROLE-RESTRICTED-VIEW:1 endDelimiter:--// +--changeset michael.hoennig:rbac-views-ROLE-RESTRICTED-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- /* Creates a view to the role table with row-level limitation based on the grants of the current user or assumed roles. */ -drop view if exists rbacrole_rv; -create or replace view rbacrole_rv as +drop view if exists rbac.role_rv; +create or replace view rbac.role_rv as select * -- @formatter:off from ( select r.*, o.objectTable, - findIdNameByObjectUuid(o.objectTable, o.uuid) as objectIdName - from rbacrole as r - join rbacobject as o on o.uuid = r.objectuuid - where isGranted(currentSubjectsUuids(), r.uuid) + base.findIdNameByObjectUuid(o.objectTable, o.uuid) as objectIdName + from rbac.role as r + join rbac.object as o on o.uuid = r.objectuuid + where rbac.isGranted(rbac.currentSubjectOrAssumedRolesUuids(), r.uuid) ) as unordered -- @formatter:on order by objectTable || '#' || objectIdName || ':' || roleType; -grant all privileges on rbacrole_rv to ${HSADMINNG_POSTGRES_RESTRICTED_USERNAME}; +grant all privileges on rbac.role_rv to ${HSADMINNG_POSTGRES_RESTRICTED_USERNAME}; --// -- ============================================================================ ---changeset rbac-views-GRANT-ENHANCED-VIEW:1 endDelimiter:--// +--changeset michael.hoennig:rbac-views-GRANT-ENHANCED-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- /* Creates a view to the grants table with additional columns for easier human readability. */ -drop view if exists rbacgrants_ev; -create or replace view rbacgrants_ev as +drop view if exists rbac.grants_ev; +create or replace view rbac.grants_ev as -- @formatter:off select x.grantUuid as uuid, x.grantedByTriggerOf as grantedByTriggerOf, - go.objectTable || '#' || findIdNameByObjectUuid(go.objectTable, go.uuid) || ':' || r.roletype as grantedByRoleIdName, + go.objectTable || '#' || base.findIdNameByObjectUuid(go.objectTable, go.uuid) || ':' || r.roletype as grantedByRoleIdName, x.ascendingIdName as ascendantIdName, x.descendingIdName as descendantIdName, x.grantedByRoleUuid, @@ -72,33 +72,33 @@ create or replace view rbacgrants_ev as coalesce( 'user:' || au.name, - 'role:' || aro.objectTable || '#' || findIdNameByObjectUuid(aro.objectTable, aro.uuid) || ':' || ar.roletype + 'role:' || aro.objectTable || '#' || base.findIdNameByObjectUuid(aro.objectTable, aro.uuid) || ':' || ar.roletype ) as ascendingIdName, aro.objectTable, aro.uuid, ( case when dro is not null - then ('role:' || dro.objectTable || '#' || findIdNameByObjectUuid(dro.objectTable, dro.uuid) || ':' || dr.roletype) + then ('role:' || dro.objectTable || '#' || base.findIdNameByObjectUuid(dro.objectTable, dro.uuid) || ':' || dr.roletype) when dp.op = 'INSERT' - then 'perm:' || dpo.objecttable || '#' || findIdNameByObjectUuid(dpo.objectTable, dpo.uuid) || ':' || dp.op || '>' || dp.opTableName - else 'perm:' || dpo.objecttable || '#' || findIdNameByObjectUuid(dpo.objectTable, dpo.uuid) || ':' || dp.op + then 'perm:' || dpo.objecttable || '#' || base.findIdNameByObjectUuid(dpo.objectTable, dpo.uuid) || ':' || dp.op || '>' || dp.opTableName + else 'perm:' || dpo.objecttable || '#' || base.findIdNameByObjectUuid(dpo.objectTable, dpo.uuid) || ':' || dp.op end ) as descendingIdName, dro.objectTable, dro.uuid, dp.op, dp.optablename - from rbacgrants as g + from rbac.grants as g - left outer join rbacrole as ar on ar.uuid = g.ascendantUuid - left outer join rbacobject as aro on aro.uuid = ar.objectuuid - left outer join rbacuser as au on au.uuid = g.ascendantUuid + left outer join rbac.role as ar on ar.uuid = g.ascendantUuid + left outer join rbac.object as aro on aro.uuid = ar.objectuuid + left outer join rbac.subject as au on au.uuid = g.ascendantUuid - left outer join rbacrole as dr on dr.uuid = g.descendantUuid - left outer join rbacobject as dro on dro.uuid = dr.objectuuid - left outer join rbacpermission dp on dp.uuid = g.descendantUuid - left outer join rbacobject as dpo on dpo.uuid = dp.objectUuid + left outer join rbac.role as dr on dr.uuid = g.descendantUuid + left outer join rbac.object as dro on dro.uuid = dr.objectuuid + left outer join rbac.permission dp on dp.uuid = g.descendantUuid + left outer join rbac.object as dpo on dpo.uuid = dp.objectUuid ) as x - left outer join rbacrole as r on r.uuid = grantedByRoleUuid - left outer join rbacuser u on u.uuid = x.ascendantuuid - left outer join rbacobject go on go.uuid = r.objectuuid + left outer join rbac.role as r on r.uuid = grantedByRoleUuid + left outer join rbac.subject u on u.uuid = x.ascendantuuid + left outer join rbac.object go on go.uuid = r.objectuuid order by x.ascendingIdName, x.descendingIdName; -- @formatter:on @@ -106,116 +106,115 @@ create or replace view rbacgrants_ev as -- ============================================================================ ---changeset rbac-views-GRANT-RESTRICTED-VIEW:1 endDelimiter:--// +--changeset michael.hoennig:rbac-views-GRANT-RESTRICTED-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- /* Creates a view to the grants table with row-level limitation based on the direct grants of the current user. */ -drop view if exists rbacgrants_rv; -create or replace view rbacgrants_rv as - -- @formatter:off -select o.objectTable || '#' || findIdNameByObjectUuid(o.objectTable, o.uuid) || ':' || r.roletype as grantedByRoleIdName, +create or replace view rbac.grants_rv as +-- @formatter:off +select o.objectTable || '#' || base.findIdNameByObjectUuid(o.objectTable, o.uuid) || ':' || r.roletype as grantedByRoleIdName, g.objectTable || '#' || g.objectIdName || ':' || g.roletype as grantedRoleIdName, g.userName, g.assumed, - g.grantedByRoleUuid, g.descendantUuid as grantedRoleUuid, g.ascendantUuid as userUuid, + g.grantedByRoleUuid, g.descendantUuid as grantedRoleUuid, g.ascendantUuid as subjectUuid, g.objectTable, g.objectUuid, g.objectIdName, g.roleType as grantedRoleType from ( select g.grantedbyroleuuid, g.ascendantuuid, g.descendantuuid, g.assumed, u.name as userName, o.objecttable, r.objectuuid, r.roletype, - findIdNameByObjectUuid(o.objectTable, o.uuid) as objectIdName - from rbacgrants as g - join rbacrole as r on r.uuid = g.descendantUuid - join rbacobject o on o.uuid = r.objectuuid - left outer join rbacuser u on u.uuid = g.ascendantuuid - where isGranted(currentSubjectsUuids(), r.uuid) + base.findIdNameByObjectUuid(o.objectTable, o.uuid) as objectIdName + from rbac.grants as g + join rbac.role as r on r.uuid = g.descendantUuid + join rbac.object o on o.uuid = r.objectuuid + left outer join rbac.subject u on u.uuid = g.ascendantuuid + where rbac.isGranted(rbac.currentSubjectOrAssumedRolesUuids(), r.uuid) ) as g - join RbacRole as r on r.uuid = grantedByRoleUuid - join RbacObject as o on o.uuid = r.objectUuid + join rbac.role as r on r.uuid = grantedByRoleUuid + join rbac.object as o on o.uuid = r.objectUuid order by grantedRoleIdName; -- @formatter:on -grant all privileges on rbacrole_rv to ${HSADMINNG_POSTGRES_RESTRICTED_USERNAME}; +grant all privileges on rbac.role_rv to ${HSADMINNG_POSTGRES_RESTRICTED_USERNAME}; --// -- ============================================================================ ---changeset rbac-views-GRANTS-RV-INSERT-TRIGGER:1 endDelimiter:--// +--changeset michael.hoennig:rbac-views-GRANTS-RV-INSERT-TRIGGER endDelimiter:--// -- ---------------------------------------------------------------------------- /** - Instead of insert trigger function for RbacGrants_RV. + Instead of insert trigger function for rbac.grants_rv. */ -create or replace function insertRbacGrant() +create or replace function rbac.insert_grant_tf() returns trigger language plpgsql as $$ declare - newGrant RbacGrants_RV; + newGrant rbac.grants_rv; begin - call grantRoleToUser(assumedRoleUuid(), new.grantedRoleUuid, new.userUuid, new.assumed); + call rbac.grantRoleToSubject(rbac.assumedRoleUuid(), new.grantedRoleUuid, new.subjectUuid, new.assumed); select grv.* - from RbacGrants_RV grv - where grv.userUuid=new.userUuid and grv.grantedRoleUuid=new.grantedRoleUuid + from rbac.grants_rv grv + where grv.subjectUuid=new.subjectUuid and grv.grantedRoleUuid=new.grantedRoleUuid into newGrant; return newGrant; end; $$; /* - Creates an instead of insert trigger for the RbacGrants_rv view. + Creates an instead of insert trigger for the rbac.grants_rv view. */ -create trigger insertRbacGrant_Trigger +create trigger insert_grant_tg instead of insert - on RbacGrants_rv + on rbac.grants_rv for each row -execute function insertRbacGrant(); +execute function rbac.insert_grant_tf(); --/ -- ============================================================================ ---changeset rbac-views-GRANTS-RV-DELETE-TRIGGER:1 endDelimiter:--// +--changeset michael.hoennig:rbac-views-GRANTS-RV-DELETE-TRIGGER endDelimiter:--// -- ---------------------------------------------------------------------------- /** - Instead of delete trigger function for RbacGrants_RV. + Instead of delete trigger function for rbac.grants_rv. - Checks if the current subject (user / assumed role) has the permission to revoke the grant. + Checks if the current subject or assumed role have the permission to revoke the grant. */ -create or replace function deleteRbacGrant() +create or replace function rbac.delete_grant_tf() returns trigger language plpgsql as $$ begin - call revokeRoleFromUser(old.grantedByRoleUuid, old.grantedRoleUuid, old.userUuid); + call rbac.revokeRoleFromSubject(old.grantedByRoleUuid, old.grantedRoleUuid, old.subjectUuid); return old; end; $$; /* - Creates an instead of delete trigger for the RbacGrants_rv view. + Creates an instead of delete trigger for the rbac.grants_rv view. */ -create trigger deleteRbacGrant_Trigger +create trigger delete_grant_tg instead of delete - on RbacGrants_rv + on rbac.grants_rv for each row -execute function deleteRbacGrant(); +execute function rbac.delete_grant_tf(); --/ -- ============================================================================ ---changeset rbac-views-USER-ENHANCED-VIEW:1 endDelimiter:--// +--changeset michael.hoennig:rbac-views-USER-ENHANCED-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- /* Creates a view to the users table with additional columns for easier human readability. */ -drop view if exists RbacUser_ev; -create or replace view RbacUser_ev as +drop view if exists rbac.subject_ev; +create or replace view rbac.subject_ev as select distinct * -- @formatter:off from ( - select usersInRolesOfCurrentUser.* - from RbacUser as usersInRolesOfCurrentUser - join RbacGrants as g on g.ascendantuuid = usersInRolesOfCurrentUser.uuid - join rbacrole_ev as r on r.uuid = g.descendantuuid + select usersInRolesOfcurrentSubject.* + from rbac.subject as usersInRolesOfcurrentSubject + join rbac.grants as g on g.ascendantuuid = usersInRolesOfcurrentSubject.uuid + join rbac.role_ev as r on r.uuid = g.descendantuuid union select users.* - from RbacUser as users + from rbac.subject as users ) as unordered -- @formatter:on order by unordered.name; @@ -223,53 +222,53 @@ select distinct * -- ============================================================================ ---changeset rbac-views-USER-RESTRICTED-VIEW:1 endDelimiter:--// +--changeset michael.hoennig:rbac-views-USER-RESTRICTED-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- /* Creates a view to the users table with row-level limitation based on the grants of the current user or assumed roles. */ -drop view if exists RbacUser_rv; -create or replace view RbacUser_rv as +drop view if exists rbac.subject_rv; +create or replace view rbac.subject_rv as select distinct * -- @formatter:off from ( - select usersInRolesOfCurrentUser.* - from RbacUser as usersInRolesOfCurrentUser - join RbacGrants as g on g.ascendantuuid = usersInRolesOfCurrentUser.uuid - join rbacrole_rv as r on r.uuid = g.descendantuuid + select usersInRolesOfcurrentSubject.* + from rbac.subject as usersInRolesOfcurrentSubject + join rbac.grants as g on g.ascendantuuid = usersInRolesOfcurrentSubject.uuid + join rbac.role_rv as r on r.uuid = g.descendantuuid union select users.* - from RbacUser as users - where cardinality(assumedRoles()) = 0 and - (currentUserUuid() = users.uuid or hasGlobalRoleGranted(currentUserUuid())) + from rbac.subject as users + where cardinality(base.assumedRoles()) = 0 and + (rbac.currentSubjectUuid() = users.uuid or rbac.hasGlobalRoleGranted(rbac.currentSubjectUuid())) ) as unordered -- @formatter:on order by unordered.name; -grant all privileges on RbacUser_rv to ${HSADMINNG_POSTGRES_RESTRICTED_USERNAME}; +grant all privileges on rbac.subject_rv to ${HSADMINNG_POSTGRES_RESTRICTED_USERNAME}; --// -- ============================================================================ ---changeset rbac-views-USER-RV-INSERT-TRIGGER:1 endDelimiter:--// +--changeset michael.hoennig:rbac-views-USER-RV-INSERT-TRIGGER endDelimiter:--// -- ---------------------------------------------------------------------------- /** - Instead of insert trigger function for RbacUser_rv. + Instead of insert trigger function for rbac.subject_rv. */ -create or replace function insertRbacUser() +create or replace function rbac.insert_subject_tf() returns trigger language plpgsql as $$ declare refUuid uuid; - newUser RbacUser; + newUser rbac.subject; begin insert - into RbacReference as r (uuid, type) - values( new.uuid, 'RbacUser') + into rbac.reference as r (uuid, type) + values( new.uuid, 'rbac.subject') returning r.uuid into refUuid; insert - into RbacUser (uuid, name) + into rbac.subject (uuid, name) values (refUuid, new.name) returning * into newUser; return newUser; @@ -277,84 +276,84 @@ end; $$; /* - Creates an instead of insert trigger for the RbacUser_rv view. + Creates an instead of insert trigger for the rbac.subject_rv view. */ -create trigger insertRbacUser_Trigger +create trigger insert_subject_tg instead of insert - on RbacUser_rv + on rbac.subject_rv for each row -execute function insertRbacUser(); +execute function rbac.insert_subject_tf(); --// -- ============================================================================ ---changeset rbac-views-USER-RV-DELETE-TRIGGER:1 endDelimiter:--// +--changeset michael.hoennig:rbac-views-USER-RV-DELETE-TRIGGER endDelimiter:--// -- ---------------------------------------------------------------------------- /** - Instead of delete trigger function for RbacUser_RV. + Instead of delete trigger function for rbac.subject_rv. Checks if the current subject (user / assumed role) has the permission to delete the user. */ -create or replace function deleteRbacUser() +create or replace function rbac.delete_subject_tf() returns trigger language plpgsql as $$ begin - if currentUserUuid() = old.uuid or hasGlobalRoleGranted(currentUserUuid()) then - delete from RbacUser where uuid = old.uuid; + if rbac.currentSubjectUuid() = old.uuid or rbac.hasGlobalRoleGranted(rbac.currentSubjectUuid()) then + delete from rbac.subject where uuid = old.uuid; return old; end if; - raise exception '[403] User % not allowed to delete user uuid %', currentUser(), old.uuid; + raise exception '[403] User % not allowed to delete user uuid %', base.currentSubject(), old.uuid; end; $$; /* - Creates an instead of delete trigger for the RbacUser_rv view. + Creates an instead of delete trigger for the rbac.subject_rv view. */ -create trigger deleteRbacUser_Trigger +create trigger delete_subject_tg instead of delete - on RbacUser_rv + on rbac.subject_rv for each row -execute function deleteRbacUser(); +execute function rbac.delete_subject_tf(); --/ -- ============================================================================ ---changeset rbac-views-OWN-GRANTED-PERMISSIONS-VIEW:1 endDelimiter:--// +--changeset michael.hoennig:rbac-views-OWN-GRANTED-PERMISSIONS-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- /* Creates a view to all permissions granted to the current user or based on the grants of the current user or assumed roles. */ -- @formatter:off -drop view if exists RbacOwnGrantedPermissions_rv; -create or replace view RbacOwnGrantedPermissions_rv as +drop view if exists rbac.own_granted_permissions_rv; +create or replace view rbac.own_granted_permissions_rv as select r.uuid as roleuuid, p.uuid as permissionUuid, (r.objecttable || ':' || r.objectidname || ':' || r.roletype) as roleName, p.op, o.objecttable, r.objectidname, o.uuid as objectuuid - from rbacrole_rv r - join rbacgrants g on g.ascendantuuid = r.uuid - join rbacpermission p on p.uuid = g.descendantuuid - join rbacobject o on o.uuid = p.objectuuid; -grant all privileges on RbacOwnGrantedPermissions_rv to ${HSADMINNG_POSTGRES_RESTRICTED_USERNAME}; + from rbac.role_rv r + join rbac.grants g on g.ascendantuuid = r.uuid + join rbac.permission p on p.uuid = g.descendantuuid + join rbac.object o on o.uuid = p.objectuuid; +grant all privileges on rbac.own_granted_permissions_rv to ${HSADMINNG_POSTGRES_RESTRICTED_USERNAME}; -- @formatter:om -- ============================================================================ ---changeset rbac-views-GRANTED-PERMISSIONS:1 endDelimiter:--// +--changeset michael.hoennig:rbac-views-GRANTED-PERMISSIONS endDelimiter:--// -- ---------------------------------------------------------------------------- /* Returns all permissions granted to the given user, which are also visible to the current user or assumed roles. */ -create or replace function grantedPermissionsRaw(targetUserUuid uuid) - returns table(roleUuid uuid, roleName text, permissionUuid uuid, op RbacOp, opTableName varchar(60), objectTable varchar(60), objectIdName varchar, objectUuid uuid) +create or replace function rbac.grantedPermissionsRaw(targetSubjectUuid uuid) + returns table(roleUuid uuid, roleName text, permissionUuid uuid, op rbac.RbacOp, opTableName varchar(60), objectTable varchar(60), objectIdName varchar, objectUuid uuid) returns null on null input language plpgsql as $$ declare - currentUserUuid uuid; + currentSubjectUuid uuid; begin -- @formatter:off - currentUserUuid := currentUserUuid(); + currentSubjectUuid := rbac.currentSubjectUuid(); - if hasGlobalRoleGranted(targetUserUuid) and not hasGlobalRoleGranted(currentUserUuid) then - raise exception '[403] permissions of user "%" are not accessible to user "%"', targetUserUuid, currentUser(); + if rbac.hasGlobalRoleGranted(targetSubjectUuid) and not rbac.hasGlobalRoleGranted(currentSubjectUuid) then + raise exception '[403] permissions of user "%" are not accessible to user "%"', targetSubjectUuid, base.currentSubject(); end if; return query select @@ -364,29 +363,29 @@ begin xp.permissionObjectTable, xp.permissionObjectIdName, xp.permissionObjectUuid from (select r.uuid as roleUuid, r.roletype, ro.objectTable as roleObjectTable, - findIdNameByObjectUuid(ro.objectTable, ro.uuid) as roleObjectIdName, + base.findIdNameByObjectUuid(ro.objectTable, ro.uuid) as roleObjectIdName, p.uuid as permissionUuid, p.op, p.opTableName, po.objecttable as permissionObjectTable, - findIdNameByObjectUuid(po.objectTable, po.uuid) as permissionObjectIdName, + base.findIdNameByObjectUuid(po.objectTable, po.uuid) as permissionObjectIdName, po.uuid as permissionObjectUuid - from queryPermissionsGrantedToSubjectId( targetUserUuid) as p - join rbacgrants as g on g.descendantUuid = p.uuid - join rbacobject as po on po.uuid = p.objectUuid - join rbacrole_rv as r on r.uuid = g.ascendantUuid - join rbacobject as ro on ro.uuid = r.objectUuid - where isGranted(targetUserUuid, r.uuid) + from rbac.queryPermissionsGrantedToSubjectId( targetSubjectUuid) as p + join rbac.grants as g on g.descendantUuid = p.uuid + join rbac.object as po on po.uuid = p.objectUuid + join rbac.role_rv as r on r.uuid = g.ascendantUuid + join rbac.object as ro on ro.uuid = r.objectUuid + where rbac.isGranted(targetSubjectUuid, r.uuid) ) xp; -- @formatter:on end; $$; -create or replace function grantedPermissions(targetUserUuid uuid) - returns table(roleUuid uuid, roleName text, permissionUuid uuid, op RbacOp, opTableName varchar(60), objectTable varchar(60), objectIdName varchar, objectUuid uuid) +create or replace function rbac.grantedPermissions(targetSubjectUuid uuid) + returns table(roleUuid uuid, roleName text, permissionUuid uuid, op rbac.RbacOp, opTableName varchar(60), objectTable varchar(60), objectIdName varchar, objectUuid uuid) returns null on null input language sql as $$ - select * from grantedPermissionsRaw(targetUserUuid) + select * from rbac.grantedPermissionsRaw(targetSubjectUuid) union all - select roleUuid, roleName, permissionUuid, 'SELECT'::RbacOp, opTableName, objectTable, objectIdName, objectUuid - from grantedPermissionsRaw(targetUserUuid) - where op <> 'SELECT'::RbacOp; + select roleUuid, roleName, permissionUuid, 'SELECT'::rbac.RbacOp, opTableName, objectTable, objectIdName, objectUuid + from rbac.grantedPermissionsRaw(targetSubjectUuid) + where op <> 'SELECT'::rbac.RbacOp; $$; --// diff --git a/src/main/resources/db/changelog/1-rbac/1056-rbac-trigger-context.sql b/src/main/resources/db/changelog/1-rbac/1056-rbac-trigger-context.sql index 80a92987..783992de 100644 --- a/src/main/resources/db/changelog/1-rbac/1056-rbac-trigger-context.sql +++ b/src/main/resources/db/changelog/1-rbac/1056-rbac-trigger-context.sql @@ -2,10 +2,10 @@ -- ============================================================================ ---changeset rbac-trigger-context-ENTER:1 endDelimiter:--// +--changeset michael.hoennig:rbac-trigger-context-ENTER endDelimiter:--// -- ---------------------------------------------------------------------------- -create or replace procedure enterTriggerForObjectUuid(currentObjectUuid uuid) +create or replace procedure rbac.enterTriggerForObjectUuid(currentObjectUuid uuid) language plpgsql as $$ declare existingObjectUuid text; @@ -19,13 +19,13 @@ end; $$; -- ============================================================================ ---changeset rbac-trigger-context-CURRENT-ID:1 endDelimiter:--// +--changeset michael.hoennig:rbac-trigger-context-CURRENT-ID endDelimiter:--// -- ---------------------------------------------------------------------------- /* - Returns the uuid of the object uuid whose trigger is currently executed as set via `enterTriggerForObjectUuid(...)`. + Returns the uuid of the object uuid whose trigger is currently executed as set via `rbac.enterTriggerForObjectUuid(...)`. */ -create or replace function currentTriggerObjectUuid() +create or replace function rbac.currentTriggerObjectUuid() returns uuid stable -- leakproof language plpgsql as $$ @@ -44,10 +44,10 @@ end; $$; -- ============================================================================ ---changeset rbac-trigger-context-LEAVE:1 endDelimiter:--// +--changeset michael.hoennig:rbac-trigger-context-LEAVE endDelimiter:--// -- ---------------------------------------------------------------------------- -create or replace procedure leaveTriggerForObjectUuid(currentObjectUuid uuid) +create or replace procedure rbac.leaveTriggerForObjectUuid(currentObjectUuid uuid) language plpgsql as $$ declare existingObjectUuid uuid; diff --git a/src/main/resources/db/changelog/1-rbac/1057-rbac-role-builder.sql b/src/main/resources/db/changelog/1-rbac/1057-rbac-role-builder.sql index cb20bbbc..1ac28119 100644 --- a/src/main/resources/db/changelog/1-rbac/1057-rbac-role-builder.sql +++ b/src/main/resources/db/changelog/1-rbac/1057-rbac-role-builder.sql @@ -3,62 +3,61 @@ -- ================================================================= -- CREATE ROLE ---changeset rbac-role-builder-create-role:1 endDelimiter:--// +--changeset michael.hoennig:rbac-role-builder-define-role endDelimiter:--// -- ----------------------------------------------------------------- --- TODO: rename to defineRoleWithGrants because it does not complain if the role already exists -create or replace function createRoleWithGrants( - roleDescriptor RbacRoleDescriptor, - permissions RbacOp[] = array[]::RbacOp[], - incomingSuperRoles RbacRoleDescriptor[] = array[]::RbacRoleDescriptor[], - outgoingSubRoles RbacRoleDescriptor[] = array[]::RbacRoleDescriptor[], - userUuids uuid[] = array[]::uuid[], - grantedByRole RbacRoleDescriptor = null +create or replace function rbac.defineRoleWithGrants( + roleDescriptor rbac.RoleDescriptor, + permissions rbac.RbacOp[] = array[]::rbac.RbacOp[], + incomingSuperRoles rbac.RoleDescriptor[] = array[]::rbac.RoleDescriptor[], + outgoingSubRoles rbac.RoleDescriptor[] = array[]::rbac.RoleDescriptor[], + subjectUuids uuid[] = array[]::uuid[], + grantedByRole rbac.RoleDescriptor = null ) returns uuid called on null input language plpgsql as $$ declare roleUuid uuid; - permission RbacOp; + permission rbac.RbacOp; permissionUuid uuid; - subRoleDesc RbacRoleDescriptor; - superRoleDesc RbacRoleDescriptor; + subRoleDesc rbac.RoleDescriptor; + superRoleDesc rbac.RoleDescriptor; subRoleUuid uuid; superRoleUuid uuid; - userUuid uuid; + subjectUuid uuid; userGrantsByRoleUuid uuid; begin - roleUuid := coalesce(findRoleId(roleDescriptor), createRole(roleDescriptor)); + roleUuid := coalesce(rbac.findRoleId(roleDescriptor), rbac.createRole(roleDescriptor)); foreach permission in array permissions loop - permissionUuid := createPermission(roleDescriptor.objectuuid, permission); - call grantPermissionToRole(permissionUuid, roleUuid); + permissionUuid := rbac.createPermission(roleDescriptor.objectuuid, permission); + call rbac.grantPermissionToRole(permissionUuid, roleUuid); end loop; foreach superRoleDesc in array array_remove(incomingSuperRoles, null) loop - superRoleUuid := getRoleId(superRoleDesc); - call grantRoleToRole(roleUuid, superRoleUuid, superRoleDesc.assumed); + superRoleUuid := rbac.getRoleId(superRoleDesc); + call rbac.grantRoleToRole(roleUuid, superRoleUuid, superRoleDesc.assumed); end loop; foreach subRoleDesc in array array_remove(outgoingSubRoles, null) loop - subRoleUuid := getRoleId(subRoleDesc); - call grantRoleToRole(subRoleUuid, roleUuid, subRoleDesc.assumed); + subRoleUuid := rbac.getRoleId(subRoleDesc); + call rbac.grantRoleToRole(subRoleUuid, roleUuid, subRoleDesc.assumed); end loop; - if cardinality(userUuids) > 0 then + if cardinality(subjectUuids) > 0 then -- direct grants to users need a grantedByRole which can revoke the grant if grantedByRole is null then userGrantsByRoleUuid := roleUuid; -- TODO.impl: or do we want to require an explicit userGrantsByRoleUuid? else - userGrantsByRoleUuid := getRoleId(grantedByRole); + userGrantsByRoleUuid := rbac.getRoleId(grantedByRole); end if; - foreach userUuid in array userUuids + foreach subjectUuid in array subjectUuids loop - call grantRoleToUserUnchecked(userGrantsByRoleUuid, roleUuid, userUuid); + call rbac.grantRoleToSubjectUnchecked(userGrantsByRoleUuid, roleUuid, subjectUuid); end loop; end if; diff --git a/src/main/resources/db/changelog/1-rbac/1058-rbac-generators.sql b/src/main/resources/db/changelog/1-rbac/1058-rbac-generators.sql index 44281bed..ed114dd5 100644 --- a/src/main/resources/db/changelog/1-rbac/1058-rbac-generators.sql +++ b/src/main/resources/db/changelog/1-rbac/1058-rbac-generators.sql @@ -2,10 +2,10 @@ -- ============================================================================ ---changeset rbac-generators-RELATED-OBJECT:1 endDelimiter:--// +--changeset michael.hoennig:rbac-generators-RELATED-OBJECT endDelimiter:--// -- ---------------------------------------------------------------------------- -create or replace procedure generateRelatedRbacObject(targetTable varchar) +create or replace procedure rbac.generateRelatedRbacObject(targetTable varchar) language plpgsql as $$ declare createInsertTriggerSQL text; @@ -15,16 +15,16 @@ begin create trigger createRbacObjectFor_%s_Trigger before insert on %s for each row - execute procedure insertRelatedRbacObject(); + execute procedure rbac.insert_related_object(); $sql$, targetTable, targetTable); execute createInsertTriggerSQL; createDeleteTriggerSQL = format($sql$ - create trigger deleteRbacRulesFor_%s_Trigger + create trigger delete_related_rbac_rules_for_%s_tg after delete on %s for each row - execute procedure deleteRelatedRbacObject(); + execute procedure rbac.delete_related_rbac_rules_tf(); $sql$, targetTable, targetTable); execute createDeleteTriggerSQL; end; $$; @@ -32,62 +32,62 @@ end; $$; -- ============================================================================ ---changeset rbac-generators-ROLE-DESCRIPTORS:1 endDelimiter:--// +--changeset michael.hoennig:rbac-generators-ROLE-DESCRIPTORS endDelimiter:--// -- ---------------------------------------------------------------------------- -create procedure generateRbacRoleDescriptors(prefix text, targetTable text) +create procedure rbac.generateRbacRoleDescriptors(prefix text, targetTable text) language plpgsql as $$ declare sql text; begin sql = format($sql$ create or replace function %1$sOwner(entity %2$s, assumed boolean = true) - returns RbacRoleDescriptor + returns rbac.RoleDescriptor language plpgsql strict as $f$ begin - return roleDescriptor('%2$s', entity.uuid, 'OWNER', assumed); + return rbac.roleDescriptorOf('%2$s', entity.uuid, 'OWNER', assumed); end; $f$; create or replace function %1$sAdmin(entity %2$s, assumed boolean = true) - returns RbacRoleDescriptor + returns rbac.RoleDescriptor language plpgsql strict as $f$ begin - return roleDescriptor('%2$s', entity.uuid, 'ADMIN', assumed); + return rbac.roleDescriptorOf('%2$s', entity.uuid, 'ADMIN', assumed); end; $f$; create or replace function %1$sAgent(entity %2$s, assumed boolean = true) - returns RbacRoleDescriptor + returns rbac.RoleDescriptor language plpgsql strict as $f$ begin - return roleDescriptor('%2$s', entity.uuid, 'AGENT', assumed); + return rbac.roleDescriptorOf('%2$s', entity.uuid, 'AGENT', assumed); end; $f$; create or replace function %1$sTenant(entity %2$s, assumed boolean = true) - returns RbacRoleDescriptor + returns rbac.RoleDescriptor language plpgsql strict as $f$ begin - return roleDescriptor('%2$s', entity.uuid, 'TENANT', assumed); + return rbac.roleDescriptorOf('%2$s', entity.uuid, 'TENANT', assumed); end; $f$; -- TODO: remove guest role create or replace function %1$sGuest(entity %2$s, assumed boolean = true) - returns RbacRoleDescriptor + returns rbac.RoleDescriptor language plpgsql strict as $f$ begin - return roleDescriptor('%2$s', entity.uuid, 'GUEST', assumed); + return rbac.roleDescriptorOf('%2$s', entity.uuid, 'GUEST', assumed); end; $f$; create or replace function %1$sReferrer(entity %2$s) - returns RbacRoleDescriptor + returns rbac.RoleDescriptor language plpgsql strict as $f$ begin - return roleDescriptor('%2$s', entity.uuid, 'REFERRER'); + return rbac.roleDescriptorOf('%2$s', entity.uuid, 'REFERRER'); end; $f$; $sql$, prefix, targetTable); @@ -97,10 +97,10 @@ end; $$; -- ============================================================================ ---changeset rbac-generators-IDENTITY-VIEW:1 endDelimiter:--// +--changeset michael.hoennig:rbac-generators-IDENTITY-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -create or replace procedure generateRbacIdentityViewFromQuery(targetTable text, sqlQuery text) +create or replace procedure rbac.generateRbacIdentityViewFromQuery(targetTable text, sqlQuery text) language plpgsql as $$ declare sql text; @@ -140,7 +140,7 @@ begin execute sql; end; $$; -create or replace procedure generateRbacIdentityViewFromProjection(targetTable text, sqlProjection text) +create or replace procedure rbac.generateRbacIdentityViewFromProjection(targetTable text, sqlProjection text) language plpgsql as $$ declare sqlQuery text; @@ -148,19 +148,19 @@ begin targettable := lower(targettable); sqlQuery = format($sql$ - select target.uuid, cleanIdentifier(%2$s) as idName + select target.uuid, base.cleanIdentifier(%2$s) as idName from %1$s as target; $sql$, targetTable, sqlProjection); - call generateRbacIdentityViewFromQuery(targetTable, sqlQuery); + call rbac.generateRbacIdentityViewFromQuery(targetTable, sqlQuery); end; $$; --// -- ============================================================================ ---changeset rbac-generators-RESTRICTED-VIEW:1 endDelimiter:--// +--changeset michael.hoennig:rbac-generators-RESTRICTED-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -create or replace procedure generateRbacRestrictedView(targetTable text, orderBy text, columnUpdates text = null, columnNames text = '*') +create or replace procedure rbac.generateRbacRestrictedView(targetTable text, orderBy text, columnUpdates text = null, columnNames text = '*') language plpgsql as $$ declare sql text; @@ -168,7 +168,7 @@ declare begin targetTable := lower(targetTable); if columnNames = '*' then - columnNames := columnsNames(targetTable); + columnNames := base.tableColumnNames(targetTable); end if; /* @@ -179,31 +179,31 @@ begin with accessible_%1$s_uuids as ( with recursive recursive_grants as - (select distinct rbacgrants.descendantuuid, - rbacgrants.ascendantuuid, + (select distinct rbac.grants.descendantuuid, + rbac.grants.ascendantuuid, 1 as level, true - from rbacgrants - where rbacgrants.assumed - and (rbacgrants.ascendantuuid = any (currentsubjectsuuids())) + from rbac.grants + where rbac.grants.assumed + and (rbac.grants.ascendantuuid = any (rbac.currentSubjectOrAssumedRolesUuids())) union all select distinct g.descendantuuid, g.ascendantuuid, grants.level + 1 as level, - assertTrue(grants.level < 22, 'too many grant-levels: ' || grants.level) - from rbacgrants g + base.assertTrue(grants.level < 22, 'too many grant-levels: ' || grants.level) + from rbac.grants g join recursive_grants grants on grants.descendantuuid = g.ascendantuuid where g.assumed), grant_count AS ( SELECT COUNT(*) AS grant_count FROM recursive_grants ), - count_check as (select assertTrue((select count(*) as grant_count from recursive_grants) < 400000, + count_check as (select base.assertTrue((select count(*) as grant_count from recursive_grants) < 400000, 'too many grants for current subjects: ' || (select count(*) as grant_count from recursive_grants)) as valid) select distinct perm.objectuuid from recursive_grants - join rbacpermission perm on recursive_grants.descendantuuid = perm.uuid - join rbacobject obj on obj.uuid = perm.objectuuid + join rbac.permission perm on recursive_grants.descendantuuid = perm.uuid + join rbac.object obj on obj.uuid = perm.objectuuid join count_check cc on cc.valid where obj.objectTable = '%1$s' -- 'SELECT' permission is included in all other permissions ) @@ -256,11 +256,11 @@ begin returns trigger language plpgsql as $f$ begin - if old.uuid in (select queryAccessibleObjectUuidsOfSubjectIds('DELETE', '%1$s', currentSubjectsUuids())) then + if old.uuid in (select rbac.queryAccessibleObjectUuidsOfSubjectIds('DELETE', '%1$s', rbac.currentSubjectOrAssumedRolesUuids())) then delete from %1$s p where p.uuid = old.uuid; return old; end if; - raise exception '[403] Subject %% is not allowed to delete %1$s uuid %%', currentSubjectsUuids(), old.uuid; + raise exception '[403] Subject %% is not allowed to delete %1$s uuid %%', rbac.currentSubjectOrAssumedRolesUuids(), old.uuid; end; $f$; $sql$, targetTable); execute sql; @@ -287,13 +287,13 @@ begin returns trigger language plpgsql as $f$ begin - if old.uuid in (select queryAccessibleObjectUuidsOfSubjectIds('UPDATE', '%1$s', currentSubjectsUuids())) then + if old.uuid in (select rbac.queryAccessibleObjectUuidsOfSubjectIds('UPDATE', '%1$s', rbac.currentSubjectOrAssumedRolesUuids())) then update %1$s set %2$s where uuid = old.uuid; return old; end if; - raise exception '[403] Subject %% is not allowed to update %1$s uuid %%', currentSubjectsUuids(), old.uuid; + raise exception '[403] Subject %% is not allowed to update %1$s uuid %%', rbac.currentSubjectOrAssumedRolesUuids(), old.uuid; end; $f$; $sql$, targetTable, columnUpdates); execute sql; diff --git a/src/main/resources/db/changelog/1-rbac/1059-rbac-statistics.sql b/src/main/resources/db/changelog/1-rbac/1059-rbac-statistics.sql index 1ef6283a..cb8e35bf 100644 --- a/src/main/resources/db/changelog/1-rbac/1059-rbac-statistics.sql +++ b/src/main/resources/db/changelog/1-rbac/1059-rbac-statistics.sql @@ -1,28 +1,28 @@ --liquibase formatted sql ---changeset rbac-statistics:1 endDelimiter:--// +--changeset michael.hoennig:rbac-statistics endDelimiter:--// /* Creates a view which presents some statistics about the RBAC tables. */ -create view RbacStatisticsView as +create view rbac.statistics_v as select no, to_char("count", '9 999 999 999') as "count", "table" from (select 1 as no, count(*) as "count", 'login users' as "table" - from RbacUser + from rbac.subject union select 2 as no, count(*) as "count", 'roles' as "table" - from RbacRole + from rbac.role union select 3 as no, count(*) as "count", 'permissions' as "table" - from RbacPermission + from rbac.permission union select 4 as no, count(*) as "count", 'references' as "table" - from RbacReference + from rbac.reference union select 5 as no, count(*) as "count", 'grants' as "table" - from RbacGrants + from rbac.grants union select 6 as no, count(*) as "count", 'objects' as "table" - from RbacObject) as totals + from rbac.object) as totals order by totals.no; --// diff --git a/src/main/resources/db/changelog/1-rbac/1080-rbac-global.sql b/src/main/resources/db/changelog/1-rbac/1080-rbac-global.sql index c28a464d..cf62891f 100644 --- a/src/main/resources/db/changelog/1-rbac/1080-rbac-global.sql +++ b/src/main/resources/db/changelog/1-rbac/1080-rbac-global.sql @@ -1,7 +1,7 @@ --liquibase formatted sql -- ============================================================================ ---changeset rbac-global-GLOBAL-OBJECT:1 endDelimiter:--// +--changeset michael.hoennig:rbac-global-OBJECT endDelimiter:--// -- ---------------------------------------------------------------------------- /* The purpose of this table is provide root business objects @@ -11,184 +11,184 @@ In production databases, there is only a single row in this table, in test stages, there can be one row for each test data realm. */ -create table Global +create table rbac.global ( - uuid uuid primary key references RbacObject (uuid) on delete cascade, + uuid uuid primary key references rbac.object (uuid) on delete cascade, name varchar(63) unique ); -create unique index Global_Singleton on Global ((0)); +create unique index Global_Singleton on rbac.global ((0)); -grant select on global to ${HSADMINNG_POSTGRES_RESTRICTED_USERNAME}; +grant select on rbac.global to ${HSADMINNG_POSTGRES_RESTRICTED_USERNAME}; --// -- ============================================================================ ---changeset rbac-global-IS-GLOBAL-ADMIN:1 endDelimiter:--// +--changeset michael.hoennig:rbac-global-IS-GLOBAL-ADMIN endDelimiter:--// -- ------------------------------------------------------------------ -create or replace function isGlobalAdmin() +create or replace function rbac.isGlobalAdmin() returns boolean language plpgsql as $$ begin - return isGranted(currentSubjectsUuids(), findRoleId(globalAdmin())); + return rbac.isGranted(rbac.currentSubjectOrAssumedRolesUuids(), rbac.findRoleId(rbac.globalAdmin())); end; $$; --// -- ============================================================================ ---changeset rbac-global-HAS-GLOBAL-PERMISSION:1 endDelimiter:--// +--changeset michael.hoennig:rbac-global-HAS-GLOBAL-PERMISSION endDelimiter:--// -- ------------------------------------------------------------------ -create or replace function hasGlobalPermission(op RbacOp) +create or replace function rbac.hasGlobalPermission(op rbac.RbacOp) returns boolean language sql as $$ -- TODO.perf: this could to be optimized -select (select uuid from global) in - (select queryAccessibleObjectUuidsOfSubjectIds(op, 'global', currentSubjectsUuids())); +select (select uuid from rbac.global) in + (select rbac.queryAccessibleObjectUuidsOfSubjectIds(op, 'rbac.global', rbac.currentSubjectOrAssumedRolesUuids())); $$; --// -- ============================================================================ ---changeset rbac-global-GLOBAL-IDENTITY-VIEW:1 endDelimiter:--// +--changeset michael.hoennig:rbac-global-IDENTITY-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- /* - Creates a view to the global object table which maps the identifying name to the objectUuid. + Creates a view to the rbac.global object table which maps the identifying name to the objectUuid. */ -drop view if exists global_iv; -create or replace view global_iv as +drop view if exists rbac.global_iv; +create or replace view rbac.global_iv as select target.uuid, target.name as idName - from global as target; -grant all privileges on global_iv to ${HSADMINNG_POSTGRES_RESTRICTED_USERNAME}; + from rbac.global as target; +grant all privileges on rbac.global_iv to ${HSADMINNG_POSTGRES_RESTRICTED_USERNAME}; /* Returns the objectUuid for a given identifying name (in this case the idName). */ -create or replace function globalUuidByIdName(idName varchar) +create or replace function rbac.globalUuidByIdName(idName varchar) returns uuid language sql strict as $$ -select uuid from global_iv iv where iv.idName = globalUuidByIdName.idName; +select uuid from rbac.global_iv iv where iv.idName = globalUuidByIdName.idName; $$; /* Returns the identifying name for a given objectUuid (in this case the idName). */ -create or replace function globalIdNameByUuid(uuid uuid) +create or replace function rbac.globalIdNameByUuid(uuid uuid) returns varchar language sql strict as $$ -select idName from global_iv iv where iv.uuid = globalIdNameByUuid.uuid; +select idName from rbac.global_iv iv where iv.uuid = globalIdNameByUuid.uuid; $$; --// --liquibase formatted sql -- ============================================================================ ---changeset rbac-global-PSEUDO-OBJECT:1 endDelimiter:--// +--changeset michael.hoennig:rbac-global-PSEUDO-OBJECT endDelimiter:--// -- ---------------------------------------------------------------------------- /** - A single row to be referenced as a global object. + A single row to be referenced as a rbac.Global object. */ begin transaction; -call defineContext('initializing table "global"', null, null, null); +call base.defineContext('initializing table "rbac.global"', null, null, null); insert - into RbacObject (objecttable) values ('global'); + into rbac.object (objecttable) values ('rbac.global'); insert - into Global (uuid, name) values ((select uuid from RbacObject where objectTable = 'global'), 'global'); + into rbac.global (uuid, name) values ((select uuid from rbac.object where objectTable = 'rbac.global'), 'global'); commit; --// -- ============================================================================ ---changeset rbac-global-ADMIN-ROLE:1 endDelimiter:--// +--changeset michael.hoennig:rbac-global-ADMIN-ROLE endDelimiter:--// -- ---------------------------------------------------------------------------- /* - A global administrator role. + A rbac.Global administrator role. */ -create or replace function globalAdmin(assumed boolean = true) - returns RbacRoleDescriptor +create or replace function rbac.globalAdmin(assumed boolean = true) + returns rbac.RoleDescriptor returns null on null input stable -- leakproof language sql as $$ -select 'global', (select uuid from RbacObject where objectTable = 'global'), 'ADMIN'::RbacRoleType, assumed; +select 'rbac.global', (select uuid from rbac.object where objectTable = 'rbac.global'), 'ADMIN'::rbac.RoleType, assumed; $$; begin transaction; - call defineContext('creating role:global#global:ADMIN', null, null, null); - select createRole(globalAdmin()); + call base.defineContext('creating role:rbac.global#global:ADMIN', null, null, null); + select rbac.createRole(rbac.globalAdmin()); commit; --// -- ============================================================================ ---changeset rbac-global-GUEST-ROLE:1 endDelimiter:--// +--changeset michael.hoennig:rbac-global-GUEST-ROLE endDelimiter:--// -- ---------------------------------------------------------------------------- /* - A global guest role. + A rbac.Global guest role. */ -create or replace function globalGuest(assumed boolean = true) - returns RbacRoleDescriptor +create or replace function rbac.globalglobalGuest(assumed boolean = true) + returns rbac.RoleDescriptor returns null on null input stable -- leakproof language sql as $$ -select 'global', (select uuid from RbacObject where objectTable = 'global'), 'GUEST'::RbacRoleType, assumed; +select 'rbac.global', (select uuid from rbac.object where objectTable = 'rbac.global'), 'GUEST'::rbac.RoleType, assumed; $$; begin transaction; - call defineContext('creating role:global#global:guest', null, null, null); - select createRole(globalGuest()); + call base.defineContext('creating role:rbac.global#global:guest', null, null, null); + select rbac.createRole(rbac.globalglobalGuest()); commit; --// -- ============================================================================ ---changeset rbac-global-ADMIN-USERS:1 context:dev,tc endDelimiter:--// +--changeset michael.hoennig:rbac-global-ADMIN-USERS context:dev,tc endDelimiter:--// -- ---------------------------------------------------------------------------- /* - Create two users and assign both to the administrators role. + Create two users and assign both to the administrators' role. */ do language plpgsql $$ declare admins uuid ; begin - call defineContext('creating fake test-realm admin users', null, null, null); + call base.defineContext('creating fake test-realm admin users', null, null, null); - admins = findRoleId(globalAdmin()); - call grantRoleToUserUnchecked(admins, admins, createRbacUser('superuser-alex@hostsharing.net')); - call grantRoleToUserUnchecked(admins, admins, createRbacUser('superuser-fran@hostsharing.net')); - perform createRbacUser('selfregistered-user-drew@hostsharing.org'); - perform createRbacUser('selfregistered-test-user@hostsharing.org'); + admins = rbac.findRoleId(rbac.globalAdmin()); + call rbac.grantRoleToSubjectUnchecked(admins, admins, rbac.create_subject('superuser-alex@hostsharing.net')); + call rbac.grantRoleToSubjectUnchecked(admins, admins, rbac.create_subject('superuser-fran@hostsharing.net')); + perform rbac.create_subject('selfregistered-user-drew@hostsharing.org'); + perform rbac.create_subject('selfregistered-test-user@hostsharing.org'); end; $$; --// -- ============================================================================ ---changeset rbac-global-TEST:1 context:dev,tc runAlways:true endDelimiter:--// +--changeset michael.hoennig:rbac-global-TEST context:dev,tc runAlways:true endDelimiter:--// -- ---------------------------------------------------------------------------- /* - Tests if currentUserUuid() can fetch the user from the session variable. + Tests if rbac.currentSubjectUuid() can fetch the user from the session variable. */ do language plpgsql $$ declare userName varchar; begin - call defineContext('testing currentUserUuid', null, 'superuser-fran@hostsharing.net', null); - select userName from RbacUser where uuid = currentUserUuid() into userName; + call base.defineContext('testing currentSubjectUuid', null, 'superuser-fran@hostsharing.net', null); + select userName from rbac.subject where uuid = rbac.currentSubjectUuid() into userName; if userName <> 'superuser-fran@hostsharing.net' then - raise exception 'setting or fetching initial currentUser failed, got: %', userName; + raise exception 'setting or fetching initial currentSubject failed, got: %', userName; end if; - call defineContext('testing currentUserUuid', null, 'superuser-alex@hostsharing.net', null); - select userName from RbacUser where uuid = currentUserUuid() into userName; + call base.defineContext('testing currentSubjectUuid', null, 'superuser-alex@hostsharing.net', null); + select userName from rbac.subject where uuid = rbac.currentSubjectUuid() into userName; if userName = 'superuser-alex@hostsharing.net' then - raise exception 'currentUser should not change in one transaction, but did change, got: %', userName; + raise exception 'currentSubject should not change in one transaction, but did change, got: %', userName; end if; end; $$; --// diff --git a/src/main/resources/db/changelog/2-test/201-test-customer/2010-test-customer.sql b/src/main/resources/db/changelog/2-test/201-test-customer/2010-test-customer.sql index 559ba51a..4c0b2b81 100644 --- a/src/main/resources/db/changelog/2-test/201-test-customer/2010-test-customer.sql +++ b/src/main/resources/db/changelog/2-test/201-test-customer/2010-test-customer.sql @@ -1,12 +1,12 @@ --liquibase formatted sql -- ============================================================================ ---changeset test-customer-MAIN-TABLE:1 endDelimiter:--// +--changeset michael.hoennig:test-customer-MAIN-TABLE endDelimiter:--// -- ---------------------------------------------------------------------------- create table if not exists test_customer ( - uuid uuid unique references RbacObject (uuid), + uuid uuid unique references rbac.object (uuid), version int not null default 0, reference int not null unique check (reference between 10000 and 99999), prefix character(3) unique, diff --git a/src/main/resources/db/changelog/2-test/201-test-customer/2013-test-customer-rbac.md b/src/main/resources/db/changelog/2-test/201-test-customer/2013-test-customer-rbac.md index 19e67a38..b1c4ab5a 100644 --- a/src/main/resources/db/changelog/2-test/201-test-customer/2013-test-customer-rbac.md +++ b/src/main/resources/db/changelog/2-test/201-test-customer/2013-test-customer-rbac.md @@ -32,12 +32,12 @@ end user:creator ==>|XX| role:customer:OWNER %% granting roles to roles -role:global:ADMIN ==>|XX| role:customer:OWNER +role:rbac.global:ADMIN ==>|XX| role:customer:OWNER role:customer:OWNER ==> role:customer:ADMIN role:customer:ADMIN ==> role:customer:TENANT %% granting permissions to roles -role:global:ADMIN ==> perm:customer:INSERT +role:rbac.global:ADMIN ==> perm:customer:INSERT role:customer:OWNER ==> perm:customer:DELETE role:customer:ADMIN ==> perm:customer:UPDATE role:customer:TENANT ==> perm:customer:SELECT diff --git a/src/main/resources/db/changelog/2-test/201-test-customer/2013-test-customer-rbac.sql b/src/main/resources/db/changelog/2-test/201-test-customer/2013-test-customer-rbac.sql index e1540c9a..237c8179 100644 --- a/src/main/resources/db/changelog/2-test/201-test-customer/2013-test-customer-rbac.sql +++ b/src/main/resources/db/changelog/2-test/201-test-customer/2013-test-customer-rbac.sql @@ -3,21 +3,21 @@ -- ============================================================================ ---changeset test-customer-rbac-OBJECT:1 endDelimiter:--// +--changeset RbacObjectGenerator:test-customer-rbac-OBJECT endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRelatedRbacObject('test_customer'); +call rbac.generateRelatedRbacObject('test_customer'); --// -- ============================================================================ ---changeset test-customer-rbac-ROLE-DESCRIPTORS:1 endDelimiter:--// +--changeset RbacRoleDescriptorsGenerator:test-customer-rbac-ROLE-DESCRIPTORS endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRbacRoleDescriptors('testCustomer', 'test_customer'); +call rbac.generateRbacRoleDescriptors('testCustomer', 'test_customer'); --// -- ============================================================================ ---changeset test-customer-rbac-insert-trigger:1 endDelimiter:--// +--changeset RolesGrantsAndPermissionsGenerator:test-customer-rbac-insert-trigger endDelimiter:--// -- ---------------------------------------------------------------------------- /* @@ -32,28 +32,28 @@ create or replace procedure buildRbacSystemForTestCustomer( declare begin - call enterTriggerForObjectUuid(NEW.uuid); + call rbac.enterTriggerForObjectUuid(NEW.uuid); - perform createRoleWithGrants( + perform rbac.defineRoleWithGrants( testCustomerOWNER(NEW), permissions => array['DELETE'], - incomingSuperRoles => array[globalADMIN(unassumed())], - userUuids => array[currentUserUuid()] + incomingSuperRoles => array[rbac.globalADMIN(rbac.unassumed())], + subjectUuids => array[rbac.currentSubjectUuid()] ); - perform createRoleWithGrants( + perform rbac.defineRoleWithGrants( testCustomerADMIN(NEW), permissions => array['UPDATE'], incomingSuperRoles => array[testCustomerOWNER(NEW)] ); - perform createRoleWithGrants( + perform rbac.defineRoleWithGrants( testCustomerTENANT(NEW), permissions => array['SELECT'], incomingSuperRoles => array[testCustomerADMIN(NEW)] ); - call leaveTriggerForObjectUuid(NEW.uuid); + call rbac.leaveTriggerForObjectUuid(NEW.uuid); end; $$; /* @@ -77,26 +77,26 @@ execute procedure insertTriggerForTestCustomer_tf(); -- ============================================================================ ---changeset test-customer-rbac-GRANTING-INSERT-PERMISSION:1 endDelimiter:--// +--changeset InsertTriggerGenerator:test-customer-rbac-GRANTING-INSERT-PERMISSION endDelimiter:--// -- ---------------------------------------------------------------------------- --- granting INSERT permission to global ---------------------------- +-- granting INSERT permission to rbac.global ---------------------------- /* - Grants INSERT INTO test_customer permissions to specified role of pre-existing global rows. + Grants INSERT INTO test_customer permissions to specified role of pre-existing rbac.global rows. */ do language plpgsql $$ declare - row global; + row rbac.global; begin - call defineContext('create INSERT INTO test_customer permissions for pre-exising global rows'); + call base.defineContext('create INSERT INTO test_customer permissions for pre-exising rbac.global rows'); - FOR row IN SELECT * FROM global + FOR row IN SELECT * FROM rbac.global -- unconditional for all rows in that table LOOP - call grantPermissionToRole( - createPermission(row.uuid, 'INSERT', 'test_customer'), - globalADMIN()); + call rbac.grantPermissionToRole( + rbac.createPermission(row.uuid, 'INSERT', 'test_customer'), + rbac.globalADMIN()); END LOOP; end; $$; @@ -104,28 +104,28 @@ $$; /** Grants test_customer INSERT permission to specified role of new global rows. */ -create or replace function new_test_customer_grants_insert_to_global_tf() +create or replace function rbac.new_test_customer_grants_insert_to_global_tf() returns trigger language plpgsql strict as $$ begin -- unconditional for all rows in that table - call grantPermissionToRole( - createPermission(NEW.uuid, 'INSERT', 'test_customer'), - globalADMIN()); + call rbac.grantPermissionToRole( + rbac.createPermission(NEW.uuid, 'INSERT', 'test_customer'), + rbac.globalADMIN()); -- end. return NEW; end; $$; -- z_... is to put it at the end of after insert triggers, to make sure the roles exist -create trigger z_new_test_customer_grants_insert_to_global_tg - after insert on global +create trigger z_new_test_customer_grants_after_insert_tg + after insert on rbac.global for each row -execute procedure new_test_customer_grants_insert_to_global_tf(); +execute procedure rbac.new_test_customer_grants_insert_to_global_tf(); -- ============================================================================ ---changeset test_customer-rbac-CHECKING-INSERT-PERMISSION:1 endDelimiter:--// +--changeset InsertTriggerGenerator:test_customer-rbac-CHECKING-INSERT-PERMISSION endDelimiter:--// -- ---------------------------------------------------------------------------- /** @@ -137,13 +137,13 @@ create or replace function test_customer_insert_permission_check_tf() declare superObjectUuid uuid; begin - -- check INSERT INSERT if global ADMIN - if isGlobalAdmin() then + -- check INSERT INSERT if rbac.global ADMIN + if rbac.isGlobalAdmin() then return NEW; end if; raise exception '[403] insert into test_customer values(%) not allowed for current subjects % (%)', - NEW, currentSubjects(), currentSubjectsUuids(); + NEW, base.currentSubjects(), rbac.currentSubjectOrAssumedRolesUuids(); end; $$; create trigger test_customer_insert_permission_check_tg @@ -154,10 +154,10 @@ create trigger test_customer_insert_permission_check_tg -- ============================================================================ ---changeset test-customer-rbac-IDENTITY-VIEW:1 endDelimiter:--// +--changeset RbacIdentityViewGenerator:test-customer-rbac-IDENTITY-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRbacIdentityViewFromProjection('test_customer', +call rbac.generateRbacIdentityViewFromProjection('test_customer', $idName$ prefix $idName$); @@ -165,9 +165,9 @@ call generateRbacIdentityViewFromProjection('test_customer', -- ============================================================================ ---changeset test-customer-rbac-RESTRICTED-VIEW:1 endDelimiter:--// +--changeset RbacRestrictedViewGenerator:test-customer-rbac-RESTRICTED-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRbacRestrictedView('test_customer', +call rbac.generateRbacRestrictedView('test_customer', $orderBy$ reference $orderBy$, diff --git a/src/main/resources/db/changelog/2-test/201-test-customer/2018-test-customer-test-data.sql b/src/main/resources/db/changelog/2-test/201-test-customer/2018-test-customer-test-data.sql index f05cbafb..b1a22df4 100644 --- a/src/main/resources/db/changelog/2-test/201-test-customer/2018-test-customer-test-data.sql +++ b/src/main/resources/db/changelog/2-test/201-test-customer/2018-test-customer-test-data.sql @@ -2,7 +2,7 @@ -- ============================================================================ ---changeset test-customer-TEST-DATA-GENERATOR:1 endDelimiter:--// +--changeset michael.hoennig:test-customer-TEST-DATA-GENERATOR endDelimiter:--// -- ---------------------------------------------------------------------------- /* Generates a customer reference number for a given test data counter. @@ -32,7 +32,7 @@ declare begin custRowId = uuid_generate_v4(); custAdminName = 'customer-admin@' || custPrefix || '.example.com'; - custAdminUuid = createRbacUser(custAdminName); + custAdminUuid = rbac.create_subject(custAdminName); insert into test_customer (reference, prefix, adminUserName) @@ -40,9 +40,9 @@ begin select * into newCust from test_customer where reference=custReference; - call grantRoleToUser( - getRoleId(testCustomerOwner(newCust)), - getRoleId(testCustomerAdmin(newCust)), + call rbac.grantRoleToSubject( + rbac.getRoleId(testCustomerOwner(newCust)), + rbac.getRoleId(testCustomerAdmin(newCust)), custAdminUuid, true); end; $$; @@ -59,7 +59,7 @@ create or replace procedure createTestCustomerTestData( begin for t in startCount..endCount loop - call createTestCustomerTestData(testCustomerReference(t), intToVarChar(t, 3)); + call createTestCustomerTestData(testCustomerReference(t), base.intToVarChar(t, 3)); commit; end loop; end; $$; @@ -67,12 +67,12 @@ end; $$; -- ============================================================================ ---changeset test-customer-TEST-DATA-GENERATION:1 –context=dev,tc endDelimiter:--// +--changeset michael.hoennig:test-customer-TEST-DATA-GENERATION –context=dev,tc endDelimiter:--// -- ---------------------------------------------------------------------------- do language plpgsql $$ begin - call defineContext('creating RBAC test customer', null, 'superuser-alex@hostsharing.net', 'global#global:ADMIN'); + call base.defineContext('creating RBAC test customer', null, 'superuser-alex@hostsharing.net', 'rbac.global#global:ADMIN'); call createTestCustomerTestData(99901, 'xxx'); call createTestCustomerTestData(99902, 'yyy'); diff --git a/src/main/resources/db/changelog/2-test/202-test-package/2020-test-package.sql b/src/main/resources/db/changelog/2-test/202-test-package/2020-test-package.sql index 30739cd3..83453f0a 100644 --- a/src/main/resources/db/changelog/2-test/202-test-package/2020-test-package.sql +++ b/src/main/resources/db/changelog/2-test/202-test-package/2020-test-package.sql @@ -1,12 +1,12 @@ --liquibase formatted sql -- ============================================================================ ---changeset test-package-MAIN-TABLE:1 endDelimiter:--// +--changeset michael.hoennig:test-package-MAIN-TABLE endDelimiter:--// -- ---------------------------------------------------------------------------- create table if not exists test_package ( - uuid uuid unique references RbacObject (uuid), + uuid uuid unique references rbac.object (uuid), version int not null default 0, customerUuid uuid references test_customer (uuid), name varchar(5), diff --git a/src/main/resources/db/changelog/2-test/202-test-package/2023-test-package-rbac.md b/src/main/resources/db/changelog/2-test/202-test-package/2023-test-package-rbac.md index af3a5f84..4114d6b3 100644 --- a/src/main/resources/db/changelog/2-test/202-test-package/2023-test-package-rbac.md +++ b/src/main/resources/db/changelog/2-test/202-test-package/2023-test-package-rbac.md @@ -42,7 +42,7 @@ subgraph package["`**package**`"] end %% granting roles to roles -role:global:ADMIN -.->|XX| role:customer:OWNER +role:rbac.global:ADMIN -.->|XX| role:customer:OWNER role:customer:OWNER -.-> role:customer:ADMIN role:customer:ADMIN -.-> role:customer:TENANT role:customer:ADMIN ==> role:package:OWNER diff --git a/src/main/resources/db/changelog/2-test/202-test-package/2023-test-package-rbac.sql b/src/main/resources/db/changelog/2-test/202-test-package/2023-test-package-rbac.sql index 9ec9c06a..87f5717c 100644 --- a/src/main/resources/db/changelog/2-test/202-test-package/2023-test-package-rbac.sql +++ b/src/main/resources/db/changelog/2-test/202-test-package/2023-test-package-rbac.sql @@ -3,21 +3,21 @@ -- ============================================================================ ---changeset test-package-rbac-OBJECT:1 endDelimiter:--// +--changeset RbacObjectGenerator:test-package-rbac-OBJECT endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRelatedRbacObject('test_package'); +call rbac.generateRelatedRbacObject('test_package'); --// -- ============================================================================ ---changeset test-package-rbac-ROLE-DESCRIPTORS:1 endDelimiter:--// +--changeset RbacRoleDescriptorsGenerator:test-package-rbac-ROLE-DESCRIPTORS endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRbacRoleDescriptors('testPackage', 'test_package'); +call rbac.generateRbacRoleDescriptors('testPackage', 'test_package'); --// -- ============================================================================ ---changeset test-package-rbac-insert-trigger:1 endDelimiter:--// +--changeset RolesGrantsAndPermissionsGenerator:test-package-rbac-insert-trigger endDelimiter:--// -- ---------------------------------------------------------------------------- /* @@ -33,31 +33,31 @@ declare newCustomer test_customer; begin - call enterTriggerForObjectUuid(NEW.uuid); + call rbac.enterTriggerForObjectUuid(NEW.uuid); SELECT * FROM test_customer WHERE uuid = NEW.customerUuid INTO newCustomer; assert newCustomer.uuid is not null, format('newCustomer must not be null for NEW.customerUuid = %s', NEW.customerUuid); - perform createRoleWithGrants( + perform rbac.defineRoleWithGrants( testPackageOWNER(NEW), permissions => array['DELETE', 'UPDATE'], incomingSuperRoles => array[testCustomerADMIN(newCustomer)] ); - perform createRoleWithGrants( + perform rbac.defineRoleWithGrants( testPackageADMIN(NEW), incomingSuperRoles => array[testPackageOWNER(NEW)] ); - perform createRoleWithGrants( + perform rbac.defineRoleWithGrants( testPackageTENANT(NEW), permissions => array['SELECT'], incomingSuperRoles => array[testPackageADMIN(NEW)], outgoingSubRoles => array[testCustomerTENANT(newCustomer)] ); - call leaveTriggerForObjectUuid(NEW.uuid); + call rbac.leaveTriggerForObjectUuid(NEW.uuid); end; $$; /* @@ -81,7 +81,7 @@ execute procedure insertTriggerForTestPackage_tf(); -- ============================================================================ ---changeset test-package-rbac-update-trigger:1 endDelimiter:--// +--changeset RolesGrantsAndPermissionsGenerator:test-package-rbac-update-trigger endDelimiter:--// -- ---------------------------------------------------------------------------- /* @@ -99,7 +99,7 @@ declare newCustomer test_customer; begin - call enterTriggerForObjectUuid(NEW.uuid); + call rbac.enterTriggerForObjectUuid(NEW.uuid); SELECT * FROM test_customer WHERE uuid = OLD.customerUuid INTO oldCustomer; assert oldCustomer.uuid is not null, format('oldCustomer must not be null for OLD.customerUuid = %s', OLD.customerUuid); @@ -110,15 +110,15 @@ begin if NEW.customerUuid <> OLD.customerUuid then - call revokeRoleFromRole(testPackageOWNER(OLD), testCustomerADMIN(oldCustomer)); - call grantRoleToRole(testPackageOWNER(NEW), testCustomerADMIN(newCustomer)); + call rbac.revokeRoleFromRole(testPackageOWNER(OLD), testCustomerADMIN(oldCustomer)); + call rbac.grantRoleToRole(testPackageOWNER(NEW), testCustomerADMIN(newCustomer)); - call revokeRoleFromRole(testCustomerTENANT(oldCustomer), testPackageTENANT(OLD)); - call grantRoleToRole(testCustomerTENANT(newCustomer), testPackageTENANT(NEW)); + call rbac.revokeRoleFromRole(testCustomerTENANT(oldCustomer), testPackageTENANT(OLD)); + call rbac.grantRoleToRole(testCustomerTENANT(newCustomer), testPackageTENANT(NEW)); end if; - call leaveTriggerForObjectUuid(NEW.uuid); + call rbac.leaveTriggerForObjectUuid(NEW.uuid); end; $$; /* @@ -142,7 +142,7 @@ execute procedure updateTriggerForTestPackage_tf(); -- ============================================================================ ---changeset test-package-rbac-GRANTING-INSERT-PERMISSION:1 endDelimiter:--// +--changeset InsertTriggerGenerator:test-package-rbac-GRANTING-INSERT-PERMISSION endDelimiter:--// -- ---------------------------------------------------------------------------- -- granting INSERT permission to test_customer ---------------------------- @@ -154,13 +154,13 @@ do language plpgsql $$ declare row test_customer; begin - call defineContext('create INSERT INTO test_package permissions for pre-exising test_customer rows'); + call base.defineContext('create INSERT INTO test_package permissions for pre-exising test_customer rows'); FOR row IN SELECT * FROM test_customer -- unconditional for all rows in that table LOOP - call grantPermissionToRole( - createPermission(row.uuid, 'INSERT', 'test_package'), + call rbac.grantPermissionToRole( + rbac.createPermission(row.uuid, 'INSERT', 'test_package'), testCustomerADMIN(row)); END LOOP; end; @@ -175,22 +175,22 @@ create or replace function new_test_package_grants_insert_to_test_customer_tf() strict as $$ begin -- unconditional for all rows in that table - call grantPermissionToRole( - createPermission(NEW.uuid, 'INSERT', 'test_package'), + call rbac.grantPermissionToRole( + rbac.createPermission(NEW.uuid, 'INSERT', 'test_package'), testCustomerADMIN(NEW)); -- end. return NEW; end; $$; -- z_... is to put it at the end of after insert triggers, to make sure the roles exist -create trigger z_new_test_package_grants_insert_to_test_customer_tg +create trigger z_new_test_package_grants_after_insert_tg after insert on test_customer for each row execute procedure new_test_package_grants_insert_to_test_customer_tf(); -- ============================================================================ ---changeset test_package-rbac-CHECKING-INSERT-PERMISSION:1 endDelimiter:--// +--changeset InsertTriggerGenerator:test_package-rbac-CHECKING-INSERT-PERMISSION endDelimiter:--// -- ---------------------------------------------------------------------------- /** @@ -203,12 +203,12 @@ declare superObjectUuid uuid; begin -- check INSERT permission via direct foreign key: NEW.customerUuid - if hasInsertPermission(NEW.customerUuid, 'test_package') then + if rbac.hasInsertPermission(NEW.customerUuid, 'test_package') then return NEW; end if; raise exception '[403] insert into test_package values(%) not allowed for current subjects % (%)', - NEW, currentSubjects(), currentSubjectsUuids(); + NEW, base.currentSubjects(), rbac.currentSubjectOrAssumedRolesUuids(); end; $$; create trigger test_package_insert_permission_check_tg @@ -219,10 +219,10 @@ create trigger test_package_insert_permission_check_tg -- ============================================================================ ---changeset test-package-rbac-IDENTITY-VIEW:1 endDelimiter:--// +--changeset RbacIdentityViewGenerator:test-package-rbac-IDENTITY-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRbacIdentityViewFromProjection('test_package', +call rbac.generateRbacIdentityViewFromProjection('test_package', $idName$ name $idName$); @@ -230,9 +230,9 @@ call generateRbacIdentityViewFromProjection('test_package', -- ============================================================================ ---changeset test-package-rbac-RESTRICTED-VIEW:1 endDelimiter:--// +--changeset RbacRestrictedViewGenerator:test-package-rbac-RESTRICTED-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRbacRestrictedView('test_package', +call rbac.generateRbacRestrictedView('test_package', $orderBy$ name $orderBy$, diff --git a/src/main/resources/db/changelog/2-test/202-test-package/2028-test-package-test-data.sql b/src/main/resources/db/changelog/2-test/202-test-package/2028-test-package-test-data.sql index bf4a9f3b..95430732 100644 --- a/src/main/resources/db/changelog/2-test/202-test-package/2028-test-package-test-data.sql +++ b/src/main/resources/db/changelog/2-test/202-test-package/2028-test-package-test-data.sql @@ -1,7 +1,7 @@ --liquibase formatted sql -- ============================================================================ ---changeset test-package-TEST-DATA-GENERATOR:1 endDelimiter:--// +--changeset michael.hoennig:test-package-TEST-DATA-GENERATOR endDelimiter:--// -- ---------------------------------------------------------------------------- /* Creates the given number of test packages for the given customer. @@ -22,17 +22,17 @@ begin pacName = cust.prefix || to_char(t, 'fm00'); custAdminUser = 'customer-admin@' || cust.prefix || '.example.com'; custAdminRole = 'test_customer#' || cust.prefix || ':ADMIN'; - call defineContext('creating RBAC test package', null, 'superuser-fran@hostsharing.net', custAdminRole); + call base.defineContext('creating RBAC test package', null, 'superuser-fran@hostsharing.net', custAdminRole); insert into test_package (customerUuid, name, description) values (cust.uuid, pacName, 'Here you can add your own description of package ' || pacName || '.') returning * into pac; - call grantRoleToUser( - getRoleId(testCustomerAdmin(cust)), - findRoleId(testPackageAdmin(pac)), - createRbacUser('pac-admin-' || pacName || '@' || cust.prefix || '.example.com'), + call rbac.grantRoleToSubject( + rbac.getRoleId(testCustomerAdmin(cust)), + rbac.findRoleId(testPackageAdmin(pac)), + rbac.create_subject('pac-admin-' || pacName || '@' || cust.prefix || '.example.com'), true); end loop; @@ -59,7 +59,7 @@ $$; -- ============================================================================ ---changeset test-package-TEST-DATA-GENERATION:1 –context=dev,tc endDelimiter:--// +--changeset michael.hoennig:test-package-TEST-DATA-GENERATION –context=dev,tc endDelimiter:--// -- ---------------------------------------------------------------------------- do language plpgsql $$ diff --git a/src/main/resources/db/changelog/2-test/203-test-domain/2030-test-domain.sql b/src/main/resources/db/changelog/2-test/203-test-domain/2030-test-domain.sql index 6b50dcae..c9db1c5e 100644 --- a/src/main/resources/db/changelog/2-test/203-test-domain/2030-test-domain.sql +++ b/src/main/resources/db/changelog/2-test/203-test-domain/2030-test-domain.sql @@ -1,12 +1,12 @@ --liquibase formatted sql -- ============================================================================ ---changeset test-domain-MAIN-TABLE:1 endDelimiter:--// +--changeset michael.hoennig:test-domain-MAIN-TABLE endDelimiter:--// -- ---------------------------------------------------------------------------- create table if not exists test_domain ( - uuid uuid unique references RbacObject (uuid), + uuid uuid unique references rbac.object (uuid), packageUuid uuid references test_package (uuid), name character varying(253), description character varying(96) diff --git a/src/main/resources/db/changelog/2-test/203-test-domain/2033-test-domain-rbac.md b/src/main/resources/db/changelog/2-test/203-test-domain/2033-test-domain-rbac.md index 72693972..a9716182 100644 --- a/src/main/resources/db/changelog/2-test/203-test-domain/2033-test-domain-rbac.md +++ b/src/main/resources/db/changelog/2-test/203-test-domain/2033-test-domain-rbac.md @@ -54,7 +54,7 @@ subgraph package.customer["`**package.customer**`"] end %% granting roles to roles -role:global:ADMIN -.->|XX| role:package.customer:OWNER +role:rbac.global:ADMIN -.->|XX| role:package.customer:OWNER role:package.customer:OWNER -.-> role:package.customer:ADMIN role:package.customer:ADMIN -.-> role:package.customer:TENANT role:package.customer:ADMIN -.-> role:package:OWNER diff --git a/src/main/resources/db/changelog/2-test/203-test-domain/2033-test-domain-rbac.sql b/src/main/resources/db/changelog/2-test/203-test-domain/2033-test-domain-rbac.sql index 042021c9..eb657b4c 100644 --- a/src/main/resources/db/changelog/2-test/203-test-domain/2033-test-domain-rbac.sql +++ b/src/main/resources/db/changelog/2-test/203-test-domain/2033-test-domain-rbac.sql @@ -3,21 +3,21 @@ -- ============================================================================ ---changeset test-domain-rbac-OBJECT:1 endDelimiter:--// +--changeset RbacObjectGenerator:test-domain-rbac-OBJECT endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRelatedRbacObject('test_domain'); +call rbac.generateRelatedRbacObject('test_domain'); --// -- ============================================================================ ---changeset test-domain-rbac-ROLE-DESCRIPTORS:1 endDelimiter:--// +--changeset RbacRoleDescriptorsGenerator:test-domain-rbac-ROLE-DESCRIPTORS endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRbacRoleDescriptors('testDomain', 'test_domain'); +call rbac.generateRbacRoleDescriptors('testDomain', 'test_domain'); --// -- ============================================================================ ---changeset test-domain-rbac-insert-trigger:1 endDelimiter:--// +--changeset RolesGrantsAndPermissionsGenerator:test-domain-rbac-insert-trigger endDelimiter:--// -- ---------------------------------------------------------------------------- /* @@ -33,27 +33,27 @@ declare newPackage test_package; begin - call enterTriggerForObjectUuid(NEW.uuid); + call rbac.enterTriggerForObjectUuid(NEW.uuid); SELECT * FROM test_package WHERE uuid = NEW.packageUuid INTO newPackage; assert newPackage.uuid is not null, format('newPackage must not be null for NEW.packageUuid = %s', NEW.packageUuid); - perform createRoleWithGrants( + perform rbac.defineRoleWithGrants( testDomainOWNER(NEW), permissions => array['DELETE', 'UPDATE'], incomingSuperRoles => array[testPackageADMIN(newPackage)], outgoingSubRoles => array[testPackageTENANT(newPackage)] ); - perform createRoleWithGrants( + perform rbac.defineRoleWithGrants( testDomainADMIN(NEW), permissions => array['SELECT'], incomingSuperRoles => array[testDomainOWNER(NEW)], outgoingSubRoles => array[testPackageTENANT(newPackage)] ); - call leaveTriggerForObjectUuid(NEW.uuid); + call rbac.leaveTriggerForObjectUuid(NEW.uuid); end; $$; /* @@ -77,7 +77,7 @@ execute procedure insertTriggerForTestDomain_tf(); -- ============================================================================ ---changeset test-domain-rbac-update-trigger:1 endDelimiter:--// +--changeset RolesGrantsAndPermissionsGenerator:test-domain-rbac-update-trigger endDelimiter:--// -- ---------------------------------------------------------------------------- /* @@ -95,7 +95,7 @@ declare newPackage test_package; begin - call enterTriggerForObjectUuid(NEW.uuid); + call rbac.enterTriggerForObjectUuid(NEW.uuid); SELECT * FROM test_package WHERE uuid = OLD.packageUuid INTO oldPackage; assert oldPackage.uuid is not null, format('oldPackage must not be null for OLD.packageUuid = %s', OLD.packageUuid); @@ -106,18 +106,18 @@ begin if NEW.packageUuid <> OLD.packageUuid then - call revokeRoleFromRole(testDomainOWNER(OLD), testPackageADMIN(oldPackage)); - call grantRoleToRole(testDomainOWNER(NEW), testPackageADMIN(newPackage)); + call rbac.revokeRoleFromRole(testDomainOWNER(OLD), testPackageADMIN(oldPackage)); + call rbac.grantRoleToRole(testDomainOWNER(NEW), testPackageADMIN(newPackage)); - call revokeRoleFromRole(testPackageTENANT(oldPackage), testDomainOWNER(OLD)); - call grantRoleToRole(testPackageTENANT(newPackage), testDomainOWNER(NEW)); + call rbac.revokeRoleFromRole(testPackageTENANT(oldPackage), testDomainOWNER(OLD)); + call rbac.grantRoleToRole(testPackageTENANT(newPackage), testDomainOWNER(NEW)); - call revokeRoleFromRole(testPackageTENANT(oldPackage), testDomainADMIN(OLD)); - call grantRoleToRole(testPackageTENANT(newPackage), testDomainADMIN(NEW)); + call rbac.revokeRoleFromRole(testPackageTENANT(oldPackage), testDomainADMIN(OLD)); + call rbac.grantRoleToRole(testPackageTENANT(newPackage), testDomainADMIN(NEW)); end if; - call leaveTriggerForObjectUuid(NEW.uuid); + call rbac.leaveTriggerForObjectUuid(NEW.uuid); end; $$; /* @@ -141,7 +141,7 @@ execute procedure updateTriggerForTestDomain_tf(); -- ============================================================================ ---changeset test-domain-rbac-GRANTING-INSERT-PERMISSION:1 endDelimiter:--// +--changeset InsertTriggerGenerator:test-domain-rbac-GRANTING-INSERT-PERMISSION endDelimiter:--// -- ---------------------------------------------------------------------------- -- granting INSERT permission to test_package ---------------------------- @@ -153,13 +153,13 @@ do language plpgsql $$ declare row test_package; begin - call defineContext('create INSERT INTO test_domain permissions for pre-exising test_package rows'); + call base.defineContext('create INSERT INTO test_domain permissions for pre-exising test_package rows'); FOR row IN SELECT * FROM test_package -- unconditional for all rows in that table LOOP - call grantPermissionToRole( - createPermission(row.uuid, 'INSERT', 'test_domain'), + call rbac.grantPermissionToRole( + rbac.createPermission(row.uuid, 'INSERT', 'test_domain'), testPackageADMIN(row)); END LOOP; end; @@ -174,22 +174,22 @@ create or replace function new_test_domain_grants_insert_to_test_package_tf() strict as $$ begin -- unconditional for all rows in that table - call grantPermissionToRole( - createPermission(NEW.uuid, 'INSERT', 'test_domain'), + call rbac.grantPermissionToRole( + rbac.createPermission(NEW.uuid, 'INSERT', 'test_domain'), testPackageADMIN(NEW)); -- end. return NEW; end; $$; -- z_... is to put it at the end of after insert triggers, to make sure the roles exist -create trigger z_new_test_domain_grants_insert_to_test_package_tg +create trigger z_new_test_domain_grants_after_insert_tg after insert on test_package for each row execute procedure new_test_domain_grants_insert_to_test_package_tf(); -- ============================================================================ ---changeset test_domain-rbac-CHECKING-INSERT-PERMISSION:1 endDelimiter:--// +--changeset InsertTriggerGenerator:test_domain-rbac-CHECKING-INSERT-PERMISSION endDelimiter:--// -- ---------------------------------------------------------------------------- /** @@ -202,12 +202,12 @@ declare superObjectUuid uuid; begin -- check INSERT permission via direct foreign key: NEW.packageUuid - if hasInsertPermission(NEW.packageUuid, 'test_domain') then + if rbac.hasInsertPermission(NEW.packageUuid, 'test_domain') then return NEW; end if; raise exception '[403] insert into test_domain values(%) not allowed for current subjects % (%)', - NEW, currentSubjects(), currentSubjectsUuids(); + NEW, base.currentSubjects(), rbac.currentSubjectOrAssumedRolesUuids(); end; $$; create trigger test_domain_insert_permission_check_tg @@ -218,10 +218,10 @@ create trigger test_domain_insert_permission_check_tg -- ============================================================================ ---changeset test-domain-rbac-IDENTITY-VIEW:1 endDelimiter:--// +--changeset RbacIdentityViewGenerator:test-domain-rbac-IDENTITY-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRbacIdentityViewFromProjection('test_domain', +call rbac.generateRbacIdentityViewFromProjection('test_domain', $idName$ name $idName$); @@ -229,9 +229,9 @@ call generateRbacIdentityViewFromProjection('test_domain', -- ============================================================================ ---changeset test-domain-rbac-RESTRICTED-VIEW:1 endDelimiter:--// +--changeset RbacRestrictedViewGenerator:test-domain-rbac-RESTRICTED-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRbacRestrictedView('test_domain', +call rbac.generateRbacRestrictedView('test_domain', $orderBy$ name $orderBy$, diff --git a/src/main/resources/db/changelog/2-test/203-test-domain/2038-test-domain-test-data.sql b/src/main/resources/db/changelog/2-test/203-test-domain/2038-test-domain-test-data.sql index e2aa870f..5cd9b4b0 100644 --- a/src/main/resources/db/changelog/2-test/203-test-domain/2038-test-domain-test-data.sql +++ b/src/main/resources/db/changelog/2-test/203-test-domain/2038-test-domain-test-data.sql @@ -1,7 +1,7 @@ --liquibase formatted sql -- ============================================================================ ---changeset hs-domain-TEST-DATA-GENERATOR:1 endDelimiter:--// +--changeset michael.hoennig:hs-domain-TEST-DATA-GENERATOR endDelimiter:--// -- ---------------------------------------------------------------------------- /* Creates the given count of test unix users for a single package. @@ -21,11 +21,11 @@ begin for t in 0..(domainCount-1) loop pacAdmin = 'pac-admin-' || pac.name || '@' || pac.custPrefix || '.example.com'; - call defineContext('creating RBAC test domain', null, pacAdmin, null); + call base.defineContext('creating RBAC test domain', null, pacAdmin, null); insert into test_domain (name, packageUuid) - values (pac.name || '-' || intToVarChar(t, 4), pac.uuid); + values (pac.name || '-' || base.intToVarChar(t, 4), pac.uuid); end loop; end; $$; @@ -54,7 +54,7 @@ end; $$; -- ============================================================================ ---changeset hs-domain-TEST-DATA-GENERATION:1 –context=dev,tc endDelimiter:--// +--changeset michael.hoennig:hs-domain-TEST-DATA-GENERATION –context=dev,tc endDelimiter:--// -- ---------------------------------------------------------------------------- do language plpgsql $$ diff --git a/src/main/resources/db/changelog/5-hs-office/501-contact/5010-hs-office-contact.sql b/src/main/resources/db/changelog/5-hs-office/501-contact/5010-hs-office-contact.sql index 514f2ca0..305d80d1 100644 --- a/src/main/resources/db/changelog/5-hs-office/501-contact/5010-hs-office-contact.sql +++ b/src/main/resources/db/changelog/5-hs-office/501-contact/5010-hs-office-contact.sql @@ -1,12 +1,12 @@ --liquibase formatted sql -- ============================================================================ ---changeset hs-office-contact-MAIN-TABLE:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-contact-MAIN-TABLE endDelimiter:--// -- ---------------------------------------------------------------------------- create table if not exists hs_office_contact ( - uuid uuid unique references RbacObject (uuid) initially deferred, + uuid uuid unique references rbac.object (uuid) initially deferred, version int not null default 0, caption varchar(128) not null, postalAddress text, @@ -17,8 +17,8 @@ create table if not exists hs_office_contact -- ============================================================================ ---changeset hs-office-contact-MAIN-TABLE-JOURNAL:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-contact-MAIN-TABLE-JOURNAL endDelimiter:--// -- ---------------------------------------------------------------------------- -call create_journal('hs_office_contact'); +call base.create_journal('hs_office_contact'); --// diff --git a/src/main/resources/db/changelog/5-hs-office/501-contact/5013-hs-office-contact-rbac.md b/src/main/resources/db/changelog/5-hs-office/501-contact/5013-hs-office-contact-rbac.md index fe736072..b91848c6 100644 --- a/src/main/resources/db/changelog/5-hs-office/501-contact/5013-hs-office-contact-rbac.md +++ b/src/main/resources/db/changelog/5-hs-office/501-contact/5013-hs-office-contact-rbac.md @@ -32,7 +32,7 @@ end user:creator ==> role:contact:OWNER %% granting roles to roles -role:global:ADMIN ==> role:contact:OWNER +role:rbac.global:ADMIN ==> role:contact:OWNER role:contact:OWNER ==> role:contact:ADMIN role:contact:ADMIN ==> role:contact:REFERRER @@ -40,6 +40,6 @@ role:contact:ADMIN ==> role:contact:REFERRER role:contact:OWNER ==> perm:contact:DELETE role:contact:ADMIN ==> perm:contact:UPDATE role:contact:REFERRER ==> perm:contact:SELECT -role:global:GUEST ==> perm:contact:INSERT +role:rbac.global:GUEST ==> perm:contact:INSERT ``` diff --git a/src/main/resources/db/changelog/5-hs-office/501-contact/5013-hs-office-contact-rbac.sql b/src/main/resources/db/changelog/5-hs-office/501-contact/5013-hs-office-contact-rbac.sql index d1fabf3e..eb83c6e7 100644 --- a/src/main/resources/db/changelog/5-hs-office/501-contact/5013-hs-office-contact-rbac.sql +++ b/src/main/resources/db/changelog/5-hs-office/501-contact/5013-hs-office-contact-rbac.sql @@ -3,21 +3,21 @@ -- ============================================================================ ---changeset hs-office-contact-rbac-OBJECT:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-contact-rbac-OBJECT endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRelatedRbacObject('hs_office_contact'); +call rbac.generateRelatedRbacObject('hs_office_contact'); --// -- ============================================================================ ---changeset hs-office-contact-rbac-ROLE-DESCRIPTORS:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-contact-rbac-ROLE-DESCRIPTORS endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRbacRoleDescriptors('hsOfficeContact', 'hs_office_contact'); +call rbac.generateRbacRoleDescriptors('hsOfficeContact', 'hs_office_contact'); --// -- ============================================================================ ---changeset hs-office-contact-rbac-insert-trigger:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-contact-rbac-insert-trigger endDelimiter:--// -- ---------------------------------------------------------------------------- /* @@ -32,28 +32,28 @@ create or replace procedure buildRbacSystemForHsOfficeContact( declare begin - call enterTriggerForObjectUuid(NEW.uuid); + call rbac.enterTriggerForObjectUuid(NEW.uuid); - perform createRoleWithGrants( + perform rbac.defineRoleWithGrants( hsOfficeContactOWNER(NEW), permissions => array['DELETE'], - incomingSuperRoles => array[globalADMIN()], - userUuids => array[currentUserUuid()] + incomingSuperRoles => array[rbac.globalAdmin()], + subjectUuids => array[rbac.currentSubjectUuid()] ); - perform createRoleWithGrants( + perform rbac.defineRoleWithGrants( hsOfficeContactADMIN(NEW), permissions => array['UPDATE'], incomingSuperRoles => array[hsOfficeContactOWNER(NEW)] ); - perform createRoleWithGrants( + perform rbac.defineRoleWithGrants( hsOfficeContactREFERRER(NEW), permissions => array['SELECT'], incomingSuperRoles => array[hsOfficeContactADMIN(NEW)] ); - call leaveTriggerForObjectUuid(NEW.uuid); + call rbac.leaveTriggerForObjectUuid(NEW.uuid); end; $$; /* @@ -77,10 +77,10 @@ execute procedure insertTriggerForHsOfficeContact_tf(); -- ============================================================================ ---changeset hs-office-contact-rbac-IDENTITY-VIEW:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-contact-rbac-IDENTITY-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRbacIdentityViewFromProjection('hs_office_contact', +call rbac.generateRbacIdentityViewFromProjection('hs_office_contact', $idName$ caption $idName$); @@ -88,9 +88,9 @@ call generateRbacIdentityViewFromProjection('hs_office_contact', -- ============================================================================ ---changeset hs-office-contact-rbac-RESTRICTED-VIEW:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-contact-rbac-RESTRICTED-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRbacRestrictedView('hs_office_contact', +call rbac.generateRbacRestrictedView('hs_office_contact', $orderBy$ caption $orderBy$, diff --git a/src/main/resources/db/changelog/5-hs-office/501-contact/5016-hs-office-contact-migration.sql b/src/main/resources/db/changelog/5-hs-office/501-contact/5016-hs-office-contact-migration.sql index 79cdd3bf..fe0f1553 100644 --- a/src/main/resources/db/changelog/5-hs-office/501-contact/5016-hs-office-contact-migration.sql +++ b/src/main/resources/db/changelog/5-hs-office/501-contact/5016-hs-office-contact-migration.sql @@ -4,7 +4,7 @@ -- Once we don't need the external remote views anymore, create revert changesets. -- ============================================================================ ---changeset hs-office-contact-MIGRATION-mapping:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-contact-MIGRATION-mapping endDelimiter:--// -- ---------------------------------------------------------------------------- CREATE TABLE hs_office_contact_legacy_id @@ -16,7 +16,7 @@ CREATE TABLE hs_office_contact_legacy_id -- ============================================================================ ---changeset hs-office-contact-MIGRATION-sequence:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-contact-MIGRATION-sequence endDelimiter:--// -- ---------------------------------------------------------------------------- CREATE SEQUENCE IF NOT EXISTS hs_office_contact_legacy_id_seq @@ -27,7 +27,7 @@ CREATE SEQUENCE IF NOT EXISTS hs_office_contact_legacy_id_seq -- ============================================================================ ---changeset hs-office-contact-MIGRATION-default:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-contact-MIGRATION-default endDelimiter:--// -- ---------------------------------------------------------------------------- ALTER TABLE hs_office_contact_legacy_id @@ -37,17 +37,17 @@ ALTER TABLE hs_office_contact_legacy_id --/ -- ============================================================================ ---changeset hs-office-contact-MIGRATION-insert:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-contact-MIGRATION-insert endDelimiter:--// -- ---------------------------------------------------------------------------- -CALL defineContext('schema-migration'); +CALL base.defineContext('schema-migration'); INSERT INTO hs_office_contact_legacy_id(uuid, contact_id) SELECT uuid, nextVal('hs_office_contact_legacy_id_seq') FROM hs_office_contact; --/ -- ============================================================================ ---changeset hs-office-contact-MIGRATION-insert-trigger:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-contact-MIGRATION-insert-trigger endDelimiter:--// -- ---------------------------------------------------------------------------- create or replace function insertContactLegacyIdMapping() returns trigger @@ -72,7 +72,7 @@ create trigger createContactLegacyIdMapping -- ============================================================================ ---changeset hs-office-contact-MIGRATION-delete-trigger:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-contact-MIGRATION-delete-trigger endDelimiter:--// -- ---------------------------------------------------------------------------- create or replace function deleteContactLegacyIdMapping() returns trigger diff --git a/src/main/resources/db/changelog/5-hs-office/501-contact/5018-hs-office-contact-test-data.sql b/src/main/resources/db/changelog/5-hs-office/501-contact/5018-hs-office-contact-test-data.sql index fbee80ad..7e77c396 100644 --- a/src/main/resources/db/changelog/5-hs-office/501-contact/5018-hs-office-contact-test-data.sql +++ b/src/main/resources/db/changelog/5-hs-office/501-contact/5018-hs-office-contact-test-data.sql @@ -2,7 +2,7 @@ -- ============================================================================ ---changeset hs-office-contact-TEST-DATA-GENERATOR:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-contact-TEST-DATA-GENERATOR endDelimiter:--// -- ---------------------------------------------------------------------------- /* @@ -14,10 +14,10 @@ declare postalAddr varchar; emailAddr varchar; begin - emailAddr = 'contact-admin@' || cleanIdentifier(contCaption) || '.example.com'; - call defineContext('creating contact test-data'); - perform createRbacUser(emailAddr); - call defineContext('creating contact test-data', null, emailAddr); + emailAddr = 'contact-admin@' || base.cleanIdentifier(contCaption) || '.example.com'; + call base.defineContext('creating contact test-data'); + perform rbac.create_subject(emailAddr); + call base.defineContext('creating contact test-data', null, emailAddr); postalAddr := E'Vorname Nachname\nStraße Hnr\nPLZ Stadt'; @@ -44,7 +44,7 @@ create or replace procedure createHsOfficeContactTestData( begin for t in startCount..endCount loop - call createHsOfficeContactTestData(intToVarChar(t, 4) || '#' || t); + call createHsOfficeContactTestData(base.intToVarChar(t, 4) || '#' || t); commit; end loop; end; $$; @@ -52,7 +52,7 @@ end; $$; -- ============================================================================ ---changeset hs-office-contact-TEST-DATA-GENERATION:1 –context=dev,tc endDelimiter:--// +--changeset michael.hoennig:hs-office-contact-TEST-DATA-GENERATION –context=dev,tc endDelimiter:--// -- ---------------------------------------------------------------------------- do language plpgsql $$ diff --git a/src/main/resources/db/changelog/5-hs-office/502-person/5020-hs-office-person.sql b/src/main/resources/db/changelog/5-hs-office/502-person/5020-hs-office-person.sql index 528b512c..30fa1477 100644 --- a/src/main/resources/db/changelog/5-hs-office/502-person/5020-hs-office-person.sql +++ b/src/main/resources/db/changelog/5-hs-office/502-person/5020-hs-office-person.sql @@ -1,7 +1,7 @@ --liquibase formatted sql -- ============================================================================ ---changeset hs-office-person-MAIN-TABLE:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-person-MAIN-TABLE endDelimiter:--// -- ---------------------------------------------------------------------------- CREATE TYPE HsOfficePersonType AS ENUM ( @@ -16,7 +16,7 @@ CREATE CAST (character varying as HsOfficePersonType) WITH INOUT AS IMPLICIT; create table if not exists hs_office_person ( - uuid uuid unique references RbacObject (uuid) initially deferred, + uuid uuid unique references rbac.object (uuid) initially deferred, version int not null default 0, personType HsOfficePersonType not null, tradeName varchar(96), @@ -28,8 +28,8 @@ create table if not exists hs_office_person -- ============================================================================ ---changeset hs-office-person-MAIN-TABLE-JOURNAL:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-person-MAIN-TABLE-JOURNAL endDelimiter:--// -- ---------------------------------------------------------------------------- -call create_journal('hs_office_person'); +call base.create_journal('hs_office_person'); --// diff --git a/src/main/resources/db/changelog/5-hs-office/502-person/5023-hs-office-person-rbac.md b/src/main/resources/db/changelog/5-hs-office/502-person/5023-hs-office-person-rbac.md index d0eebfdd..4ace6eed 100644 --- a/src/main/resources/db/changelog/5-hs-office/502-person/5023-hs-office-person-rbac.md +++ b/src/main/resources/db/changelog/5-hs-office/502-person/5023-hs-office-person-rbac.md @@ -32,12 +32,12 @@ end user:creator ==> role:person:OWNER %% granting roles to roles -role:global:ADMIN ==> role:person:OWNER +role:rbac.global:ADMIN ==> role:person:OWNER role:person:OWNER ==> role:person:ADMIN role:person:ADMIN ==> role:person:REFERRER %% granting permissions to roles -role:global:GUEST ==> perm:person:INSERT +role:rbac.global:GUEST ==> perm:person:INSERT role:person:OWNER ==> perm:person:DELETE role:person:ADMIN ==> perm:person:UPDATE role:person:REFERRER ==> perm:person:SELECT diff --git a/src/main/resources/db/changelog/5-hs-office/502-person/5023-hs-office-person-rbac.sql b/src/main/resources/db/changelog/5-hs-office/502-person/5023-hs-office-person-rbac.sql index bdaca63c..f652529f 100644 --- a/src/main/resources/db/changelog/5-hs-office/502-person/5023-hs-office-person-rbac.sql +++ b/src/main/resources/db/changelog/5-hs-office/502-person/5023-hs-office-person-rbac.sql @@ -3,21 +3,21 @@ -- ============================================================================ ---changeset hs-office-person-rbac-OBJECT:1 endDelimiter:--// +--changeset RbacObjectGenerator:hs-office-person-rbac-OBJECT endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRelatedRbacObject('hs_office_person'); +call rbac.generateRelatedRbacObject('hs_office_person'); --// -- ============================================================================ ---changeset hs-office-person-rbac-ROLE-DESCRIPTORS:1 endDelimiter:--// +--changeset RbacRoleDescriptorsGenerator:hs-office-person-rbac-ROLE-DESCRIPTORS endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRbacRoleDescriptors('hsOfficePerson', 'hs_office_person'); +call rbac.generateRbacRoleDescriptors('hsOfficePerson', 'hs_office_person'); --// -- ============================================================================ ---changeset hs-office-person-rbac-insert-trigger:1 endDelimiter:--// +--changeset RolesGrantsAndPermissionsGenerator:hs-office-person-rbac-insert-trigger endDelimiter:--// -- ---------------------------------------------------------------------------- /* @@ -32,28 +32,28 @@ create or replace procedure buildRbacSystemForHsOfficePerson( declare begin - call enterTriggerForObjectUuid(NEW.uuid); + call rbac.enterTriggerForObjectUuid(NEW.uuid); - perform createRoleWithGrants( + perform rbac.defineRoleWithGrants( hsOfficePersonOWNER(NEW), permissions => array['DELETE'], - incomingSuperRoles => array[globalADMIN()], - userUuids => array[currentUserUuid()] + incomingSuperRoles => array[rbac.globalADMIN()], + subjectUuids => array[rbac.currentSubjectUuid()] ); - perform createRoleWithGrants( + perform rbac.defineRoleWithGrants( hsOfficePersonADMIN(NEW), permissions => array['UPDATE'], incomingSuperRoles => array[hsOfficePersonOWNER(NEW)] ); - perform createRoleWithGrants( + perform rbac.defineRoleWithGrants( hsOfficePersonREFERRER(NEW), permissions => array['SELECT'], incomingSuperRoles => array[hsOfficePersonADMIN(NEW)] ); - call leaveTriggerForObjectUuid(NEW.uuid); + call rbac.leaveTriggerForObjectUuid(NEW.uuid); end; $$; /* @@ -77,10 +77,10 @@ execute procedure insertTriggerForHsOfficePerson_tf(); -- ============================================================================ ---changeset hs-office-person-rbac-IDENTITY-VIEW:1 endDelimiter:--// +--changeset RbacIdentityViewGenerator:hs-office-person-rbac-IDENTITY-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRbacIdentityViewFromProjection('hs_office_person', +call rbac.generateRbacIdentityViewFromProjection('hs_office_person', $idName$ concat(tradeName, familyName, givenName) $idName$); @@ -88,9 +88,9 @@ call generateRbacIdentityViewFromProjection('hs_office_person', -- ============================================================================ ---changeset hs-office-person-rbac-RESTRICTED-VIEW:1 endDelimiter:--// +--changeset RbacRestrictedViewGenerator:hs-office-person-rbac-RESTRICTED-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRbacRestrictedView('hs_office_person', +call rbac.generateRbacRestrictedView('hs_office_person', $orderBy$ concat(tradeName, familyName, givenName) $orderBy$, diff --git a/src/main/resources/db/changelog/5-hs-office/502-person/5028-hs-office-person-test-data.sql b/src/main/resources/db/changelog/5-hs-office/502-person/5028-hs-office-person-test-data.sql index 8900886c..c9b078e2 100644 --- a/src/main/resources/db/changelog/5-hs-office/502-person/5028-hs-office-person-test-data.sql +++ b/src/main/resources/db/changelog/5-hs-office/502-person/5028-hs-office-person-test-data.sql @@ -2,7 +2,7 @@ -- ============================================================================ ---changeset hs-office-person-TEST-DATA-GENERATOR:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-person-TEST-DATA-GENERATOR endDelimiter:--// -- ---------------------------------------------------------------------------- /* @@ -20,10 +20,10 @@ declare emailAddr varchar; begin fullName := concat_ws(', ', newTradeName, newFamilyName, newGivenName); - emailAddr = 'person-' || left(cleanIdentifier(fullName), 32) || '@example.com'; - call defineContext('creating person test-data'); - perform createRbacUser(emailAddr); - call defineContext('creating person test-data', null, emailAddr); + emailAddr = 'person-' || left(base.cleanIdentifier(fullName), 32) || '@example.com'; + call base.defineContext('creating person test-data'); + perform rbac.create_subject(emailAddr); + call base.defineContext('creating person test-data', null, emailAddr); raise notice 'creating test person: % by %', fullName, emailAddr; insert @@ -43,7 +43,7 @@ create or replace procedure createTestPersonTestData( begin for t in startCount..endCount loop - call createHsOfficePersonTestData('LP', intToVarChar(t, 4)); + call createHsOfficePersonTestData('LP', base.intToVarChar(t, 4)); commit; end loop; end; $$; @@ -51,7 +51,7 @@ end; $$; -- ============================================================================ ---changeset hs-office-person-TEST-DATA-GENERATION:1 –context=dev,tc endDelimiter:--// +--changeset michael.hoennig:hs-office-person-TEST-DATA-GENERATION –context=dev,tc endDelimiter:--// -- ---------------------------------------------------------------------------- do language plpgsql $$ diff --git a/src/main/resources/db/changelog/5-hs-office/503-relation/5030-hs-office-relation.sql b/src/main/resources/db/changelog/5-hs-office/503-relation/5030-hs-office-relation.sql index 1c207177..387bacd3 100644 --- a/src/main/resources/db/changelog/5-hs-office/503-relation/5030-hs-office-relation.sql +++ b/src/main/resources/db/changelog/5-hs-office/503-relation/5030-hs-office-relation.sql @@ -1,7 +1,7 @@ --liquibase formatted sql -- ============================================================================ ---changeset hs-office-relation-MAIN-TABLE:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-relation-MAIN-TABLE endDelimiter:--// -- ---------------------------------------------------------------------------- CREATE TYPE HsOfficeRelationType AS ENUM ( @@ -18,7 +18,7 @@ CREATE CAST (character varying as HsOfficeRelationType) WITH INOUT AS IMPLICIT; create table if not exists hs_office_relation ( - uuid uuid unique references RbacObject (uuid) initially deferred, -- on delete cascade + uuid uuid unique references rbac.object (uuid) initially deferred, -- on delete cascade version int not null default 0, anchorUuid uuid not null references hs_office_person(uuid), holderUuid uuid not null references hs_office_person(uuid), @@ -30,8 +30,8 @@ create table if not exists hs_office_relation -- ============================================================================ ---changeset hs-office-relation-MAIN-TABLE-JOURNAL:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-relation-MAIN-TABLE-JOURNAL endDelimiter:--// -- ---------------------------------------------------------------------------- -call create_journal('hs_office_relation'); +call base.create_journal('hs_office_relation'); --// diff --git a/src/main/resources/db/changelog/5-hs-office/503-relation/5033-hs-office-relation-rbac-REPRESENTATIVE.md b/src/main/resources/db/changelog/5-hs-office/503-relation/5033-hs-office-relation-rbac-REPRESENTATIVE.md index 0d944401..743aa7bf 100644 --- a/src/main/resources/db/changelog/5-hs-office/503-relation/5033-hs-office-relation-rbac-REPRESENTATIVE.md +++ b/src/main/resources/db/changelog/5-hs-office/503-relation/5033-hs-office-relation-rbac-REPRESENTATIVE.md @@ -72,16 +72,16 @@ end user:creator ==> role:relation:OWNER %% granting roles to roles -role:global:ADMIN -.-> role:anchorPerson:OWNER +role:rbac.global:ADMIN -.-> role:anchorPerson:OWNER role:anchorPerson:OWNER -.-> role:anchorPerson:ADMIN role:anchorPerson:ADMIN -.-> role:anchorPerson:REFERRER -role:global:ADMIN -.-> role:holderPerson:OWNER +role:rbac.global:ADMIN -.-> role:holderPerson:OWNER role:holderPerson:OWNER -.-> role:holderPerson:ADMIN role:holderPerson:ADMIN -.-> role:holderPerson:REFERRER -role:global:ADMIN -.-> role:contact:OWNER +role:rbac.global:ADMIN -.-> role:contact:OWNER role:contact:OWNER -.-> role:contact:ADMIN role:contact:ADMIN -.-> role:contact:REFERRER -role:global:ADMIN ==> role:relation:OWNER +role:rbac.global:ADMIN ==> role:relation:OWNER role:holderPerson:ADMIN ==> role:relation:OWNER role:relation:OWNER ==> role:relation:ADMIN role:relation:ADMIN ==> role:anchorPerson:OWNER diff --git a/src/main/resources/db/changelog/5-hs-office/503-relation/5033-hs-office-relation-rbac.md b/src/main/resources/db/changelog/5-hs-office/503-relation/5033-hs-office-relation-rbac.md index 47d4d220..ccd95235 100644 --- a/src/main/resources/db/changelog/5-hs-office/503-relation/5033-hs-office-relation-rbac.md +++ b/src/main/resources/db/changelog/5-hs-office/503-relation/5033-hs-office-relation-rbac.md @@ -72,16 +72,16 @@ end user:creator ==> role:relation:OWNER %% granting roles to roles -role:global:ADMIN -.-> role:anchorPerson:OWNER +role:rbac.global:ADMIN -.-> role:anchorPerson:OWNER role:anchorPerson:OWNER -.-> role:anchorPerson:ADMIN role:anchorPerson:ADMIN -.-> role:anchorPerson:REFERRER -role:global:ADMIN -.-> role:holderPerson:OWNER +role:rbac.global:ADMIN -.-> role:holderPerson:OWNER role:holderPerson:OWNER -.-> role:holderPerson:ADMIN role:holderPerson:ADMIN -.-> role:holderPerson:REFERRER -role:global:ADMIN -.-> role:contact:OWNER +role:rbac.global:ADMIN -.-> role:contact:OWNER role:contact:OWNER -.-> role:contact:ADMIN role:contact:ADMIN -.-> role:contact:REFERRER -role:global:ADMIN ==> role:relation:OWNER +role:rbac.global:ADMIN ==> role:relation:OWNER role:relation:OWNER ==> role:relation:ADMIN role:relation:ADMIN ==> role:relation:AGENT role:relation:AGENT ==> role:relation:TENANT diff --git a/src/main/resources/db/changelog/5-hs-office/503-relation/5033-hs-office-relation-rbac.sql b/src/main/resources/db/changelog/5-hs-office/503-relation/5033-hs-office-relation-rbac.sql index 63c2061a..d6f36ad5 100644 --- a/src/main/resources/db/changelog/5-hs-office/503-relation/5033-hs-office-relation-rbac.sql +++ b/src/main/resources/db/changelog/5-hs-office/503-relation/5033-hs-office-relation-rbac.sql @@ -3,21 +3,21 @@ -- ============================================================================ ---changeset hs-office-relation-rbac-OBJECT:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-relation-rbac-OBJECT endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRelatedRbacObject('hs_office_relation'); +call rbac.generateRelatedRbacObject('hs_office_relation'); --// -- ============================================================================ ---changeset hs-office-relation-rbac-ROLE-DESCRIPTORS:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-relation-rbac-ROLE-DESCRIPTORS endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRbacRoleDescriptors('hsOfficeRelation', 'hs_office_relation'); +call rbac.generateRbacRoleDescriptors('hsOfficeRelation', 'hs_office_relation'); --// -- ============================================================================ ---changeset hs-office-relation-rbac-insert-trigger:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-relation-rbac-insert-trigger endDelimiter:--// -- ---------------------------------------------------------------------------- /* @@ -35,7 +35,7 @@ declare newContact hs_office_contact; begin - call enterTriggerForObjectUuid(NEW.uuid); + call rbac.enterTriggerForObjectUuid(NEW.uuid); SELECT * FROM hs_office_person WHERE uuid = NEW.holderUuid INTO newHolderPerson; assert newHolderPerson.uuid is not null, format('newHolderPerson must not be null for NEW.holderUuid = %s', NEW.holderUuid); @@ -47,25 +47,25 @@ begin assert newContact.uuid is not null, format('newContact must not be null for NEW.contactUuid = %s', NEW.contactUuid); - perform createRoleWithGrants( + perform rbac.defineRoleWithGrants( hsOfficeRelationOWNER(NEW), permissions => array['DELETE'], - incomingSuperRoles => array[globalADMIN()], - userUuids => array[currentUserUuid()] + incomingSuperRoles => array[rbac.globalAdmin()], + subjectUuids => array[rbac.currentSubjectUuid()] ); - perform createRoleWithGrants( + perform rbac.defineRoleWithGrants( hsOfficeRelationADMIN(NEW), permissions => array['UPDATE'], incomingSuperRoles => array[hsOfficeRelationOWNER(NEW)] ); - perform createRoleWithGrants( + perform rbac.defineRoleWithGrants( hsOfficeRelationAGENT(NEW), incomingSuperRoles => array[hsOfficeRelationADMIN(NEW)] ); - perform createRoleWithGrants( + perform rbac.defineRoleWithGrants( hsOfficeRelationTENANT(NEW), permissions => array['SELECT'], incomingSuperRoles => array[ @@ -78,15 +78,15 @@ begin ); IF NEW.type = 'REPRESENTATIVE' THEN - call grantRoleToRole(hsOfficePersonOWNER(newAnchorPerson), hsOfficeRelationADMIN(NEW)); - call grantRoleToRole(hsOfficeRelationAGENT(NEW), hsOfficePersonADMIN(newAnchorPerson)); - call grantRoleToRole(hsOfficeRelationOWNER(NEW), hsOfficePersonADMIN(newHolderPerson)); + call rbac.grantRoleToRole(hsOfficePersonOWNER(newAnchorPerson), hsOfficeRelationADMIN(NEW)); + call rbac.grantRoleToRole(hsOfficeRelationAGENT(NEW), hsOfficePersonADMIN(newAnchorPerson)); + call rbac.grantRoleToRole(hsOfficeRelationOWNER(NEW), hsOfficePersonADMIN(newHolderPerson)); ELSE - call grantRoleToRole(hsOfficeRelationAGENT(NEW), hsOfficePersonADMIN(newHolderPerson)); - call grantRoleToRole(hsOfficeRelationOWNER(NEW), hsOfficePersonADMIN(newAnchorPerson)); + call rbac.grantRoleToRole(hsOfficeRelationAGENT(NEW), hsOfficePersonADMIN(newHolderPerson)); + call rbac.grantRoleToRole(hsOfficeRelationOWNER(NEW), hsOfficePersonADMIN(newAnchorPerson)); END IF; - call leaveTriggerForObjectUuid(NEW.uuid); + call rbac.leaveTriggerForObjectUuid(NEW.uuid); end; $$; /* @@ -110,7 +110,7 @@ execute procedure insertTriggerForHsOfficeRelation_tf(); -- ============================================================================ ---changeset hs-office-relation-rbac-update-trigger:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-relation-rbac-update-trigger endDelimiter:--// -- ---------------------------------------------------------------------------- /* @@ -125,7 +125,7 @@ create or replace procedure updateRbacRulesForHsOfficeRelation( begin if NEW.contactUuid is distinct from OLD.contactUuid then - delete from rbacgrants g where g.grantedbytriggerof = OLD.uuid; + delete from rbac.grants g where g.grantedbytriggerof = OLD.uuid; call buildRbacSystemForHsOfficeRelation(NEW); end if; end; $$; @@ -151,7 +151,7 @@ execute procedure updateTriggerForHsOfficeRelation_tf(); -- ============================================================================ ---changeset hs-office-relation-rbac-GRANTING-INSERT-PERMISSION:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-relation-rbac-GRANTING-INSERT-PERMISSION endDelimiter:--// -- ---------------------------------------------------------------------------- -- granting INSERT permission to hs_office_person ---------------------------- @@ -163,13 +163,13 @@ do language plpgsql $$ declare row hs_office_person; begin - call defineContext('create INSERT INTO hs_office_relation permissions for pre-exising hs_office_person rows'); + call base.defineContext('create INSERT INTO hs_office_relation permissions for pre-exising hs_office_person rows'); FOR row IN SELECT * FROM hs_office_person -- unconditional for all rows in that table LOOP - call grantPermissionToRole( - createPermission(row.uuid, 'INSERT', 'hs_office_relation'), + call rbac.grantPermissionToRole( + rbac.createPermission(row.uuid, 'INSERT', 'hs_office_relation'), hsOfficePersonADMIN(row)); END LOOP; end; @@ -184,8 +184,8 @@ create or replace function new_hs_office_relation_grants_insert_to_hs_office_per strict as $$ begin -- unconditional for all rows in that table - call grantPermissionToRole( - createPermission(NEW.uuid, 'INSERT', 'hs_office_relation'), + call rbac.grantPermissionToRole( + rbac.createPermission(NEW.uuid, 'INSERT', 'hs_office_relation'), hsOfficePersonADMIN(NEW)); -- end. return NEW; @@ -199,7 +199,7 @@ execute procedure new_hs_office_relation_grants_insert_to_hs_office_person_tf(); -- ============================================================================ ---changeset hs_office_relation-rbac-CHECKING-INSERT-PERMISSION:1 endDelimiter:--// +--changeset michael.hoennig:hs_office_relation-rbac-CHECKING-INSERT-PERMISSION endDelimiter:--// -- ---------------------------------------------------------------------------- /** @@ -212,12 +212,12 @@ declare superObjectUuid uuid; begin -- check INSERT permission via direct foreign key: NEW.anchorUuid - if hasInsertPermission(NEW.anchorUuid, 'hs_office_relation') then + if rbac.hasInsertPermission(NEW.anchorUuid, 'hs_office_relation') then return NEW; end if; raise exception '[403] insert into hs_office_relation not allowed for current subjects % (%)', - currentSubjects(), currentSubjectsUuids(); + base.currentSubjects(), rbac.currentSubjectOrAssumedRolesUuids(); end; $$; create trigger hs_office_relation_insert_permission_check_tg @@ -228,10 +228,10 @@ create trigger hs_office_relation_insert_permission_check_tg -- ============================================================================ ---changeset hs-office-relation-rbac-IDENTITY-VIEW:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-relation-rbac-IDENTITY-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRbacIdentityViewFromProjection('hs_office_relation', +call rbac.generateRbacIdentityViewFromProjection('hs_office_relation', $idName$ (select idName from hs_office_person_iv p where p.uuid = anchorUuid) || '-with-' || target.type || '-' @@ -241,9 +241,9 @@ call generateRbacIdentityViewFromProjection('hs_office_relation', -- ============================================================================ ---changeset hs-office-relation-rbac-RESTRICTED-VIEW:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-relation-rbac-RESTRICTED-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRbacRestrictedView('hs_office_relation', +call rbac.generateRbacRestrictedView('hs_office_relation', $orderBy$ (select idName from hs_office_person_iv p where p.uuid = target.holderUuid) $orderBy$, diff --git a/src/main/resources/db/changelog/5-hs-office/503-relation/5038-hs-office-relation-test-data.sql b/src/main/resources/db/changelog/5-hs-office/503-relation/5038-hs-office-relation-test-data.sql index 120ffe62..39c204a9 100644 --- a/src/main/resources/db/changelog/5-hs-office/503-relation/5038-hs-office-relation-test-data.sql +++ b/src/main/resources/db/changelog/5-hs-office/503-relation/5038-hs-office-relation-test-data.sql @@ -2,7 +2,7 @@ -- ============================================================================ ---changeset hs-office-relation-TEST-DATA-GENERATOR:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-relation-TEST-DATA-GENERATOR endDelimiter:--// -- ---------------------------------------------------------------------------- /* @@ -22,7 +22,7 @@ declare contact hs_office_contact; begin - idName := cleanIdentifier( anchorPersonName || '-' || holderPersonName); + idName := base.cleanIdentifier( anchorPersonName || '-' || holderPersonName); select p.* into anchorPerson @@ -69,8 +69,8 @@ declare begin for t in startCount..endCount loop - select p.* from hs_office_person p where tradeName = intToVarChar(t, 4) into person; - select c.* from hs_office_contact c where c.caption = intToVarChar(t, 4) || '#' || t into contact; + select p.* from hs_office_person p where tradeName = base.intToVarChar(t, 4) into person; + select c.* from hs_office_contact c where c.caption = base.intToVarChar(t, 4) || '#' || t into contact; call createHsOfficeRelationTestData(person.uuid, contact.uuid, 'REPRESENTATIVE'); commit; @@ -80,12 +80,12 @@ end; $$; -- ============================================================================ ---changeset hs-office-relation-TEST-DATA-GENERATION:1 –context=dev,tc endDelimiter:--// +--changeset michael.hoennig:hs-office-relation-TEST-DATA-GENERATION –context=dev,tc endDelimiter:--// -- ---------------------------------------------------------------------------- do language plpgsql $$ begin - call defineContext('creating relation test-data', null, 'superuser-alex@hostsharing.net', 'global#global:ADMIN'); + call base.defineContext('creating relation test-data', null, 'superuser-alex@hostsharing.net', 'rbac.global#global:ADMIN'); call createHsOfficeRelationTestData('First GmbH', 'PARTNER', 'Hostsharing eG', 'first contact'); call createHsOfficeRelationTestData('Firby', 'REPRESENTATIVE', 'First GmbH', 'first contact'); diff --git a/src/main/resources/db/changelog/5-hs-office/504-partner/5040-hs-office-partner.sql b/src/main/resources/db/changelog/5-hs-office/504-partner/5040-hs-office-partner.sql index a8a88adc..eae97773 100644 --- a/src/main/resources/db/changelog/5-hs-office/504-partner/5040-hs-office-partner.sql +++ b/src/main/resources/db/changelog/5-hs-office/504-partner/5040-hs-office-partner.sql @@ -2,12 +2,12 @@ -- ============================================================================ ---changeset hs-office-partner-DETAILS-TABLE:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-partner-DETAILS-TABLE endDelimiter:--// -- ---------------------------------------------------------------------------- create table hs_office_partner_details ( - uuid uuid unique references RbacObject (uuid) initially deferred, + uuid uuid unique references rbac.object (uuid) initially deferred, version int not null default 0, registrationOffice varchar(96), registrationNumber varchar(96), @@ -20,19 +20,19 @@ create table hs_office_partner_details -- ============================================================================ ---changeset hs-office-partner-DETAILS-TABLE-JOURNAL:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-partner-DETAILS-TABLE-JOURNAL endDelimiter:--// -- ---------------------------------------------------------------------------- -call create_journal('hs_office_partner_details'); +call base.create_journal('hs_office_partner_details'); --// -- ============================================================================ ---changeset hs-office-partner-MAIN-TABLE:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-partner-MAIN-TABLE endDelimiter:--// -- ---------------------------------------------------------------------------- create table hs_office_partner ( - uuid uuid unique references RbacObject (uuid) initially deferred, + uuid uuid unique references rbac.object (uuid) initially deferred, version int not null default 0, partnerNumber numeric(5) unique not null, partnerRelUuid uuid not null references hs_office_relation(uuid), -- deleted in after delete trigger @@ -42,7 +42,7 @@ create table hs_office_partner -- ============================================================================ ---changeset hs-office-partner-DELETE-DEPENDENTS-TRIGGER:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-partner-DELETE-DEPENDENTS-TRIGGER endDelimiter:--// -- ---------------------------------------------------------------------------- /** @@ -80,8 +80,8 @@ create trigger hs_office_partner_delete_dependents_trigger execute procedure deleteHsOfficeDependentsOnPartnerDelete(); -- ============================================================================ ---changeset hs-office-partner-MAIN-TABLE-JOURNAL:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-partner-MAIN-TABLE-JOURNAL endDelimiter:--// -- ---------------------------------------------------------------------------- -call create_journal('hs_office_partner'); +call base.create_journal('hs_office_partner'); --// diff --git a/src/main/resources/db/changelog/5-hs-office/504-partner/5043-hs-office-partner-rbac.md b/src/main/resources/db/changelog/5-hs-office/504-partner/5043-hs-office-partner-rbac.md index ecbe29de..162d81bf 100644 --- a/src/main/resources/db/changelog/5-hs-office/504-partner/5043-hs-office-partner-rbac.md +++ b/src/main/resources/db/changelog/5-hs-office/504-partner/5043-hs-office-partner-rbac.md @@ -87,16 +87,16 @@ subgraph partnerRel.holderPerson["`**partnerRel.holderPerson**`"] end %% granting roles to roles -role:global:ADMIN -.-> role:partnerRel.anchorPerson:OWNER +role:rbac.global:ADMIN -.-> role:partnerRel.anchorPerson:OWNER role:partnerRel.anchorPerson:OWNER -.-> role:partnerRel.anchorPerson:ADMIN role:partnerRel.anchorPerson:ADMIN -.-> role:partnerRel.anchorPerson:REFERRER -role:global:ADMIN -.-> role:partnerRel.holderPerson:OWNER +role:rbac.global:ADMIN -.-> role:partnerRel.holderPerson:OWNER role:partnerRel.holderPerson:OWNER -.-> role:partnerRel.holderPerson:ADMIN role:partnerRel.holderPerson:ADMIN -.-> role:partnerRel.holderPerson:REFERRER -role:global:ADMIN -.-> role:partnerRel.contact:OWNER +role:rbac.global:ADMIN -.-> role:partnerRel.contact:OWNER role:partnerRel.contact:OWNER -.-> role:partnerRel.contact:ADMIN role:partnerRel.contact:ADMIN -.-> role:partnerRel.contact:REFERRER -role:global:ADMIN -.-> role:partnerRel:OWNER +role:rbac.global:ADMIN -.-> role:partnerRel:OWNER role:partnerRel:OWNER -.-> role:partnerRel:ADMIN role:partnerRel:ADMIN -.-> role:partnerRel:AGENT role:partnerRel:AGENT -.-> role:partnerRel:TENANT @@ -108,7 +108,7 @@ role:partnerRel.anchorPerson:ADMIN -.-> role:partnerRel:OWNER role:partnerRel.holderPerson:ADMIN -.-> role:partnerRel:AGENT %% granting permissions to roles -role:global:ADMIN ==> perm:partner:INSERT +role:rbac.global:ADMIN ==> perm:partner:INSERT role:partnerRel:OWNER ==> perm:partner:DELETE role:partnerRel:ADMIN ==> perm:partner:UPDATE role:partnerRel:TENANT ==> perm:partner:SELECT diff --git a/src/main/resources/db/changelog/5-hs-office/504-partner/5043-hs-office-partner-rbac.sql b/src/main/resources/db/changelog/5-hs-office/504-partner/5043-hs-office-partner-rbac.sql index bd1c673d..4c8aab39 100644 --- a/src/main/resources/db/changelog/5-hs-office/504-partner/5043-hs-office-partner-rbac.sql +++ b/src/main/resources/db/changelog/5-hs-office/504-partner/5043-hs-office-partner-rbac.sql @@ -3,21 +3,21 @@ -- ============================================================================ ---changeset hs-office-partner-rbac-OBJECT:1 endDelimiter:--// +--changeset RbacObjectGenerator:hs-office-partner-rbac-OBJECT endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRelatedRbacObject('hs_office_partner'); +call rbac.generateRelatedRbacObject('hs_office_partner'); --// -- ============================================================================ ---changeset hs-office-partner-rbac-ROLE-DESCRIPTORS:1 endDelimiter:--// +--changeset RbacRoleDescriptorsGenerator:hs-office-partner-rbac-ROLE-DESCRIPTORS endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRbacRoleDescriptors('hsOfficePartner', 'hs_office_partner'); +call rbac.generateRbacRoleDescriptors('hsOfficePartner', 'hs_office_partner'); --// -- ============================================================================ ---changeset hs-office-partner-rbac-insert-trigger:1 endDelimiter:--// +--changeset RolesGrantsAndPermissionsGenerator:hs-office-partner-rbac-insert-trigger endDelimiter:--// -- ---------------------------------------------------------------------------- /* @@ -34,7 +34,7 @@ declare newPartnerDetails hs_office_partner_details; begin - call enterTriggerForObjectUuid(NEW.uuid); + call rbac.enterTriggerForObjectUuid(NEW.uuid); SELECT * FROM hs_office_relation WHERE uuid = NEW.partnerRelUuid INTO newPartnerRel; assert newPartnerRel.uuid is not null, format('newPartnerRel must not be null for NEW.partnerRelUuid = %s', NEW.partnerRelUuid); @@ -42,14 +42,14 @@ begin SELECT * FROM hs_office_partner_details WHERE uuid = NEW.detailsUuid INTO newPartnerDetails; assert newPartnerDetails.uuid is not null, format('newPartnerDetails must not be null for NEW.detailsUuid = %s', NEW.detailsUuid); - call grantPermissionToRole(createPermission(NEW.uuid, 'DELETE'), hsOfficeRelationOWNER(newPartnerRel)); - call grantPermissionToRole(createPermission(NEW.uuid, 'SELECT'), hsOfficeRelationTENANT(newPartnerRel)); - call grantPermissionToRole(createPermission(NEW.uuid, 'UPDATE'), hsOfficeRelationADMIN(newPartnerRel)); - call grantPermissionToRole(createPermission(newPartnerDetails.uuid, 'DELETE'), hsOfficeRelationOWNER(newPartnerRel)); - call grantPermissionToRole(createPermission(newPartnerDetails.uuid, 'SELECT'), hsOfficeRelationAGENT(newPartnerRel)); - call grantPermissionToRole(createPermission(newPartnerDetails.uuid, 'UPDATE'), hsOfficeRelationAGENT(newPartnerRel)); + call rbac.grantPermissionToRole(rbac.createPermission(NEW.uuid, 'DELETE'), hsOfficeRelationOWNER(newPartnerRel)); + call rbac.grantPermissionToRole(rbac.createPermission(NEW.uuid, 'SELECT'), hsOfficeRelationTENANT(newPartnerRel)); + call rbac.grantPermissionToRole(rbac.createPermission(NEW.uuid, 'UPDATE'), hsOfficeRelationADMIN(newPartnerRel)); + call rbac.grantPermissionToRole(rbac.createPermission(newPartnerDetails.uuid, 'DELETE'), hsOfficeRelationOWNER(newPartnerRel)); + call rbac.grantPermissionToRole(rbac.createPermission(newPartnerDetails.uuid, 'SELECT'), hsOfficeRelationAGENT(newPartnerRel)); + call rbac.grantPermissionToRole(rbac.createPermission(newPartnerDetails.uuid, 'UPDATE'), hsOfficeRelationAGENT(newPartnerRel)); - call leaveTriggerForObjectUuid(NEW.uuid); + call rbac.leaveTriggerForObjectUuid(NEW.uuid); end; $$; /* @@ -73,7 +73,7 @@ execute procedure insertTriggerForHsOfficePartner_tf(); -- ============================================================================ ---changeset hs-office-partner-rbac-update-trigger:1 endDelimiter:--// +--changeset RolesGrantsAndPermissionsGenerator:hs-office-partner-rbac-update-trigger endDelimiter:--// -- ---------------------------------------------------------------------------- /* @@ -93,7 +93,7 @@ declare newPartnerDetails hs_office_partner_details; begin - call enterTriggerForObjectUuid(NEW.uuid); + call rbac.enterTriggerForObjectUuid(NEW.uuid); SELECT * FROM hs_office_relation WHERE uuid = OLD.partnerRelUuid INTO oldPartnerRel; assert oldPartnerRel.uuid is not null, format('oldPartnerRel must not be null for OLD.partnerRelUuid = %s', OLD.partnerRelUuid); @@ -110,27 +110,27 @@ begin if NEW.partnerRelUuid <> OLD.partnerRelUuid then - call revokePermissionFromRole(getPermissionId(OLD.uuid, 'DELETE'), hsOfficeRelationOWNER(oldPartnerRel)); - call grantPermissionToRole(createPermission(NEW.uuid, 'DELETE'), hsOfficeRelationOWNER(newPartnerRel)); + call rbac.revokePermissionFromRole(rbac.getPermissionId(OLD.uuid, 'DELETE'), hsOfficeRelationOWNER(oldPartnerRel)); + call rbac.grantPermissionToRole(rbac.createPermission(NEW.uuid, 'DELETE'), hsOfficeRelationOWNER(newPartnerRel)); - call revokePermissionFromRole(getPermissionId(OLD.uuid, 'UPDATE'), hsOfficeRelationADMIN(oldPartnerRel)); - call grantPermissionToRole(createPermission(NEW.uuid, 'UPDATE'), hsOfficeRelationADMIN(newPartnerRel)); + call rbac.revokePermissionFromRole(rbac.getPermissionId(OLD.uuid, 'UPDATE'), hsOfficeRelationADMIN(oldPartnerRel)); + call rbac.grantPermissionToRole(rbac.createPermission(NEW.uuid, 'UPDATE'), hsOfficeRelationADMIN(newPartnerRel)); - call revokePermissionFromRole(getPermissionId(OLD.uuid, 'SELECT'), hsOfficeRelationTENANT(oldPartnerRel)); - call grantPermissionToRole(createPermission(NEW.uuid, 'SELECT'), hsOfficeRelationTENANT(newPartnerRel)); + call rbac.revokePermissionFromRole(rbac.getPermissionId(OLD.uuid, 'SELECT'), hsOfficeRelationTENANT(oldPartnerRel)); + call rbac.grantPermissionToRole(rbac.createPermission(NEW.uuid, 'SELECT'), hsOfficeRelationTENANT(newPartnerRel)); - call revokePermissionFromRole(getPermissionId(oldPartnerDetails.uuid, 'DELETE'), hsOfficeRelationOWNER(oldPartnerRel)); - call grantPermissionToRole(createPermission(newPartnerDetails.uuid, 'DELETE'), hsOfficeRelationOWNER(newPartnerRel)); + call rbac.revokePermissionFromRole(rbac.getPermissionId(oldPartnerDetails.uuid, 'DELETE'), hsOfficeRelationOWNER(oldPartnerRel)); + call rbac.grantPermissionToRole(rbac.createPermission(newPartnerDetails.uuid, 'DELETE'), hsOfficeRelationOWNER(newPartnerRel)); - call revokePermissionFromRole(getPermissionId(oldPartnerDetails.uuid, 'UPDATE'), hsOfficeRelationAGENT(oldPartnerRel)); - call grantPermissionToRole(createPermission(newPartnerDetails.uuid, 'UPDATE'), hsOfficeRelationAGENT(newPartnerRel)); + call rbac.revokePermissionFromRole(rbac.getPermissionId(oldPartnerDetails.uuid, 'UPDATE'), hsOfficeRelationAGENT(oldPartnerRel)); + call rbac.grantPermissionToRole(rbac.createPermission(newPartnerDetails.uuid, 'UPDATE'), hsOfficeRelationAGENT(newPartnerRel)); - call revokePermissionFromRole(getPermissionId(oldPartnerDetails.uuid, 'SELECT'), hsOfficeRelationAGENT(oldPartnerRel)); - call grantPermissionToRole(createPermission(newPartnerDetails.uuid, 'SELECT'), hsOfficeRelationAGENT(newPartnerRel)); + call rbac.revokePermissionFromRole(rbac.getPermissionId(oldPartnerDetails.uuid, 'SELECT'), hsOfficeRelationAGENT(oldPartnerRel)); + call rbac.grantPermissionToRole(rbac.createPermission(newPartnerDetails.uuid, 'SELECT'), hsOfficeRelationAGENT(newPartnerRel)); end if; - call leaveTriggerForObjectUuid(NEW.uuid); + call rbac.leaveTriggerForObjectUuid(NEW.uuid); end; $$; /* @@ -154,26 +154,26 @@ execute procedure updateTriggerForHsOfficePartner_tf(); -- ============================================================================ ---changeset hs-office-partner-rbac-GRANTING-INSERT-PERMISSION:1 endDelimiter:--// +--changeset InsertTriggerGenerator:hs-office-partner-rbac-GRANTING-INSERT-PERMISSION endDelimiter:--// -- ---------------------------------------------------------------------------- --- granting INSERT permission to global ---------------------------- +-- granting INSERT permission to rbac.global ---------------------------- /* - Grants INSERT INTO hs_office_partner permissions to specified role of pre-existing global rows. + Grants INSERT INTO hs_office_partner permissions to specified role of pre-existing rbac.global rows. */ do language plpgsql $$ declare - row global; + row rbac.global; begin - call defineContext('create INSERT INTO hs_office_partner permissions for pre-exising global rows'); + call base.defineContext('create INSERT INTO hs_office_partner permissions for pre-exising rbac.global rows'); - FOR row IN SELECT * FROM global + FOR row IN SELECT * FROM rbac.global -- unconditional for all rows in that table LOOP - call grantPermissionToRole( - createPermission(row.uuid, 'INSERT', 'hs_office_partner'), - globalADMIN()); + call rbac.grantPermissionToRole( + rbac.createPermission(row.uuid, 'INSERT', 'hs_office_partner'), + rbac.globalADMIN()); END LOOP; end; $$; @@ -181,28 +181,28 @@ $$; /** Grants hs_office_partner INSERT permission to specified role of new global rows. */ -create or replace function new_hs_office_partner_grants_insert_to_global_tf() +create or replace function rbac.new_hsof_partner_grants_insert_to_global_tf() returns trigger language plpgsql strict as $$ begin -- unconditional for all rows in that table - call grantPermissionToRole( - createPermission(NEW.uuid, 'INSERT', 'hs_office_partner'), - globalADMIN()); + call rbac.grantPermissionToRole( + rbac.createPermission(NEW.uuid, 'INSERT', 'hs_office_partner'), + rbac.globalADMIN()); -- end. return NEW; end; $$; -- z_... is to put it at the end of after insert triggers, to make sure the roles exist -create trigger z_new_hs_office_partner_grants_insert_to_global_tg - after insert on global +create trigger z_new_hs_office_partner_grants_after_insert_tg + after insert on rbac.global for each row -execute procedure new_hs_office_partner_grants_insert_to_global_tf(); +execute procedure rbac.new_hsof_partner_grants_insert_to_global_tf(); -- ============================================================================ ---changeset hs_office_partner-rbac-CHECKING-INSERT-PERMISSION:1 endDelimiter:--// +--changeset InsertTriggerGenerator:hs_office_partner-rbac-CHECKING-INSERT-PERMISSION endDelimiter:--// -- ---------------------------------------------------------------------------- /** @@ -214,13 +214,13 @@ create or replace function hs_office_partner_insert_permission_check_tf() declare superObjectUuid uuid; begin - -- check INSERT INSERT if global ADMIN - if isGlobalAdmin() then + -- check INSERT INSERT if rbac.global ADMIN + if rbac.isGlobalAdmin() then return NEW; end if; raise exception '[403] insert into hs_office_partner values(%) not allowed for current subjects % (%)', - NEW, currentSubjects(), currentSubjectsUuids(); + NEW, base.currentSubjects(), rbac.currentSubjectOrAssumedRolesUuids(); end; $$; create trigger hs_office_partner_insert_permission_check_tg @@ -231,10 +231,10 @@ create trigger hs_office_partner_insert_permission_check_tg -- ============================================================================ ---changeset hs-office-partner-rbac-IDENTITY-VIEW:1 endDelimiter:--// +--changeset RbacIdentityViewGenerator:hs-office-partner-rbac-IDENTITY-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRbacIdentityViewFromProjection('hs_office_partner', +call rbac.generateRbacIdentityViewFromProjection('hs_office_partner', $idName$ 'P-' || partnerNumber $idName$); @@ -242,9 +242,9 @@ call generateRbacIdentityViewFromProjection('hs_office_partner', -- ============================================================================ ---changeset hs-office-partner-rbac-RESTRICTED-VIEW:1 endDelimiter:--// +--changeset RbacRestrictedViewGenerator:hs-office-partner-rbac-RESTRICTED-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRbacRestrictedView('hs_office_partner', +call rbac.generateRbacRestrictedView('hs_office_partner', $orderBy$ 'P-' || partnerNumber $orderBy$, diff --git a/src/main/resources/db/changelog/5-hs-office/504-partner/5044-hs-office-partner-details-rbac.md b/src/main/resources/db/changelog/5-hs-office/504-partner/5044-hs-office-partner-details-rbac.md index 347896bb..e79f14f4 100644 --- a/src/main/resources/db/changelog/5-hs-office/504-partner/5044-hs-office-partner-details-rbac.md +++ b/src/main/resources/db/changelog/5-hs-office/504-partner/5044-hs-office-partner-details-rbac.md @@ -18,6 +18,6 @@ subgraph partnerDetails["`**partnerDetails**`"] end %% granting permissions to roles -role:global:ADMIN ==> perm:partnerDetails:INSERT +role:rbac.global:ADMIN ==> perm:partnerDetails:INSERT ``` diff --git a/src/main/resources/db/changelog/5-hs-office/504-partner/5044-hs-office-partner-details-rbac.sql b/src/main/resources/db/changelog/5-hs-office/504-partner/5044-hs-office-partner-details-rbac.sql index 8a7f2725..840003e3 100644 --- a/src/main/resources/db/changelog/5-hs-office/504-partner/5044-hs-office-partner-details-rbac.sql +++ b/src/main/resources/db/changelog/5-hs-office/504-partner/5044-hs-office-partner-details-rbac.sql @@ -3,21 +3,21 @@ -- ============================================================================ ---changeset hs-office-partner-details-rbac-OBJECT:1 endDelimiter:--// +--changeset RbacObjectGenerator:hs-office-partner-details-rbac-OBJECT endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRelatedRbacObject('hs_office_partner_details'); +call rbac.generateRelatedRbacObject('hs_office_partner_details'); --// -- ============================================================================ ---changeset hs-office-partner-details-rbac-ROLE-DESCRIPTORS:1 endDelimiter:--// +--changeset RbacRoleDescriptorsGenerator:hs-office-partner-details-rbac-ROLE-DESCRIPTORS endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRbacRoleDescriptors('hsOfficePartnerDetails', 'hs_office_partner_details'); +call rbac.generateRbacRoleDescriptors('hsOfficePartnerDetails', 'hs_office_partner_details'); --// -- ============================================================================ ---changeset hs-office-partner-details-rbac-insert-trigger:1 endDelimiter:--// +--changeset RolesGrantsAndPermissionsGenerator:hs-office-partner-details-rbac-insert-trigger endDelimiter:--// -- ---------------------------------------------------------------------------- /* @@ -32,9 +32,9 @@ create or replace procedure buildRbacSystemForHsOfficePartnerDetails( declare begin - call enterTriggerForObjectUuid(NEW.uuid); + call rbac.enterTriggerForObjectUuid(NEW.uuid); - call leaveTriggerForObjectUuid(NEW.uuid); + call rbac.leaveTriggerForObjectUuid(NEW.uuid); end; $$; /* @@ -58,26 +58,26 @@ execute procedure insertTriggerForHsOfficePartnerDetails_tf(); -- ============================================================================ ---changeset hs-office-partner-details-rbac-GRANTING-INSERT-PERMISSION:1 endDelimiter:--// +--changeset InsertTriggerGenerator:hs-office-partner-details-rbac-GRANTING-INSERT-PERMISSION endDelimiter:--// -- ---------------------------------------------------------------------------- --- granting INSERT permission to global ---------------------------- +-- granting INSERT permission to rbac.global ---------------------------- /* - Grants INSERT INTO hs_office_partner_details permissions to specified role of pre-existing global rows. + Grants INSERT INTO hs_office_partner_details permissions to specified role of pre-existing rbac.global rows. */ do language plpgsql $$ declare - row global; + row rbac.global; begin - call defineContext('create INSERT INTO hs_office_partner_details permissions for pre-exising global rows'); + call base.defineContext('create INSERT INTO hs_office_partner_details permissions for pre-exising rbac.global rows'); - FOR row IN SELECT * FROM global + FOR row IN SELECT * FROM rbac.global -- unconditional for all rows in that table LOOP - call grantPermissionToRole( - createPermission(row.uuid, 'INSERT', 'hs_office_partner_details'), - globalADMIN()); + call rbac.grantPermissionToRole( + rbac.createPermission(row.uuid, 'INSERT', 'hs_office_partner_details'), + rbac.globalADMIN()); END LOOP; end; $$; @@ -85,28 +85,28 @@ $$; /** Grants hs_office_partner_details INSERT permission to specified role of new global rows. */ -create or replace function new_hs_office_partner_details_grants_insert_to_global_tf() +create or replace function rbac.new_hsof_partner_details_grants_insert_to_global_tf() returns trigger language plpgsql strict as $$ begin -- unconditional for all rows in that table - call grantPermissionToRole( - createPermission(NEW.uuid, 'INSERT', 'hs_office_partner_details'), - globalADMIN()); + call rbac.grantPermissionToRole( + rbac.createPermission(NEW.uuid, 'INSERT', 'hs_office_partner_details'), + rbac.globalADMIN()); -- end. return NEW; end; $$; -- z_... is to put it at the end of after insert triggers, to make sure the roles exist -create trigger z_new_hs_office_partner_details_grants_insert_to_global_tg - after insert on global +create trigger z_new_hs_office_partner_details_grants_after_insert_tg + after insert on rbac.global for each row -execute procedure new_hs_office_partner_details_grants_insert_to_global_tf(); +execute procedure rbac.new_hsof_partner_details_grants_insert_to_global_tf(); -- ============================================================================ ---changeset hs_office_partner_details-rbac-CHECKING-INSERT-PERMISSION:1 endDelimiter:--// +--changeset InsertTriggerGenerator:hs_office_partner_details-rbac-CHECKING-INSERT-PERMISSION endDelimiter:--// -- ---------------------------------------------------------------------------- /** @@ -118,13 +118,13 @@ create or replace function hs_office_partner_details_insert_permission_check_tf( declare superObjectUuid uuid; begin - -- check INSERT INSERT if global ADMIN - if isGlobalAdmin() then + -- check INSERT INSERT if rbac.global ADMIN + if rbac.isGlobalAdmin() then return NEW; end if; raise exception '[403] insert into hs_office_partner_details values(%) not allowed for current subjects % (%)', - NEW, currentSubjects(), currentSubjectsUuids(); + NEW, base.currentSubjects(), rbac.currentSubjectOrAssumedRolesUuids(); end; $$; create trigger hs_office_partner_details_insert_permission_check_tg @@ -135,10 +135,10 @@ create trigger hs_office_partner_details_insert_permission_check_tg -- ============================================================================ ---changeset hs-office-partner-details-rbac-IDENTITY-VIEW:1 endDelimiter:--// +--changeset RbacIdentityViewGenerator:hs-office-partner-details-rbac-IDENTITY-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRbacIdentityViewFromQuery('hs_office_partner_details', +call rbac.generateRbacIdentityViewFromQuery('hs_office_partner_details', $idName$ SELECT partnerDetails.uuid as uuid, partner_iv.idName as idName FROM hs_office_partner_details AS partnerDetails @@ -149,9 +149,9 @@ call generateRbacIdentityViewFromQuery('hs_office_partner_details', -- ============================================================================ ---changeset hs-office-partner-details-rbac-RESTRICTED-VIEW:1 endDelimiter:--// +--changeset RbacRestrictedViewGenerator:hs-office-partner-details-rbac-RESTRICTED-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRbacRestrictedView('hs_office_partner_details', +call rbac.generateRbacRestrictedView('hs_office_partner_details', $orderBy$ uuid $orderBy$, diff --git a/src/main/resources/db/changelog/5-hs-office/504-partner/5046-hs-office-partner-migration.sql b/src/main/resources/db/changelog/5-hs-office/504-partner/5046-hs-office-partner-migration.sql index f48e99d5..9facdb93 100644 --- a/src/main/resources/db/changelog/5-hs-office/504-partner/5046-hs-office-partner-migration.sql +++ b/src/main/resources/db/changelog/5-hs-office/504-partner/5046-hs-office-partner-migration.sql @@ -4,7 +4,7 @@ -- Once we don't need the external remote views anymore, create revert changesets. -- ============================================================================ ---changeset hs-office-partner-MIGRATION-mapping:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-partner-MIGRATION-mapping endDelimiter:--// -- ---------------------------------------------------------------------------- CREATE TABLE hs_office_partner_legacy_id @@ -16,7 +16,7 @@ CREATE TABLE hs_office_partner_legacy_id -- ============================================================================ ---changeset hs-office-partner-MIGRATION-sequence:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-partner-MIGRATION-sequence endDelimiter:--// -- ---------------------------------------------------------------------------- CREATE SEQUENCE IF NOT EXISTS hs_office_partner_legacy_id_seq @@ -27,7 +27,7 @@ CREATE SEQUENCE IF NOT EXISTS hs_office_partner_legacy_id_seq -- ============================================================================ ---changeset hs-office-partner-MIGRATION-default:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-partner-MIGRATION-default endDelimiter:--// -- ---------------------------------------------------------------------------- ALTER TABLE hs_office_partner_legacy_id @@ -36,17 +36,17 @@ ALTER TABLE hs_office_partner_legacy_id --/ -- ============================================================================ ---changeset hs-office-partner-MIGRATION-insert:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-partner-MIGRATION-insert endDelimiter:--// -- ---------------------------------------------------------------------------- -CALL defineContext('schema-migration'); +CALL base.defineContext('schema-migration'); INSERT INTO hs_office_partner_legacy_id(uuid, bp_id) SELECT uuid, nextVal('hs_office_partner_legacy_id_seq') FROM hs_office_partner; --/ -- ============================================================================ ---changeset hs-office-partner-MIGRATION-insert-trigger:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-partner-MIGRATION-insert-trigger endDelimiter:--// -- ---------------------------------------------------------------------------- create or replace function insertPartnerLegacyIdMapping() returns trigger @@ -71,7 +71,7 @@ create trigger createPartnerLegacyIdMapping -- ============================================================================ ---changeset hs-office-partner-MIGRATION-delete-trigger:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-partner-MIGRATION-delete-trigger endDelimiter:--// -- ---------------------------------------------------------------------------- create or replace function deletePartnerLegacyIdMapping() returns trigger diff --git a/src/main/resources/db/changelog/5-hs-office/504-partner/5048-hs-office-partner-test-data.sql b/src/main/resources/db/changelog/5-hs-office/504-partner/5048-hs-office-partner-test-data.sql index 4ac1dff9..c28192b3 100644 --- a/src/main/resources/db/changelog/5-hs-office/504-partner/5048-hs-office-partner-test-data.sql +++ b/src/main/resources/db/changelog/5-hs-office/504-partner/5048-hs-office-partner-test-data.sql @@ -2,7 +2,7 @@ -- ============================================================================ ---changeset hs-office-partner-TEST-DATA-GENERATOR:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-partner-TEST-DATA-GENERATOR endDelimiter:--// -- ---------------------------------------------------------------------------- /* @@ -21,7 +21,7 @@ declare relatedPerson hs_office_person; relatedDetailsUuid uuid; begin - idName := cleanIdentifier( partnerPersonName|| '-' || contactCaption); + idName := base.cleanIdentifier( partnerPersonName|| '-' || contactCaption); select p.* from hs_office_person p where p.tradeName = mandantTradeName @@ -66,12 +66,12 @@ end; $$; -- ============================================================================ ---changeset hs-office-partner-TEST-DATA-GENERATION:1 –context=dev,tc endDelimiter:--// +--changeset michael.hoennig:hs-office-partner-TEST-DATA-GENERATION –context=dev,tc endDelimiter:--// -- ---------------------------------------------------------------------------- do language plpgsql $$ begin - call defineContext('creating partner test-data ', null, 'superuser-alex@hostsharing.net', 'global#global:ADMIN'); + call base.defineContext('creating partner test-data ', null, 'superuser-alex@hostsharing.net', 'rbac.global#global:ADMIN'); call createHsOfficePartnerTestData('Hostsharing eG', 10001, 'First GmbH', 'first contact'); call createHsOfficePartnerTestData('Hostsharing eG', 10002, 'Second e.K.', 'second contact'); diff --git a/src/main/resources/db/changelog/5-hs-office/505-bankaccount/5050-hs-office-bankaccount.sql b/src/main/resources/db/changelog/5-hs-office/505-bankaccount/5050-hs-office-bankaccount.sql index e061a3ca..8b27cbe9 100644 --- a/src/main/resources/db/changelog/5-hs-office/505-bankaccount/5050-hs-office-bankaccount.sql +++ b/src/main/resources/db/changelog/5-hs-office/505-bankaccount/5050-hs-office-bankaccount.sql @@ -1,11 +1,11 @@ -- ============================================================================ ---changeset hs-office-bankaccount-MAIN-TABLE:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-bankaccount-MAIN-TABLE endDelimiter:--// -- ---------------------------------------------------------------------------- create table hs_office_bankaccount ( - uuid uuid unique references RbacObject (uuid) initially deferred, + uuid uuid unique references rbac.object (uuid) initially deferred, version int not null default 0, holder varchar(64) not null, iban varchar(34) not null, @@ -15,8 +15,8 @@ create table hs_office_bankaccount -- ============================================================================ ---changeset hs-office-bankaccount-MAIN-TABLE-JOURNAL:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-bankaccount-MAIN-TABLE-JOURNAL endDelimiter:--// -- ---------------------------------------------------------------------------- -call create_journal('hs_office_bankaccount'); +call base.create_journal('hs_office_bankaccount'); --// diff --git a/src/main/resources/db/changelog/5-hs-office/505-bankaccount/5053-hs-office-bankaccount-rbac.md b/src/main/resources/db/changelog/5-hs-office/505-bankaccount/5053-hs-office-bankaccount-rbac.md index 4558815c..7a2b3af9 100644 --- a/src/main/resources/db/changelog/5-hs-office/505-bankaccount/5053-hs-office-bankaccount-rbac.md +++ b/src/main/resources/db/changelog/5-hs-office/505-bankaccount/5053-hs-office-bankaccount-rbac.md @@ -32,12 +32,12 @@ end user:creator ==> role:bankAccount:OWNER %% granting roles to roles -role:global:ADMIN ==> role:bankAccount:OWNER +role:rbac.global:ADMIN ==> role:bankAccount:OWNER role:bankAccount:OWNER ==> role:bankAccount:ADMIN role:bankAccount:ADMIN ==> role:bankAccount:REFERRER %% granting permissions to roles -role:global:GUEST ==> perm:bankAccount:INSERT +role:rbac.global:GUEST ==> perm:bankAccount:INSERT role:bankAccount:OWNER ==> perm:bankAccount:DELETE role:bankAccount:ADMIN ==> perm:bankAccount:UPDATE role:bankAccount:REFERRER ==> perm:bankAccount:SELECT diff --git a/src/main/resources/db/changelog/5-hs-office/505-bankaccount/5053-hs-office-bankaccount-rbac.sql b/src/main/resources/db/changelog/5-hs-office/505-bankaccount/5053-hs-office-bankaccount-rbac.sql index 724dd658..4b8895d7 100644 --- a/src/main/resources/db/changelog/5-hs-office/505-bankaccount/5053-hs-office-bankaccount-rbac.sql +++ b/src/main/resources/db/changelog/5-hs-office/505-bankaccount/5053-hs-office-bankaccount-rbac.sql @@ -3,21 +3,21 @@ -- ============================================================================ ---changeset hs-office-bankaccount-rbac-OBJECT:1 endDelimiter:--// +--changeset RbacObjectGenerator:hs-office-bankaccount-rbac-OBJECT endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRelatedRbacObject('hs_office_bankaccount'); +call rbac.generateRelatedRbacObject('hs_office_bankaccount'); --// -- ============================================================================ ---changeset hs-office-bankaccount-rbac-ROLE-DESCRIPTORS:1 endDelimiter:--// +--changeset RbacRoleDescriptorsGenerator:hs-office-bankaccount-rbac-ROLE-DESCRIPTORS endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRbacRoleDescriptors('hsOfficeBankAccount', 'hs_office_bankaccount'); +call rbac.generateRbacRoleDescriptors('hsOfficeBankAccount', 'hs_office_bankaccount'); --// -- ============================================================================ ---changeset hs-office-bankaccount-rbac-insert-trigger:1 endDelimiter:--// +--changeset RolesGrantsAndPermissionsGenerator:hs-office-bankaccount-rbac-insert-trigger endDelimiter:--// -- ---------------------------------------------------------------------------- /* @@ -32,28 +32,28 @@ create or replace procedure buildRbacSystemForHsOfficeBankAccount( declare begin - call enterTriggerForObjectUuid(NEW.uuid); + call rbac.enterTriggerForObjectUuid(NEW.uuid); - perform createRoleWithGrants( + perform rbac.defineRoleWithGrants( hsOfficeBankAccountOWNER(NEW), permissions => array['DELETE'], - incomingSuperRoles => array[globalADMIN()], - userUuids => array[currentUserUuid()] + incomingSuperRoles => array[rbac.globalADMIN()], + subjectUuids => array[rbac.currentSubjectUuid()] ); - perform createRoleWithGrants( + perform rbac.defineRoleWithGrants( hsOfficeBankAccountADMIN(NEW), permissions => array['UPDATE'], incomingSuperRoles => array[hsOfficeBankAccountOWNER(NEW)] ); - perform createRoleWithGrants( + perform rbac.defineRoleWithGrants( hsOfficeBankAccountREFERRER(NEW), permissions => array['SELECT'], incomingSuperRoles => array[hsOfficeBankAccountADMIN(NEW)] ); - call leaveTriggerForObjectUuid(NEW.uuid); + call rbac.leaveTriggerForObjectUuid(NEW.uuid); end; $$; /* @@ -77,10 +77,10 @@ execute procedure insertTriggerForHsOfficeBankAccount_tf(); -- ============================================================================ ---changeset hs-office-bankaccount-rbac-IDENTITY-VIEW:1 endDelimiter:--// +--changeset RbacIdentityViewGenerator:hs-office-bankaccount-rbac-IDENTITY-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRbacIdentityViewFromProjection('hs_office_bankaccount', +call rbac.generateRbacIdentityViewFromProjection('hs_office_bankaccount', $idName$ iban $idName$); @@ -88,9 +88,9 @@ call generateRbacIdentityViewFromProjection('hs_office_bankaccount', -- ============================================================================ ---changeset hs-office-bankaccount-rbac-RESTRICTED-VIEW:1 endDelimiter:--// +--changeset RbacRestrictedViewGenerator:hs-office-bankaccount-rbac-RESTRICTED-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRbacRestrictedView('hs_office_bankaccount', +call rbac.generateRbacRestrictedView('hs_office_bankaccount', $orderBy$ iban $orderBy$, diff --git a/src/main/resources/db/changelog/5-hs-office/505-bankaccount/5058-hs-office-bankaccount-test-data.sql b/src/main/resources/db/changelog/5-hs-office/505-bankaccount/5058-hs-office-bankaccount-test-data.sql index 338ab61c..aa28bdf4 100644 --- a/src/main/resources/db/changelog/5-hs-office/505-bankaccount/5058-hs-office-bankaccount-test-data.sql +++ b/src/main/resources/db/changelog/5-hs-office/505-bankaccount/5058-hs-office-bankaccount-test-data.sql @@ -2,7 +2,7 @@ -- ============================================================================ ---changeset hs-office-bankaccount-TEST-DATA-GENERATOR:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-bankaccount-TEST-DATA-GENERATOR endDelimiter:--// -- ---------------------------------------------------------------------------- /* @@ -13,9 +13,9 @@ create or replace procedure createHsOfficeBankAccountTestData(givenHolder varcha declare emailAddr varchar; begin - emailAddr = 'bankaccount-admin@' || cleanIdentifier(givenHolder) || '.example.com'; - perform createRbacUser(emailAddr); - call defineContext('creating bankaccount test-data', null, emailAddr); + emailAddr = 'bankaccount-admin@' || base.cleanIdentifier(givenHolder) || '.example.com'; + perform rbac.create_subject(emailAddr); + call base.defineContext('creating bankaccount test-data', null, emailAddr); raise notice 'creating test bankaccount: %', givenHolder; insert @@ -26,12 +26,12 @@ end; $$; -- ============================================================================ ---changeset hs-office-bankaccount-TEST-DATA-GENERATION:1 –context=dev,tc endDelimiter:--// +--changeset michael.hoennig:hs-office-bankaccount-TEST-DATA-GENERATION –context=dev,tc endDelimiter:--// -- ---------------------------------------------------------------------------- do language plpgsql $$ begin - call defineContext('creating bankaccount test-data'); + call base.defineContext('creating bankaccount test-data'); -- IBANs+BICs taken from https://ibanvalidieren.de/beispiele.html call createHsOfficeBankAccountTestData('First GmbH', 'DE02120300000000202051', 'BYLADEM1001'); diff --git a/src/main/resources/db/changelog/5-hs-office/506-debitor/5060-hs-office-debitor.sql b/src/main/resources/db/changelog/5-hs-office/506-debitor/5060-hs-office-debitor.sql index bbf72543..3ea372f7 100644 --- a/src/main/resources/db/changelog/5-hs-office/506-debitor/5060-hs-office-debitor.sql +++ b/src/main/resources/db/changelog/5-hs-office/506-debitor/5060-hs-office-debitor.sql @@ -1,12 +1,12 @@ --liquibase formatted sql -- ============================================================================ ---changeset hs-office-debitor-MAIN-TABLE:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-debitor-MAIN-TABLE endDelimiter:--// -- ---------------------------------------------------------------------------- create table hs_office_debitor ( - uuid uuid unique references RbacObject (uuid) initially deferred, + uuid uuid unique references rbac.object (uuid) initially deferred, version int not null default 0, debitorNumberSuffix char(2) not null check (debitorNumberSuffix::text ~ '^[0-9][0-9]$'), debitorRelUuid uuid not null references hs_office_relation(uuid), @@ -25,7 +25,7 @@ create table hs_office_debitor -- ============================================================================ ---changeset hs-office-debitor-DELETE-DEPENDENTS-TRIGGER:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-debitor-DELETE-DEPENDENTS-TRIGGER endDelimiter:--// -- ---------------------------------------------------------------------------- /** @@ -58,8 +58,8 @@ execute procedure deleteHsOfficeDependentsOnDebitorDelete(); -- ============================================================================ ---changeset hs-office-debitor-MAIN-TABLE-JOURNAL:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-debitor-MAIN-TABLE-JOURNAL endDelimiter:--// -- ---------------------------------------------------------------------------- -call create_journal('hs_office_debitor'); +call base.create_journal('hs_office_debitor'); --// diff --git a/src/main/resources/db/changelog/5-hs-office/506-debitor/5063-hs-office-debitor-rbac.md b/src/main/resources/db/changelog/5-hs-office/506-debitor/5063-hs-office-debitor-rbac.md index ef8bc404..7caebefa 100644 --- a/src/main/resources/db/changelog/5-hs-office/506-debitor/5063-hs-office-debitor-rbac.md +++ b/src/main/resources/db/changelog/5-hs-office/506-debitor/5063-hs-office-debitor-rbac.md @@ -140,16 +140,16 @@ subgraph refundBankAccount["`**refundBankAccount**`"] end %% granting roles to roles -role:global:ADMIN -.-> role:debitorRel.anchorPerson:OWNER +role:rbac.global:ADMIN -.-> role:debitorRel.anchorPerson:OWNER role:debitorRel.anchorPerson:OWNER -.-> role:debitorRel.anchorPerson:ADMIN role:debitorRel.anchorPerson:ADMIN -.-> role:debitorRel.anchorPerson:REFERRER -role:global:ADMIN -.-> role:debitorRel.holderPerson:OWNER +role:rbac.global:ADMIN -.-> role:debitorRel.holderPerson:OWNER role:debitorRel.holderPerson:OWNER -.-> role:debitorRel.holderPerson:ADMIN role:debitorRel.holderPerson:ADMIN -.-> role:debitorRel.holderPerson:REFERRER -role:global:ADMIN -.-> role:debitorRel.contact:OWNER +role:rbac.global:ADMIN -.-> role:debitorRel.contact:OWNER role:debitorRel.contact:OWNER -.-> role:debitorRel.contact:ADMIN role:debitorRel.contact:ADMIN -.-> role:debitorRel.contact:REFERRER -role:global:ADMIN -.-> role:debitorRel:OWNER +role:rbac.global:ADMIN -.-> role:debitorRel:OWNER role:debitorRel:OWNER -.-> role:debitorRel:ADMIN role:debitorRel:ADMIN -.-> role:debitorRel:AGENT role:debitorRel:AGENT -.-> role:debitorRel:TENANT @@ -159,21 +159,21 @@ role:debitorRel:TENANT -.-> role:debitorRel.holderPerson:REFERRER role:debitorRel:TENANT -.-> role:debitorRel.contact:REFERRER role:debitorRel.anchorPerson:ADMIN -.-> role:debitorRel:OWNER role:debitorRel.holderPerson:ADMIN -.-> role:debitorRel:AGENT -role:global:ADMIN -.-> role:refundBankAccount:OWNER +role:rbac.global:ADMIN -.-> role:refundBankAccount:OWNER role:refundBankAccount:OWNER -.-> role:refundBankAccount:ADMIN role:refundBankAccount:ADMIN -.-> role:refundBankAccount:REFERRER role:refundBankAccount:ADMIN ==> role:debitorRel:AGENT role:debitorRel:AGENT ==> role:refundBankAccount:REFERRER -role:global:ADMIN -.-> role:partnerRel.anchorPerson:OWNER +role:rbac.global:ADMIN -.-> role:partnerRel.anchorPerson:OWNER role:partnerRel.anchorPerson:OWNER -.-> role:partnerRel.anchorPerson:ADMIN role:partnerRel.anchorPerson:ADMIN -.-> role:partnerRel.anchorPerson:REFERRER -role:global:ADMIN -.-> role:partnerRel.holderPerson:OWNER +role:rbac.global:ADMIN -.-> role:partnerRel.holderPerson:OWNER role:partnerRel.holderPerson:OWNER -.-> role:partnerRel.holderPerson:ADMIN role:partnerRel.holderPerson:ADMIN -.-> role:partnerRel.holderPerson:REFERRER -role:global:ADMIN -.-> role:partnerRel.contact:OWNER +role:rbac.global:ADMIN -.-> role:partnerRel.contact:OWNER role:partnerRel.contact:OWNER -.-> role:partnerRel.contact:ADMIN role:partnerRel.contact:ADMIN -.-> role:partnerRel.contact:REFERRER -role:global:ADMIN -.-> role:partnerRel:OWNER +role:rbac.global:ADMIN -.-> role:partnerRel:OWNER role:partnerRel:OWNER -.-> role:partnerRel:ADMIN role:partnerRel:ADMIN -.-> role:partnerRel:AGENT role:partnerRel:AGENT -.-> role:partnerRel:TENANT @@ -188,7 +188,7 @@ role:partnerRel:AGENT ==> role:debitorRel:AGENT role:debitorRel:AGENT ==> role:partnerRel:TENANT %% granting permissions to roles -role:global:ADMIN ==> perm:debitor:INSERT +role:rbac.global:ADMIN ==> perm:debitor:INSERT role:debitorRel:OWNER ==> perm:debitor:DELETE role:debitorRel:ADMIN ==> perm:debitor:UPDATE role:debitorRel:TENANT ==> perm:debitor:SELECT diff --git a/src/main/resources/db/changelog/5-hs-office/506-debitor/5063-hs-office-debitor-rbac.sql b/src/main/resources/db/changelog/5-hs-office/506-debitor/5063-hs-office-debitor-rbac.sql index 8e91d7e7..6800076f 100644 --- a/src/main/resources/db/changelog/5-hs-office/506-debitor/5063-hs-office-debitor-rbac.sql +++ b/src/main/resources/db/changelog/5-hs-office/506-debitor/5063-hs-office-debitor-rbac.sql @@ -3,21 +3,21 @@ -- ============================================================================ ---changeset hs-office-debitor-rbac-OBJECT:1 endDelimiter:--// +--changeset RbacObjectGenerator:hs-office-debitor-rbac-OBJECT endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRelatedRbacObject('hs_office_debitor'); +call rbac.generateRelatedRbacObject('hs_office_debitor'); --// -- ============================================================================ ---changeset hs-office-debitor-rbac-ROLE-DESCRIPTORS:1 endDelimiter:--// +--changeset RbacRoleDescriptorsGenerator:hs-office-debitor-rbac-ROLE-DESCRIPTORS endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRbacRoleDescriptors('hsOfficeDebitor', 'hs_office_debitor'); +call rbac.generateRbacRoleDescriptors('hsOfficeDebitor', 'hs_office_debitor'); --// -- ============================================================================ ---changeset hs-office-debitor-rbac-insert-trigger:1 endDelimiter:--// +--changeset RolesGrantsAndPermissionsGenerator:hs-office-debitor-rbac-insert-trigger endDelimiter:--// -- ---------------------------------------------------------------------------- /* @@ -35,7 +35,7 @@ declare newRefundBankAccount hs_office_bankaccount; begin - call enterTriggerForObjectUuid(NEW.uuid); + call rbac.enterTriggerForObjectUuid(NEW.uuid); SELECT partnerRel.* FROM hs_office_relation AS partnerRel @@ -51,17 +51,17 @@ begin SELECT * FROM hs_office_bankaccount WHERE uuid = NEW.refundBankAccountUuid INTO newRefundBankAccount; - call grantRoleToRole(hsOfficeBankAccountREFERRER(newRefundBankAccount), hsOfficeRelationAGENT(newDebitorRel)); - call grantRoleToRole(hsOfficeRelationADMIN(newDebitorRel), hsOfficeRelationADMIN(newPartnerRel)); - call grantRoleToRole(hsOfficeRelationAGENT(newDebitorRel), hsOfficeBankAccountADMIN(newRefundBankAccount)); - call grantRoleToRole(hsOfficeRelationAGENT(newDebitorRel), hsOfficeRelationAGENT(newPartnerRel)); - call grantRoleToRole(hsOfficeRelationTENANT(newPartnerRel), hsOfficeRelationAGENT(newDebitorRel)); + call rbac.grantRoleToRole(hsOfficeBankAccountREFERRER(newRefundBankAccount), hsOfficeRelationAGENT(newDebitorRel)); + call rbac.grantRoleToRole(hsOfficeRelationADMIN(newDebitorRel), hsOfficeRelationADMIN(newPartnerRel)); + call rbac.grantRoleToRole(hsOfficeRelationAGENT(newDebitorRel), hsOfficeBankAccountADMIN(newRefundBankAccount)); + call rbac.grantRoleToRole(hsOfficeRelationAGENT(newDebitorRel), hsOfficeRelationAGENT(newPartnerRel)); + call rbac.grantRoleToRole(hsOfficeRelationTENANT(newPartnerRel), hsOfficeRelationAGENT(newDebitorRel)); - call grantPermissionToRole(createPermission(NEW.uuid, 'DELETE'), hsOfficeRelationOWNER(newDebitorRel)); - call grantPermissionToRole(createPermission(NEW.uuid, 'SELECT'), hsOfficeRelationTENANT(newDebitorRel)); - call grantPermissionToRole(createPermission(NEW.uuid, 'UPDATE'), hsOfficeRelationADMIN(newDebitorRel)); + call rbac.grantPermissionToRole(rbac.createPermission(NEW.uuid, 'DELETE'), hsOfficeRelationOWNER(newDebitorRel)); + call rbac.grantPermissionToRole(rbac.createPermission(NEW.uuid, 'SELECT'), hsOfficeRelationTENANT(newDebitorRel)); + call rbac.grantPermissionToRole(rbac.createPermission(NEW.uuid, 'UPDATE'), hsOfficeRelationADMIN(newDebitorRel)); - call leaveTriggerForObjectUuid(NEW.uuid); + call rbac.leaveTriggerForObjectUuid(NEW.uuid); end; $$; /* @@ -85,7 +85,7 @@ execute procedure insertTriggerForHsOfficeDebitor_tf(); -- ============================================================================ ---changeset hs-office-debitor-rbac-update-trigger:1 endDelimiter:--// +--changeset RolesGrantsAndPermissionsGenerator:hs-office-debitor-rbac-update-trigger endDelimiter:--// -- ---------------------------------------------------------------------------- /* @@ -101,7 +101,7 @@ begin if NEW.debitorRelUuid is distinct from OLD.debitorRelUuid or NEW.refundBankAccountUuid is distinct from OLD.refundBankAccountUuid then - delete from rbacgrants g where g.grantedbytriggerof = OLD.uuid; + delete from rbac.grants g where g.grantedbytriggerof = OLD.uuid; call buildRbacSystemForHsOfficeDebitor(NEW); end if; end; $$; @@ -127,26 +127,26 @@ execute procedure updateTriggerForHsOfficeDebitor_tf(); -- ============================================================================ ---changeset hs-office-debitor-rbac-GRANTING-INSERT-PERMISSION:1 endDelimiter:--// +--changeset InsertTriggerGenerator:hs-office-debitor-rbac-GRANTING-INSERT-PERMISSION endDelimiter:--// -- ---------------------------------------------------------------------------- --- granting INSERT permission to global ---------------------------- +-- granting INSERT permission to rbac.global ---------------------------- /* - Grants INSERT INTO hs_office_debitor permissions to specified role of pre-existing global rows. + Grants INSERT INTO hs_office_debitor permissions to specified role of pre-existing rbac.global rows. */ do language plpgsql $$ declare - row global; + row rbac.global; begin - call defineContext('create INSERT INTO hs_office_debitor permissions for pre-exising global rows'); + call base.defineContext('create INSERT INTO hs_office_debitor permissions for pre-exising rbac.global rows'); - FOR row IN SELECT * FROM global + FOR row IN SELECT * FROM rbac.global -- unconditional for all rows in that table LOOP - call grantPermissionToRole( - createPermission(row.uuid, 'INSERT', 'hs_office_debitor'), - globalADMIN()); + call rbac.grantPermissionToRole( + rbac.createPermission(row.uuid, 'INSERT', 'hs_office_debitor'), + rbac.globalADMIN()); END LOOP; end; $$; @@ -154,28 +154,28 @@ $$; /** Grants hs_office_debitor INSERT permission to specified role of new global rows. */ -create or replace function new_hs_office_debitor_grants_insert_to_global_tf() +create or replace function rbac.new_hsof_debitor_grants_insert_to_global_tf() returns trigger language plpgsql strict as $$ begin -- unconditional for all rows in that table - call grantPermissionToRole( - createPermission(NEW.uuid, 'INSERT', 'hs_office_debitor'), - globalADMIN()); + call rbac.grantPermissionToRole( + rbac.createPermission(NEW.uuid, 'INSERT', 'hs_office_debitor'), + rbac.globalADMIN()); -- end. return NEW; end; $$; -- z_... is to put it at the end of after insert triggers, to make sure the roles exist -create trigger z_new_hs_office_debitor_grants_insert_to_global_tg - after insert on global +create trigger z_new_hs_office_debitor_grants_after_insert_tg + after insert on rbac.global for each row -execute procedure new_hs_office_debitor_grants_insert_to_global_tf(); +execute procedure rbac.new_hsof_debitor_grants_insert_to_global_tf(); -- ============================================================================ ---changeset hs_office_debitor-rbac-CHECKING-INSERT-PERMISSION:1 endDelimiter:--// +--changeset InsertTriggerGenerator:hs_office_debitor-rbac-CHECKING-INSERT-PERMISSION endDelimiter:--// -- ---------------------------------------------------------------------------- /** @@ -187,13 +187,13 @@ create or replace function hs_office_debitor_insert_permission_check_tf() declare superObjectUuid uuid; begin - -- check INSERT INSERT if global ADMIN - if isGlobalAdmin() then + -- check INSERT INSERT if rbac.global ADMIN + if rbac.isGlobalAdmin() then return NEW; end if; raise exception '[403] insert into hs_office_debitor values(%) not allowed for current subjects % (%)', - NEW, currentSubjects(), currentSubjectsUuids(); + NEW, base.currentSubjects(), rbac.currentSubjectOrAssumedRolesUuids(); end; $$; create trigger hs_office_debitor_insert_permission_check_tg @@ -204,10 +204,10 @@ create trigger hs_office_debitor_insert_permission_check_tg -- ============================================================================ ---changeset hs-office-debitor-rbac-IDENTITY-VIEW:1 endDelimiter:--// +--changeset RbacIdentityViewGenerator:hs-office-debitor-rbac-IDENTITY-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRbacIdentityViewFromQuery('hs_office_debitor', +call rbac.generateRbacIdentityViewFromQuery('hs_office_debitor', $idName$ SELECT debitor.uuid AS uuid, 'D-' || (SELECT partner.partnerNumber @@ -224,9 +224,9 @@ call generateRbacIdentityViewFromQuery('hs_office_debitor', -- ============================================================================ ---changeset hs-office-debitor-rbac-RESTRICTED-VIEW:1 endDelimiter:--// +--changeset RbacRestrictedViewGenerator:hs-office-debitor-rbac-RESTRICTED-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRbacRestrictedView('hs_office_debitor', +call rbac.generateRbacRestrictedView('hs_office_debitor', $orderBy$ defaultPrefix $orderBy$, diff --git a/src/main/resources/db/changelog/5-hs-office/506-debitor/5068-hs-office-debitor-test-data.sql b/src/main/resources/db/changelog/5-hs-office/506-debitor/5068-hs-office-debitor-test-data.sql index da9a5f2e..a648bace 100644 --- a/src/main/resources/db/changelog/5-hs-office/506-debitor/5068-hs-office-debitor-test-data.sql +++ b/src/main/resources/db/changelog/5-hs-office/506-debitor/5068-hs-office-debitor-test-data.sql @@ -2,7 +2,7 @@ -- ============================================================================ ---changeset hs-office-debitor-TEST-DATA-GENERATOR:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-debitor-TEST-DATA-GENERATOR endDelimiter:--// -- ---------------------------------------------------------------------------- /* @@ -20,7 +20,7 @@ declare relatedDebitorRelUuid uuid; relatedBankAccountUuid uuid; begin - idName := cleanIdentifier( forPartnerPersonName|| '-' || forBillingContactCaption); + idName := base.cleanIdentifier( forPartnerPersonName|| '-' || forBillingContactCaption); select debitorRel.uuid into relatedDebitorRelUuid @@ -45,12 +45,12 @@ end; $$; -- ============================================================================ ---changeset hs-office-debitor-TEST-DATA-GENERATION:1 –context=dev,tc endDelimiter:--// +--changeset michael.hoennig:hs-office-debitor-TEST-DATA-GENERATION –context=dev,tc endDelimiter:--// -- ---------------------------------------------------------------------------- do language plpgsql $$ begin - call defineContext('creating debitor test-data', null, 'superuser-alex@hostsharing.net', 'global#global:ADMIN'); + call base.defineContext('creating debitor test-data', null, 'superuser-alex@hostsharing.net', 'rbac.global#global:ADMIN'); call createHsOfficeDebitorTestData(11, 'First GmbH', 'first contact', 'fir'); call createHsOfficeDebitorTestData(12, 'Second e.K.', 'second contact', 'sec'); diff --git a/src/main/resources/db/changelog/5-hs-office/507-sepamandate/5070-hs-office-sepamandate.sql b/src/main/resources/db/changelog/5-hs-office/507-sepamandate/5070-hs-office-sepamandate.sql index c2ffd86d..16714cda 100644 --- a/src/main/resources/db/changelog/5-hs-office/507-sepamandate/5070-hs-office-sepamandate.sql +++ b/src/main/resources/db/changelog/5-hs-office/507-sepamandate/5070-hs-office-sepamandate.sql @@ -1,12 +1,12 @@ --liquibase formatted sql -- ============================================================================ ---changeset hs-office-sepamandate-MAIN-TABLE:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-sepamandate-MAIN-TABLE endDelimiter:--// -- ---------------------------------------------------------------------------- create table if not exists hs_office_sepamandate ( - uuid uuid unique references RbacObject (uuid) initially deferred, + uuid uuid unique references rbac.object (uuid) initially deferred, version int not null default 0, debitorUuid uuid not null references hs_office_debitor(uuid), bankAccountUuid uuid not null references hs_office_bankaccount(uuid), @@ -18,8 +18,8 @@ create table if not exists hs_office_sepamandate -- ============================================================================ ---changeset hs-office-sepamandate-MAIN-TABLE-JOURNAL:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-sepamandate-MAIN-TABLE-JOURNAL endDelimiter:--// -- ---------------------------------------------------------------------------- -call create_journal('hs_office_sepamandate'); +call base.create_journal('hs_office_sepamandate'); --// diff --git a/src/main/resources/db/changelog/5-hs-office/507-sepamandate/5073-hs-office-sepamandate-rbac.md b/src/main/resources/db/changelog/5-hs-office/507-sepamandate/5073-hs-office-sepamandate-rbac.md index d6b47c0e..a2a89591 100644 --- a/src/main/resources/db/changelog/5-hs-office/507-sepamandate/5073-hs-office-sepamandate-rbac.md +++ b/src/main/resources/db/changelog/5-hs-office/507-sepamandate/5073-hs-office-sepamandate-rbac.md @@ -99,16 +99,16 @@ end user:creator ==> role:sepaMandate:OWNER %% granting roles to roles -role:global:ADMIN -.-> role:debitorRel.anchorPerson:OWNER +role:rbac.global:ADMIN -.-> role:debitorRel.anchorPerson:OWNER role:debitorRel.anchorPerson:OWNER -.-> role:debitorRel.anchorPerson:ADMIN role:debitorRel.anchorPerson:ADMIN -.-> role:debitorRel.anchorPerson:REFERRER -role:global:ADMIN -.-> role:debitorRel.holderPerson:OWNER +role:rbac.global:ADMIN -.-> role:debitorRel.holderPerson:OWNER role:debitorRel.holderPerson:OWNER -.-> role:debitorRel.holderPerson:ADMIN role:debitorRel.holderPerson:ADMIN -.-> role:debitorRel.holderPerson:REFERRER -role:global:ADMIN -.-> role:debitorRel.contact:OWNER +role:rbac.global:ADMIN -.-> role:debitorRel.contact:OWNER role:debitorRel.contact:OWNER -.-> role:debitorRel.contact:ADMIN role:debitorRel.contact:ADMIN -.-> role:debitorRel.contact:REFERRER -role:global:ADMIN -.-> role:debitorRel:OWNER +role:rbac.global:ADMIN -.-> role:debitorRel:OWNER role:debitorRel:OWNER -.-> role:debitorRel:ADMIN role:debitorRel:ADMIN -.-> role:debitorRel:AGENT role:debitorRel:AGENT -.-> role:debitorRel:TENANT @@ -118,10 +118,10 @@ role:debitorRel:TENANT -.-> role:debitorRel.holderPerson:REFERRER role:debitorRel:TENANT -.-> role:debitorRel.contact:REFERRER role:debitorRel.anchorPerson:ADMIN -.-> role:debitorRel:OWNER role:debitorRel.holderPerson:ADMIN -.-> role:debitorRel:AGENT -role:global:ADMIN -.-> role:bankAccount:OWNER +role:rbac.global:ADMIN -.-> role:bankAccount:OWNER role:bankAccount:OWNER -.-> role:bankAccount:ADMIN role:bankAccount:ADMIN -.-> role:bankAccount:REFERRER -role:global:ADMIN ==> role:sepaMandate:OWNER +role:rbac.global:ADMIN ==> role:sepaMandate:OWNER role:sepaMandate:OWNER ==> role:sepaMandate:ADMIN role:sepaMandate:ADMIN ==> role:sepaMandate:AGENT role:sepaMandate:AGENT ==> role:bankAccount:REFERRER diff --git a/src/main/resources/db/changelog/5-hs-office/507-sepamandate/5073-hs-office-sepamandate-rbac.sql b/src/main/resources/db/changelog/5-hs-office/507-sepamandate/5073-hs-office-sepamandate-rbac.sql index 6b6595a0..63f139d6 100644 --- a/src/main/resources/db/changelog/5-hs-office/507-sepamandate/5073-hs-office-sepamandate-rbac.sql +++ b/src/main/resources/db/changelog/5-hs-office/507-sepamandate/5073-hs-office-sepamandate-rbac.sql @@ -3,21 +3,21 @@ -- ============================================================================ ---changeset hs-office-sepamandate-rbac-OBJECT:1 endDelimiter:--// +--changeset RbacObjectGenerator:hs-office-sepamandate-rbac-OBJECT endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRelatedRbacObject('hs_office_sepamandate'); +call rbac.generateRelatedRbacObject('hs_office_sepamandate'); --// -- ============================================================================ ---changeset hs-office-sepamandate-rbac-ROLE-DESCRIPTORS:1 endDelimiter:--// +--changeset RbacRoleDescriptorsGenerator:hs-office-sepamandate-rbac-ROLE-DESCRIPTORS endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRbacRoleDescriptors('hsOfficeSepaMandate', 'hs_office_sepamandate'); +call rbac.generateRbacRoleDescriptors('hsOfficeSepaMandate', 'hs_office_sepamandate'); --// -- ============================================================================ ---changeset hs-office-sepamandate-rbac-insert-trigger:1 endDelimiter:--// +--changeset RolesGrantsAndPermissionsGenerator:hs-office-sepamandate-rbac-insert-trigger endDelimiter:--// -- ---------------------------------------------------------------------------- /* @@ -34,7 +34,7 @@ declare newDebitorRel hs_office_relation; begin - call enterTriggerForObjectUuid(NEW.uuid); + call rbac.enterTriggerForObjectUuid(NEW.uuid); SELECT * FROM hs_office_bankaccount WHERE uuid = NEW.bankAccountUuid INTO newBankAccount; assert newBankAccount.uuid is not null, format('newBankAccount must not be null for NEW.bankAccountUuid = %s', NEW.bankAccountUuid); @@ -47,20 +47,20 @@ begin assert newDebitorRel.uuid is not null, format('newDebitorRel must not be null for NEW.debitorUuid = %s', NEW.debitorUuid); - perform createRoleWithGrants( + perform rbac.defineRoleWithGrants( hsOfficeSepaMandateOWNER(NEW), permissions => array['DELETE'], - incomingSuperRoles => array[globalADMIN()], - userUuids => array[currentUserUuid()] + incomingSuperRoles => array[rbac.globalADMIN()], + subjectUuids => array[rbac.currentSubjectUuid()] ); - perform createRoleWithGrants( + perform rbac.defineRoleWithGrants( hsOfficeSepaMandateADMIN(NEW), permissions => array['UPDATE'], incomingSuperRoles => array[hsOfficeSepaMandateOWNER(NEW)] ); - perform createRoleWithGrants( + perform rbac.defineRoleWithGrants( hsOfficeSepaMandateAGENT(NEW), incomingSuperRoles => array[hsOfficeSepaMandateADMIN(NEW)], outgoingSubRoles => array[ @@ -68,7 +68,7 @@ begin hsOfficeRelationAGENT(newDebitorRel)] ); - perform createRoleWithGrants( + perform rbac.defineRoleWithGrants( hsOfficeSepaMandateREFERRER(NEW), permissions => array['SELECT'], incomingSuperRoles => array[ @@ -78,7 +78,7 @@ begin outgoingSubRoles => array[hsOfficeRelationTENANT(newDebitorRel)] ); - call leaveTriggerForObjectUuid(NEW.uuid); + call rbac.leaveTriggerForObjectUuid(NEW.uuid); end; $$; /* @@ -102,7 +102,7 @@ execute procedure insertTriggerForHsOfficeSepaMandate_tf(); -- ============================================================================ ---changeset hs-office-sepamandate-rbac-GRANTING-INSERT-PERMISSION:1 endDelimiter:--// +--changeset InsertTriggerGenerator:hs-office-sepamandate-rbac-GRANTING-INSERT-PERMISSION endDelimiter:--// -- ---------------------------------------------------------------------------- -- granting INSERT permission to hs_office_relation ---------------------------- @@ -114,13 +114,13 @@ do language plpgsql $$ declare row hs_office_relation; begin - call defineContext('create INSERT INTO hs_office_sepamandate permissions for pre-exising hs_office_relation rows'); + call base.defineContext('create INSERT INTO hs_office_sepamandate permissions for pre-exising hs_office_relation rows'); FOR row IN SELECT * FROM hs_office_relation WHERE type = 'DEBITOR' LOOP - call grantPermissionToRole( - createPermission(row.uuid, 'INSERT', 'hs_office_sepamandate'), + call rbac.grantPermissionToRole( + rbac.createPermission(row.uuid, 'INSERT', 'hs_office_sepamandate'), hsOfficeRelationADMIN(row)); END LOOP; end; @@ -129,28 +129,28 @@ $$; /** Grants hs_office_sepamandate INSERT permission to specified role of new hs_office_relation rows. */ -create or replace function new_hs_office_sepamandate_grants_insert_to_hs_office_relation_tf() +create or replace function new_hsof_sepamandate_grants_insert_to_hsof_relation_tf() returns trigger language plpgsql strict as $$ begin if NEW.type = 'DEBITOR' then - call grantPermissionToRole( - createPermission(NEW.uuid, 'INSERT', 'hs_office_sepamandate'), + call rbac.grantPermissionToRole( + rbac.createPermission(NEW.uuid, 'INSERT', 'hs_office_sepamandate'), hsOfficeRelationADMIN(NEW)); end if; return NEW; end; $$; -- z_... is to put it at the end of after insert triggers, to make sure the roles exist -create trigger z_new_hs_office_sepamandate_grants_insert_to_hs_office_relation_tg +create trigger z_new_hs_office_sepamandate_grants_after_insert_tg after insert on hs_office_relation for each row -execute procedure new_hs_office_sepamandate_grants_insert_to_hs_office_relation_tf(); +execute procedure new_hsof_sepamandate_grants_insert_to_hsof_relation_tf(); -- ============================================================================ ---changeset hs_office_sepamandate-rbac-CHECKING-INSERT-PERMISSION:1 endDelimiter:--// +--changeset InsertTriggerGenerator:hs_office_sepamandate-rbac-CHECKING-INSERT-PERMISSION endDelimiter:--// -- ---------------------------------------------------------------------------- /** @@ -169,12 +169,12 @@ begin WHERE debitor.uuid = NEW.debitorUuid ); assert superObjectUuid is not null, 'object uuid fetched depending on hs_office_sepamandate.debitorUuid must not be null, also check fetchSql in RBAC DSL'; - if hasInsertPermission(superObjectUuid, 'hs_office_sepamandate') then + if rbac.hasInsertPermission(superObjectUuid, 'hs_office_sepamandate') then return NEW; end if; raise exception '[403] insert into hs_office_sepamandate values(%) not allowed for current subjects % (%)', - NEW, currentSubjects(), currentSubjectsUuids(); + NEW, base.currentSubjects(), rbac.currentSubjectOrAssumedRolesUuids(); end; $$; create trigger hs_office_sepamandate_insert_permission_check_tg @@ -185,10 +185,10 @@ create trigger hs_office_sepamandate_insert_permission_check_tg -- ============================================================================ ---changeset hs-office-sepamandate-rbac-IDENTITY-VIEW:1 endDelimiter:--// +--changeset RbacIdentityViewGenerator:hs-office-sepamandate-rbac-IDENTITY-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRbacIdentityViewFromQuery('hs_office_sepamandate', +call rbac.generateRbacIdentityViewFromQuery('hs_office_sepamandate', $idName$ select sm.uuid as uuid, ba.iban || '-' || sm.validity as idName from hs_office_sepamandate sm @@ -198,9 +198,9 @@ call generateRbacIdentityViewFromQuery('hs_office_sepamandate', -- ============================================================================ ---changeset hs-office-sepamandate-rbac-RESTRICTED-VIEW:1 endDelimiter:--// +--changeset RbacRestrictedViewGenerator:hs-office-sepamandate-rbac-RESTRICTED-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRbacRestrictedView('hs_office_sepamandate', +call rbac.generateRbacRestrictedView('hs_office_sepamandate', $orderBy$ validity $orderBy$, diff --git a/src/main/resources/db/changelog/5-hs-office/507-sepamandate/5076-hs-office-sepamandate-migration.sql b/src/main/resources/db/changelog/5-hs-office/507-sepamandate/5076-hs-office-sepamandate-migration.sql index 4b483c6b..01e2298b 100644 --- a/src/main/resources/db/changelog/5-hs-office/507-sepamandate/5076-hs-office-sepamandate-migration.sql +++ b/src/main/resources/db/changelog/5-hs-office/507-sepamandate/5076-hs-office-sepamandate-migration.sql @@ -4,7 +4,7 @@ -- Once we don't need the external remote views anymore, create revert changesets. -- ============================================================================ ---changeset hs-office-sepamandate-MIGRATION-mapping:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-sepamandate-MIGRATION-mapping endDelimiter:--// -- ---------------------------------------------------------------------------- CREATE TABLE hs_office_sepamandate_legacy_id @@ -16,7 +16,7 @@ CREATE TABLE hs_office_sepamandate_legacy_id -- ============================================================================ ---changeset hs-office-sepamandate-MIGRATION-sequence:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-sepamandate-MIGRATION-sequence endDelimiter:--// -- ---------------------------------------------------------------------------- CREATE SEQUENCE IF NOT EXISTS hs_office_sepamandate_legacy_id_seq @@ -27,7 +27,7 @@ CREATE SEQUENCE IF NOT EXISTS hs_office_sepamandate_legacy_id_seq -- ============================================================================ ---changeset hs-office-sepamandate-MIGRATION-default:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-sepamandate-MIGRATION-default endDelimiter:--// -- ---------------------------------------------------------------------------- ALTER TABLE hs_office_sepamandate_legacy_id @@ -38,17 +38,17 @@ ALTER TABLE hs_office_sepamandate_legacy_id -- ============================================================================ ---changeset hs-office-sepamandate-MIGRATION-insert:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-sepamandate-MIGRATION-insert endDelimiter:--// -- ---------------------------------------------------------------------------- -CALL defineContext('schema-migration'); +CALL base.defineContext('schema-migration'); INSERT INTO hs_office_sepamandate_legacy_id(uuid, sepa_mandate_id) SELECT uuid, nextVal('hs_office_sepamandate_legacy_id_seq') FROM hs_office_sepamandate; --/ -- ============================================================================ ---changeset hs-office-sepamandate-MIGRATION-insert-trigger:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-sepamandate-MIGRATION-insert-trigger endDelimiter:--// -- ---------------------------------------------------------------------------- create or replace function insertSepaMandateLegacyIdMapping() returns trigger @@ -73,7 +73,7 @@ create trigger createSepaMandateLegacyIdMapping -- ============================================================================ ---changeset hs-office-sepamandate-MIGRATION-delete-trigger:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-sepamandate-MIGRATION-delete-trigger endDelimiter:--// -- ---------------------------------------------------------------------------- create or replace function deleteSepaMandateLegacyIdMapping() returns trigger diff --git a/src/main/resources/db/changelog/5-hs-office/507-sepamandate/5078-hs-office-sepamandate-test-data.sql b/src/main/resources/db/changelog/5-hs-office/507-sepamandate/5078-hs-office-sepamandate-test-data.sql index 6c8aa15e..c737be8f 100644 --- a/src/main/resources/db/changelog/5-hs-office/507-sepamandate/5078-hs-office-sepamandate-test-data.sql +++ b/src/main/resources/db/changelog/5-hs-office/507-sepamandate/5078-hs-office-sepamandate-test-data.sql @@ -2,7 +2,7 @@ -- ============================================================================ ---changeset hs-office-sepaMandate-TEST-DATA-GENERATOR:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-sepaMandate-TEST-DATA-GENERATOR endDelimiter:--// -- ---------------------------------------------------------------------------- /* @@ -38,12 +38,12 @@ end; $$; -- ============================================================================ ---changeset hs-office-sepaMandate-TEST-DATA-GENERATION:1 –context=dev,tc endDelimiter:--// +--changeset michael.hoennig:hs-office-sepaMandate-TEST-DATA-GENERATION –context=dev,tc endDelimiter:--// -- ---------------------------------------------------------------------------- do language plpgsql $$ begin - call defineContext('creating SEPA-mandate test-data', null, 'superuser-alex@hostsharing.net', 'global#global:ADMIN'); + call base.defineContext('creating SEPA-mandate test-data', null, 'superuser-alex@hostsharing.net', 'rbac.global#global:ADMIN'); call createHsOfficeSepaMandateTestData(10001, '11', 'DE02120300000000202051', 'ref-10001-11'); call createHsOfficeSepaMandateTestData(10002, '12', 'DE02100500000054540402', 'ref-10002-12'); diff --git a/src/main/resources/db/changelog/5-hs-office/510-membership/5100-hs-office-membership.sql b/src/main/resources/db/changelog/5-hs-office/510-membership/5100-hs-office-membership.sql index 47831f9d..7fe4223e 100644 --- a/src/main/resources/db/changelog/5-hs-office/510-membership/5100-hs-office-membership.sql +++ b/src/main/resources/db/changelog/5-hs-office/510-membership/5100-hs-office-membership.sql @@ -1,7 +1,7 @@ --liquibase formatted sql -- ============================================================================ ---changeset hs-office-membership-MAIN-TABLE:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-membership-MAIN-TABLE endDelimiter:--// -- ---------------------------------------------------------------------------- CREATE TYPE HsOfficeMembershipStatus AS ENUM ( @@ -19,7 +19,7 @@ CREATE CAST (character varying as HsOfficeMembershipStatus) WITH INOUT AS IMPLIC create table if not exists hs_office_membership ( - uuid uuid unique references RbacObject (uuid) initially deferred, + uuid uuid unique references rbac.object (uuid) initially deferred, version int not null default 0, partnerUuid uuid not null references hs_office_partner(uuid), memberNumberSuffix char(2) not null check (memberNumberSuffix::text ~ '^[0-9][0-9]$'), @@ -33,8 +33,8 @@ create table if not exists hs_office_membership -- ============================================================================ ---changeset hs-office-membership-MAIN-TABLE-JOURNAL:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-membership-MAIN-TABLE-JOURNAL endDelimiter:--// -- ---------------------------------------------------------------------------- -call create_journal('hs_office_membership'); +call base.create_journal('hs_office_membership'); --// diff --git a/src/main/resources/db/changelog/5-hs-office/510-membership/5103-hs-office-membership-rbac.md b/src/main/resources/db/changelog/5-hs-office/510-membership/5103-hs-office-membership-rbac.md index 083e244e..2b7b2739 100644 --- a/src/main/resources/db/changelog/5-hs-office/510-membership/5103-hs-office-membership-rbac.md +++ b/src/main/resources/db/changelog/5-hs-office/510-membership/5103-hs-office-membership-rbac.md @@ -85,16 +85,16 @@ end user:creator ==> role:membership:OWNER %% granting roles to roles -role:global:ADMIN -.-> role:partnerRel.anchorPerson:OWNER +role:rbac.global:ADMIN -.-> role:partnerRel.anchorPerson:OWNER role:partnerRel.anchorPerson:OWNER -.-> role:partnerRel.anchorPerson:ADMIN role:partnerRel.anchorPerson:ADMIN -.-> role:partnerRel.anchorPerson:REFERRER -role:global:ADMIN -.-> role:partnerRel.holderPerson:OWNER +role:rbac.global:ADMIN -.-> role:partnerRel.holderPerson:OWNER role:partnerRel.holderPerson:OWNER -.-> role:partnerRel.holderPerson:ADMIN role:partnerRel.holderPerson:ADMIN -.-> role:partnerRel.holderPerson:REFERRER -role:global:ADMIN -.-> role:partnerRel.contact:OWNER +role:rbac.global:ADMIN -.-> role:partnerRel.contact:OWNER role:partnerRel.contact:OWNER -.-> role:partnerRel.contact:ADMIN role:partnerRel.contact:ADMIN -.-> role:partnerRel.contact:REFERRER -role:global:ADMIN -.-> role:partnerRel:OWNER +role:rbac.global:ADMIN -.-> role:partnerRel:OWNER role:partnerRel:OWNER -.-> role:partnerRel:ADMIN role:partnerRel:ADMIN -.-> role:partnerRel:AGENT role:partnerRel:AGENT -.-> role:partnerRel:TENANT @@ -111,7 +111,7 @@ role:partnerRel:AGENT ==> role:membership:AGENT role:membership:AGENT ==> role:partnerRel:TENANT %% granting permissions to roles -role:global:ADMIN ==> perm:membership:INSERT +role:rbac.global:ADMIN ==> perm:membership:INSERT role:membership:ADMIN ==> perm:membership:DELETE role:membership:ADMIN ==> perm:membership:UPDATE role:membership:AGENT ==> perm:membership:SELECT diff --git a/src/main/resources/db/changelog/5-hs-office/510-membership/5103-hs-office-membership-rbac.sql b/src/main/resources/db/changelog/5-hs-office/510-membership/5103-hs-office-membership-rbac.sql index 7e628d39..f7a540b4 100644 --- a/src/main/resources/db/changelog/5-hs-office/510-membership/5103-hs-office-membership-rbac.sql +++ b/src/main/resources/db/changelog/5-hs-office/510-membership/5103-hs-office-membership-rbac.sql @@ -3,21 +3,21 @@ -- ============================================================================ ---changeset hs-office-membership-rbac-OBJECT:1 endDelimiter:--// +--changeset RbacObjectGenerator:hs-office-membership-rbac-OBJECT endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRelatedRbacObject('hs_office_membership'); +call rbac.generateRelatedRbacObject('hs_office_membership'); --// -- ============================================================================ ---changeset hs-office-membership-rbac-ROLE-DESCRIPTORS:1 endDelimiter:--// +--changeset RbacRoleDescriptorsGenerator:hs-office-membership-rbac-ROLE-DESCRIPTORS endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRbacRoleDescriptors('hsOfficeMembership', 'hs_office_membership'); +call rbac.generateRbacRoleDescriptors('hsOfficeMembership', 'hs_office_membership'); --// -- ============================================================================ ---changeset hs-office-membership-rbac-insert-trigger:1 endDelimiter:--// +--changeset RolesGrantsAndPermissionsGenerator:hs-office-membership-rbac-insert-trigger endDelimiter:--// -- ---------------------------------------------------------------------------- /* @@ -33,7 +33,7 @@ declare newPartnerRel hs_office_relation; begin - call enterTriggerForObjectUuid(NEW.uuid); + call rbac.enterTriggerForObjectUuid(NEW.uuid); SELECT partnerRel.* FROM hs_office_partner AS partner @@ -43,12 +43,12 @@ begin assert newPartnerRel.uuid is not null, format('newPartnerRel must not be null for NEW.partnerUuid = %s', NEW.partnerUuid); - perform createRoleWithGrants( + perform rbac.defineRoleWithGrants( hsOfficeMembershipOWNER(NEW), - userUuids => array[currentUserUuid()] + subjectUuids => array[rbac.currentSubjectUuid()] ); - perform createRoleWithGrants( + perform rbac.defineRoleWithGrants( hsOfficeMembershipADMIN(NEW), permissions => array['DELETE', 'UPDATE'], incomingSuperRoles => array[ @@ -56,7 +56,7 @@ begin hsOfficeRelationADMIN(newPartnerRel)] ); - perform createRoleWithGrants( + perform rbac.defineRoleWithGrants( hsOfficeMembershipAGENT(NEW), permissions => array['SELECT'], incomingSuperRoles => array[ @@ -65,7 +65,7 @@ begin outgoingSubRoles => array[hsOfficeRelationTENANT(newPartnerRel)] ); - call leaveTriggerForObjectUuid(NEW.uuid); + call rbac.leaveTriggerForObjectUuid(NEW.uuid); end; $$; /* @@ -89,26 +89,26 @@ execute procedure insertTriggerForHsOfficeMembership_tf(); -- ============================================================================ ---changeset hs-office-membership-rbac-GRANTING-INSERT-PERMISSION:1 endDelimiter:--// +--changeset InsertTriggerGenerator:hs-office-membership-rbac-GRANTING-INSERT-PERMISSION endDelimiter:--// -- ---------------------------------------------------------------------------- --- granting INSERT permission to global ---------------------------- +-- granting INSERT permission to rbac.global ---------------------------- /* - Grants INSERT INTO hs_office_membership permissions to specified role of pre-existing global rows. + Grants INSERT INTO hs_office_membership permissions to specified role of pre-existing rbac.global rows. */ do language plpgsql $$ declare - row global; + row rbac.global; begin - call defineContext('create INSERT INTO hs_office_membership permissions for pre-exising global rows'); + call base.defineContext('create INSERT INTO hs_office_membership permissions for pre-exising rbac.global rows'); - FOR row IN SELECT * FROM global + FOR row IN SELECT * FROM rbac.global -- unconditional for all rows in that table LOOP - call grantPermissionToRole( - createPermission(row.uuid, 'INSERT', 'hs_office_membership'), - globalADMIN()); + call rbac.grantPermissionToRole( + rbac.createPermission(row.uuid, 'INSERT', 'hs_office_membership'), + rbac.globalADMIN()); END LOOP; end; $$; @@ -116,28 +116,28 @@ $$; /** Grants hs_office_membership INSERT permission to specified role of new global rows. */ -create or replace function new_hs_office_membership_grants_insert_to_global_tf() +create or replace function rbac.new_hsof_membership_grants_insert_to_global_tf() returns trigger language plpgsql strict as $$ begin -- unconditional for all rows in that table - call grantPermissionToRole( - createPermission(NEW.uuid, 'INSERT', 'hs_office_membership'), - globalADMIN()); + call rbac.grantPermissionToRole( + rbac.createPermission(NEW.uuid, 'INSERT', 'hs_office_membership'), + rbac.globalADMIN()); -- end. return NEW; end; $$; -- z_... is to put it at the end of after insert triggers, to make sure the roles exist -create trigger z_new_hs_office_membership_grants_insert_to_global_tg - after insert on global +create trigger z_new_hs_office_membership_grants_after_insert_tg + after insert on rbac.global for each row -execute procedure new_hs_office_membership_grants_insert_to_global_tf(); +execute procedure rbac.new_hsof_membership_grants_insert_to_global_tf(); -- ============================================================================ ---changeset hs_office_membership-rbac-CHECKING-INSERT-PERMISSION:1 endDelimiter:--// +--changeset InsertTriggerGenerator:hs_office_membership-rbac-CHECKING-INSERT-PERMISSION endDelimiter:--// -- ---------------------------------------------------------------------------- /** @@ -149,13 +149,13 @@ create or replace function hs_office_membership_insert_permission_check_tf() declare superObjectUuid uuid; begin - -- check INSERT INSERT if global ADMIN - if isGlobalAdmin() then + -- check INSERT INSERT if rbac.global ADMIN + if rbac.isGlobalAdmin() then return NEW; end if; raise exception '[403] insert into hs_office_membership values(%) not allowed for current subjects % (%)', - NEW, currentSubjects(), currentSubjectsUuids(); + NEW, base.currentSubjects(), rbac.currentSubjectOrAssumedRolesUuids(); end; $$; create trigger hs_office_membership_insert_permission_check_tg @@ -166,10 +166,10 @@ create trigger hs_office_membership_insert_permission_check_tg -- ============================================================================ ---changeset hs-office-membership-rbac-IDENTITY-VIEW:1 endDelimiter:--// +--changeset RbacIdentityViewGenerator:hs-office-membership-rbac-IDENTITY-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRbacIdentityViewFromQuery('hs_office_membership', +call rbac.generateRbacIdentityViewFromQuery('hs_office_membership', $idName$ SELECT m.uuid AS uuid, 'M-' || p.partnerNumber || m.memberNumberSuffix as idName @@ -180,9 +180,9 @@ call generateRbacIdentityViewFromQuery('hs_office_membership', -- ============================================================================ ---changeset hs-office-membership-rbac-RESTRICTED-VIEW:1 endDelimiter:--// +--changeset RbacRestrictedViewGenerator:hs-office-membership-rbac-RESTRICTED-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRbacRestrictedView('hs_office_membership', +call rbac.generateRbacRestrictedView('hs_office_membership', $orderBy$ validity $orderBy$, diff --git a/src/main/resources/db/changelog/5-hs-office/510-membership/5108-hs-office-membership-test-data.sql b/src/main/resources/db/changelog/5-hs-office/510-membership/5108-hs-office-membership-test-data.sql index 205efcc9..bb25dc6f 100644 --- a/src/main/resources/db/changelog/5-hs-office/510-membership/5108-hs-office-membership-test-data.sql +++ b/src/main/resources/db/changelog/5-hs-office/510-membership/5108-hs-office-membership-test-data.sql @@ -2,7 +2,7 @@ -- ============================================================================ ---changeset hs-office-membership-TEST-DATA-GENERATOR:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-membership-TEST-DATA-GENERATOR endDelimiter:--// -- ---------------------------------------------------------------------------- /* @@ -28,12 +28,12 @@ end; $$; -- ============================================================================ ---changeset hs-office-membership-TEST-DATA-GENERATION:1 –context=dev,tc endDelimiter:--// +--changeset michael.hoennig:hs-office-membership-TEST-DATA-GENERATION –context=dev,tc endDelimiter:--// -- ---------------------------------------------------------------------------- do language plpgsql $$ begin - call defineContext('creating Membership test-data', null, 'superuser-alex@hostsharing.net', 'global#global:ADMIN'); + call base.defineContext('creating Membership test-data', null, 'superuser-alex@hostsharing.net', 'rbac.global#global:ADMIN'); call createHsOfficeMembershipTestData(10001, '01'); call createHsOfficeMembershipTestData(10002, '02'); diff --git a/src/main/resources/db/changelog/5-hs-office/511-coopshares/5110-hs-office-coopshares.sql b/src/main/resources/db/changelog/5-hs-office/511-coopshares/5110-hs-office-coopshares.sql index 599c9cfc..119b4a2a 100644 --- a/src/main/resources/db/changelog/5-hs-office/511-coopshares/5110-hs-office-coopshares.sql +++ b/src/main/resources/db/changelog/5-hs-office/511-coopshares/5110-hs-office-coopshares.sql @@ -1,7 +1,7 @@ --liquibase formatted sql -- ============================================================================ ---changeset hs-office-coopshares-MAIN-TABLE:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-coopshares-MAIN-TABLE endDelimiter:--// -- ---------------------------------------------------------------------------- CREATE TYPE HsOfficeCoopSharesTransactionType AS ENUM ('ADJUSTMENT', 'SUBSCRIPTION', 'CANCELLATION'); @@ -10,7 +10,7 @@ CREATE CAST (character varying as HsOfficeCoopSharesTransactionType) WITH INOUT create table if not exists hs_office_coopsharestransaction ( - uuid uuid unique references RbacObject (uuid) initially deferred, + uuid uuid unique references rbac.object (uuid) initially deferred, version int not null default 0, membershipUuid uuid not null references hs_office_membership(uuid), transactionType HsOfficeCoopSharesTransactionType not null, @@ -23,7 +23,7 @@ create table if not exists hs_office_coopsharestransaction --// -- ============================================================================ ---changeset hs-office-coopshares-BUSINESS-RULES:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-coopshares-BUSINESS-RULES endDelimiter:--// -- ---------------------------------------------------------------------------- alter table hs_office_coopsharestransaction @@ -33,7 +33,7 @@ alter table hs_office_coopsharestransaction --// -- ============================================================================ ---changeset hs-office-coopshares-SHARE-COUNT-CONSTRAINT:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-coopshares-SHARE-COUNT-CONSTRAINT endDelimiter:--// -- ---------------------------------------------------------------------------- create or replace function checkSharesByMembershipUuid(forMembershipUuid UUID, newShareCount integer) @@ -61,8 +61,8 @@ alter table hs_office_coopsharestransaction --// -- ============================================================================ ---changeset hs-office-coopshares-MAIN-TABLE-JOURNAL:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-coopshares-MAIN-TABLE-JOURNAL endDelimiter:--// -- ---------------------------------------------------------------------------- -call create_journal('hs_office_coopsharestransaction'); +call base.create_journal('hs_office_coopsharestransaction'); --// diff --git a/src/main/resources/db/changelog/5-hs-office/511-coopshares/5113-hs-office-coopshares-rbac.md b/src/main/resources/db/changelog/5-hs-office/511-coopshares/5113-hs-office-coopshares-rbac.md index 23103840..aac10ba1 100644 --- a/src/main/resources/db/changelog/5-hs-office/511-coopshares/5113-hs-office-coopshares-rbac.md +++ b/src/main/resources/db/changelog/5-hs-office/511-coopshares/5113-hs-office-coopshares-rbac.md @@ -86,16 +86,16 @@ subgraph membership.partnerRel.holderPerson["`**membership.partnerRel.holderPers end %% granting roles to roles -role:global:ADMIN -.-> role:membership.partnerRel.anchorPerson:OWNER +role:rbac.global:ADMIN -.-> role:membership.partnerRel.anchorPerson:OWNER role:membership.partnerRel.anchorPerson:OWNER -.-> role:membership.partnerRel.anchorPerson:ADMIN role:membership.partnerRel.anchorPerson:ADMIN -.-> role:membership.partnerRel.anchorPerson:REFERRER -role:global:ADMIN -.-> role:membership.partnerRel.holderPerson:OWNER +role:rbac.global:ADMIN -.-> role:membership.partnerRel.holderPerson:OWNER role:membership.partnerRel.holderPerson:OWNER -.-> role:membership.partnerRel.holderPerson:ADMIN role:membership.partnerRel.holderPerson:ADMIN -.-> role:membership.partnerRel.holderPerson:REFERRER -role:global:ADMIN -.-> role:membership.partnerRel.contact:OWNER +role:rbac.global:ADMIN -.-> role:membership.partnerRel.contact:OWNER role:membership.partnerRel.contact:OWNER -.-> role:membership.partnerRel.contact:ADMIN role:membership.partnerRel.contact:ADMIN -.-> role:membership.partnerRel.contact:REFERRER -role:global:ADMIN -.-> role:membership.partnerRel:OWNER +role:rbac.global:ADMIN -.-> role:membership.partnerRel:OWNER role:membership.partnerRel:OWNER -.-> role:membership.partnerRel:ADMIN role:membership.partnerRel:ADMIN -.-> role:membership.partnerRel:AGENT role:membership.partnerRel:AGENT -.-> role:membership.partnerRel:TENANT diff --git a/src/main/resources/db/changelog/5-hs-office/511-coopshares/5113-hs-office-coopshares-rbac.sql b/src/main/resources/db/changelog/5-hs-office/511-coopshares/5113-hs-office-coopshares-rbac.sql index 6707bdaa..e96609e1 100644 --- a/src/main/resources/db/changelog/5-hs-office/511-coopshares/5113-hs-office-coopshares-rbac.sql +++ b/src/main/resources/db/changelog/5-hs-office/511-coopshares/5113-hs-office-coopshares-rbac.sql @@ -3,21 +3,21 @@ -- ============================================================================ ---changeset hs-office-coopsharestransaction-rbac-OBJECT:1 endDelimiter:--// +--changeset RbacObjectGenerator:hs-office-coopsharestransaction-rbac-OBJECT endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRelatedRbacObject('hs_office_coopsharestransaction'); +call rbac.generateRelatedRbacObject('hs_office_coopsharestransaction'); --// -- ============================================================================ ---changeset hs-office-coopsharestransaction-rbac-ROLE-DESCRIPTORS:1 endDelimiter:--// +--changeset RbacRoleDescriptorsGenerator:hs-office-coopsharestransaction-rbac-ROLE-DESCRIPTORS endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRbacRoleDescriptors('hsOfficeCoopSharesTransaction', 'hs_office_coopsharestransaction'); +call rbac.generateRbacRoleDescriptors('hsOfficeCoopSharesTransaction', 'hs_office_coopsharestransaction'); --// -- ============================================================================ ---changeset hs-office-coopsharestransaction-rbac-insert-trigger:1 endDelimiter:--// +--changeset RolesGrantsAndPermissionsGenerator:hs-office-coopsharestransaction-rbac-insert-trigger endDelimiter:--// -- ---------------------------------------------------------------------------- /* @@ -33,15 +33,15 @@ declare newMembership hs_office_membership; begin - call enterTriggerForObjectUuid(NEW.uuid); + call rbac.enterTriggerForObjectUuid(NEW.uuid); SELECT * FROM hs_office_membership WHERE uuid = NEW.membershipUuid INTO newMembership; assert newMembership.uuid is not null, format('newMembership must not be null for NEW.membershipUuid = %s', NEW.membershipUuid); - call grantPermissionToRole(createPermission(NEW.uuid, 'SELECT'), hsOfficeMembershipAGENT(newMembership)); - call grantPermissionToRole(createPermission(NEW.uuid, 'UPDATE'), hsOfficeMembershipADMIN(newMembership)); + call rbac.grantPermissionToRole(rbac.createPermission(NEW.uuid, 'SELECT'), hsOfficeMembershipAGENT(newMembership)); + call rbac.grantPermissionToRole(rbac.createPermission(NEW.uuid, 'UPDATE'), hsOfficeMembershipADMIN(newMembership)); - call leaveTriggerForObjectUuid(NEW.uuid); + call rbac.leaveTriggerForObjectUuid(NEW.uuid); end; $$; /* @@ -65,7 +65,7 @@ execute procedure insertTriggerForHsOfficeCoopSharesTransaction_tf(); -- ============================================================================ ---changeset hs-office-coopsharestransaction-rbac-GRANTING-INSERT-PERMISSION:1 endDelimiter:--// +--changeset InsertTriggerGenerator:hs-office-coopsharestransaction-rbac-GRANTING-INSERT-PERMISSION endDelimiter:--// -- ---------------------------------------------------------------------------- -- granting INSERT permission to hs_office_membership ---------------------------- @@ -77,13 +77,13 @@ do language plpgsql $$ declare row hs_office_membership; begin - call defineContext('create INSERT INTO hs_office_coopsharestransaction permissions for pre-exising hs_office_membership rows'); + call base.defineContext('create INSERT INTO hs_office_coopsharestransaction permissions for pre-exising hs_office_membership rows'); FOR row IN SELECT * FROM hs_office_membership -- unconditional for all rows in that table LOOP - call grantPermissionToRole( - createPermission(row.uuid, 'INSERT', 'hs_office_coopsharestransaction'), + call rbac.grantPermissionToRole( + rbac.createPermission(row.uuid, 'INSERT', 'hs_office_coopsharestransaction'), hsOfficeMembershipADMIN(row)); END LOOP; end; @@ -92,28 +92,28 @@ $$; /** Grants hs_office_coopsharestransaction INSERT permission to specified role of new hs_office_membership rows. */ -create or replace function new_hs_office_coopsharestransaction_grants_insert_to_hs_office_membership_tf() +create or replace function new_hsof_coopsharetx_grants_insert_to_hsof_membership_tf() returns trigger language plpgsql strict as $$ begin -- unconditional for all rows in that table - call grantPermissionToRole( - createPermission(NEW.uuid, 'INSERT', 'hs_office_coopsharestransaction'), + call rbac.grantPermissionToRole( + rbac.createPermission(NEW.uuid, 'INSERT', 'hs_office_coopsharestransaction'), hsOfficeMembershipADMIN(NEW)); -- end. return NEW; end; $$; -- z_... is to put it at the end of after insert triggers, to make sure the roles exist -create trigger z_new_hs_office_coopsharestransaction_grants_insert_to_hs_office_membership_tg +create trigger z_new_hs_office_coopsharestransaction_grants_after_insert_tg after insert on hs_office_membership for each row -execute procedure new_hs_office_coopsharestransaction_grants_insert_to_hs_office_membership_tf(); +execute procedure new_hsof_coopsharetx_grants_insert_to_hsof_membership_tf(); -- ============================================================================ ---changeset hs_office_coopsharestransaction-rbac-CHECKING-INSERT-PERMISSION:1 endDelimiter:--// +--changeset InsertTriggerGenerator:hs_office_coopsharestransaction-rbac-CHECKING-INSERT-PERMISSION endDelimiter:--// -- ---------------------------------------------------------------------------- /** @@ -126,12 +126,12 @@ declare superObjectUuid uuid; begin -- check INSERT permission via direct foreign key: NEW.membershipUuid - if hasInsertPermission(NEW.membershipUuid, 'hs_office_coopsharestransaction') then + if rbac.hasInsertPermission(NEW.membershipUuid, 'hs_office_coopsharestransaction') then return NEW; end if; raise exception '[403] insert into hs_office_coopsharestransaction values(%) not allowed for current subjects % (%)', - NEW, currentSubjects(), currentSubjectsUuids(); + NEW, base.currentSubjects(), rbac.currentSubjectOrAssumedRolesUuids(); end; $$; create trigger hs_office_coopsharestransaction_insert_permission_check_tg @@ -142,10 +142,10 @@ create trigger hs_office_coopsharestransaction_insert_permission_check_tg -- ============================================================================ ---changeset hs-office-coopsharestransaction-rbac-IDENTITY-VIEW:1 endDelimiter:--// +--changeset RbacIdentityViewGenerator:hs-office-coopsharestransaction-rbac-IDENTITY-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRbacIdentityViewFromProjection('hs_office_coopsharestransaction', +call rbac.generateRbacIdentityViewFromProjection('hs_office_coopsharestransaction', $idName$ reference $idName$); @@ -153,9 +153,9 @@ call generateRbacIdentityViewFromProjection('hs_office_coopsharestransaction', -- ============================================================================ ---changeset hs-office-coopsharestransaction-rbac-RESTRICTED-VIEW:1 endDelimiter:--// +--changeset RbacRestrictedViewGenerator:hs-office-coopsharestransaction-rbac-RESTRICTED-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRbacRestrictedView('hs_office_coopsharestransaction', +call rbac.generateRbacRestrictedView('hs_office_coopsharestransaction', $orderBy$ reference $orderBy$, diff --git a/src/main/resources/db/changelog/5-hs-office/511-coopshares/5116-hs-office-coopshares-migration.sql b/src/main/resources/db/changelog/5-hs-office/511-coopshares/5116-hs-office-coopshares-migration.sql index dd64356e..bd690b3e 100644 --- a/src/main/resources/db/changelog/5-hs-office/511-coopshares/5116-hs-office-coopshares-migration.sql +++ b/src/main/resources/db/changelog/5-hs-office/511-coopshares/5116-hs-office-coopshares-migration.sql @@ -4,7 +4,7 @@ -- Once we don't need the external remote views anymore, create revert changesets. -- ============================================================================ ---changeset hs-office-coopshares-MIGRATION-mapping:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-coopshares-MIGRATION-mapping endDelimiter:--// -- ---------------------------------------------------------------------------- CREATE TABLE hs_office_coopsharestransaction_legacy_id @@ -16,7 +16,7 @@ CREATE TABLE hs_office_coopsharestransaction_legacy_id -- ============================================================================ ---changeset hs-office-coopshares-MIGRATION-sequence:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-coopshares-MIGRATION-sequence endDelimiter:--// -- ---------------------------------------------------------------------------- CREATE SEQUENCE IF NOT EXISTS hs_office_coopsharestransaction_legacy_id_seq @@ -27,7 +27,7 @@ CREATE SEQUENCE IF NOT EXISTS hs_office_coopsharestransaction_legacy_id_seq -- ============================================================================ ---changeset hs-office-coopshares-MIGRATION-default:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-coopshares-MIGRATION-default endDelimiter:--// -- ---------------------------------------------------------------------------- ALTER TABLE hs_office_coopsharestransaction_legacy_id @@ -37,17 +37,17 @@ ALTER TABLE hs_office_coopsharestransaction_legacy_id --/ -- ============================================================================ ---changeset hs-office-coopshares-MIGRATION-insert:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-coopshares-MIGRATION-insert endDelimiter:--// -- ---------------------------------------------------------------------------- -CALL defineContext('schema-migration'); +CALL base.defineContext('schema-migration'); INSERT INTO hs_office_coopsharestransaction_legacy_id(uuid, member_share_id) SELECT uuid, nextVal('hs_office_coopsharestransaction_legacy_id_seq') FROM hs_office_coopsharestransaction; --/ -- ============================================================================ ---changeset hs-office-coopShares-MIGRATION-insert-trigger:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-coopShares-MIGRATION-insert-trigger endDelimiter:--// -- ---------------------------------------------------------------------------- create or replace function insertCoopSharesLegacyIdMapping() returns trigger @@ -72,7 +72,7 @@ create trigger createCoopSharesLegacyIdMapping -- ============================================================================ ---changeset hs-office-coopShares-MIGRATION-delete-trigger:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-coopShares-MIGRATION-delete-trigger endDelimiter:--// -- ---------------------------------------------------------------------------- create or replace function deleteCoopSharesLegacyIdMapping() returns trigger diff --git a/src/main/resources/db/changelog/5-hs-office/511-coopshares/5118-hs-office-coopshares-test-data.sql b/src/main/resources/db/changelog/5-hs-office/511-coopshares/5118-hs-office-coopshares-test-data.sql index 4efb55db..c894b00f 100644 --- a/src/main/resources/db/changelog/5-hs-office/511-coopshares/5118-hs-office-coopshares-test-data.sql +++ b/src/main/resources/db/changelog/5-hs-office/511-coopshares/5118-hs-office-coopshares-test-data.sql @@ -2,7 +2,7 @@ -- ============================================================================ ---changeset hs-office-coopSharesTransaction-TEST-DATA-GENERATOR:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-coopSharesTransaction-TEST-DATA-GENERATOR endDelimiter:--// -- ---------------------------------------------------------------------------- /* @@ -38,12 +38,12 @@ end; $$; -- ============================================================================ ---changeset hs-office-coopSharesTransaction-TEST-DATA-GENERATION:1 –context=dev,tc endDelimiter:--// +--changeset michael.hoennig:hs-office-coopSharesTransaction-TEST-DATA-GENERATION –context=dev,tc endDelimiter:--// -- ---------------------------------------------------------------------------- do language plpgsql $$ begin - call defineContext('creating coopSharesTransaction test-data'); + call base.defineContext('creating coopSharesTransaction test-data'); SET CONSTRAINTS ALL DEFERRED; call createHsOfficeCoopSharesTransactionTestData(10001, '01'); diff --git a/src/main/resources/db/changelog/5-hs-office/512-coopassets/5120-hs-office-coopassets.sql b/src/main/resources/db/changelog/5-hs-office/512-coopassets/5120-hs-office-coopassets.sql index 289d5c2e..fa3ddf51 100644 --- a/src/main/resources/db/changelog/5-hs-office/512-coopassets/5120-hs-office-coopassets.sql +++ b/src/main/resources/db/changelog/5-hs-office/512-coopassets/5120-hs-office-coopassets.sql @@ -1,7 +1,7 @@ --liquibase formatted sql -- ============================================================================ ---changeset hs-office-coopassets-MAIN-TABLE:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-coopassets-MAIN-TABLE endDelimiter:--// -- ---------------------------------------------------------------------------- CREATE TYPE HsOfficeCoopAssetsTransactionType AS ENUM ('ADJUSTMENT', @@ -17,7 +17,7 @@ CREATE CAST (character varying as HsOfficeCoopAssetsTransactionType) WITH INOUT create table if not exists hs_office_coopassetstransaction ( - uuid uuid unique references RbacObject (uuid) initially deferred, + uuid uuid unique references rbac.object (uuid) initially deferred, version int not null default 0, membershipUuid uuid not null references hs_office_membership(uuid), transactionType HsOfficeCoopAssetsTransactionType not null, @@ -31,7 +31,7 @@ create table if not exists hs_office_coopassetstransaction -- ============================================================================ ---changeset hs-office-coopassets-BUSINESS-RULES:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-coopassets-BUSINESS-RULES endDelimiter:--// -- ---------------------------------------------------------------------------- alter table hs_office_coopassetstransaction @@ -41,7 +41,7 @@ alter table hs_office_coopassetstransaction --// -- ============================================================================ ---changeset hs-office-coopassets-ASSET-VALUE-CONSTRAINT:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-coopassets-ASSET-VALUE-CONSTRAINT endDelimiter:--// -- ---------------------------------------------------------------------------- create or replace function checkAssetsByMembershipUuid(forMembershipUuid UUID, newAssetValue money) @@ -69,8 +69,8 @@ alter table hs_office_coopassetstransaction -- ============================================================================ ---changeset hs-office-coopassets-MAIN-TABLE-JOURNAL:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-coopassets-MAIN-TABLE-JOURNAL endDelimiter:--// -- ---------------------------------------------------------------------------- -call create_journal('hs_office_coopassetstransaction'); +call base.create_journal('hs_office_coopassetstransaction'); --// diff --git a/src/main/resources/db/changelog/5-hs-office/512-coopassets/5123-hs-office-coopassets-rbac.md b/src/main/resources/db/changelog/5-hs-office/512-coopassets/5123-hs-office-coopassets-rbac.md index de30185b..dba2011f 100644 --- a/src/main/resources/db/changelog/5-hs-office/512-coopassets/5123-hs-office-coopassets-rbac.md +++ b/src/main/resources/db/changelog/5-hs-office/512-coopassets/5123-hs-office-coopassets-rbac.md @@ -86,16 +86,16 @@ subgraph membership.partnerRel.holderPerson["`**membership.partnerRel.holderPers end %% granting roles to roles -role:global:ADMIN -.-> role:membership.partnerRel.anchorPerson:OWNER +role:rbac.global:ADMIN -.-> role:membership.partnerRel.anchorPerson:OWNER role:membership.partnerRel.anchorPerson:OWNER -.-> role:membership.partnerRel.anchorPerson:ADMIN role:membership.partnerRel.anchorPerson:ADMIN -.-> role:membership.partnerRel.anchorPerson:REFERRER -role:global:ADMIN -.-> role:membership.partnerRel.holderPerson:OWNER +role:rbac.global:ADMIN -.-> role:membership.partnerRel.holderPerson:OWNER role:membership.partnerRel.holderPerson:OWNER -.-> role:membership.partnerRel.holderPerson:ADMIN role:membership.partnerRel.holderPerson:ADMIN -.-> role:membership.partnerRel.holderPerson:REFERRER -role:global:ADMIN -.-> role:membership.partnerRel.contact:OWNER +role:rbac.global:ADMIN -.-> role:membership.partnerRel.contact:OWNER role:membership.partnerRel.contact:OWNER -.-> role:membership.partnerRel.contact:ADMIN role:membership.partnerRel.contact:ADMIN -.-> role:membership.partnerRel.contact:REFERRER -role:global:ADMIN -.-> role:membership.partnerRel:OWNER +role:rbac.global:ADMIN -.-> role:membership.partnerRel:OWNER role:membership.partnerRel:OWNER -.-> role:membership.partnerRel:ADMIN role:membership.partnerRel:ADMIN -.-> role:membership.partnerRel:AGENT role:membership.partnerRel:AGENT -.-> role:membership.partnerRel:TENANT diff --git a/src/main/resources/db/changelog/5-hs-office/512-coopassets/5123-hs-office-coopassets-rbac.sql b/src/main/resources/db/changelog/5-hs-office/512-coopassets/5123-hs-office-coopassets-rbac.sql index 39f5a8fe..881dc899 100644 --- a/src/main/resources/db/changelog/5-hs-office/512-coopassets/5123-hs-office-coopassets-rbac.sql +++ b/src/main/resources/db/changelog/5-hs-office/512-coopassets/5123-hs-office-coopassets-rbac.sql @@ -3,21 +3,21 @@ -- ============================================================================ ---changeset hs-office-coopassetstransaction-rbac-OBJECT:1 endDelimiter:--// +--changeset RbacObjectGenerator:hs-office-coopassetstransaction-rbac-OBJECT endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRelatedRbacObject('hs_office_coopassetstransaction'); +call rbac.generateRelatedRbacObject('hs_office_coopassetstransaction'); --// -- ============================================================================ ---changeset hs-office-coopassetstransaction-rbac-ROLE-DESCRIPTORS:1 endDelimiter:--// +--changeset RbacRoleDescriptorsGenerator:hs-office-coopassetstransaction-rbac-ROLE-DESCRIPTORS endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRbacRoleDescriptors('hsOfficeCoopAssetsTransaction', 'hs_office_coopassetstransaction'); +call rbac.generateRbacRoleDescriptors('hsOfficeCoopAssetsTransaction', 'hs_office_coopassetstransaction'); --// -- ============================================================================ ---changeset hs-office-coopassetstransaction-rbac-insert-trigger:1 endDelimiter:--// +--changeset RolesGrantsAndPermissionsGenerator:hs-office-coopassetstransaction-rbac-insert-trigger endDelimiter:--// -- ---------------------------------------------------------------------------- /* @@ -33,15 +33,15 @@ declare newMembership hs_office_membership; begin - call enterTriggerForObjectUuid(NEW.uuid); + call rbac.enterTriggerForObjectUuid(NEW.uuid); SELECT * FROM hs_office_membership WHERE uuid = NEW.membershipUuid INTO newMembership; assert newMembership.uuid is not null, format('newMembership must not be null for NEW.membershipUuid = %s', NEW.membershipUuid); - call grantPermissionToRole(createPermission(NEW.uuid, 'SELECT'), hsOfficeMembershipAGENT(newMembership)); - call grantPermissionToRole(createPermission(NEW.uuid, 'UPDATE'), hsOfficeMembershipADMIN(newMembership)); + call rbac.grantPermissionToRole(rbac.createPermission(NEW.uuid, 'SELECT'), hsOfficeMembershipAGENT(newMembership)); + call rbac.grantPermissionToRole(rbac.createPermission(NEW.uuid, 'UPDATE'), hsOfficeMembershipADMIN(newMembership)); - call leaveTriggerForObjectUuid(NEW.uuid); + call rbac.leaveTriggerForObjectUuid(NEW.uuid); end; $$; /* @@ -65,7 +65,7 @@ execute procedure insertTriggerForHsOfficeCoopAssetsTransaction_tf(); -- ============================================================================ ---changeset hs-office-coopassetstransaction-rbac-GRANTING-INSERT-PERMISSION:1 endDelimiter:--// +--changeset InsertTriggerGenerator:hs-office-coopassetstransaction-rbac-GRANTING-INSERT-PERMISSION endDelimiter:--// -- ---------------------------------------------------------------------------- -- granting INSERT permission to hs_office_membership ---------------------------- @@ -77,13 +77,13 @@ do language plpgsql $$ declare row hs_office_membership; begin - call defineContext('create INSERT INTO hs_office_coopassetstransaction permissions for pre-exising hs_office_membership rows'); + call base.defineContext('create INSERT INTO hs_office_coopassetstransaction permissions for pre-exising hs_office_membership rows'); FOR row IN SELECT * FROM hs_office_membership -- unconditional for all rows in that table LOOP - call grantPermissionToRole( - createPermission(row.uuid, 'INSERT', 'hs_office_coopassetstransaction'), + call rbac.grantPermissionToRole( + rbac.createPermission(row.uuid, 'INSERT', 'hs_office_coopassetstransaction'), hsOfficeMembershipADMIN(row)); END LOOP; end; @@ -92,28 +92,28 @@ $$; /** Grants hs_office_coopassetstransaction INSERT permission to specified role of new hs_office_membership rows. */ -create or replace function new_hs_office_coopassetstransaction_grants_insert_to_hs_office_membership_tf() +create or replace function new_hsof_coopassettx_grants_insert_to_hsof_membership_tf() returns trigger language plpgsql strict as $$ begin -- unconditional for all rows in that table - call grantPermissionToRole( - createPermission(NEW.uuid, 'INSERT', 'hs_office_coopassetstransaction'), + call rbac.grantPermissionToRole( + rbac.createPermission(NEW.uuid, 'INSERT', 'hs_office_coopassetstransaction'), hsOfficeMembershipADMIN(NEW)); -- end. return NEW; end; $$; -- z_... is to put it at the end of after insert triggers, to make sure the roles exist -create trigger z_new_hs_office_coopassetstransaction_grants_insert_to_hs_office_membership_tg +create trigger z_new_hs_office_coopassetstransaction_grants_after_insert_tg after insert on hs_office_membership for each row -execute procedure new_hs_office_coopassetstransaction_grants_insert_to_hs_office_membership_tf(); +execute procedure new_hsof_coopassettx_grants_insert_to_hsof_membership_tf(); -- ============================================================================ ---changeset hs_office_coopassetstransaction-rbac-CHECKING-INSERT-PERMISSION:1 endDelimiter:--// +--changeset InsertTriggerGenerator:hs_office_coopassetstransaction-rbac-CHECKING-INSERT-PERMISSION endDelimiter:--// -- ---------------------------------------------------------------------------- /** @@ -126,12 +126,12 @@ declare superObjectUuid uuid; begin -- check INSERT permission via direct foreign key: NEW.membershipUuid - if hasInsertPermission(NEW.membershipUuid, 'hs_office_coopassetstransaction') then + if rbac.hasInsertPermission(NEW.membershipUuid, 'hs_office_coopassetstransaction') then return NEW; end if; raise exception '[403] insert into hs_office_coopassetstransaction values(%) not allowed for current subjects % (%)', - NEW, currentSubjects(), currentSubjectsUuids(); + NEW, base.currentSubjects(), rbac.currentSubjectOrAssumedRolesUuids(); end; $$; create trigger hs_office_coopassetstransaction_insert_permission_check_tg @@ -142,10 +142,10 @@ create trigger hs_office_coopassetstransaction_insert_permission_check_tg -- ============================================================================ ---changeset hs-office-coopassetstransaction-rbac-IDENTITY-VIEW:1 endDelimiter:--// +--changeset RbacIdentityViewGenerator:hs-office-coopassetstransaction-rbac-IDENTITY-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRbacIdentityViewFromProjection('hs_office_coopassetstransaction', +call rbac.generateRbacIdentityViewFromProjection('hs_office_coopassetstransaction', $idName$ reference $idName$); @@ -153,9 +153,9 @@ call generateRbacIdentityViewFromProjection('hs_office_coopassetstransaction', -- ============================================================================ ---changeset hs-office-coopassetstransaction-rbac-RESTRICTED-VIEW:1 endDelimiter:--// +--changeset RbacRestrictedViewGenerator:hs-office-coopassetstransaction-rbac-RESTRICTED-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRbacRestrictedView('hs_office_coopassetstransaction', +call rbac.generateRbacRestrictedView('hs_office_coopassetstransaction', $orderBy$ reference $orderBy$, diff --git a/src/main/resources/db/changelog/5-hs-office/512-coopassets/5126-hs-office-coopassets-migration.sql b/src/main/resources/db/changelog/5-hs-office/512-coopassets/5126-hs-office-coopassets-migration.sql index 8c346566..f506e855 100644 --- a/src/main/resources/db/changelog/5-hs-office/512-coopassets/5126-hs-office-coopassets-migration.sql +++ b/src/main/resources/db/changelog/5-hs-office/512-coopassets/5126-hs-office-coopassets-migration.sql @@ -4,7 +4,7 @@ -- Once we don't need the external remote views anymore, create revert changesets. -- ============================================================================ ---changeset hs-office-coopassets-MIGRATION-mapping:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-coopassets-MIGRATION-mapping endDelimiter:--// -- ---------------------------------------------------------------------------- CREATE TABLE hs_office_coopassetstransaction_legacy_id @@ -16,7 +16,7 @@ CREATE TABLE hs_office_coopassetstransaction_legacy_id -- ============================================================================ ---changeset hs-office-coopassets-MIGRATION-sequence:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-coopassets-MIGRATION-sequence endDelimiter:--// -- ---------------------------------------------------------------------------- CREATE SEQUENCE IF NOT EXISTS hs_office_coopassetstransaction_legacy_id_seq @@ -27,7 +27,7 @@ CREATE SEQUENCE IF NOT EXISTS hs_office_coopassetstransaction_legacy_id_seq -- ============================================================================ ---changeset hs-office-coopassets-MIGRATION-default:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-coopassets-MIGRATION-default endDelimiter:--// -- ---------------------------------------------------------------------------- ALTER TABLE hs_office_coopassetstransaction_legacy_id @@ -37,17 +37,17 @@ ALTER TABLE hs_office_coopassetstransaction_legacy_id -- ============================================================================ ---changeset hs-office-coopassets-MIGRATION-insert:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-coopassets-MIGRATION-insert endDelimiter:--// -- ---------------------------------------------------------------------------- -CALL defineContext('schema-migration'); +CALL base.defineContext('schema-migration'); INSERT INTO hs_office_coopassetstransaction_legacy_id(uuid, member_asset_id) SELECT uuid, nextVal('hs_office_coopassetstransaction_legacy_id_seq') FROM hs_office_coopassetstransaction; --/ -- ============================================================================ ---changeset hs-office-coopAssets-MIGRATION-insert-trigger:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-coopAssets-MIGRATION-insert-trigger endDelimiter:--// -- ---------------------------------------------------------------------------- create or replace function insertCoopAssetsLegacyIdMapping() returns trigger @@ -72,7 +72,7 @@ create trigger createCoopAssetsLegacyIdMapping -- ============================================================================ ---changeset hs-office-coopAssets-MIGRATION-delete-trigger:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-coopAssets-MIGRATION-delete-trigger endDelimiter:--// -- ---------------------------------------------------------------------------- create or replace function deleteCoopAssetsLegacyIdMapping() returns trigger diff --git a/src/main/resources/db/changelog/5-hs-office/512-coopassets/5128-hs-office-coopassets-test-data.sql b/src/main/resources/db/changelog/5-hs-office/512-coopassets/5128-hs-office-coopassets-test-data.sql index b3cdab98..b2d9c27d 100644 --- a/src/main/resources/db/changelog/5-hs-office/512-coopassets/5128-hs-office-coopassets-test-data.sql +++ b/src/main/resources/db/changelog/5-hs-office/512-coopassets/5128-hs-office-coopassets-test-data.sql @@ -2,7 +2,7 @@ -- ============================================================================ ---changeset hs-office-coopAssetsTransaction-TEST-DATA-GENERATOR:1 endDelimiter:--// +--changeset michael.hoennig:hs-office-coopAssetsTransaction-TEST-DATA-GENERATOR endDelimiter:--// -- ---------------------------------------------------------------------------- /* @@ -38,12 +38,12 @@ end; $$; -- ============================================================================ ---changeset hs-office-coopAssetsTransaction-TEST-DATA-GENERATION:1 –context=dev,tc endDelimiter:--// +--changeset michael.hoennig:hs-office-coopAssetsTransaction-TEST-DATA-GENERATION –context=dev,tc endDelimiter:--// -- ---------------------------------------------------------------------------- do language plpgsql $$ begin - call defineContext('creating coopAssetsTransaction test-data'); + call base.defineContext('creating coopAssetsTransaction test-data'); SET CONSTRAINTS ALL DEFERRED; call createHsOfficeCoopAssetsTransactionTestData(10001, '01'); diff --git a/src/main/resources/db/changelog/6-hs-booking/610-booking-debitor/6100-hs-booking-debitor.sql b/src/main/resources/db/changelog/6-hs-booking/610-booking-debitor/6100-hs-booking-debitor.sql index 72d9563f..a610023c 100644 --- a/src/main/resources/db/changelog/6-hs-booking/610-booking-debitor/6100-hs-booking-debitor.sql +++ b/src/main/resources/db/changelog/6-hs-booking/610-booking-debitor/6100-hs-booking-debitor.sql @@ -1,7 +1,7 @@ --liquibase formatted sql -- ============================================================================ ---changeset hs-booking-debitor-RESTRICTED-VIEW:1 endDelimiter:--// +--changeset michael.hoennig:hs-booking-debitor-RESTRICTED-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- create view hs_booking_debitor_xv as diff --git a/src/main/resources/db/changelog/6-hs-booking/620-booking-project/6200-hs-booking-project.sql b/src/main/resources/db/changelog/6-hs-booking/620-booking-project/6200-hs-booking-project.sql index 564e36c0..a0250fc4 100644 --- a/src/main/resources/db/changelog/6-hs-booking/620-booking-project/6200-hs-booking-project.sql +++ b/src/main/resources/db/changelog/6-hs-booking/620-booking-project/6200-hs-booking-project.sql @@ -1,12 +1,12 @@ --liquibase formatted sql -- ============================================================================ ---changeset booking-project-MAIN-TABLE:1 endDelimiter:--// +--changeset michael.hoennig:booking-project-MAIN-TABLE endDelimiter:--// -- ---------------------------------------------------------------------------- create table if not exists hs_booking_project ( - uuid uuid unique references RbacObject (uuid), + uuid uuid unique references rbac.object (uuid), version int not null default 0, debitorUuid uuid not null references hs_office_debitor(uuid), caption varchar(80) not null @@ -15,15 +15,15 @@ create table if not exists hs_booking_project -- ============================================================================ ---changeset hs-booking-project-MAIN-TABLE-JOURNAL:1 endDelimiter:--// +--changeset michael.hoennig:hs-booking-project-MAIN-TABLE-JOURNAL endDelimiter:--// -- ---------------------------------------------------------------------------- -call create_journal('hs_booking_project'); +call base.create_journal('hs_booking_project'); --// -- ============================================================================ ---changeset hs-booking-project-MAIN-TABLE-HISTORIZATION:1 endDelimiter:--// +--changeset michael.hoennig:hs-booking-project-MAIN-TABLE-HISTORIZATION endDelimiter:--// -- ---------------------------------------------------------------------------- -call tx_create_historicization('hs_booking_project'); +call base.tx_create_historicization('hs_booking_project'); --// diff --git a/src/main/resources/db/changelog/6-hs-booking/620-booking-project/6203-hs-booking-project-rbac.md b/src/main/resources/db/changelog/6-hs-booking/620-booking-project/6203-hs-booking-project-rbac.md index 7fb81cd7..3f4204f3 100644 --- a/src/main/resources/db/changelog/6-hs-booking/620-booking-project/6203-hs-booking-project-rbac.md +++ b/src/main/resources/db/changelog/6-hs-booking/620-booking-project/6203-hs-booking-project-rbac.md @@ -44,7 +44,7 @@ subgraph project["`**project**`"] end %% granting roles to roles -role:global:ADMIN -.-> role:debitorRel:OWNER +role:rbac.global:ADMIN -.-> role:debitorRel:OWNER role:debitorRel:OWNER -.-> role:debitorRel:ADMIN role:debitorRel:ADMIN -.-> role:debitorRel:AGENT role:debitorRel:AGENT -.-> role:debitorRel:TENANT @@ -56,7 +56,7 @@ role:project:TENANT ==> role:debitorRel:TENANT %% granting permissions to roles role:debitorRel:ADMIN ==> perm:project:INSERT -role:global:ADMIN ==> perm:project:DELETE +role:rbac.global:ADMIN ==> perm:project:DELETE role:project:ADMIN ==> perm:project:UPDATE role:project:TENANT ==> perm:project:SELECT diff --git a/src/main/resources/db/changelog/6-hs-booking/620-booking-project/6203-hs-booking-project-rbac.sql b/src/main/resources/db/changelog/6-hs-booking/620-booking-project/6203-hs-booking-project-rbac.sql index c6f3544d..0f0098f7 100644 --- a/src/main/resources/db/changelog/6-hs-booking/620-booking-project/6203-hs-booking-project-rbac.sql +++ b/src/main/resources/db/changelog/6-hs-booking/620-booking-project/6203-hs-booking-project-rbac.sql @@ -3,21 +3,21 @@ -- ============================================================================ ---changeset hs-booking-project-rbac-OBJECT:1 endDelimiter:--// +--changeset michael.hoennig:hs-booking-project-rbac-OBJECT endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRelatedRbacObject('hs_booking_project'); +call rbac.generateRelatedRbacObject('hs_booking_project'); --// -- ============================================================================ ---changeset hs-booking-project-rbac-ROLE-DESCRIPTORS:1 endDelimiter:--// +--changeset michael.hoennig:hs-booking-project-rbac-ROLE-DESCRIPTORS endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRbacRoleDescriptors('hsBookingProject', 'hs_booking_project'); +call rbac.generateRbacRoleDescriptors('hsBookingProject', 'hs_booking_project'); --// -- ============================================================================ ---changeset hs-booking-project-rbac-insert-trigger:1 endDelimiter:--// +--changeset michael.hoennig:hs-booking-project-rbac-insert-trigger endDelimiter:--// -- ---------------------------------------------------------------------------- /* @@ -34,7 +34,7 @@ declare newDebitorRel hs_office_relation; begin - call enterTriggerForObjectUuid(NEW.uuid); + call rbac.enterTriggerForObjectUuid(NEW.uuid); SELECT * FROM hs_office_debitor WHERE uuid = NEW.debitorUuid INTO newDebitor; assert newDebitor.uuid is not null, format('newDebitor must not be null for NEW.debitorUuid = %s', NEW.debitorUuid); @@ -47,32 +47,32 @@ begin assert newDebitorRel.uuid is not null, format('newDebitorRel must not be null for NEW.debitorUuid = %s', NEW.debitorUuid); - perform createRoleWithGrants( + perform rbac.defineRoleWithGrants( hsBookingProjectOWNER(NEW), - incomingSuperRoles => array[hsOfficeRelationAGENT(newDebitorRel, unassumed())] + incomingSuperRoles => array[hsOfficeRelationAGENT(newDebitorRel, rbac.unassumed())] ); - perform createRoleWithGrants( + perform rbac.defineRoleWithGrants( hsBookingProjectADMIN(NEW), permissions => array['UPDATE'], incomingSuperRoles => array[hsBookingProjectOWNER(NEW)] ); - perform createRoleWithGrants( + perform rbac.defineRoleWithGrants( hsBookingProjectAGENT(NEW), incomingSuperRoles => array[hsBookingProjectADMIN(NEW)] ); - perform createRoleWithGrants( + perform rbac.defineRoleWithGrants( hsBookingProjectTENANT(NEW), permissions => array['SELECT'], incomingSuperRoles => array[hsBookingProjectAGENT(NEW)], outgoingSubRoles => array[hsOfficeRelationTENANT(newDebitorRel)] ); - call grantPermissionToRole(createPermission(NEW.uuid, 'DELETE'), globalAdmin()); + call rbac.grantPermissionToRole(rbac.createPermission(NEW.uuid, 'DELETE'), rbac.globalAdmin()); - call leaveTriggerForObjectUuid(NEW.uuid); + call rbac.leaveTriggerForObjectUuid(NEW.uuid); end; $$; /* @@ -96,7 +96,7 @@ execute procedure insertTriggerForHsBookingProject_tf(); -- ============================================================================ ---changeset hs-booking-project-rbac-GRANTING-INSERT-PERMISSION:1 endDelimiter:--// +--changeset michael.hoennig:hs-booking-project-rbac-GRANTING-INSERT-PERMISSION endDelimiter:--// -- ---------------------------------------------------------------------------- -- granting INSERT permission to hs_office_relation ---------------------------- @@ -108,13 +108,13 @@ do language plpgsql $$ declare row hs_office_relation; begin - call defineContext('create INSERT INTO hs_booking_project permissions for pre-exising hs_office_relation rows'); + call base.defineContext('create INSERT INTO hs_booking_project permissions for pre-exising hs_office_relation rows'); FOR row IN SELECT * FROM hs_office_relation WHERE type = 'DEBITOR' LOOP - call grantPermissionToRole( - createPermission(row.uuid, 'INSERT', 'hs_booking_project'), + call rbac.grantPermissionToRole( + rbac.createPermission(row.uuid, 'INSERT', 'hs_booking_project'), hsOfficeRelationADMIN(row)); END LOOP; end; @@ -129,8 +129,8 @@ create or replace function new_hs_booking_project_grants_insert_to_hs_office_rel strict as $$ begin if NEW.type = 'DEBITOR' then - call grantPermissionToRole( - createPermission(NEW.uuid, 'INSERT', 'hs_booking_project'), + call rbac.grantPermissionToRole( + rbac.createPermission(NEW.uuid, 'INSERT', 'hs_booking_project'), hsOfficeRelationADMIN(NEW)); end if; return NEW; @@ -144,7 +144,7 @@ execute procedure new_hs_booking_project_grants_insert_to_hs_office_relation_tf( -- ============================================================================ ---changeset hs_booking_project-rbac-CHECKING-INSERT-PERMISSION:1 endDelimiter:--// +--changeset michael.hoennig:hs_booking_project-rbac-CHECKING-INSERT-PERMISSION endDelimiter:--// -- ---------------------------------------------------------------------------- /** @@ -163,12 +163,12 @@ begin WHERE debitor.uuid = NEW.debitorUuid ); assert superObjectUuid is not null, 'object uuid fetched depending on hs_booking_project.debitorUuid must not be null, also check fetchSql in RBAC DSL'; - if hasInsertPermission(superObjectUuid, 'hs_booking_project') then + if rbac.hasInsertPermission(superObjectUuid, 'hs_booking_project') then return NEW; end if; raise exception '[403] insert into hs_booking_project values(%) not allowed for current subjects % (%)', - NEW, currentSubjects(), currentSubjectsUuids(); + NEW, base.currentSubjects(), rbac.currentSubjectOrAssumedRolesUuids(); end; $$; create trigger hs_booking_project_insert_permission_check_tg @@ -179,12 +179,12 @@ create trigger hs_booking_project_insert_permission_check_tg -- ============================================================================ ---changeset hs-booking-project-rbac-IDENTITY-VIEW:1 endDelimiter:--// +--changeset michael.hoennig:hs-booking-project-rbac-IDENTITY-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRbacIdentityViewFromQuery('hs_booking_project', +call rbac.generateRbacIdentityViewFromQuery('hs_booking_project', $idName$ - SELECT bookingProject.uuid as uuid, debitorIV.idName || '-' || cleanIdentifier(bookingProject.caption) as idName + SELECT bookingProject.uuid as uuid, debitorIV.idName || '-' || base.cleanIdentifier(bookingProject.caption) as idName FROM hs_booking_project bookingProject JOIN hs_office_debitor_iv debitorIV ON debitorIV.uuid = bookingProject.debitorUuid $idName$); @@ -192,9 +192,9 @@ call generateRbacIdentityViewFromQuery('hs_booking_project', -- ============================================================================ ---changeset hs-booking-project-rbac-RESTRICTED-VIEW:1 endDelimiter:--// +--changeset michael.hoennig:hs-booking-project-rbac-RESTRICTED-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRbacRestrictedView('hs_booking_project', +call rbac.generateRbacRestrictedView('hs_booking_project', $orderBy$ caption $orderBy$, diff --git a/src/main/resources/db/changelog/6-hs-booking/620-booking-project/6208-hs-booking-project-test-data.sql b/src/main/resources/db/changelog/6-hs-booking/620-booking-project/6208-hs-booking-project-test-data.sql index 2113ae5e..7275ce2c 100644 --- a/src/main/resources/db/changelog/6-hs-booking/620-booking-project/6208-hs-booking-project-test-data.sql +++ b/src/main/resources/db/changelog/6-hs-booking/620-booking-project/6208-hs-booking-project-test-data.sql @@ -2,7 +2,7 @@ -- ============================================================================ ---changeset hs-booking-project-TEST-DATA-GENERATOR:1 endDelimiter:--// +--changeset michael.hoennig:hs-booking-project-TEST-DATA-GENERATOR endDelimiter:--// -- ---------------------------------------------------------------------------- /* @@ -34,12 +34,12 @@ end; $$; -- ============================================================================ ---changeset hs-booking-project-TEST-DATA-GENERATION:1 –context=dev,tc endDelimiter:--// +--changeset michael.hoennig:hs-booking-project-TEST-DATA-GENERATION –context=dev,tc endDelimiter:--// -- ---------------------------------------------------------------------------- do language plpgsql $$ begin - call defineContext('creating booking-project test-data', null, 'superuser-alex@hostsharing.net', 'global#global:ADMIN'); + call base.defineContext('creating booking-project test-data', null, 'superuser-alex@hostsharing.net', 'rbac.global#global:ADMIN'); call createHsBookingProjectTransactionTestData(10001, '11'); call createHsBookingProjectTransactionTestData(10002, '12'); diff --git a/src/main/resources/db/changelog/6-hs-booking/630-booking-item/6203-hs-booking-item-rbac.md b/src/main/resources/db/changelog/6-hs-booking/630-booking-item/6203-hs-booking-item-rbac.md deleted file mode 100644 index 4775616f..00000000 --- a/src/main/resources/db/changelog/6-hs-booking/630-booking-item/6203-hs-booking-item-rbac.md +++ /dev/null @@ -1,63 +0,0 @@ -### rbac bookingItem - -This code generated was by RbacViewMermaidFlowchartGenerator, do not amend manually. - -```mermaid -%%{init:{'flowchart':{'htmlLabels':false}}}%% -flowchart TB - -subgraph bookingItem["`**bookingItem**`"] - direction TB - style bookingItem fill:#dd4901,stroke:#274d6e,stroke-width:8px - - subgraph bookingItem:roles[ ] - style bookingItem:roles fill:#dd4901,stroke:white - - role:bookingItem:OWNER[[bookingItem:OWNER]] - role:bookingItem:ADMIN[[bookingItem:ADMIN]] - role:bookingItem:AGENT[[bookingItem:AGENT]] - role:bookingItem:TENANT[[bookingItem:TENANT]] - end - - subgraph bookingItem:permissions[ ] - style bookingItem:permissions fill:#dd4901,stroke:white - - perm:bookingItem:INSERT{{bookingItem:INSERT}} - perm:bookingItem:DELETE{{bookingItem:DELETE}} - perm:bookingItem:UPDATE{{bookingItem:UPDATE}} - perm:bookingItem:SELECT{{bookingItem:SELECT}} - end -end - -subgraph project["`**project**`"] - direction TB - style project fill:#99bcdb,stroke:#274d6e,stroke-width:8px - - subgraph project:roles[ ] - style project:roles fill:#99bcdb,stroke:white - - role:project:OWNER[[project:OWNER]] - role:project:ADMIN[[project:ADMIN]] - role:project:AGENT[[project:AGENT]] - role:project:TENANT[[project:TENANT]] - end -end - -%% granting roles to roles -role:project:OWNER -.-> role:project:ADMIN -role:project:ADMIN -.-> role:project:AGENT -role:project:AGENT -.-> role:project:TENANT -role:project:AGENT ==> role:bookingItem:OWNER -role:bookingItem:OWNER ==> role:bookingItem:ADMIN -role:bookingItem:ADMIN ==> role:bookingItem:AGENT -role:bookingItem:AGENT ==> role:bookingItem:TENANT -role:bookingItem:TENANT ==> role:project:TENANT - -%% granting permissions to roles -role:global:ADMIN ==> perm:bookingItem:INSERT -role:global:ADMIN ==> perm:bookingItem:DELETE -role:project:ADMIN ==> perm:bookingItem:INSERT -role:bookingItem:ADMIN ==> perm:bookingItem:UPDATE -role:bookingItem:TENANT ==> perm:bookingItem:SELECT - -``` diff --git a/src/main/resources/db/changelog/6-hs-booking/630-booking-item/6203-hs-booking-item-rbac.sql b/src/main/resources/db/changelog/6-hs-booking/630-booking-item/6203-hs-booking-item-rbac.sql deleted file mode 100644 index bcd6523e..00000000 --- a/src/main/resources/db/changelog/6-hs-booking/630-booking-item/6203-hs-booking-item-rbac.sql +++ /dev/null @@ -1,277 +0,0 @@ ---liquibase formatted sql --- This code generated was by RbacViewPostgresGenerator, do not amend manually. - - --- ============================================================================ ---changeset hs-booking-item-rbac-OBJECT:1 endDelimiter:--// --- ---------------------------------------------------------------------------- -call generateRelatedRbacObject('hs_booking_item'); ---// - - --- ============================================================================ ---changeset hs-booking-item-rbac-ROLE-DESCRIPTORS:1 endDelimiter:--// --- ---------------------------------------------------------------------------- -call generateRbacRoleDescriptors('hsBookingItem', 'hs_booking_item'); ---// - - --- ============================================================================ ---changeset hs-booking-item-rbac-insert-trigger:1 endDelimiter:--// --- ---------------------------------------------------------------------------- - -/* - Creates the roles, grants and permission for the AFTER INSERT TRIGGER. - */ - -create or replace procedure buildRbacSystemForHsBookingItem( - NEW hs_booking_item -) - language plpgsql as $$ - -declare - newProject hs_booking_project; - newParentItem hs_booking_item; - -begin - call enterTriggerForObjectUuid(NEW.uuid); - - SELECT * FROM hs_booking_project WHERE uuid = NEW.projectUuid INTO newProject; - - SELECT * FROM hs_booking_item WHERE uuid = NEW.parentItemUuid INTO newParentItem; - - perform createRoleWithGrants( - hsBookingItemOWNER(NEW), - incomingSuperRoles => array[ - hsBookingItemAGENT(newParentItem), - hsBookingProjectAGENT(newProject)] - ); - - perform createRoleWithGrants( - hsBookingItemADMIN(NEW), - permissions => array['UPDATE'], - incomingSuperRoles => array[hsBookingItemOWNER(NEW)] - ); - - perform createRoleWithGrants( - hsBookingItemAGENT(NEW), - incomingSuperRoles => array[hsBookingItemADMIN(NEW)] - ); - - perform createRoleWithGrants( - hsBookingItemTENANT(NEW), - permissions => array['SELECT'], - incomingSuperRoles => array[hsBookingItemAGENT(NEW)], - outgoingSubRoles => array[ - hsBookingItemTENANT(newParentItem), - hsBookingProjectTENANT(newProject)] - ); - - - - call grantPermissionToRole(createPermission(NEW.uuid, 'DELETE'), globalAdmin()); - - call leaveTriggerForObjectUuid(NEW.uuid); -end; $$; - -/* - AFTER INSERT TRIGGER to create the role+grant structure for a new hs_booking_item row. - */ - -create or replace function insertTriggerForHsBookingItem_tf() - returns trigger - language plpgsql - strict as $$ -begin - call buildRbacSystemForHsBookingItem(NEW); - return NEW; -end; $$; - -create trigger insertTriggerForHsBookingItem_tg - after insert on hs_booking_item - for each row -execute procedure insertTriggerForHsBookingItem_tf(); ---// - - --- ============================================================================ ---changeset hs-booking-item-rbac-GRANTING-INSERT-PERMISSION:1 endDelimiter:--// --- ---------------------------------------------------------------------------- - --- granting INSERT permission to global ---------------------------- - -/* - Grants INSERT INTO hs_booking_item permissions to specified role of pre-existing global rows. - */ -do language plpgsql $$ - declare - row global; - begin - call defineContext('create INSERT INTO hs_booking_item permissions for pre-exising global rows'); - - FOR row IN SELECT * FROM global - -- unconditional for all rows in that table - LOOP - call grantPermissionToRole( - createPermission(row.uuid, 'INSERT', 'hs_booking_item'), - globalADMIN()); - END LOOP; - end; -$$; - -/** - Grants hs_booking_item INSERT permission to specified role of new global rows. -*/ -create or replace function new_hs_booking_item_grants_insert_to_global_tf() - returns trigger - language plpgsql - strict as $$ -begin - -- unconditional for all rows in that table - call grantPermissionToRole( - createPermission(NEW.uuid, 'INSERT', 'hs_booking_item'), - globalADMIN()); - -- end. - return NEW; -end; $$; - --- z_... is to put it at the end of after insert triggers, to make sure the roles exist -create trigger z_new_hs_booking_item_grants_insert_to_global_tg - after insert on global - for each row -execute procedure new_hs_booking_item_grants_insert_to_global_tf(); - --- granting INSERT permission to hs_booking_project ---------------------------- - -/* - Grants INSERT INTO hs_booking_item permissions to specified role of pre-existing hs_booking_project rows. - */ -do language plpgsql $$ - declare - row hs_booking_project; - begin - call defineContext('create INSERT INTO hs_booking_item permissions for pre-exising hs_booking_project rows'); - - FOR row IN SELECT * FROM hs_booking_project - -- unconditional for all rows in that table - LOOP - call grantPermissionToRole( - createPermission(row.uuid, 'INSERT', 'hs_booking_item'), - hsBookingProjectADMIN(row)); - END LOOP; - end; -$$; - -/** - Grants hs_booking_item INSERT permission to specified role of new hs_booking_project rows. -*/ -create or replace function new_hs_booking_item_grants_insert_to_hs_booking_project_tf() - returns trigger - language plpgsql - strict as $$ -begin - -- unconditional for all rows in that table - call grantPermissionToRole( - createPermission(NEW.uuid, 'INSERT', 'hs_booking_item'), - hsBookingProjectADMIN(NEW)); - -- end. - return NEW; -end; $$; - --- z_... is to put it at the end of after insert triggers, to make sure the roles exist -create trigger z_new_hs_booking_item_grants_insert_to_hs_booking_project_tg - after insert on hs_booking_project - for each row -execute procedure new_hs_booking_item_grants_insert_to_hs_booking_project_tf(); - --- granting INSERT permission to hs_booking_item ---------------------------- - --- Granting INSERT INTO hs_hosting_asset permissions to specified role of pre-existing hs_hosting_asset rows slipped, --- because there cannot yet be any pre-existing rows in the same table yet. - -/** - Grants hs_booking_item INSERT permission to specified role of new hs_booking_item rows. -*/ -create or replace function new_hs_booking_item_grants_insert_to_hs_booking_item_tf() - returns trigger - language plpgsql - strict as $$ -begin - -- unconditional for all rows in that table - call grantPermissionToRole( - createPermission(NEW.uuid, 'INSERT', 'hs_booking_item'), - hsBookingItemADMIN(NEW)); - -- end. - return NEW; -end; $$; - --- z_... is to put it at the end of after insert triggers, to make sure the roles exist -create trigger z_new_hs_booking_item_grants_insert_to_hs_booking_item_tg - after insert on hs_booking_item - for each row -execute procedure new_hs_booking_item_grants_insert_to_hs_booking_item_tf(); - - --- ============================================================================ ---changeset hs_booking_item-rbac-CHECKING-INSERT-PERMISSION:1 endDelimiter:--// --- ---------------------------------------------------------------------------- - -/** - Checks if the user respectively the assumed roles are allowed to insert a row to hs_booking_item. -*/ -create or replace function hs_booking_item_insert_permission_check_tf() - returns trigger - language plpgsql as $$ -declare - superObjectUuid uuid; -begin - -- check INSERT INSERT if global ADMIN - if isGlobalAdmin() then - return NEW; - end if; - -- check INSERT permission via direct foreign key: NEW.projectUuid - if hasInsertPermission(NEW.projectUuid, 'hs_booking_item') then - return NEW; - end if; - -- check INSERT permission via direct foreign key: NEW.parentItemUuid - if hasInsertPermission(NEW.parentItemUuid, 'hs_booking_item') then - return NEW; - end if; - - raise exception '[403] insert into hs_booking_item values(%) not allowed for current subjects % (%)', - NEW, currentSubjects(), currentSubjectsUuids(); -end; $$; - -create trigger hs_booking_item_insert_permission_check_tg - before insert on hs_booking_item - for each row - execute procedure hs_booking_item_insert_permission_check_tf(); ---// - - --- ============================================================================ ---changeset hs-booking-item-rbac-IDENTITY-VIEW:1 endDelimiter:--// --- ---------------------------------------------------------------------------- - -call generateRbacIdentityViewFromProjection('hs_booking_item', - $idName$ - caption - $idName$); ---// - - --- ============================================================================ ---changeset hs-booking-item-rbac-RESTRICTED-VIEW:1 endDelimiter:--// --- ---------------------------------------------------------------------------- -call generateRbacRestrictedView('hs_booking_item', - $orderBy$ - validity - $orderBy$, - $updates$ - version = new.version, - caption = new.caption, - validity = new.validity, - resources = new.resources - $updates$); ---// - diff --git a/src/main/resources/db/changelog/6-hs-booking/630-booking-item/6300-hs-booking-item.sql b/src/main/resources/db/changelog/6-hs-booking/630-booking-item/6300-hs-booking-item.sql index 4796ac58..cda9eece 100644 --- a/src/main/resources/db/changelog/6-hs-booking/630-booking-item/6300-hs-booking-item.sql +++ b/src/main/resources/db/changelog/6-hs-booking/630-booking-item/6300-hs-booking-item.sql @@ -1,7 +1,7 @@ --liquibase formatted sql -- ============================================================================ ---changeset booking-item-MAIN-TABLE:1 endDelimiter:--// +--changeset michael.hoennig:booking-item-MAIN-TABLE endDelimiter:--// -- ---------------------------------------------------------------------------- create type HsBookingItemType as enum ( @@ -16,7 +16,7 @@ CREATE CAST (character varying as HsBookingItemType) WITH INOUT AS IMPLICIT; create table if not exists hs_booking_item ( - uuid uuid unique references RbacObject (uuid), + uuid uuid unique references rbac.object (uuid), version int not null default 0, projectUuid uuid null references hs_booking_project(uuid), type HsBookingItemType not null, @@ -32,16 +32,16 @@ create table if not exists hs_booking_item -- ============================================================================ ---changeset hs-booking-item-MAIN-TABLE-JOURNAL:1 endDelimiter:--// +--changeset michael.hoennig:hs-booking-item-MAIN-TABLE-JOURNAL endDelimiter:--// -- ---------------------------------------------------------------------------- -call create_journal('hs_booking_item'); +call base.create_journal('hs_booking_item'); --// -- ============================================================================ ---changeset hs-booking-item-MAIN-TABLE-HISTORIZATION:1 endDelimiter:--// +--changeset michael.hoennig:hs-booking-item-MAIN-TABLE-HISTORIZATION endDelimiter:--// -- ---------------------------------------------------------------------------- -call tx_create_historicization('hs_booking_item'); +call base.tx_create_historicization('hs_booking_item'); --// diff --git a/src/main/resources/db/changelog/6-hs-booking/630-booking-item/6303-hs-booking-item-rbac.md b/src/main/resources/db/changelog/6-hs-booking/630-booking-item/6303-hs-booking-item-rbac.md index 4775616f..4c19e05f 100644 --- a/src/main/resources/db/changelog/6-hs-booking/630-booking-item/6303-hs-booking-item-rbac.md +++ b/src/main/resources/db/changelog/6-hs-booking/630-booking-item/6303-hs-booking-item-rbac.md @@ -54,8 +54,8 @@ role:bookingItem:AGENT ==> role:bookingItem:TENANT role:bookingItem:TENANT ==> role:project:TENANT %% granting permissions to roles -role:global:ADMIN ==> perm:bookingItem:INSERT -role:global:ADMIN ==> perm:bookingItem:DELETE +role:rbac.global:ADMIN ==> perm:bookingItem:INSERT +role:rbac.global:ADMIN ==> perm:bookingItem:DELETE role:project:ADMIN ==> perm:bookingItem:INSERT role:bookingItem:ADMIN ==> perm:bookingItem:UPDATE role:bookingItem:TENANT ==> perm:bookingItem:SELECT diff --git a/src/main/resources/db/changelog/6-hs-booking/630-booking-item/6303-hs-booking-item-rbac.sql b/src/main/resources/db/changelog/6-hs-booking/630-booking-item/6303-hs-booking-item-rbac.sql index bcd6523e..dd0ea486 100644 --- a/src/main/resources/db/changelog/6-hs-booking/630-booking-item/6303-hs-booking-item-rbac.sql +++ b/src/main/resources/db/changelog/6-hs-booking/630-booking-item/6303-hs-booking-item-rbac.sql @@ -3,21 +3,21 @@ -- ============================================================================ ---changeset hs-booking-item-rbac-OBJECT:1 endDelimiter:--// +--changeset michael.hoennig:hs-booking-item-rbac-OBJECT endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRelatedRbacObject('hs_booking_item'); +call rbac.generateRelatedRbacObject('hs_booking_item'); --// -- ============================================================================ ---changeset hs-booking-item-rbac-ROLE-DESCRIPTORS:1 endDelimiter:--// +--changeset michael.hoennig:hs-booking-item-rbac-ROLE-DESCRIPTORS endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRbacRoleDescriptors('hsBookingItem', 'hs_booking_item'); +call rbac.generateRbacRoleDescriptors('hsBookingItem', 'hs_booking_item'); --// -- ============================================================================ ---changeset hs-booking-item-rbac-insert-trigger:1 endDelimiter:--// +--changeset michael.hoennig:hs-booking-item-rbac-insert-trigger endDelimiter:--// -- ---------------------------------------------------------------------------- /* @@ -34,31 +34,31 @@ declare newParentItem hs_booking_item; begin - call enterTriggerForObjectUuid(NEW.uuid); + call rbac.enterTriggerForObjectUuid(NEW.uuid); SELECT * FROM hs_booking_project WHERE uuid = NEW.projectUuid INTO newProject; SELECT * FROM hs_booking_item WHERE uuid = NEW.parentItemUuid INTO newParentItem; - perform createRoleWithGrants( + perform rbac.defineRoleWithGrants( hsBookingItemOWNER(NEW), incomingSuperRoles => array[ hsBookingItemAGENT(newParentItem), hsBookingProjectAGENT(newProject)] ); - perform createRoleWithGrants( + perform rbac.defineRoleWithGrants( hsBookingItemADMIN(NEW), permissions => array['UPDATE'], incomingSuperRoles => array[hsBookingItemOWNER(NEW)] ); - perform createRoleWithGrants( + perform rbac.defineRoleWithGrants( hsBookingItemAGENT(NEW), incomingSuperRoles => array[hsBookingItemADMIN(NEW)] ); - perform createRoleWithGrants( + perform rbac.defineRoleWithGrants( hsBookingItemTENANT(NEW), permissions => array['SELECT'], incomingSuperRoles => array[hsBookingItemAGENT(NEW)], @@ -69,9 +69,9 @@ begin - call grantPermissionToRole(createPermission(NEW.uuid, 'DELETE'), globalAdmin()); + call rbac.grantPermissionToRole(rbac.createPermission(NEW.uuid, 'DELETE'), rbac.globalAdmin()); - call leaveTriggerForObjectUuid(NEW.uuid); + call rbac.leaveTriggerForObjectUuid(NEW.uuid); end; $$; /* @@ -95,7 +95,7 @@ execute procedure insertTriggerForHsBookingItem_tf(); -- ============================================================================ ---changeset hs-booking-item-rbac-GRANTING-INSERT-PERMISSION:1 endDelimiter:--// +--changeset michael.hoennig:hs-booking-item-rbac-GRANTING-INSERT-PERMISSION endDelimiter:--// -- ---------------------------------------------------------------------------- -- granting INSERT permission to global ---------------------------- @@ -105,22 +105,22 @@ execute procedure insertTriggerForHsBookingItem_tf(); */ do language plpgsql $$ declare - row global; + row rbac.global%ROWTYPE; begin - call defineContext('create INSERT INTO hs_booking_item permissions for pre-exising global rows'); + call base.defineContext('create INSERT INTO hs_booking_item permissions for pre-exising rbac.global rows'); - FOR row IN SELECT * FROM global + FOR row IN SELECT * FROM rbac.global -- unconditional for all rows in that table LOOP - call grantPermissionToRole( - createPermission(row.uuid, 'INSERT', 'hs_booking_item'), - globalADMIN()); + call rbac.grantPermissionToRole( + rbac.createPermission(row.uuid, 'INSERT', 'hs_booking_item'), + rbac.globalAdmin()); END LOOP; end; $$; /** - Grants hs_booking_item INSERT permission to specified role of new global rows. + Grants hs_booking_item INSERT permission to specified role of new rbac.global rows. */ create or replace function new_hs_booking_item_grants_insert_to_global_tf() returns trigger @@ -128,16 +128,16 @@ create or replace function new_hs_booking_item_grants_insert_to_global_tf() strict as $$ begin -- unconditional for all rows in that table - call grantPermissionToRole( - createPermission(NEW.uuid, 'INSERT', 'hs_booking_item'), - globalADMIN()); + call rbac.grantPermissionToRole( + rbac.createPermission(NEW.uuid, 'INSERT', 'hs_booking_item'), + rbac.globalAdmin()); -- end. return NEW; end; $$; -- z_... is to put it at the end of after insert triggers, to make sure the roles exist create trigger z_new_hs_booking_item_grants_insert_to_global_tg - after insert on global + after insert on rbac.global for each row execute procedure new_hs_booking_item_grants_insert_to_global_tf(); @@ -150,13 +150,13 @@ do language plpgsql $$ declare row hs_booking_project; begin - call defineContext('create INSERT INTO hs_booking_item permissions for pre-exising hs_booking_project rows'); + call base.defineContext('create INSERT INTO hs_booking_item permissions for pre-exising hs_booking_project rows'); FOR row IN SELECT * FROM hs_booking_project -- unconditional for all rows in that table LOOP - call grantPermissionToRole( - createPermission(row.uuid, 'INSERT', 'hs_booking_item'), + call rbac.grantPermissionToRole( + rbac.createPermission(row.uuid, 'INSERT', 'hs_booking_item'), hsBookingProjectADMIN(row)); END LOOP; end; @@ -171,8 +171,8 @@ create or replace function new_hs_booking_item_grants_insert_to_hs_booking_proje strict as $$ begin -- unconditional for all rows in that table - call grantPermissionToRole( - createPermission(NEW.uuid, 'INSERT', 'hs_booking_item'), + call rbac.grantPermissionToRole( + rbac.createPermission(NEW.uuid, 'INSERT', 'hs_booking_item'), hsBookingProjectADMIN(NEW)); -- end. return NEW; @@ -198,8 +198,8 @@ create or replace function new_hs_booking_item_grants_insert_to_hs_booking_item_ strict as $$ begin -- unconditional for all rows in that table - call grantPermissionToRole( - createPermission(NEW.uuid, 'INSERT', 'hs_booking_item'), + call rbac.grantPermissionToRole( + rbac.createPermission(NEW.uuid, 'INSERT', 'hs_booking_item'), hsBookingItemADMIN(NEW)); -- end. return NEW; @@ -213,7 +213,7 @@ execute procedure new_hs_booking_item_grants_insert_to_hs_booking_item_tf(); -- ============================================================================ ---changeset hs_booking_item-rbac-CHECKING-INSERT-PERMISSION:1 endDelimiter:--// +--changeset michael.hoennig:hs_booking_item-rbac-CHECKING-INSERT-PERMISSION endDelimiter:--// -- ---------------------------------------------------------------------------- /** @@ -225,21 +225,21 @@ create or replace function hs_booking_item_insert_permission_check_tf() declare superObjectUuid uuid; begin - -- check INSERT INSERT if global ADMIN - if isGlobalAdmin() then + -- check INSERT INSERT if rbac.Global ADMIN + if rbac.isGlobalAdmin() then return NEW; end if; -- check INSERT permission via direct foreign key: NEW.projectUuid - if hasInsertPermission(NEW.projectUuid, 'hs_booking_item') then + if rbac.hasInsertPermission(NEW.projectUuid, 'hs_booking_item') then return NEW; end if; -- check INSERT permission via direct foreign key: NEW.parentItemUuid - if hasInsertPermission(NEW.parentItemUuid, 'hs_booking_item') then + if rbac.hasInsertPermission(NEW.parentItemUuid, 'hs_booking_item') then return NEW; end if; raise exception '[403] insert into hs_booking_item values(%) not allowed for current subjects % (%)', - NEW, currentSubjects(), currentSubjectsUuids(); + NEW, base.currentSubjects(), rbac.currentSubjectOrAssumedRolesUuids(); end; $$; create trigger hs_booking_item_insert_permission_check_tg @@ -250,10 +250,10 @@ create trigger hs_booking_item_insert_permission_check_tg -- ============================================================================ ---changeset hs-booking-item-rbac-IDENTITY-VIEW:1 endDelimiter:--// +--changeset michael.hoennig:hs-booking-item-rbac-IDENTITY-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRbacIdentityViewFromProjection('hs_booking_item', +call rbac.generateRbacIdentityViewFromProjection('hs_booking_item', $idName$ caption $idName$); @@ -261,9 +261,9 @@ call generateRbacIdentityViewFromProjection('hs_booking_item', -- ============================================================================ ---changeset hs-booking-item-rbac-RESTRICTED-VIEW:1 endDelimiter:--// +--changeset michael.hoennig:hs-booking-item-rbac-RESTRICTED-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRbacRestrictedView('hs_booking_item', +call rbac.generateRbacRestrictedView('hs_booking_item', $orderBy$ validity $orderBy$, diff --git a/src/main/resources/db/changelog/6-hs-booking/630-booking-item/6308-hs-booking-item-test-data.sql b/src/main/resources/db/changelog/6-hs-booking/630-booking-item/6308-hs-booking-item-test-data.sql index 4052b5c3..d6f31b0f 100644 --- a/src/main/resources/db/changelog/6-hs-booking/630-booking-item/6308-hs-booking-item-test-data.sql +++ b/src/main/resources/db/changelog/6-hs-booking/630-booking-item/6308-hs-booking-item-test-data.sql @@ -2,7 +2,7 @@ -- ============================================================================ ---changeset hs-booking-item-TEST-DATA-GENERATOR:1 endDelimiter:--// +--changeset michael.hoennig:hs-booking-item-TEST-DATA-GENERATOR endDelimiter:--// -- ---------------------------------------------------------------------------- /* @@ -40,14 +40,14 @@ end; $$; -- ============================================================================ ---changeset hs-booking-item-TEST-DATA-GENERATION:1 –context=dev,tc endDelimiter:--// +--changeset michael.hoennig:hs-booking-item-TEST-DATA-GENERATION –context=dev,tc endDelimiter:--// -- ---------------------------------------------------------------------------- do language plpgsql $$ declare currentTask text; begin - call defineContext('creating booking-item test-data', null, 'superuser-alex@hostsharing.net', 'global#global:ADMIN'); + call base.defineContext('creating booking-item test-data', null, 'superuser-alex@hostsharing.net', 'rbac.global#global:ADMIN'); call createHsBookingItemTransactionTestData(10001, '11'); call createHsBookingItemTransactionTestData(10002, '12'); diff --git a/src/main/resources/db/changelog/7-hs-hosting/701-hosting-asset/7010-hs-hosting-asset.sql b/src/main/resources/db/changelog/7-hs-hosting/701-hosting-asset/7010-hs-hosting-asset.sql index 83d6cacb..0bec8667 100644 --- a/src/main/resources/db/changelog/7-hs-hosting/701-hosting-asset/7010-hs-hosting-asset.sql +++ b/src/main/resources/db/changelog/7-hs-hosting/701-hosting-asset/7010-hs-hosting-asset.sql @@ -1,7 +1,7 @@ --liquibase formatted sql -- ============================================================================ ---changeset hosting-asset-MAIN-TABLE:1 endDelimiter:--// +--changeset michael.hoennig:hosting-asset-MAIN-TABLE endDelimiter:--// -- ---------------------------------------------------------------------------- create type HsHostingAssetType as enum ( @@ -30,7 +30,7 @@ CREATE CAST (character varying as HsHostingAssetType) WITH INOUT AS IMPLICIT; create table if not exists hs_hosting_asset ( - uuid uuid unique references RbacObject (uuid), + uuid uuid unique references rbac.object (uuid), version int not null default 0, bookingItemUuid uuid null references hs_booking_item(uuid), type HsHostingAssetType not null, @@ -48,7 +48,7 @@ create table if not exists hs_hosting_asset -- ============================================================================ ---changeset hosting-asset-TYPE-HIERARCHY-CHECK:1 endDelimiter:--// +--changeset michael.hoennig:hosting-asset-TYPE-HIERARCHY-CHECK endDelimiter:--// -- ---------------------------------------------------------------------------- -- TODO.impl: this could be generated from HsHostingAssetType @@ -91,7 +91,7 @@ begin when 'IPV4_NUMBER' then null when 'IPV6_NUMBER' then null - else raiseException(format('[400] unknown asset type %s', NEW.type::text)) + else base.raiseException(format('[400] unknown asset type %s', NEW.type::text)) end); if expectedParentType is not null and actualParentType is null then @@ -113,7 +113,7 @@ create trigger hs_hosting_asset_type_hierarchy_check_tg -- ============================================================================ ---changeset hosting-asset-system-sequences:1 endDelimiter:--// +--changeset michael.hoennig:hosting-asset-system-sequences endDelimiter:--// -- ---------------------------------------------------------------------------- CREATE SEQUENCE IF NOT EXISTS hs_hosting_asset_unixuser_system_id_seq @@ -127,7 +127,7 @@ CREATE SEQUENCE IF NOT EXISTS hs_hosting_asset_unixuser_system_id_seq -- ============================================================================ ---changeset hosting-asset-BOOKING-ITEM-HIERARCHY-CHECK:1 endDelimiter:--// +--changeset michael.hoennig:hosting-asset-BOOKING-ITEM-HIERARCHY-CHECK endDelimiter:--// -- ---------------------------------------------------------------------------- create or replace function hs_hosting_asset_booking_item_hierarchy_check_tf() @@ -164,16 +164,16 @@ execute procedure hs_hosting_asset_booking_item_hierarchy_check_tf(); -- ============================================================================ ---changeset hs-hosting-asset-MAIN-TABLE-JOURNAL:1 endDelimiter:--// +--changeset michael.hoennig:hs-hosting-asset-MAIN-TABLE-JOURNAL endDelimiter:--// -- ---------------------------------------------------------------------------- -call create_journal('hs_hosting_asset'); +call base.create_journal('hs_hosting_asset'); --// -- ============================================================================ ---changeset hs-hosting-asset-MAIN-TABLE-HISTORIZATION:1 endDelimiter:--// +--changeset michael.hoennig:hs-hosting-asset-MAIN-TABLE-HISTORIZATION endDelimiter:--// -- ---------------------------------------------------------------------------- -call tx_create_historicization('hs_hosting_asset'); +call base.tx_create_historicization('hs_hosting_asset'); --// diff --git a/src/main/resources/db/changelog/7-hs-hosting/701-hosting-asset/7013-hs-hosting-asset-rbac.md b/src/main/resources/db/changelog/7-hs-hosting/701-hosting-asset/7013-hs-hosting-asset-rbac.md index d06f9f9a..b5ece0c6 100644 --- a/src/main/resources/db/changelog/7-hs-hosting/701-hosting-asset/7013-hs-hosting-asset-rbac.md +++ b/src/main/resources/db/changelog/7-hs-hosting/701-hosting-asset/7013-hs-hosting-asset-rbac.md @@ -88,10 +88,10 @@ user:creator ==> role:asset:OWNER role:bookingItem:OWNER -.-> role:bookingItem:ADMIN role:bookingItem:ADMIN -.-> role:bookingItem:AGENT role:bookingItem:AGENT -.-> role:bookingItem:TENANT -role:global:ADMIN -.-> role:alarmContact:OWNER +role:rbac.global:ADMIN -.-> role:alarmContact:OWNER role:alarmContact:OWNER -.-> role:alarmContact:ADMIN role:alarmContact:ADMIN -.-> role:alarmContact:REFERRER -role:global:ADMIN ==>|XX| role:asset:OWNER +role:rbac.global:ADMIN ==>|XX| role:asset:OWNER role:bookingItem:ADMIN ==> role:asset:OWNER role:parentAsset:ADMIN ==> role:asset:OWNER role:asset:OWNER ==> role:asset:ADMIN @@ -107,9 +107,9 @@ role:asset:TENANT ==> role:parentAsset:TENANT role:alarmContact:ADMIN ==> role:asset:TENANT %% granting permissions to roles -role:global:ADMIN ==> perm:asset:INSERT +role:rbac.global:ADMIN ==> perm:asset:INSERT role:parentAsset:ADMIN ==> perm:asset:INSERT -role:global:GUEST ==> perm:asset:INSERT +role:rbac.global:GUEST ==> perm:asset:INSERT role:asset:OWNER ==> perm:asset:DELETE role:asset:ADMIN ==> perm:asset:UPDATE role:asset:TENANT ==> perm:asset:SELECT diff --git a/src/main/resources/db/changelog/7-hs-hosting/701-hosting-asset/7013-hs-hosting-asset-rbac.sql b/src/main/resources/db/changelog/7-hs-hosting/701-hosting-asset/7013-hs-hosting-asset-rbac.sql index 5ec3e044..3bfd9df8 100644 --- a/src/main/resources/db/changelog/7-hs-hosting/701-hosting-asset/7013-hs-hosting-asset-rbac.sql +++ b/src/main/resources/db/changelog/7-hs-hosting/701-hosting-asset/7013-hs-hosting-asset-rbac.sql @@ -3,21 +3,21 @@ -- ============================================================================ ---changeset hs-hosting-asset-rbac-OBJECT:1 endDelimiter:--// +--changeset michael.hoennig:hs-hosting-asset-rbac-OBJECT endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRelatedRbacObject('hs_hosting_asset'); +call rbac.generateRelatedRbacObject('hs_hosting_asset'); --// -- ============================================================================ ---changeset hs-hosting-asset-rbac-ROLE-DESCRIPTORS:1 endDelimiter:--// +--changeset michael.hoennig:hs-hosting-asset-rbac-ROLE-DESCRIPTORS endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRbacRoleDescriptors('hsHostingAsset', 'hs_hosting_asset'); +call rbac.generateRbacRoleDescriptors('hsHostingAsset', 'hs_hosting_asset'); --// -- ============================================================================ ---changeset hs-hosting-asset-rbac-insert-trigger:1 endDelimiter:--// +--changeset michael.hoennig:hs-hosting-asset-rbac-insert-trigger endDelimiter:--// -- ---------------------------------------------------------------------------- /* @@ -36,7 +36,7 @@ declare newParentAsset hs_hosting_asset; begin - call enterTriggerForObjectUuid(NEW.uuid); + call rbac.enterTriggerForObjectUuid(NEW.uuid); SELECT * FROM hs_booking_item WHERE uuid = NEW.bookingItemUuid INTO newBookingItem; @@ -46,17 +46,17 @@ begin SELECT * FROM hs_hosting_asset WHERE uuid = NEW.parentAssetUuid INTO newParentAsset; - perform createRoleWithGrants( + perform rbac.defineRoleWithGrants( hsHostingAssetOWNER(NEW), permissions => array['DELETE'], incomingSuperRoles => array[ - globalADMIN(unassumed()), + rbac.globalADMIN(rbac.unassumed()), hsBookingItemADMIN(newBookingItem), hsHostingAssetADMIN(newParentAsset)], - userUuids => array[currentUserUuid()] + subjectUuids => array[rbac.currentSubjectUuid()] ); - perform createRoleWithGrants( + perform rbac.defineRoleWithGrants( hsHostingAssetADMIN(NEW), permissions => array['UPDATE'], incomingSuperRoles => array[ @@ -65,7 +65,7 @@ begin hsHostingAssetOWNER(NEW)] ); - perform createRoleWithGrants( + perform rbac.defineRoleWithGrants( hsHostingAssetAGENT(NEW), incomingSuperRoles => array[ hsHostingAssetADMIN(NEW), @@ -75,7 +75,7 @@ begin hsOfficeContactREFERRER(newAlarmContact)] ); - perform createRoleWithGrants( + perform rbac.defineRoleWithGrants( hsHostingAssetTENANT(NEW), permissions => array['SELECT'], incomingSuperRoles => array[ @@ -89,7 +89,7 @@ begin IF NEW.type = 'DOMAIN_SETUP' THEN END IF; - call leaveTriggerForObjectUuid(NEW.uuid); + call rbac.leaveTriggerForObjectUuid(NEW.uuid); end; $$; /* @@ -113,7 +113,7 @@ execute procedure insertTriggerForHsHostingAsset_tf(); -- ============================================================================ ---changeset hs-hosting-asset-rbac-update-trigger:1 endDelimiter:--// +--changeset michael.hoennig:hs-hosting-asset-rbac-update-trigger endDelimiter:--// -- ---------------------------------------------------------------------------- /* @@ -129,7 +129,7 @@ begin if NEW.assignedToAssetUuid is distinct from OLD.assignedToAssetUuid or NEW.alarmContactUuid is distinct from OLD.alarmContactUuid then - delete from rbacgrants g where g.grantedbytriggerof = OLD.uuid; + delete from rbac.grants g where g.grantedbytriggerof = OLD.uuid; call buildRbacSystemForHsHostingAsset(NEW); end if; end; $$; @@ -155,10 +155,10 @@ execute procedure updateTriggerForHsHostingAsset_tf(); -- ============================================================================ ---changeset hs-hosting-asset-rbac-IDENTITY-VIEW:1 endDelimiter:--// +--changeset michael.hoennig:hs-hosting-asset-rbac-IDENTITY-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRbacIdentityViewFromProjection('hs_hosting_asset', +call rbac.generateRbacIdentityViewFromProjection('hs_hosting_asset', $idName$ identifier $idName$); @@ -166,9 +166,9 @@ call generateRbacIdentityViewFromProjection('hs_hosting_asset', -- ============================================================================ ---changeset hs-hosting-asset-rbac-RESTRICTED-VIEW:1 endDelimiter:--// +--changeset michael.hoennig:hs-hosting-asset-rbac-RESTRICTED-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call generateRbacRestrictedView('hs_hosting_asset', +call rbac.generateRbacRestrictedView('hs_hosting_asset', $orderBy$ identifier $orderBy$, diff --git a/src/main/resources/db/changelog/7-hs-hosting/701-hosting-asset/7016-hs-hosting-asset-migration.sql b/src/main/resources/db/changelog/7-hs-hosting/701-hosting-asset/7016-hs-hosting-asset-migration.sql index 0cff5fbe..9ce96e72 100644 --- a/src/main/resources/db/changelog/7-hs-hosting/701-hosting-asset/7016-hs-hosting-asset-migration.sql +++ b/src/main/resources/db/changelog/7-hs-hosting/701-hosting-asset/7016-hs-hosting-asset-migration.sql @@ -40,7 +40,7 @@ ALTER TABLE hs_hosting_asset_legacy_id --changeset hs-hosting-asset-MIGRATION-insert:1 endDelimiter:--// -- ---------------------------------------------------------------------------- -CALL defineContext('schema-migration'); +CALL base.defineContext('schema-migration'); INSERT INTO hs_hosting_asset_legacy_id(uuid, legacy_id) SELECT uuid, nextVal('hs_hosting_asset_legacy_id_seq') FROM hs_hosting_asset; --/ diff --git a/src/main/resources/db/changelog/7-hs-hosting/701-hosting-asset/7018-hs-hosting-asset-test-data.sql b/src/main/resources/db/changelog/7-hs-hosting/701-hosting-asset/7018-hs-hosting-asset-test-data.sql index 0af7e38e..711773ba 100644 --- a/src/main/resources/db/changelog/7-hs-hosting/701-hosting-asset/7018-hs-hosting-asset-test-data.sql +++ b/src/main/resources/db/changelog/7-hs-hosting/701-hosting-asset/7018-hs-hosting-asset-test-data.sql @@ -2,7 +2,7 @@ -- ============================================================================ ---changeset hs-hosting-asset-TEST-DATA-GENERATOR:1 endDelimiter:--// +--changeset michael.hoennig:hs-hosting-asset-TEST-DATA-GENERATOR endDelimiter:--// -- ---------------------------------------------------------------------------- /* @@ -21,16 +21,16 @@ declare defaultPrefix varchar; managedServerUuid uuid; managedWebspaceUuid uuid; - webUnixUserUuid uuid; - mboxUnixUserUuid uuid; + webUnixSubjectUuid uuid; + mboxUnixSubjectUuid uuid; domainSetupUuid uuid; domainMBoxSetupUuid uuid; mariaDbInstanceUuid uuid; - mariaDbUserUuid uuid; + mariaDbSubjectUuid uuid; pgSqlInstanceUuid uuid; - PgSqlUserUuid uuid; + PgSqlSubjectUuid uuid; begin - call defineContext('creating hosting-asset test-data', null, 'superuser-alex@hostsharing.net', 'global#global:ADMIN'); + call base.defineContext('creating hosting-asset test-data', null, 'superuser-alex@hostsharing.net', 'rbac.global#global:ADMIN'); select project.* into relatedProject from hs_booking_project project @@ -68,14 +68,14 @@ begin select uuid_generate_v4() into managedServerUuid; select uuid_generate_v4() into managedWebspaceUuid; - select uuid_generate_v4() into webUnixUserUuid; - select uuid_generate_v4() into mboxUnixUserUuid; + select uuid_generate_v4() into webUnixSubjectUuid; + select uuid_generate_v4() into mboxUnixSubjectUuid; select uuid_generate_v4() into domainSetupUuid; select uuid_generate_v4() into domainMBoxSetupUuid; select uuid_generate_v4() into mariaDbInstanceUuid; - select uuid_generate_v4() into mariaDbUserUuid; + select uuid_generate_v4() into mariaDbSubjectUuid; select uuid_generate_v4() into pgSqlInstanceUuid; - select uuid_generate_v4() into pgSqlUserUuid; + select uuid_generate_v4() into pgSqlSubjectUuid; debitorNumberSuffix := relatedDebitor.debitorNumberSuffix; defaultPrefix := relatedDebitor.defaultPrefix; @@ -86,17 +86,17 @@ begin (uuid_generate_v4(), cloudServerBI.uuid, 'CLOUD_SERVER', null, null, 'vm20' || debitorNumberSuffix, 'another CloudServer', '{}'::jsonb), (managedWebspaceUuid, managedWebspaceBI.uuid, 'MANAGED_WEBSPACE', managedServerUuid, null, defaultPrefix || '01', 'some Webspace', '{}'::jsonb), (mariaDbInstanceUuid, null, 'MARIADB_INSTANCE', managedServerUuid, null, 'vm10' || debitorNumberSuffix || '.MariaDB.default', 'some default MariaDB instance','{}'::jsonb), - (mariaDbUserUuid, null, 'MARIADB_USER', managedWebspaceUuid, mariaDbInstanceUuid, defaultPrefix || '01_web', 'some default MariaDB user', '{ "password": ">'caption' - from tx_journal_v + from base.tx_journal_v where targettable = 'hs_booking_item'; """); @@ -175,9 +175,9 @@ class HsBookingItemRepositoryIntegrationTest extends ContextBasedTestWithCleanup .containsExactlyInAnyOrder(fromFormatted( initialGrantNames, - // global-admin + // rbac.global-admin "{ grant perm:hs_booking_item#somenewbookingitem:INSERT>hs_booking_item to role:hs_booking_item#somenewbookingitem:ADMIN by system and assume }", - "{ grant perm:hs_booking_item#somenewbookingitem:DELETE to role:global#global:ADMIN by system and assume }", + "{ grant perm:hs_booking_item#somenewbookingitem:DELETE to role:rbac.global#global:ADMIN by system and assume }", // owner "{ grant role:hs_booking_item#somenewbookingitem:OWNER to role:hs_booking_project#D-1000111-D-1000111defaultproject:AGENT by system and assume }", diff --git a/src/test/java/net/hostsharing/hsadminng/hs/booking/project/HsBookingProjectControllerAcceptanceTest.java b/src/test/java/net/hostsharing/hsadminng/hs/booking/project/HsBookingProjectControllerAcceptanceTest.java index c4bc8e2e..a9f25b94 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/booking/project/HsBookingProjectControllerAcceptanceTest.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/booking/project/HsBookingProjectControllerAcceptanceTest.java @@ -57,7 +57,7 @@ class HsBookingProjectControllerAcceptanceTest extends ContextBasedTestWithClean RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .port(port) .when() .get("http://localhost/api/hs/booking/projects?debitorUuid=" + givenDebitor.getUuid()) @@ -88,7 +88,7 @@ class HsBookingProjectControllerAcceptanceTest extends ContextBasedTestWithClean final var location = RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .contentType(ContentType.JSON) .body(""" { @@ -111,9 +111,9 @@ class HsBookingProjectControllerAcceptanceTest extends ContextBasedTestWithClean .extract().header("Location"); // @formatter:on // finally, the new bookingProject can be accessed under the generated UUID - final var newUserUuid = UUID.fromString( + final var newSubjectUuid = UUID.fromString( location.substring(location.lastIndexOf('/') + 1)); - assertThat(newUserUuid).isNotNull(); + assertThat(newSubjectUuid).isNotNull(); } } @@ -128,7 +128,7 @@ class HsBookingProjectControllerAcceptanceTest extends ContextBasedTestWithClean RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .port(port) .when() .get("http://localhost/api/hs/booking/projects/" + givenBookingProjectUuid) @@ -151,7 +151,7 @@ class HsBookingProjectControllerAcceptanceTest extends ContextBasedTestWithClean RestAssured // @formatter:off .given() - .header("current-user", "selfregistered-user-drew@hostsharing.org") + .header("current-subject", "selfregistered-user-drew@hostsharing.org") .port(port) .when() .get("http://localhost/api/hs/booking/projects/" + givenBookingProjectUuid) @@ -167,7 +167,7 @@ class HsBookingProjectControllerAcceptanceTest extends ContextBasedTestWithClean RestAssured // @formatter:off .given() - .header("current-user", "person-TuckerJack@example.com") + .header("current-subject", "person-TuckerJack@example.com") .header("assumed-roles", "hs_booking_project#D-1000313-D-1000313defaultproject:AGENT") .port(port) .when() @@ -193,7 +193,7 @@ class HsBookingProjectControllerAcceptanceTest extends ContextBasedTestWithClean RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .contentType(ContentType.JSON) .body(""" { @@ -232,7 +232,7 @@ class HsBookingProjectControllerAcceptanceTest extends ContextBasedTestWithClean RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .port(port) .when() .delete("http://localhost/api/hs/booking/projects/" + givenBookingProject.getUuid()) @@ -250,7 +250,7 @@ class HsBookingProjectControllerAcceptanceTest extends ContextBasedTestWithClean RestAssured // @formatter:off .given() - .header("current-user", "selfregistered-user-drew@hostsharing.org") + .header("current-subject", "selfregistered-user-drew@hostsharing.org") .port(port) .when() .delete("http://localhost/api/hs/booking/projects/" + givenBookingProject.getUuid()) diff --git a/src/test/java/net/hostsharing/hsadminng/hs/booking/project/HsBookingProjectRepositoryIntegrationTest.java b/src/test/java/net/hostsharing/hsadminng/hs/booking/project/HsBookingProjectRepositoryIntegrationTest.java index b3a05ffa..f4ada1b2 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/booking/project/HsBookingProjectRepositoryIntegrationTest.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/booking/project/HsBookingProjectRepositoryIntegrationTest.java @@ -2,8 +2,8 @@ package net.hostsharing.hsadminng.hs.booking.project; import net.hostsharing.hsadminng.context.Context; import net.hostsharing.hsadminng.hs.booking.debitor.HsBookingDebitorRepository; -import net.hostsharing.hsadminng.rbac.rbacgrant.RawRbacGrantRepository; -import net.hostsharing.hsadminng.rbac.rbacrole.RawRbacRoleRepository; +import net.hostsharing.hsadminng.rbac.grant.RawRbacGrantRepository; +import net.hostsharing.hsadminng.rbac.role.RawRbacRoleRepository; import net.hostsharing.hsadminng.mapper.Array; import net.hostsharing.hsadminng.rbac.test.ContextBasedTestWithCleanup; import net.hostsharing.hsadminng.rbac.test.JpaAttempt; @@ -25,8 +25,8 @@ import java.time.ZonedDateTime; import java.util.Arrays; import java.util.List; -import static net.hostsharing.hsadminng.rbac.rbacgrant.RawRbacGrantEntity.distinctGrantDisplaysOf; -import static net.hostsharing.hsadminng.rbac.rbacrole.RawRbacRoleEntity.distinctRoleNamesOf; +import static net.hostsharing.hsadminng.rbac.grant.RawRbacGrantEntity.distinctGrantDisplaysOf; +import static net.hostsharing.hsadminng.rbac.role.RawRbacRoleEntity.distinctRoleNamesOf; import static net.hostsharing.hsadminng.mapper.Array.fromFormatted; import static net.hostsharing.hsadminng.rbac.test.JpaAttempt.attempt; import static org.assertj.core.api.Assertions.assertThat; @@ -64,7 +64,7 @@ class HsBookingProjectRepositoryIntegrationTest extends ContextBasedTestWithClea // given final var query = em.createNativeQuery(""" select currentTask, targetTable, targetOp, targetdelta->>'caption' - from tx_journal_v + from base.tx_journal_v where targettable = 'hs_booking_project'; """); @@ -161,8 +161,8 @@ class HsBookingProjectRepositoryIntegrationTest extends ContextBasedTestWithClea .containsExactlyInAnyOrder(fromFormatted( initialGrantNames, - // global-admin - "{ grant perm:hs_booking_project#D-1000111-somenewbookingproject:DELETE to role:global#global:ADMIN by system and assume }", + // rbacgGlobal-admin + "{ grant perm:hs_booking_project#D-1000111-somenewbookingproject:DELETE to role:rbac.global#global:ADMIN by system and assume }", // owner "{ grant role:hs_booking_project#D-1000111-somenewbookingproject:ADMIN to role:hs_booking_project#D-1000111-somenewbookingproject:OWNER by system and assume }", diff --git a/src/test/java/net/hostsharing/hsadminng/hs/hosting/asset/HsHostingAssetControllerAcceptanceTest.java b/src/test/java/net/hostsharing/hsadminng/hs/hosting/asset/HsHostingAssetControllerAcceptanceTest.java index 81f3192e..92f1ee66 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/hosting/asset/HsHostingAssetControllerAcceptanceTest.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/hosting/asset/HsHostingAssetControllerAcceptanceTest.java @@ -85,7 +85,7 @@ class HsHostingAssetControllerAcceptanceTest extends ContextBasedTestWithCleanup RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .port(port) .when() .get("http://localhost/api/hs/hosting/assets?projectUuid=" + givenProject.getUuid() + "&type=MANAGED_WEBSPACE") @@ -113,7 +113,7 @@ class HsHostingAssetControllerAcceptanceTest extends ContextBasedTestWithCleanup RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .header("assumed-roles", "hs_hosting_asset#fir01:AGENT") .port(port) .when() @@ -160,7 +160,7 @@ class HsHostingAssetControllerAcceptanceTest extends ContextBasedTestWithCleanup final var location = RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .contentType(ContentType.JSON) .body(""" { @@ -217,7 +217,7 @@ class HsHostingAssetControllerAcceptanceTest extends ContextBasedTestWithCleanup final var location = RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .header("assumed-roles", "hs_hosting_asset#vm1011:ADMIN") .contentType(ContentType.JSON) .body(""" @@ -247,9 +247,9 @@ class HsHostingAssetControllerAcceptanceTest extends ContextBasedTestWithCleanup .extract().header("Location"); // @formatter:on // finally, the new asset can be accessed under the generated UUID - final var newUserUuid = UUID.fromString( + final var newSubjectUuid = UUID.fromString( location.substring(location.lastIndexOf('/') + 1)); - assertThat(newUserUuid).isNotNull(); + assertThat(newSubjectUuid).isNotNull(); } @Test @@ -271,7 +271,7 @@ class HsHostingAssetControllerAcceptanceTest extends ContextBasedTestWithCleanup final var location = RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .contentType(ContentType.JSON) .body(""" { @@ -317,7 +317,7 @@ class HsHostingAssetControllerAcceptanceTest extends ContextBasedTestWithCleanup RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .contentType(ContentType.JSON) .body(""" { @@ -372,7 +372,7 @@ class HsHostingAssetControllerAcceptanceTest extends ContextBasedTestWithCleanup RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .contentType(ContentType.JSON) .body(""" { @@ -411,7 +411,7 @@ class HsHostingAssetControllerAcceptanceTest extends ContextBasedTestWithCleanup RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .port(port) .when() .get("http://localhost/api/hs/hosting/assets/" + givenAssetUuid) @@ -436,7 +436,7 @@ class HsHostingAssetControllerAcceptanceTest extends ContextBasedTestWithCleanup RestAssured // @formatter:off .given() - .header("current-user", "selfregistered-user-drew@hostsharing.org") + .header("current-subject", "selfregistered-user-drew@hostsharing.org") .port(port) .when() .get("http://localhost/api/hs/hosting/assets/" + givenAssetUuid) @@ -453,7 +453,7 @@ class HsHostingAssetControllerAcceptanceTest extends ContextBasedTestWithCleanup RestAssured // @formatter:off .given() - .header("current-user", "person-TuckerJack@example.com") + .header("current-subject", "person-TuckerJack@example.com") .header("assumed-roles", "hs_booking_project#D-1000313-D-1000313defaultproject:AGENT") .port(port) .when() @@ -499,7 +499,7 @@ class HsHostingAssetControllerAcceptanceTest extends ContextBasedTestWithCleanup RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .contentType(ContentType.JSON) .body(""" { @@ -573,7 +573,7 @@ class HsHostingAssetControllerAcceptanceTest extends ContextBasedTestWithCleanup RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") //.header("assumed-roles", "hs_hosting_asset#vm2001:ADMIN") .contentType(ContentType.JSON) .body(""" @@ -657,7 +657,7 @@ class HsHostingAssetControllerAcceptanceTest extends ContextBasedTestWithCleanup .build()); RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .port(port) .when() .delete("http://localhost/api/hs/hosting/assets/" + givenAsset.getUuid()) @@ -690,7 +690,7 @@ class HsHostingAssetControllerAcceptanceTest extends ContextBasedTestWithCleanup .build()); RestAssured // @formatter:off .given() - .header("current-user", "selfregistered-user-drew@hostsharing.org") + .header("current-subject", "selfregistered-user-drew@hostsharing.org") .port(port) .when() .delete("http://localhost/api/hs/hosting/assets/" + givenAsset.getUuid()) diff --git a/src/test/java/net/hostsharing/hsadminng/hs/hosting/asset/HsHostingAssetControllerRestTest.java b/src/test/java/net/hostsharing/hsadminng/hs/hosting/asset/HsHostingAssetControllerRestTest.java index ff2da459..0d9dd87b 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/hosting/asset/HsHostingAssetControllerRestTest.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/hosting/asset/HsHostingAssetControllerRestTest.java @@ -590,7 +590,7 @@ public class HsHostingAssetControllerRestTest { // when final var result = mockMvc.perform(MockMvcRequestBuilders .get("/api/hs/hosting/assets?type="+testCase.name()) - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .accept(MediaType.APPLICATION_JSON)) // then @@ -660,7 +660,7 @@ public class HsHostingAssetControllerRestTest { // when final var result = mockMvc.perform(MockMvcRequestBuilders .patch("/api/hs/hosting/assets/" + givenDomainHttpSetupUuid) - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .contentType(MediaType.APPLICATION_JSON) .content(""" { diff --git a/src/test/java/net/hostsharing/hsadminng/hs/hosting/asset/HsHostingAssetRepositoryIntegrationTest.java b/src/test/java/net/hostsharing/hsadminng/hs/hosting/asset/HsHostingAssetRepositoryIntegrationTest.java index 26861624..d408d241 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/hosting/asset/HsHostingAssetRepositoryIntegrationTest.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/hosting/asset/HsHostingAssetRepositoryIntegrationTest.java @@ -5,8 +5,8 @@ import net.hostsharing.hsadminng.hs.booking.item.HsBookingItemRealEntity; import net.hostsharing.hsadminng.hs.booking.item.HsBookingItemRealRepository; import net.hostsharing.hsadminng.hs.booking.item.HsBookingItemType; import net.hostsharing.hsadminng.hs.booking.project.HsBookingProjectRbacRepository; -import net.hostsharing.hsadminng.rbac.rbacgrant.RawRbacGrantRepository; -import net.hostsharing.hsadminng.rbac.rbacrole.RawRbacRoleRepository; +import net.hostsharing.hsadminng.rbac.grant.RawRbacGrantRepository; +import net.hostsharing.hsadminng.rbac.role.RawRbacRoleRepository; import net.hostsharing.hsadminng.mapper.Array; import net.hostsharing.hsadminng.rbac.test.ContextBasedTestWithCleanup; import net.hostsharing.hsadminng.rbac.test.JpaAttempt; @@ -35,8 +35,8 @@ import static net.hostsharing.hsadminng.hs.hosting.asset.HsHostingAssetType.DOMA import static net.hostsharing.hsadminng.hs.hosting.asset.HsHostingAssetType.EMAIL_ADDRESS; import static net.hostsharing.hsadminng.hs.hosting.asset.HsHostingAssetType.MANAGED_SERVER; import static net.hostsharing.hsadminng.hs.hosting.asset.HsHostingAssetType.MANAGED_WEBSPACE; -import static net.hostsharing.hsadminng.rbac.rbacgrant.RawRbacGrantEntity.distinctGrantDisplaysOf; -import static net.hostsharing.hsadminng.rbac.rbacrole.RawRbacRoleEntity.distinctRoleNamesOf; +import static net.hostsharing.hsadminng.rbac.grant.RawRbacGrantEntity.distinctGrantDisplaysOf; +import static net.hostsharing.hsadminng.rbac.role.RawRbacRoleEntity.distinctRoleNamesOf; import static net.hostsharing.hsadminng.mapper.Array.fromFormatted; import static net.hostsharing.hsadminng.rbac.test.JpaAttempt.attempt; import static org.assertj.core.api.Assertions.assertThat; @@ -77,7 +77,7 @@ class HsHostingAssetRepositoryIntegrationTest extends ContextBasedTestWithCleanu // given final var query = em.createNativeQuery(""" select currentTask, targetTable, targetOp, targetdelta->>'caption' - from tx_journal_v + from base.tx_journal_v where targettable = 'hs_hosting_asset'; """); @@ -200,8 +200,8 @@ class HsHostingAssetRepositoryIntegrationTest extends ContextBasedTestWithCleanu .containsExactlyInAnyOrder(fromFormatted( initialGrantNames, - // global-admin - "{ grant role:hs_hosting_asset#fir00:OWNER to role:global#global:ADMIN by system }", // workaround + // rbac.global-admin + "{ grant role:hs_hosting_asset#fir00:OWNER to role:rbac.global#global:ADMIN by system }", // workaround // owner "{ grant role:hs_hosting_asset#fir00:OWNER to user:superuser-alex@hostsharing.net by hs_hosting_asset#fir00:OWNER and assume }", @@ -250,7 +250,7 @@ class HsHostingAssetRepositoryIntegrationTest extends ContextBasedTestWithCleanu context("person-SmithPeter@example.com"); assertThatAssetIsPersisted(result.returnedValue()); - // ... a global admin can see the new domain setup as well if the domain OWNER role is assumed + // ... a rbac.global admin can see the new domain setup as well if the domain OWNER role is assumed context("superuser-alex@hostsharing.net", "hs_hosting_asset#example.net:OWNER"); // only works with the assumed role assertThatAssetIsPersisted(result.returnedValue()); } diff --git a/src/test/java/net/hostsharing/hsadminng/hs/migration/CsvDataImport.java b/src/test/java/net/hostsharing/hsadminng/hs/migration/CsvDataImport.java index f279e31d..b355706e 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/migration/CsvDataImport.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/migration/CsvDataImport.java @@ -6,7 +6,7 @@ import com.opencsv.CSVReaderBuilder; import lombok.SneakyThrows; import net.hostsharing.hsadminng.hs.hosting.asset.HsHostingAsset; import net.hostsharing.hsadminng.rbac.context.ContextBasedTest; -import net.hostsharing.hsadminng.rbac.rbacobject.BaseEntity; +import net.hostsharing.hsadminng.rbac.object.BaseEntity; import net.hostsharing.hsadminng.rbac.test.JpaAttempt; import org.junit.jupiter.api.extension.BeforeEachCallback; import org.junit.jupiter.api.extension.ExtensionContext; @@ -298,9 +298,9 @@ public class CsvDataImport extends ContextBasedTest { protected void deleteFromCommonTables() { jpaAttempt.transacted(() -> { context(rbacSuperuser); - em.createNativeQuery("delete from rbacuser_rv where name not like 'superuser-%'").executeUpdate(); - em.createNativeQuery("delete from tx_journal where true").executeUpdate(); - em.createNativeQuery("delete from tx_context where true").executeUpdate(); + em.createNativeQuery("delete from rbac.subject_rv where name not like 'superuser-%'").executeUpdate(); + em.createNativeQuery("delete from base.tx_journal where true").executeUpdate(); + em.createNativeQuery("delete from base.tx_context where true").executeUpdate(); }).assertSuccessful(); } diff --git a/src/test/java/net/hostsharing/hsadminng/hs/office/bankaccount/HsOfficeBankAccountControllerAcceptanceTest.java b/src/test/java/net/hostsharing/hsadminng/hs/office/bankaccount/HsOfficeBankAccountControllerAcceptanceTest.java index 540fd2c7..ee52e315 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/office/bankaccount/HsOfficeBankAccountControllerAcceptanceTest.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/office/bankaccount/HsOfficeBankAccountControllerAcceptanceTest.java @@ -54,7 +54,7 @@ class HsOfficeBankAccountControllerAcceptanceTest extends ContextBasedTestWithCl RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .port(port) .when() .get("http://localhost/api/hs/office/bankaccounts") @@ -120,7 +120,7 @@ class HsOfficeBankAccountControllerAcceptanceTest extends ContextBasedTestWithCl final var location = RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .contentType(ContentType.JSON) .body(""" { @@ -143,9 +143,9 @@ class HsOfficeBankAccountControllerAcceptanceTest extends ContextBasedTestWithCl .extract().header("Location"); // @formatter:on // finally, the new bankaccount can be accessed under the generated UUID - final var newUserUuid = UUID.fromString( + final var newSubjectUuid = UUID.fromString( location.substring(location.lastIndexOf('/') + 1)); - assertThat(newUserUuid).isNotNull(); + assertThat(newSubjectUuid).isNotNull(); } } @@ -159,7 +159,7 @@ class HsOfficeBankAccountControllerAcceptanceTest extends ContextBasedTestWithCl RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .port(port) .when() .get("http://localhost/api/hs/office/bankaccounts/" + givenBankAccountUuid) @@ -180,7 +180,7 @@ class HsOfficeBankAccountControllerAcceptanceTest extends ContextBasedTestWithCl RestAssured // @formatter:off .given() - .header("current-user", "selfregistered-user-drew@hostsharing.org") + .header("current-subject", "selfregistered-user-drew@hostsharing.org") .port(port) .when() .get("http://localhost/api/hs/office/bankaccounts/" + givenBankAccountUuid) @@ -196,7 +196,7 @@ class HsOfficeBankAccountControllerAcceptanceTest extends ContextBasedTestWithCl RestAssured // @formatter:off .given() - .header("current-user", "bankaccount-admin@firstbankaccount.example.com") + .header("current-subject", "bankaccount-admin@firstbankaccount.example.com") .port(port) .when() .get("http://localhost/api/hs/office/bankaccounts/" + givenBankAccountUuid) @@ -224,7 +224,7 @@ class HsOfficeBankAccountControllerAcceptanceTest extends ContextBasedTestWithCl final var location = RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .contentType(ContentType.JSON) .body(""" { @@ -262,7 +262,7 @@ class HsOfficeBankAccountControllerAcceptanceTest extends ContextBasedTestWithCl RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .port(port) .when() .delete("http://localhost/api/hs/office/bankaccounts/" + givenBankAccount.getUuid()) @@ -279,7 +279,7 @@ class HsOfficeBankAccountControllerAcceptanceTest extends ContextBasedTestWithCl RestAssured // @formatter:off .given() - .header("current-user", "selfregistered-test-user@hostsharing.org") + .header("current-subject", "selfregistered-test-user@hostsharing.org") .port(port) .when() .delete("http://localhost/api/hs/office/bankaccounts/" + givenBankAccount.getUuid()) @@ -300,7 +300,7 @@ class HsOfficeBankAccountControllerAcceptanceTest extends ContextBasedTestWithCl RestAssured // @formatter:off .given() - .header("current-user", "selfregistered-user-drew@hostsharing.org") + .header("current-subject", "selfregistered-user-drew@hostsharing.org") .port(port) .when() .delete("http://localhost/api/hs/office/bankaccounts/" + givenBankAccount.getUuid()) diff --git a/src/test/java/net/hostsharing/hsadminng/hs/office/bankaccount/HsOfficeBankAccountControllerRestTest.java b/src/test/java/net/hostsharing/hsadminng/hs/office/bankaccount/HsOfficeBankAccountControllerRestTest.java index 37f85f83..6dcd1cb5 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/office/bankaccount/HsOfficeBankAccountControllerRestTest.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/office/bankaccount/HsOfficeBankAccountControllerRestTest.java @@ -62,7 +62,7 @@ class HsOfficeBankAccountControllerRestTest { // when mockMvc.perform(MockMvcRequestBuilders .post("/api/hs/office/bankaccounts") - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .contentType(MediaType.APPLICATION_JSON) .content(""" { @@ -109,7 +109,7 @@ class HsOfficeBankAccountControllerRestTest { // when mockMvc.perform(MockMvcRequestBuilders .post("/api/hs/office/bankaccounts") - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .contentType(MediaType.APPLICATION_JSON) .content(""" { diff --git a/src/test/java/net/hostsharing/hsadminng/hs/office/bankaccount/HsOfficeBankAccountRepositoryIntegrationTest.java b/src/test/java/net/hostsharing/hsadminng/hs/office/bankaccount/HsOfficeBankAccountRepositoryIntegrationTest.java index 5fbd89a3..df853a61 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/office/bankaccount/HsOfficeBankAccountRepositoryIntegrationTest.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/office/bankaccount/HsOfficeBankAccountRepositoryIntegrationTest.java @@ -2,8 +2,8 @@ package net.hostsharing.hsadminng.hs.office.bankaccount; import net.hostsharing.hsadminng.context.Context; import net.hostsharing.hsadminng.rbac.test.ContextBasedTestWithCleanup; -import net.hostsharing.hsadminng.rbac.rbacgrant.RawRbacGrantRepository; -import net.hostsharing.hsadminng.rbac.rbacrole.RawRbacRoleRepository; +import net.hostsharing.hsadminng.rbac.grant.RawRbacGrantRepository; +import net.hostsharing.hsadminng.rbac.role.RawRbacRoleRepository; import net.hostsharing.hsadminng.mapper.Array; import net.hostsharing.hsadminng.rbac.test.JpaAttempt; import org.apache.commons.lang3.RandomStringUtils; @@ -22,8 +22,8 @@ import java.util.List; import java.util.function.Supplier; import static net.hostsharing.hsadminng.hs.office.bankaccount.TestHsOfficeBankAccount.hsOfficeBankAccount; -import static net.hostsharing.hsadminng.rbac.rbacgrant.RawRbacGrantEntity.distinctGrantDisplaysOf; -import static net.hostsharing.hsadminng.rbac.rbacrole.RawRbacRoleEntity.distinctRoleNamesOf; +import static net.hostsharing.hsadminng.rbac.grant.RawRbacGrantEntity.distinctGrantDisplaysOf; +import static net.hostsharing.hsadminng.rbac.role.RawRbacRoleEntity.distinctRoleNamesOf; import static net.hostsharing.hsadminng.rbac.test.JpaAttempt.attempt; import static org.assertj.core.api.Assertions.assertThat; @@ -109,7 +109,7 @@ class HsOfficeBankAccountRepositoryIntegrationTest extends ContextBasedTestWithC assertThat(distinctGrantDisplaysOf(rawGrantRepo.findAll())).containsExactlyInAnyOrder(Array.fromFormatted( initialGrantNames, "{ grant perm:hs_office_bankaccount#DE25500105176934832579:DELETE to role:hs_office_bankaccount#DE25500105176934832579:OWNER by system and assume }", - "{ grant role:hs_office_bankaccount#DE25500105176934832579:OWNER to role:global#global:ADMIN by system and assume }", + "{ grant role:hs_office_bankaccount#DE25500105176934832579:OWNER to role:rbac.global#global:ADMIN by system and assume }", "{ grant role:hs_office_bankaccount#DE25500105176934832579:OWNER to user:selfregistered-user-drew@hostsharing.org by hs_office_bankaccount#DE25500105176934832579:OWNER and assume }", "{ grant role:hs_office_bankaccount#DE25500105176934832579:ADMIN to role:hs_office_bankaccount#DE25500105176934832579:OWNER by system and assume }", @@ -272,7 +272,7 @@ class HsOfficeBankAccountRepositoryIntegrationTest extends ContextBasedTestWithC // given final var query = em.createNativeQuery(""" select currentTask, targetTable, targetOp, targetdelta->>'iban' - from tx_journal_v + from base.tx_journal_v where targettable = 'hs_office_bankaccount'; """); diff --git a/src/test/java/net/hostsharing/hsadminng/hs/office/contact/HsOfficeContactControllerAcceptanceTest.java b/src/test/java/net/hostsharing/hsadminng/hs/office/contact/HsOfficeContactControllerAcceptanceTest.java index 4bd2a4be..10dd8c75 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/office/contact/HsOfficeContactControllerAcceptanceTest.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/office/contact/HsOfficeContactControllerAcceptanceTest.java @@ -61,7 +61,7 @@ class HsOfficeContactControllerAcceptanceTest extends ContextBasedTestWithCleanu RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .port(port) .when() .get("http://localhost/api/hs/office/contacts") @@ -99,7 +99,7 @@ class HsOfficeContactControllerAcceptanceTest extends ContextBasedTestWithCleanu final var location = RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .contentType(ContentType.JSON) .body(""" { @@ -122,9 +122,9 @@ class HsOfficeContactControllerAcceptanceTest extends ContextBasedTestWithCleanu .extract().header("Location"); // @formatter:on // finally, the new contact can be accessed under the generated UUID - final var newUserUuid = UUID.fromString( + final var newSubjectUuid = UUID.fromString( location.substring(location.lastIndexOf('/') + 1)); - assertThat(newUserUuid).isNotNull(); + assertThat(newSubjectUuid).isNotNull(); } } @@ -138,7 +138,7 @@ class HsOfficeContactControllerAcceptanceTest extends ContextBasedTestWithCleanu RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .port(port) .when() .get("http://localhost/api/hs/office/contacts/" + givenContactUuid) @@ -159,7 +159,7 @@ class HsOfficeContactControllerAcceptanceTest extends ContextBasedTestWithCleanu RestAssured // @formatter:off .given() - .header("current-user", "selfregistered-user-drew@hostsharing.org") + .header("current-subject", "selfregistered-user-drew@hostsharing.org") .port(port) .when() .get("http://localhost/api/hs/office/contacts/" + givenContactUuid) @@ -174,7 +174,7 @@ class HsOfficeContactControllerAcceptanceTest extends ContextBasedTestWithCleanu RestAssured // @formatter:off .given() - .header("current-user", "contact-admin@firstcontact.example.com") + .header("current-subject", "contact-admin@firstcontact.example.com") .port(port) .when() .get("http://localhost/api/hs/office/contacts/" + givenContactUuid) @@ -206,7 +206,7 @@ class HsOfficeContactControllerAcceptanceTest extends ContextBasedTestWithCleanu final var location = RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .contentType(ContentType.JSON) .body(""" { @@ -253,7 +253,7 @@ class HsOfficeContactControllerAcceptanceTest extends ContextBasedTestWithCleanu final var location = RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .contentType(ContentType.JSON) .body(""" { @@ -301,7 +301,7 @@ class HsOfficeContactControllerAcceptanceTest extends ContextBasedTestWithCleanu RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .port(port) .when() .delete("http://localhost/api/hs/office/contacts/" + givenContact.getUuid()) @@ -321,7 +321,7 @@ class HsOfficeContactControllerAcceptanceTest extends ContextBasedTestWithCleanu RestAssured // @formatter:off .given() - .header("current-user", "selfregistered-test-user@hostsharing.org") + .header("current-subject", "selfregistered-test-user@hostsharing.org") .port(port) .when() .delete("http://localhost/api/hs/office/contacts/" + givenContact.getUuid()) @@ -342,7 +342,7 @@ class HsOfficeContactControllerAcceptanceTest extends ContextBasedTestWithCleanu RestAssured // @formatter:off .given() - .header("current-user", "selfregistered-user-drew@hostsharing.org") + .header("current-subject", "selfregistered-user-drew@hostsharing.org") .port(port) .when() .delete("http://localhost/api/hs/office/contacts/" + givenContact.getUuid()) diff --git a/src/test/java/net/hostsharing/hsadminng/hs/office/contact/HsOfficeContactRbacRepositoryIntegrationTest.java b/src/test/java/net/hostsharing/hsadminng/hs/office/contact/HsOfficeContactRbacRepositoryIntegrationTest.java index 5eea0091..e7759f4b 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/office/contact/HsOfficeContactRbacRepositoryIntegrationTest.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/office/contact/HsOfficeContactRbacRepositoryIntegrationTest.java @@ -2,8 +2,8 @@ package net.hostsharing.hsadminng.hs.office.contact; import net.hostsharing.hsadminng.context.Context; import net.hostsharing.hsadminng.rbac.test.ContextBasedTestWithCleanup; -import net.hostsharing.hsadminng.rbac.rbacgrant.RawRbacGrantRepository; -import net.hostsharing.hsadminng.rbac.rbacrole.RawRbacRoleRepository; +import net.hostsharing.hsadminng.rbac.grant.RawRbacGrantRepository; +import net.hostsharing.hsadminng.rbac.role.RawRbacRoleRepository; import net.hostsharing.hsadminng.mapper.Array; import net.hostsharing.hsadminng.rbac.test.JpaAttempt; import org.apache.commons.lang3.RandomStringUtils; @@ -22,8 +22,8 @@ import java.util.List; import java.util.function.Supplier; import static net.hostsharing.hsadminng.hs.office.contact.HsOfficeContactRbacTestEntity.hsOfficeContact; -import static net.hostsharing.hsadminng.rbac.rbacgrant.RawRbacGrantEntity.distinctGrantDisplaysOf; -import static net.hostsharing.hsadminng.rbac.rbacrole.RawRbacRoleEntity.distinctRoleNamesOf; +import static net.hostsharing.hsadminng.rbac.grant.RawRbacGrantEntity.distinctGrantDisplaysOf; +import static net.hostsharing.hsadminng.rbac.role.RawRbacRoleEntity.distinctRoleNamesOf; import static net.hostsharing.hsadminng.rbac.test.JpaAttempt.attempt; import static org.assertj.core.api.Assertions.assertThat; @@ -109,7 +109,7 @@ class HsOfficeContactRbacRepositoryIntegrationTest extends ContextBasedTestWithC )); assertThat(distinctGrantDisplaysOf(rawGrantRepo.findAll())).containsExactlyInAnyOrder(Array.fromFormatted( initialGrantNames, - "{ grant role:hs_office_contact#anothernewcontact:OWNER to role:global#global:ADMIN by system and assume }", + "{ grant role:hs_office_contact#anothernewcontact:OWNER to role:rbac.global#global:ADMIN by system and assume }", "{ grant perm:hs_office_contact#anothernewcontact:UPDATE to role:hs_office_contact#anothernewcontact:ADMIN by system and assume }", "{ grant role:hs_office_contact#anothernewcontact:OWNER to user:selfregistered-user-drew@hostsharing.org by hs_office_contact#anothernewcontact:OWNER and assume }", "{ grant perm:hs_office_contact#anothernewcontact:DELETE to role:hs_office_contact#anothernewcontact:OWNER by system and assume }", @@ -257,7 +257,7 @@ class HsOfficeContactRbacRepositoryIntegrationTest extends ContextBasedTestWithC // given final var query = em.createNativeQuery(""" select currentTask, targetTable, targetOp, targetdelta->>'caption' - from tx_journal_v + from base.tx_journal_v where targettable = 'hs_office_contact'; """); diff --git a/src/test/java/net/hostsharing/hsadminng/hs/office/coopassets/HsOfficeCoopAssetsTransactionControllerAcceptanceTest.java b/src/test/java/net/hostsharing/hsadminng/hs/office/coopassets/HsOfficeCoopAssetsTransactionControllerAcceptanceTest.java index cb2b937b..9358e9ba 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/office/coopassets/HsOfficeCoopAssetsTransactionControllerAcceptanceTest.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/office/coopassets/HsOfficeCoopAssetsTransactionControllerAcceptanceTest.java @@ -62,7 +62,7 @@ class HsOfficeCoopAssetsTransactionControllerAcceptanceTest extends ContextBased RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .port(port) .when() .get("http://localhost/api/hs/office/coopassetstransactions") @@ -80,7 +80,7 @@ class HsOfficeCoopAssetsTransactionControllerAcceptanceTest extends ContextBased RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .port(port) .when() .get("http://localhost/api/hs/office/coopassetstransactions?membershipUuid="+givenMembership.getUuid()) @@ -143,7 +143,7 @@ class HsOfficeCoopAssetsTransactionControllerAcceptanceTest extends ContextBased RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .port(port) .when() .get("http://localhost/api/hs/office/coopassetstransactions?membershipUuid=" @@ -176,7 +176,7 @@ class HsOfficeCoopAssetsTransactionControllerAcceptanceTest extends ContextBased final var location = RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .contentType(ContentType.JSON) .body(""" { @@ -233,7 +233,7 @@ class HsOfficeCoopAssetsTransactionControllerAcceptanceTest extends ContextBased final var location = RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .contentType(ContentType.JSON) .body(""" { @@ -289,7 +289,7 @@ class HsOfficeCoopAssetsTransactionControllerAcceptanceTest extends ContextBased RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .contentType(ContentType.JSON) .body(""" { @@ -329,7 +329,7 @@ class HsOfficeCoopAssetsTransactionControllerAcceptanceTest extends ContextBased LocalDate.of(2010, 3, 15)).get(0).getUuid(); RestAssured // @formatter:off - .given().header("current-user", "superuser-alex@hostsharing.net") + .given().header("current-subject", "superuser-alex@hostsharing.net") .port(port) .when() .get("http://localhost/api/hs/office/coopassetstransactions/" + givenCoopAssetTransactionUuid) @@ -352,7 +352,7 @@ class HsOfficeCoopAssetsTransactionControllerAcceptanceTest extends ContextBased LocalDate.of(2010, 3, 15)).get(0).getUuid(); RestAssured // @formatter:off - .given().header("current-user", "selfregistered-user-drew@hostsharing.org") + .given().header("current-subject", "selfregistered-user-drew@hostsharing.org") .port(port) .when() .get("http://localhost/api/hs/office/coopassetstransactions/" + givenCoopAssetTransactionUuid) @@ -370,7 +370,7 @@ class HsOfficeCoopAssetsTransactionControllerAcceptanceTest extends ContextBased RestAssured // @formatter:off .given() - .header("current-user", "person-FirstGmbH@example.com") + .header("current-subject", "person-FirstGmbH@example.com") .port(port) .when() .get("http://localhost/api/hs/office/coopassetstransactions/" + givenCoopAssetTransactionUuid) diff --git a/src/test/java/net/hostsharing/hsadminng/hs/office/coopassets/HsOfficeCoopAssetsTransactionControllerRestTest.java b/src/test/java/net/hostsharing/hsadminng/hs/office/coopassets/HsOfficeCoopAssetsTransactionControllerRestTest.java index 8176df09..0e4716d4 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/office/coopassets/HsOfficeCoopAssetsTransactionControllerRestTest.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/office/coopassets/HsOfficeCoopAssetsTransactionControllerRestTest.java @@ -115,7 +115,7 @@ class HsOfficeCoopAssetsTransactionControllerRestTest { // when mockMvc.perform(MockMvcRequestBuilders .post("/api/hs/office/coopassetstransactions") - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .contentType(MediaType.APPLICATION_JSON) .content(testCase.givenRequestBody()) .accept(MediaType.APPLICATION_JSON)) diff --git a/src/test/java/net/hostsharing/hsadminng/hs/office/coopassets/HsOfficeCoopAssetsTransactionRepositoryIntegrationTest.java b/src/test/java/net/hostsharing/hsadminng/hs/office/coopassets/HsOfficeCoopAssetsTransactionRepositoryIntegrationTest.java index ad059e16..cf636cc6 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/office/coopassets/HsOfficeCoopAssetsTransactionRepositoryIntegrationTest.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/office/coopassets/HsOfficeCoopAssetsTransactionRepositoryIntegrationTest.java @@ -3,8 +3,8 @@ package net.hostsharing.hsadminng.hs.office.coopassets; import net.hostsharing.hsadminng.context.Context; import net.hostsharing.hsadminng.hs.office.membership.HsOfficeMembershipRepository; import net.hostsharing.hsadminng.rbac.test.ContextBasedTestWithCleanup; -import net.hostsharing.hsadminng.rbac.rbacgrant.RawRbacGrantRepository; -import net.hostsharing.hsadminng.rbac.rbacrole.RawRbacRoleRepository; +import net.hostsharing.hsadminng.rbac.grant.RawRbacGrantRepository; +import net.hostsharing.hsadminng.rbac.role.RawRbacRoleRepository; import net.hostsharing.hsadminng.mapper.Array; import net.hostsharing.hsadminng.rbac.test.JpaAttempt; import org.junit.jupiter.api.AfterEach; @@ -24,8 +24,8 @@ import java.time.LocalDate; import java.util.Arrays; import java.util.List; -import static net.hostsharing.hsadminng.rbac.rbacgrant.RawRbacGrantEntity.distinctGrantDisplaysOf; -import static net.hostsharing.hsadminng.rbac.rbacrole.RawRbacRoleEntity.distinctRoleNamesOf; +import static net.hostsharing.hsadminng.rbac.grant.RawRbacGrantEntity.distinctGrantDisplaysOf; +import static net.hostsharing.hsadminng.rbac.role.RawRbacRoleEntity.distinctRoleNamesOf; import static net.hostsharing.hsadminng.rbac.test.JpaAttempt.attempt; import static org.assertj.core.api.Assertions.assertThat; @@ -221,7 +221,7 @@ class HsOfficeCoopAssetsTransactionRepositoryIntegrationTest extends ContextBase // given final var query = em.createNativeQuery(""" select currentTask, targetTable, targetOp, targetdelta->>'reference' - from tx_journal_v + from base.tx_journal_v where targettable = 'hs_office_coopassetstransaction'; """); diff --git a/src/test/java/net/hostsharing/hsadminng/hs/office/coopshares/HsOfficeCoopSharesTransactionControllerAcceptanceTest.java b/src/test/java/net/hostsharing/hsadminng/hs/office/coopshares/HsOfficeCoopSharesTransactionControllerAcceptanceTest.java index bdd9a34a..83fd3917 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/office/coopshares/HsOfficeCoopSharesTransactionControllerAcceptanceTest.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/office/coopshares/HsOfficeCoopSharesTransactionControllerAcceptanceTest.java @@ -69,7 +69,7 @@ class HsOfficeCoopSharesTransactionControllerAcceptanceTest extends ContextBased RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .port(port) .when() .get("http://localhost/api/hs/office/coopsharestransactions") @@ -86,7 +86,7 @@ class HsOfficeCoopSharesTransactionControllerAcceptanceTest extends ContextBased final var givenMembership = membershipRepo.findMembershipByMemberNumber(1000202); RestAssured // @formatter:off - .given().header("current-user", "superuser-alex@hostsharing.net").port(port).when().get("http://localhost/api/hs/office/coopsharestransactions?membershipUuid=" + givenMembership.getUuid()).then().log().all().assertThat().statusCode(200).contentType("application/json").body("", lenientlyEquals(""" + .given().header("current-subject", "superuser-alex@hostsharing.net").port(port).when().get("http://localhost/api/hs/office/coopsharestransactions?membershipUuid=" + givenMembership.getUuid()).then().log().all().assertThat().statusCode(200).contentType("application/json").body("", lenientlyEquals(""" [ { "transactionType": "SUBSCRIPTION", @@ -141,7 +141,7 @@ class HsOfficeCoopSharesTransactionControllerAcceptanceTest extends ContextBased final var givenMembership = membershipRepo.findMembershipByMemberNumber(1000202); RestAssured // @formatter:off - .given().header("current-user", "superuser-alex@hostsharing.net").port(port).when() + .given().header("current-subject", "superuser-alex@hostsharing.net").port(port).when() .get("http://localhost/api/hs/office/coopsharestransactions?membershipUuid=" + givenMembership.getUuid() + "&fromValueDate=2020-01-01&toValueDate=2021-12-31").then().log().all().assertThat().statusCode(200).contentType("application/json").body("", lenientlyEquals(""" [ { @@ -166,7 +166,7 @@ class HsOfficeCoopSharesTransactionControllerAcceptanceTest extends ContextBased final var givenMembership = membershipRepo.findMembershipByMemberNumber(1000101); final var location = RestAssured // @formatter:off - .given().header("current-user", "superuser-alex@hostsharing.net").contentType(ContentType.JSON).body(""" + .given().header("current-subject", "superuser-alex@hostsharing.net").contentType(ContentType.JSON).body(""" { "membershipUuid": "%s", "transactionType": "SUBSCRIPTION", @@ -210,7 +210,7 @@ class HsOfficeCoopSharesTransactionControllerAcceptanceTest extends ContextBased final var location = RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .contentType(ContentType.JSON) .body(""" { @@ -265,7 +265,7 @@ class HsOfficeCoopSharesTransactionControllerAcceptanceTest extends ContextBased final var givenMembership = membershipRepo.findMembershipByMemberNumber(1000101); RestAssured // @formatter:off - .given().header("current-user", "superuser-alex@hostsharing.net").contentType(ContentType.JSON).body(""" + .given().header("current-subject", "superuser-alex@hostsharing.net").contentType(ContentType.JSON).body(""" { "membershipUuid": "%s", "transactionType": "CANCELLATION", @@ -293,7 +293,7 @@ class HsOfficeCoopSharesTransactionControllerAcceptanceTest extends ContextBased final var givenCoopShareTransactionUuid = coopSharesTransactionRepo.findCoopSharesTransactionByOptionalMembershipUuidAndDateRange(null, LocalDate.of(2010, 3, 15), LocalDate.of(2010, 3, 15)).get(0).getUuid(); RestAssured // @formatter:off - .given().header("current-user", "superuser-alex@hostsharing.net").port(port).when().get("http://localhost/api/hs/office/coopsharestransactions/" + givenCoopShareTransactionUuid).then().log().body().assertThat().statusCode(200).contentType("application/json").body("", lenientlyEquals(""" + .given().header("current-subject", "superuser-alex@hostsharing.net").port(port).when().get("http://localhost/api/hs/office/coopsharestransactions/" + givenCoopShareTransactionUuid).then().log().body().assertThat().statusCode(200).contentType("application/json").body("", lenientlyEquals(""" { "transactionType": "SUBSCRIPTION" } @@ -306,7 +306,7 @@ class HsOfficeCoopSharesTransactionControllerAcceptanceTest extends ContextBased final var givenCoopShareTransactionUuid = coopSharesTransactionRepo.findCoopSharesTransactionByOptionalMembershipUuidAndDateRange(null, LocalDate.of(2010, 3, 15), LocalDate.of(2010, 3, 15)).get(0).getUuid(); RestAssured // @formatter:off - .given().header("current-user", "selfregistered-user-drew@hostsharing.org").port(port).when().get("http://localhost/api/hs/office/coopsharestransactions/" + givenCoopShareTransactionUuid).then().log().body().assertThat().statusCode(404); // @formatter:on + .given().header("current-subject", "selfregistered-user-drew@hostsharing.org").port(port).when().get("http://localhost/api/hs/office/coopsharestransactions/" + givenCoopShareTransactionUuid).then().log().body().assertThat().statusCode(404); // @formatter:on } @Test @@ -316,7 +316,7 @@ class HsOfficeCoopSharesTransactionControllerAcceptanceTest extends ContextBased RestAssured // @formatter:off .given() - .header("current-user", "person-FirstGmbH@example.com") + .header("current-subject", "person-FirstGmbH@example.com") .port(port) .when() .get("http://localhost/api/hs/office/coopsharestransactions/" + givenCoopShareTransactionUuid) diff --git a/src/test/java/net/hostsharing/hsadminng/hs/office/coopshares/HsOfficeCoopSharesTransactionControllerRestTest.java b/src/test/java/net/hostsharing/hsadminng/hs/office/coopshares/HsOfficeCoopSharesTransactionControllerRestTest.java index 6c126978..4d44c0fb 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/office/coopshares/HsOfficeCoopSharesTransactionControllerRestTest.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/office/coopshares/HsOfficeCoopSharesTransactionControllerRestTest.java @@ -111,7 +111,7 @@ class HsOfficeCoopSharesTransactionControllerRestTest { // when mockMvc.perform(MockMvcRequestBuilders .post("/api/hs/office/coopsharestransactions") - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .contentType(MediaType.APPLICATION_JSON) .content(testCase.givenRequestBody()) .accept(MediaType.APPLICATION_JSON)) diff --git a/src/test/java/net/hostsharing/hsadminng/hs/office/coopshares/HsOfficeCoopSharesTransactionRepositoryIntegrationTest.java b/src/test/java/net/hostsharing/hsadminng/hs/office/coopshares/HsOfficeCoopSharesTransactionRepositoryIntegrationTest.java index db1b0f39..af627350 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/office/coopshares/HsOfficeCoopSharesTransactionRepositoryIntegrationTest.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/office/coopshares/HsOfficeCoopSharesTransactionRepositoryIntegrationTest.java @@ -3,8 +3,8 @@ package net.hostsharing.hsadminng.hs.office.coopshares; import net.hostsharing.hsadminng.context.Context; import net.hostsharing.hsadminng.hs.office.membership.HsOfficeMembershipRepository; import net.hostsharing.hsadminng.rbac.test.ContextBasedTestWithCleanup; -import net.hostsharing.hsadminng.rbac.rbacgrant.RawRbacGrantRepository; -import net.hostsharing.hsadminng.rbac.rbacrole.RawRbacRoleRepository; +import net.hostsharing.hsadminng.rbac.grant.RawRbacGrantRepository; +import net.hostsharing.hsadminng.rbac.role.RawRbacRoleRepository; import net.hostsharing.hsadminng.mapper.Array; import net.hostsharing.hsadminng.rbac.test.JpaAttempt; import org.junit.jupiter.api.AfterEach; @@ -23,8 +23,8 @@ import java.time.LocalDate; import java.util.Arrays; import java.util.List; -import static net.hostsharing.hsadminng.rbac.rbacgrant.RawRbacGrantEntity.distinctGrantDisplaysOf; -import static net.hostsharing.hsadminng.rbac.rbacrole.RawRbacRoleEntity.distinctRoleNamesOf; +import static net.hostsharing.hsadminng.rbac.grant.RawRbacGrantEntity.distinctGrantDisplaysOf; +import static net.hostsharing.hsadminng.rbac.role.RawRbacRoleEntity.distinctRoleNamesOf; import static net.hostsharing.hsadminng.rbac.test.JpaAttempt.attempt; import static org.assertj.core.api.Assertions.assertThat; @@ -220,7 +220,7 @@ class HsOfficeCoopSharesTransactionRepositoryIntegrationTest extends ContextBase // given final var query = em.createNativeQuery(""" select currentTask, targetTable, targetOp, targetdelta->>'reference' - from tx_journal_v + from base.tx_journal_v where targettable = 'hs_office_coopsharestransaction'; """); diff --git a/src/test/java/net/hostsharing/hsadminng/hs/office/debitor/HsOfficeDebitorControllerAcceptanceTest.java b/src/test/java/net/hostsharing/hsadminng/hs/office/debitor/HsOfficeDebitorControllerAcceptanceTest.java index 68545a78..1f1a188a 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/office/debitor/HsOfficeDebitorControllerAcceptanceTest.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/office/debitor/HsOfficeDebitorControllerAcceptanceTest.java @@ -80,7 +80,7 @@ class HsOfficeDebitorControllerAcceptanceTest extends ContextBasedTestWithCleanu RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .port(port) .when() .get("http://localhost/api/hs/office/debitors") @@ -235,7 +235,7 @@ class HsOfficeDebitorControllerAcceptanceTest extends ContextBasedTestWithCleanu RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .port(port) .when() .get("http://localhost/api/hs/office/debitors?debitorNumber=1000212") @@ -284,7 +284,7 @@ class HsOfficeDebitorControllerAcceptanceTest extends ContextBasedTestWithCleanu final var location = RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .contentType(ContentType.JSON) .body(""" { @@ -315,9 +315,9 @@ class HsOfficeDebitorControllerAcceptanceTest extends ContextBasedTestWithCleanu .extract().header("Location"); // @formatter:on // finally, the new debitor can be accessed under the generated UUID - final var newUserUuid = UUID.fromString( + final var newSubjectUuid = UUID.fromString( location.substring(location.lastIndexOf('/') + 1)); - assertThat(newUserUuid).isNotNull(); + assertThat(newSubjectUuid).isNotNull(); } @Test @@ -329,7 +329,7 @@ class HsOfficeDebitorControllerAcceptanceTest extends ContextBasedTestWithCleanu final var location = RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .contentType(ContentType.JSON) .body(""" { @@ -367,9 +367,9 @@ class HsOfficeDebitorControllerAcceptanceTest extends ContextBasedTestWithCleanu .extract().header("Location"); // @formatter:on // finally, the new debitor can be accessed under the generated UUID - final var newUserUuid = UUID.fromString( + final var newSubjectUuid = UUID.fromString( location.substring(location.lastIndexOf('/') + 1)); - assertThat(newUserUuid).isNotNull(); + assertThat(newSubjectUuid).isNotNull(); } @Test @@ -381,7 +381,7 @@ class HsOfficeDebitorControllerAcceptanceTest extends ContextBasedTestWithCleanu final var location = RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .contentType(ContentType.JSON) .body(""" { @@ -417,7 +417,7 @@ class HsOfficeDebitorControllerAcceptanceTest extends ContextBasedTestWithCleanu RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .contentType(ContentType.JSON) .body(""" { @@ -448,7 +448,7 @@ class HsOfficeDebitorControllerAcceptanceTest extends ContextBasedTestWithCleanu RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .port(port) .when() .get("http://localhost/api/hs/office/debitors/" + givenDebitorUuid) @@ -509,7 +509,7 @@ class HsOfficeDebitorControllerAcceptanceTest extends ContextBasedTestWithCleanu RestAssured // @formatter:off .given() - .header("current-user", "selfregistered-user-drew@hostsharing.org") + .header("current-subject", "selfregistered-user-drew@hostsharing.org") .port(port) .when() .get("http://localhost/api/hs/office/debitors/" + givenDebitorUuid) @@ -524,7 +524,7 @@ class HsOfficeDebitorControllerAcceptanceTest extends ContextBasedTestWithCleanu RestAssured // @formatter:off .given() - .header("current-user", "contact-admin@firstcontact.example.com") + .header("current-subject", "contact-admin@firstcontact.example.com") .port(port) .when() .get("http://localhost/api/hs/office/debitors/" + givenDebitorUuid) @@ -554,7 +554,7 @@ class HsOfficeDebitorControllerAcceptanceTest extends ContextBasedTestWithCleanu final var location = RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .contentType(ContentType.JSON) .body(""" { @@ -637,7 +637,7 @@ class HsOfficeDebitorControllerAcceptanceTest extends ContextBasedTestWithCleanu // @formatter:on RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .header("assumed-roles", "hs_office_contact#fourthcontact:ADMIN") .contentType(ContentType.JSON) .body(""" @@ -666,7 +666,7 @@ class HsOfficeDebitorControllerAcceptanceTest extends ContextBasedTestWithCleanu RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .port(port) .when() .delete("http://localhost/api/hs/office/debitors/" + givenDebitor.getUuid()) @@ -685,7 +685,7 @@ class HsOfficeDebitorControllerAcceptanceTest extends ContextBasedTestWithCleanu RestAssured // @formatter:off .given() - .header("current-user", "contact-admin@fourthcontact.example.com") + .header("current-subject", "contact-admin@fourthcontact.example.com") .port(port) .when() .delete("http://localhost/api/hs/office/debitors/" + givenDebitor.getUuid()) @@ -704,7 +704,7 @@ class HsOfficeDebitorControllerAcceptanceTest extends ContextBasedTestWithCleanu RestAssured // @formatter:off .given() - .header("current-user", "selfregistered-user-drew@hostsharing.org") + .header("current-subject", "selfregistered-user-drew@hostsharing.org") .port(port) .when() .delete("http://localhost/api/hs/office/debitors/" + givenDebitor.getUuid()) diff --git a/src/test/java/net/hostsharing/hsadminng/hs/office/debitor/HsOfficeDebitorRepositoryIntegrationTest.java b/src/test/java/net/hostsharing/hsadminng/hs/office/debitor/HsOfficeDebitorRepositoryIntegrationTest.java index 1d16254d..97f30b8a 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/office/debitor/HsOfficeDebitorRepositoryIntegrationTest.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/office/debitor/HsOfficeDebitorRepositoryIntegrationTest.java @@ -9,9 +9,9 @@ import net.hostsharing.hsadminng.hs.office.relation.HsOfficeRelation; import net.hostsharing.hsadminng.hs.office.relation.HsOfficeRelationRealEntity; import net.hostsharing.hsadminng.hs.office.relation.HsOfficeRelationType; import net.hostsharing.hsadminng.rbac.test.ContextBasedTestWithCleanup; -import net.hostsharing.hsadminng.rbac.rbacgrant.RawRbacGrantRepository; -import net.hostsharing.hsadminng.rbac.rbacgrant.RbacGrantsDiagramService; -import net.hostsharing.hsadminng.rbac.rbacrole.RawRbacRoleRepository; +import net.hostsharing.hsadminng.rbac.grant.RawRbacGrantRepository; +import net.hostsharing.hsadminng.rbac.grant.RbacGrantsDiagramService; +import net.hostsharing.hsadminng.rbac.role.RawRbacRoleRepository; import net.hostsharing.hsadminng.mapper.Array; import net.hostsharing.hsadminng.rbac.test.JpaAttempt; import org.hibernate.Hibernate; @@ -34,8 +34,8 @@ import java.util.Arrays; import java.util.List; import static net.hostsharing.hsadminng.rbac.test.EntityList.one; -import static net.hostsharing.hsadminng.rbac.rbacgrant.RawRbacGrantEntity.distinctGrantDisplaysOf; -import static net.hostsharing.hsadminng.rbac.rbacrole.RawRbacRoleEntity.distinctRoleNamesOf; +import static net.hostsharing.hsadminng.rbac.grant.RawRbacGrantEntity.distinctGrantDisplaysOf; +import static net.hostsharing.hsadminng.rbac.role.RawRbacRoleEntity.distinctRoleNamesOf; import static net.hostsharing.hsadminng.rbac.test.JpaAttempt.attempt; import static org.assertj.core.api.Assertions.assertThat; @@ -190,7 +190,7 @@ class HsOfficeDebitorRepositoryIntegrationTest extends ContextBasedTestWithClean // owner "{ grant perm:debitor#D-1000122:DELETE to role:relation#FirstGmbH-with-DEBITOR-FourtheG:OWNER by system and assume }", "{ grant perm:relation#FirstGmbH-with-DEBITOR-FourtheG:DELETE to role:relation#FirstGmbH-with-DEBITOR-FourtheG:OWNER by system and assume }", - "{ grant role:relation#FirstGmbH-with-DEBITOR-FourtheG:OWNER to role:global#global:ADMIN by system and assume }", + "{ grant role:relation#FirstGmbH-with-DEBITOR-FourtheG:OWNER to role:rbac.global#global:ADMIN by system and assume }", "{ grant role:relation#FirstGmbH-with-DEBITOR-FourtheG:OWNER to role:person#FirstGmbH:ADMIN by system and assume }", "{ grant role:relation#FirstGmbH-with-DEBITOR-FourtheG:OWNER to user:superuser-alex@hostsharing.net by relation#FirstGmbH-with-DEBITOR-FourtheG:OWNER and assume }", @@ -349,7 +349,7 @@ class HsOfficeDebitorRepositoryIntegrationTest extends ContextBasedTestWithClean // then result.assertSuccessful(); - assertThatDebitorIsVisibleForUserWithRole(result.returnedValue(), "global#global:ADMIN", true); + assertThatDebitorIsVisibleForUserWithRole(result.returnedValue(), "rbac.global#global:ADMIN", true); // ... partner role was reassigned: assertThatDebitorIsNotVisibleForUserWithRole( @@ -398,7 +398,7 @@ class HsOfficeDebitorRepositoryIntegrationTest extends ContextBasedTestWithClean result.assertSuccessful(); assertThatDebitorIsVisibleForUserWithRole( result.returnedValue(), - "global#global:ADMIN", true); + "rbac.global#global:ADMIN", true); // ... bank-account role was assigned: assertThatDebitorIsVisibleForUserWithRole( @@ -427,7 +427,7 @@ class HsOfficeDebitorRepositoryIntegrationTest extends ContextBasedTestWithClean result.assertSuccessful(); assertThatDebitorIsVisibleForUserWithRole( result.returnedValue(), - "global#global:ADMIN", true); + "rbac.global#global:ADMIN", true); // ... bank-account role was removed from previous bank-account admin: assertThatDebitorIsNotVisibleForUserWithRole( @@ -590,7 +590,7 @@ class HsOfficeDebitorRepositoryIntegrationTest extends ContextBasedTestWithClean // given final var query = em.createNativeQuery(""" select currentTask, targetTable, targetOp, targetdelta->>'defaultprefix' - from tx_journal_v + from base.tx_journal_v where targettable = 'hs_office_debitor'; """); diff --git a/src/test/java/net/hostsharing/hsadminng/hs/office/membership/HsOfficeMembershipControllerAcceptanceTest.java b/src/test/java/net/hostsharing/hsadminng/hs/office/membership/HsOfficeMembershipControllerAcceptanceTest.java index f0e108dc..ee6b956c 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/office/membership/HsOfficeMembershipControllerAcceptanceTest.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/office/membership/HsOfficeMembershipControllerAcceptanceTest.java @@ -67,7 +67,7 @@ class HsOfficeMembershipControllerAcceptanceTest extends ContextBasedTestWithCle RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .port(port) .when() .get("http://localhost/api/hs/office/memberships") @@ -113,7 +113,7 @@ class HsOfficeMembershipControllerAcceptanceTest extends ContextBasedTestWithCle RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .port(port) .when() .queryParam("partnerUuid", partner.getUuid() ) @@ -141,7 +141,7 @@ class HsOfficeMembershipControllerAcceptanceTest extends ContextBasedTestWithCle RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .port(port) .when() .queryParam("memberNumber", 1000202 ) @@ -178,7 +178,7 @@ class HsOfficeMembershipControllerAcceptanceTest extends ContextBasedTestWithCle final var location = RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .contentType(ContentType.JSON) .body(""" { @@ -204,10 +204,10 @@ class HsOfficeMembershipControllerAcceptanceTest extends ContextBasedTestWithCle .extract().header("Location"); // @formatter:on // finally, the new membership can be accessed under the generated UUID - final var newUserUuid = UUID.fromString( + final var newSubjectUuid = UUID.fromString( location.substring(location.lastIndexOf('/') + 1)); - assertThat(newUserUuid).isNotNull(); - assertThat(membershipRepo.findByUuid(newUserUuid)).isPresent(); + assertThat(newSubjectUuid).isNotNull(); + assertThat(membershipRepo.findByUuid(newSubjectUuid)).isPresent(); } } @@ -221,7 +221,7 @@ class HsOfficeMembershipControllerAcceptanceTest extends ContextBasedTestWithCle RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .port(port) .when() .get("http://localhost/api/hs/office/memberships/" + givenMembershipUuid) @@ -247,7 +247,7 @@ class HsOfficeMembershipControllerAcceptanceTest extends ContextBasedTestWithCle RestAssured // @formatter:off .given() - .header("current-user", "selfregistered-user-drew@hostsharing.org") + .header("current-subject", "selfregistered-user-drew@hostsharing.org") .port(port) .when() .get("http://localhost/api/hs/office/memberships/" + givenMembershipUuid) @@ -262,7 +262,7 @@ class HsOfficeMembershipControllerAcceptanceTest extends ContextBasedTestWithCle RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .header("assumed-roles", "hs_office_relation#HostsharingeG-with-PARTNER-ThirdOHG:AGENT") .port(port) .when() @@ -294,7 +294,7 @@ class HsOfficeMembershipControllerAcceptanceTest extends ContextBasedTestWithCle final var location = RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .contentType(ContentType.JSON) .body(""" { @@ -338,7 +338,7 @@ class HsOfficeMembershipControllerAcceptanceTest extends ContextBasedTestWithCle // when RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .header("assumed-roles", givenPartnerAdmin) .contentType(ContentType.JSON) .body(""" @@ -373,7 +373,7 @@ class HsOfficeMembershipControllerAcceptanceTest extends ContextBasedTestWithCle RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .port(port) .when() .delete("http://localhost/api/hs/office/memberships/" + givenMembership.getUuid()) @@ -391,7 +391,7 @@ class HsOfficeMembershipControllerAcceptanceTest extends ContextBasedTestWithCle RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .header("assumed-roles", "hs_office_relation#HostsharingeG-with-PARTNER-FirstGmbH:AGENT") .port(port) .when() @@ -410,7 +410,7 @@ class HsOfficeMembershipControllerAcceptanceTest extends ContextBasedTestWithCle RestAssured // @formatter:off .given() - .header("current-user", "selfregistered-user-drew@hostsharing.org") + .header("current-subject", "selfregistered-user-drew@hostsharing.org") .port(port) .when() .delete("http://localhost/api/hs/office/memberships/" + givenMembership.getUuid()) diff --git a/src/test/java/net/hostsharing/hsadminng/hs/office/membership/HsOfficeMembershipControllerRestTest.java b/src/test/java/net/hostsharing/hsadminng/hs/office/membership/HsOfficeMembershipControllerRestTest.java index 7c62859b..2a5005e6 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/office/membership/HsOfficeMembershipControllerRestTest.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/office/membership/HsOfficeMembershipControllerRestTest.java @@ -69,7 +69,7 @@ public class HsOfficeMembershipControllerRestTest { // when mockMvc.perform(MockMvcRequestBuilders .post("/api/hs/office/memberships") - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .contentType(MediaType.APPLICATION_JSON) .content(""" { @@ -99,7 +99,7 @@ public class HsOfficeMembershipControllerRestTest { // when mockMvc.perform(MockMvcRequestBuilders .post("/api/hs/office/memberships") - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .contentType(MediaType.APPLICATION_JSON) .content(""" { @@ -125,7 +125,7 @@ public class HsOfficeMembershipControllerRestTest { // when mockMvc.perform(MockMvcRequestBuilders .post("/api/hs/office/memberships") - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .contentType(MediaType.APPLICATION_JSON) .content(""" { diff --git a/src/test/java/net/hostsharing/hsadminng/hs/office/membership/HsOfficeMembershipRepositoryIntegrationTest.java b/src/test/java/net/hostsharing/hsadminng/hs/office/membership/HsOfficeMembershipRepositoryIntegrationTest.java index 6e013be2..5916abc0 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/office/membership/HsOfficeMembershipRepositoryIntegrationTest.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/office/membership/HsOfficeMembershipRepositoryIntegrationTest.java @@ -5,8 +5,8 @@ import net.hostsharing.hsadminng.context.Context; import net.hostsharing.hsadminng.hs.office.debitor.HsOfficeDebitorRepository; import net.hostsharing.hsadminng.hs.office.partner.HsOfficePartnerRepository; import net.hostsharing.hsadminng.rbac.test.ContextBasedTestWithCleanup; -import net.hostsharing.hsadminng.rbac.rbacgrant.RawRbacGrantRepository; -import net.hostsharing.hsadminng.rbac.rbacrole.RawRbacRoleRepository; +import net.hostsharing.hsadminng.rbac.grant.RawRbacGrantRepository; +import net.hostsharing.hsadminng.rbac.role.RawRbacRoleRepository; import net.hostsharing.hsadminng.mapper.Array; import net.hostsharing.hsadminng.rbac.test.JpaAttempt; import org.junit.jupiter.api.Nested; @@ -24,8 +24,8 @@ import java.time.LocalDate; import java.util.Arrays; import java.util.List; -import static net.hostsharing.hsadminng.rbac.rbacgrant.RawRbacGrantEntity.distinctGrantDisplaysOf; -import static net.hostsharing.hsadminng.rbac.rbacrole.RawRbacRoleEntity.distinctRoleNamesOf; +import static net.hostsharing.hsadminng.rbac.grant.RawRbacGrantEntity.distinctGrantDisplaysOf; +import static net.hostsharing.hsadminng.rbac.role.RawRbacRoleEntity.distinctRoleNamesOf; import static net.hostsharing.hsadminng.rbac.test.JpaAttempt.attempt; import static org.assertj.core.api.Assertions.assertThat; @@ -337,7 +337,7 @@ class HsOfficeMembershipRepositoryIntegrationTest extends ContextBasedTestWithCl // given final var query = em.createNativeQuery(""" select currentTask, targetTable, targetOp, targetdelta->>'membernumbersuffix' - from tx_journal_v + from base.tx_journal_v where targettable = 'hs_office_membership'; """); diff --git a/src/test/java/net/hostsharing/hsadminng/hs/office/partner/HsOfficePartnerControllerAcceptanceTest.java b/src/test/java/net/hostsharing/hsadminng/hs/office/partner/HsOfficePartnerControllerAcceptanceTest.java index fc7287e4..8c75ed16 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/office/partner/HsOfficePartnerControllerAcceptanceTest.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/office/partner/HsOfficePartnerControllerAcceptanceTest.java @@ -62,7 +62,7 @@ class HsOfficePartnerControllerAcceptanceTest extends ContextBasedTestWithCleanu RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .port(port) .when() .get("http://localhost/api/hs/office/partners") @@ -96,7 +96,7 @@ class HsOfficePartnerControllerAcceptanceTest extends ContextBasedTestWithCleanu final var location = RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .contentType(ContentType.JSON) .body(""" { @@ -141,9 +141,9 @@ class HsOfficePartnerControllerAcceptanceTest extends ContextBasedTestWithCleanu .extract().header("Location"); // @formatter:on // finally, the new partner can be accessed under the generated UUID - final var newUserUuid = UUID.fromString( + final var newSubjectUuid = UUID.fromString( location.substring(location.lastIndexOf('/') + 1)); - assertThat(newUserUuid).isNotNull(); + assertThat(newSubjectUuid).isNotNull(); } @Test @@ -155,7 +155,7 @@ class HsOfficePartnerControllerAcceptanceTest extends ContextBasedTestWithCleanu final var location = RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .contentType(ContentType.JSON) .body(""" { @@ -193,7 +193,7 @@ class HsOfficePartnerControllerAcceptanceTest extends ContextBasedTestWithCleanu final var location = RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .contentType(ContentType.JSON) .body(""" { @@ -238,7 +238,7 @@ class HsOfficePartnerControllerAcceptanceTest extends ContextBasedTestWithCleanu RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .port(port) .when() .get("http://localhost/api/hs/office/partners/" + givenPartnerUuid) @@ -270,7 +270,7 @@ class HsOfficePartnerControllerAcceptanceTest extends ContextBasedTestWithCleanu RestAssured // @formatter:off .given() - .header("current-user", "selfregistered-user-drew@hostsharing.org") + .header("current-subject", "selfregistered-user-drew@hostsharing.org") .port(port) .when() .get("http://localhost/api/hs/office/partners/" + givenPartnerUuid) @@ -285,7 +285,7 @@ class HsOfficePartnerControllerAcceptanceTest extends ContextBasedTestWithCleanu RestAssured // @formatter:off .given() - .header("current-user", "contact-admin@firstcontact.example.com") + .header("current-subject", "contact-admin@firstcontact.example.com") .port(port) .when() .get("http://localhost/api/hs/office/partners/" + givenPartnerUuid) @@ -316,7 +316,7 @@ class HsOfficePartnerControllerAcceptanceTest extends ContextBasedTestWithCleanu RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .contentType(ContentType.JSON) .body(""" { @@ -383,7 +383,7 @@ class HsOfficePartnerControllerAcceptanceTest extends ContextBasedTestWithCleanu RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .contentType(ContentType.JSON) .body(""" { @@ -421,7 +421,7 @@ class HsOfficePartnerControllerAcceptanceTest extends ContextBasedTestWithCleanu final var location = RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .contentType(ContentType.JSON) .body(""" { @@ -469,7 +469,7 @@ class HsOfficePartnerControllerAcceptanceTest extends ContextBasedTestWithCleanu RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .port(port) .when() .delete("http://localhost/api/hs/office/partners/" + givenPartner.getUuid()) @@ -489,7 +489,7 @@ class HsOfficePartnerControllerAcceptanceTest extends ContextBasedTestWithCleanu RestAssured // @formatter:off .given() - .header("current-user", "contact-admin@fourthcontact.example.com") + .header("current-subject", "contact-admin@fourthcontact.example.com") .port(port) .when() .delete("http://localhost/api/hs/office/partners/" + givenPartner.getUuid()) @@ -508,7 +508,7 @@ class HsOfficePartnerControllerAcceptanceTest extends ContextBasedTestWithCleanu RestAssured // @formatter:off .given() - .header("current-user", "selfregistered-user-drew@hostsharing.org") + .header("current-subject", "selfregistered-user-drew@hostsharing.org") .port(port) .when() .delete("http://localhost/api/hs/office/partners/" + givenPartner.getUuid()) diff --git a/src/test/java/net/hostsharing/hsadminng/hs/office/partner/HsOfficePartnerControllerRestTest.java b/src/test/java/net/hostsharing/hsadminng/hs/office/partner/HsOfficePartnerControllerRestTest.java index 97b56052..a42a4780 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/office/partner/HsOfficePartnerControllerRestTest.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/office/partner/HsOfficePartnerControllerRestTest.java @@ -95,7 +95,7 @@ class HsOfficePartnerControllerRestTest { // when mockMvc.perform(MockMvcRequestBuilders .post("/api/hs/office/partners") - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .contentType(MediaType.APPLICATION_JSON) .content(""" { @@ -132,7 +132,7 @@ class HsOfficePartnerControllerRestTest { // when mockMvc.perform(MockMvcRequestBuilders .post("/api/hs/office/partners") - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .contentType(MediaType.APPLICATION_JSON) .content(""" { @@ -184,7 +184,7 @@ class HsOfficePartnerControllerRestTest { // when mockMvc.perform(MockMvcRequestBuilders .delete("/api/hs/office/partners/" + givenPartnerUuid) - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)) diff --git a/src/test/java/net/hostsharing/hsadminng/hs/office/partner/HsOfficePartnerRepositoryIntegrationTest.java b/src/test/java/net/hostsharing/hsadminng/hs/office/partner/HsOfficePartnerRepositoryIntegrationTest.java index 2d871048..f0ad1527 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/office/partner/HsOfficePartnerRepositoryIntegrationTest.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/office/partner/HsOfficePartnerRepositoryIntegrationTest.java @@ -7,9 +7,9 @@ import net.hostsharing.hsadminng.hs.office.relation.HsOfficeRelationRealEntity; import net.hostsharing.hsadminng.hs.office.relation.HsOfficeRelationRealRepository; import net.hostsharing.hsadminng.hs.office.relation.HsOfficeRelationType; import net.hostsharing.hsadminng.rbac.test.ContextBasedTestWithCleanup; -import net.hostsharing.hsadminng.rbac.rbacgrant.RawRbacGrantRepository; -import net.hostsharing.hsadminng.rbac.rbacrole.RawRbacObjectRepository; -import net.hostsharing.hsadminng.rbac.rbacrole.RawRbacRoleRepository; +import net.hostsharing.hsadminng.rbac.grant.RawRbacGrantRepository; +import net.hostsharing.hsadminng.rbac.role.RawRbacObjectRepository; +import net.hostsharing.hsadminng.rbac.role.RawRbacRoleRepository; import net.hostsharing.hsadminng.rbac.test.JpaAttempt; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Nested; @@ -27,9 +27,9 @@ import java.util.Arrays; import java.util.List; import java.util.Objects; -import static net.hostsharing.hsadminng.rbac.rbacgrant.RawRbacGrantEntity.distinctGrantDisplaysOf; -import static net.hostsharing.hsadminng.rbac.rbacrole.RawRbacObjectEntity.objectDisplaysOf; -import static net.hostsharing.hsadminng.rbac.rbacrole.RawRbacRoleEntity.distinctRoleNamesOf; +import static net.hostsharing.hsadminng.rbac.grant.RawRbacGrantEntity.distinctGrantDisplaysOf; +import static net.hostsharing.hsadminng.rbac.role.RawRbacObjectEntity.objectDisplaysOf; +import static net.hostsharing.hsadminng.rbac.role.RawRbacRoleEntity.distinctRoleNamesOf; import static net.hostsharing.hsadminng.mapper.Array.from; import static net.hostsharing.hsadminng.rbac.test.JpaAttempt.attempt; import static org.assertj.core.api.Assertions.assertThat; @@ -158,7 +158,7 @@ class HsOfficePartnerRepositoryIntegrationTest extends ContextBasedTestWithClean "{ grant perm:relation#HostsharingeG-with-PARTNER-EBess:SELECT to role:relation#HostsharingeG-with-PARTNER-EBess:TENANT by system and assume }", // relation owner - "{ grant role:relation#HostsharingeG-with-PARTNER-EBess:OWNER to role:global#global:ADMIN by system and assume }", + "{ grant role:relation#HostsharingeG-with-PARTNER-EBess:OWNER to role:rbac.global#global:ADMIN by system and assume }", "{ grant role:relation#HostsharingeG-with-PARTNER-EBess:OWNER to user:superuser-alex@hostsharing.net by relation#HostsharingeG-with-PARTNER-EBess:OWNER and assume }", // relation admin @@ -278,7 +278,7 @@ class HsOfficePartnerRepositoryIntegrationTest extends ContextBasedTestWithClean assertThatPartnerIsVisibleForUserWithRole( givenPartner, - "global#global:ADMIN"); + "rbac.global#global:ADMIN"); assertThatPartnerIsVisibleForUserWithRole( givenPartner, "hs_office_person#ThirdOHG:ADMIN"); @@ -434,7 +434,7 @@ class HsOfficePartnerRepositoryIntegrationTest extends ContextBasedTestWithClean // given final var query = em.createNativeQuery(""" select currentTask, targetTable, targetOp, targetdelta->>'partnernumber' - from tx_journal_v + from base.tx_journal_v where targettable = 'hs_office_partner'; """); diff --git a/src/test/java/net/hostsharing/hsadminng/hs/office/person/HsOfficePersonControllerAcceptanceTest.java b/src/test/java/net/hostsharing/hsadminng/hs/office/person/HsOfficePersonControllerAcceptanceTest.java index 4a136331..9339ff56 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/office/person/HsOfficePersonControllerAcceptanceTest.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/office/person/HsOfficePersonControllerAcceptanceTest.java @@ -56,7 +56,7 @@ class HsOfficePersonControllerAcceptanceTest extends ContextBasedTestWithCleanup RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .port(port) .when() .get("http://localhost/api/hs/office/persons") @@ -76,7 +76,7 @@ class HsOfficePersonControllerAcceptanceTest extends ContextBasedTestWithCleanup final var location = RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .contentType(ContentType.JSON) .body(""" { @@ -99,9 +99,9 @@ class HsOfficePersonControllerAcceptanceTest extends ContextBasedTestWithCleanup .extract().header("Location"); // @formatter:on // finally, the new person can be accessed under the generated UUID - final var newUserUuid = UUID.fromString( + final var newSubjectUuid = UUID.fromString( location.substring(location.lastIndexOf('/') + 1)); - assertThat(newUserUuid).isNotNull(); + assertThat(newSubjectUuid).isNotNull(); } } @@ -116,7 +116,7 @@ class HsOfficePersonControllerAcceptanceTest extends ContextBasedTestWithCleanup RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .port(port) .when() .get("http://localhost/api/hs/office/persons/" + givenPersonUuid) @@ -139,7 +139,7 @@ class HsOfficePersonControllerAcceptanceTest extends ContextBasedTestWithCleanup RestAssured // @formatter:off .given() - .header("current-user", "selfregistered-user-drew@hostsharing.org") + .header("current-subject", "selfregistered-user-drew@hostsharing.org") .port(port) .when() .get("http://localhost/api/hs/office/persons/" + givenPersonUuid) @@ -156,7 +156,7 @@ class HsOfficePersonControllerAcceptanceTest extends ContextBasedTestWithCleanup RestAssured // @formatter:off .given() - .header("current-user", "person-ErbenBesslerMelBessler@example.com") + .header("current-subject", "person-ErbenBesslerMelBessler@example.com") .port(port) .when() .get("http://localhost/api/hs/office/persons/" + givenPersonUuid) @@ -185,7 +185,7 @@ class HsOfficePersonControllerAcceptanceTest extends ContextBasedTestWithCleanup final var location = RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .contentType(ContentType.JSON) .body(""" { @@ -227,7 +227,7 @@ class HsOfficePersonControllerAcceptanceTest extends ContextBasedTestWithCleanup final var location = RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .contentType(ContentType.JSON) .body(""" { @@ -271,7 +271,7 @@ class HsOfficePersonControllerAcceptanceTest extends ContextBasedTestWithCleanup RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .port(port) .when() .delete("http://localhost/api/hs/office/persons/" + givenPerson.getUuid()) @@ -290,7 +290,7 @@ class HsOfficePersonControllerAcceptanceTest extends ContextBasedTestWithCleanup RestAssured // @formatter:off .given() - .header("current-user", "selfregistered-test-user@hostsharing.org") + .header("current-subject", "selfregistered-test-user@hostsharing.org") .port(port) .when() .delete("http://localhost/api/hs/office/persons/" + givenPerson.getUuid()) @@ -310,7 +310,7 @@ class HsOfficePersonControllerAcceptanceTest extends ContextBasedTestWithCleanup RestAssured // @formatter:off .given() - .header("current-user", "selfregistered-user-drew@hostsharing.org") + .header("current-subject", "selfregistered-user-drew@hostsharing.org") .port(port) .when() .delete("http://localhost/api/hs/office/persons/" + givenPerson.getUuid()) diff --git a/src/test/java/net/hostsharing/hsadminng/hs/office/person/HsOfficePersonRepositoryIntegrationTest.java b/src/test/java/net/hostsharing/hsadminng/hs/office/person/HsOfficePersonRepositoryIntegrationTest.java index 6ee4f486..43a9792f 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/office/person/HsOfficePersonRepositoryIntegrationTest.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/office/person/HsOfficePersonRepositoryIntegrationTest.java @@ -2,8 +2,8 @@ package net.hostsharing.hsadminng.hs.office.person; import net.hostsharing.hsadminng.context.Context; import net.hostsharing.hsadminng.rbac.test.ContextBasedTestWithCleanup; -import net.hostsharing.hsadminng.rbac.rbacgrant.RawRbacGrantRepository; -import net.hostsharing.hsadminng.rbac.rbacrole.RawRbacRoleRepository; +import net.hostsharing.hsadminng.rbac.grant.RawRbacGrantRepository; +import net.hostsharing.hsadminng.rbac.role.RawRbacRoleRepository; import net.hostsharing.hsadminng.mapper.Array; import net.hostsharing.hsadminng.rbac.test.JpaAttempt; import org.apache.commons.lang3.RandomStringUtils; @@ -22,8 +22,8 @@ import java.util.List; import java.util.function.Supplier; import static net.hostsharing.hsadminng.hs.office.person.TestHsOfficePerson.hsOfficePerson; -import static net.hostsharing.hsadminng.rbac.rbacgrant.RawRbacGrantEntity.distinctGrantDisplaysOf; -import static net.hostsharing.hsadminng.rbac.rbacrole.RawRbacRoleEntity.distinctRoleNamesOf; +import static net.hostsharing.hsadminng.rbac.grant.RawRbacGrantEntity.distinctGrantDisplaysOf; +import static net.hostsharing.hsadminng.rbac.role.RawRbacRoleEntity.distinctRoleNamesOf; import static net.hostsharing.hsadminng.rbac.test.JpaAttempt.attempt; import static org.assertj.core.api.Assertions.assertThat; @@ -112,7 +112,7 @@ class HsOfficePersonRepositoryIntegrationTest extends ContextBasedTestWithCleanu "{ grant perm:hs_office_person#anothernewperson:INSERT>hs_office_relation to role:hs_office_person#anothernewperson:ADMIN by system and assume }", "{ grant role:hs_office_person#anothernewperson:OWNER to user:selfregistered-user-drew@hostsharing.org by hs_office_person#anothernewperson:OWNER and assume }", - "{ grant role:hs_office_person#anothernewperson:OWNER to role:global#global:ADMIN by system and assume }", + "{ grant role:hs_office_person#anothernewperson:OWNER to role:rbac.global#global:ADMIN by system and assume }", "{ grant perm:hs_office_person#anothernewperson:UPDATE to role:hs_office_person#anothernewperson:ADMIN by system and assume }", "{ grant perm:hs_office_person#anothernewperson:DELETE to role:hs_office_person#anothernewperson:OWNER by system and assume }", "{ grant role:hs_office_person#anothernewperson:ADMIN to role:hs_office_person#anothernewperson:OWNER by system and assume }", @@ -261,7 +261,7 @@ class HsOfficePersonRepositoryIntegrationTest extends ContextBasedTestWithCleanu // given final var query = em.createNativeQuery(""" select currentTask, targetTable, targetOp, targetdelta->>'tradename', targetdelta->>'lastname' - from tx_journal_v + from base.tx_journal_v where targettable = 'hs_office_person'; """); diff --git a/src/test/java/net/hostsharing/hsadminng/hs/office/relation/HsOfficeRelationControllerAcceptanceTest.java b/src/test/java/net/hostsharing/hsadminng/hs/office/relation/HsOfficeRelationControllerAcceptanceTest.java index 265a65e3..44605216 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/office/relation/HsOfficeRelationControllerAcceptanceTest.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/office/relation/HsOfficeRelationControllerAcceptanceTest.java @@ -66,7 +66,7 @@ class HsOfficeRelationControllerAcceptanceTest extends ContextBasedTestWithClean RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .port(port) .when() .get("http://localhost/api/hs/office/relations?personUuid=%s&relationType=%s" @@ -129,7 +129,7 @@ class HsOfficeRelationControllerAcceptanceTest extends ContextBasedTestWithClean final var location = RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .contentType(ContentType.JSON) .body(""" { @@ -161,9 +161,9 @@ class HsOfficeRelationControllerAcceptanceTest extends ContextBasedTestWithClean .extract().header("Location"); // @formatter:on // finally, the new relation can be accessed under the generated UUID - final var newUserUuid = toCleanup(HsOfficeRelationRealEntity.class, UUID.fromString( + final var newSubjectUuid = toCleanup(HsOfficeRelationRealEntity.class, UUID.fromString( location.substring(location.lastIndexOf('/') + 1))); - assertThat(newUserUuid).isNotNull(); + assertThat(newSubjectUuid).isNotNull(); } @Test @@ -176,7 +176,7 @@ class HsOfficeRelationControllerAcceptanceTest extends ContextBasedTestWithClean final var location = RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .contentType(ContentType.JSON) .body(""" { @@ -208,7 +208,7 @@ class HsOfficeRelationControllerAcceptanceTest extends ContextBasedTestWithClean final var location = RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .contentType(ContentType.JSON) .body(""" { @@ -241,7 +241,7 @@ class HsOfficeRelationControllerAcceptanceTest extends ContextBasedTestWithClean final var location = RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .contentType(ContentType.JSON) .body(""" { @@ -275,7 +275,7 @@ class HsOfficeRelationControllerAcceptanceTest extends ContextBasedTestWithClean RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .port(port) .when() .get("http://localhost/api/hs/office/relations/" + givenRelationUuid) @@ -298,7 +298,7 @@ class HsOfficeRelationControllerAcceptanceTest extends ContextBasedTestWithClean RestAssured // @formatter:off .given() - .header("current-user", "selfregistered-user-drew@hostsharing.org") + .header("current-subject", "selfregistered-user-drew@hostsharing.org") .port(port) .when() .get("http://localhost/api/hs/office/relations/" + givenRelationUuid) @@ -314,7 +314,7 @@ class HsOfficeRelationControllerAcceptanceTest extends ContextBasedTestWithClean RestAssured // @formatter:off .given() - .header("current-user", "contact-admin@firstcontact.example.com") + .header("current-subject", "contact-admin@firstcontact.example.com") .port(port) .when() .get("http://localhost/api/hs/office/relations/" + givenRelation.getUuid()) @@ -357,7 +357,7 @@ class HsOfficeRelationControllerAcceptanceTest extends ContextBasedTestWithClean RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .contentType(ContentType.JSON) .body(""" { @@ -400,7 +400,7 @@ class HsOfficeRelationControllerAcceptanceTest extends ContextBasedTestWithClean RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .port(port) .when() .delete("http://localhost/api/hs/office/relations/" + givenRelation.getUuid()) @@ -419,7 +419,7 @@ class HsOfficeRelationControllerAcceptanceTest extends ContextBasedTestWithClean RestAssured // @formatter:off .given() - .header("current-user", "contact-admin@seventhcontact.example.com") + .header("current-subject", "contact-admin@seventhcontact.example.com") .port(port) .when() .delete("http://localhost/api/hs/office/relations/" + givenRelation.getUuid()) @@ -438,7 +438,7 @@ class HsOfficeRelationControllerAcceptanceTest extends ContextBasedTestWithClean RestAssured // @formatter:off .given() - .header("current-user", "selfregistered-user-drew@hostsharing.org") + .header("current-subject", "selfregistered-user-drew@hostsharing.org") .port(port) .when() .delete("http://localhost/api/hs/office/relations/" + givenRelation.getUuid()) diff --git a/src/test/java/net/hostsharing/hsadminng/hs/office/relation/HsOfficeRelationRepositoryIntegrationTest.java b/src/test/java/net/hostsharing/hsadminng/hs/office/relation/HsOfficeRelationRepositoryIntegrationTest.java index b9ccb589..e285e8c3 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/office/relation/HsOfficeRelationRepositoryIntegrationTest.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/office/relation/HsOfficeRelationRepositoryIntegrationTest.java @@ -4,8 +4,8 @@ import net.hostsharing.hsadminng.context.Context; import net.hostsharing.hsadminng.hs.office.contact.HsOfficeContactRealRepository; import net.hostsharing.hsadminng.hs.office.person.HsOfficePersonRepository; import net.hostsharing.hsadminng.rbac.test.ContextBasedTestWithCleanup; -import net.hostsharing.hsadminng.rbac.rbacgrant.RawRbacGrantRepository; -import net.hostsharing.hsadminng.rbac.rbacrole.RawRbacRoleRepository; +import net.hostsharing.hsadminng.rbac.grant.RawRbacGrantRepository; +import net.hostsharing.hsadminng.rbac.role.RawRbacRoleRepository; import net.hostsharing.hsadminng.mapper.Array; import net.hostsharing.hsadminng.rbac.test.JpaAttempt; import org.junit.jupiter.api.Nested; @@ -24,8 +24,8 @@ import java.util.List; import static net.hostsharing.hsadminng.hs.office.person.HsOfficePersonType.NATURAL_PERSON; import static net.hostsharing.hsadminng.hs.office.person.HsOfficePersonType.UNINCORPORATED_FIRM; -import static net.hostsharing.hsadminng.rbac.rbacgrant.RawRbacGrantEntity.distinctGrantDisplaysOf; -import static net.hostsharing.hsadminng.rbac.rbacrole.RawRbacRoleEntity.distinctRoleNamesOf; +import static net.hostsharing.hsadminng.rbac.grant.RawRbacGrantEntity.distinctGrantDisplaysOf; +import static net.hostsharing.hsadminng.rbac.role.RawRbacRoleEntity.distinctRoleNamesOf; import static net.hostsharing.hsadminng.rbac.test.JpaAttempt.attempt; import static org.assertj.core.api.Assertions.assertThat; @@ -133,7 +133,7 @@ class HsOfficeRelationRepositoryIntegrationTest extends ContextBasedTestWithClea initialGrantNames, "{ grant perm:hs_office_relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:DELETE to role:hs_office_relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:OWNER by system and assume }", - "{ grant role:hs_office_relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:OWNER to role:global#global:ADMIN by system and assume }", + "{ grant role:hs_office_relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:OWNER to role:rbac.global#global:ADMIN by system and assume }", "{ grant role:hs_office_relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:OWNER to user:superuser-alex@hostsharing.net by hs_office_relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:OWNER and assume }", "{ grant perm:hs_office_relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:UPDATE to role:hs_office_relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:ADMIN by system and assume }", @@ -233,7 +233,7 @@ class HsOfficeRelationRepositoryIntegrationTest extends ContextBasedTestWithClea assertThat(result.returnedValue().getContact().getCaption()).isEqualTo("sixth contact"); assertThatRelationIsVisibleForUserWithRole( result.returnedValue(), - "global#global:ADMIN"); + "rbac.global#global:ADMIN"); assertThatRelationIsVisibleForUserWithRole( result.returnedValue(), "hs_office_contact#sixthcontact:ADMIN"); @@ -395,7 +395,7 @@ class HsOfficeRelationRepositoryIntegrationTest extends ContextBasedTestWithClea // given final var query = em.createNativeQuery(""" select currentTask, targetTable, targetOp, targetdelta->>'mark' - from tx_journal_v + from base.tx_journal_v where targettable = 'hs_office_relation'; """); diff --git a/src/test/java/net/hostsharing/hsadminng/hs/office/sepamandate/HsOfficeSepaMandateControllerAcceptanceTest.java b/src/test/java/net/hostsharing/hsadminng/hs/office/sepamandate/HsOfficeSepaMandateControllerAcceptanceTest.java index 7d7e2c3a..026ce95c 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/office/sepamandate/HsOfficeSepaMandateControllerAcceptanceTest.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/office/sepamandate/HsOfficeSepaMandateControllerAcceptanceTest.java @@ -62,7 +62,7 @@ class HsOfficeSepaMandateControllerAcceptanceTest extends ContextBasedTestWithCl RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .port(port) .when() .get("http://localhost/api/hs/office/sepamandates") @@ -111,7 +111,7 @@ class HsOfficeSepaMandateControllerAcceptanceTest extends ContextBasedTestWithCl final var location = RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .contentType(ContentType.JSON) .body(""" { @@ -138,9 +138,9 @@ class HsOfficeSepaMandateControllerAcceptanceTest extends ContextBasedTestWithCl .extract().header("Location"); // @formatter:on // finally, the new sepaMandate can be accessed under the generated UUID - final var newUserUuid = UUID.fromString( + final var newSubjectUuid = UUID.fromString( location.substring(location.lastIndexOf('/') + 1)); - assertThat(newUserUuid).isNotNull(); + assertThat(newSubjectUuid).isNotNull(); } // TODO.test: move validation tests to a ...WebMvcTest @@ -153,7 +153,7 @@ class HsOfficeSepaMandateControllerAcceptanceTest extends ContextBasedTestWithCl final var location = RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .contentType(ContentType.JSON) .body(""" { @@ -178,7 +178,7 @@ class HsOfficeSepaMandateControllerAcceptanceTest extends ContextBasedTestWithCl final var location = RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .contentType(ContentType.JSON) .body(""" { @@ -208,7 +208,7 @@ class HsOfficeSepaMandateControllerAcceptanceTest extends ContextBasedTestWithCl final var location = RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .contentType(ContentType.JSON) .body(""" { @@ -242,7 +242,7 @@ class HsOfficeSepaMandateControllerAcceptanceTest extends ContextBasedTestWithCl RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .port(port) .when() .get("http://localhost/api/hs/office/sepamandates/" + givenSepaMandateUuid) @@ -272,7 +272,7 @@ class HsOfficeSepaMandateControllerAcceptanceTest extends ContextBasedTestWithCl RestAssured // @formatter:off .given() - .header("current-user", "selfregistered-user-drew@hostsharing.org") + .header("current-subject", "selfregistered-user-drew@hostsharing.org") .port(port) .when() .get("http://localhost/api/hs/office/sepamandates/" + givenSepaMandateUuid) @@ -289,7 +289,7 @@ class HsOfficeSepaMandateControllerAcceptanceTest extends ContextBasedTestWithCl RestAssured // @formatter:off .given() - .header("current-user", "bankaccount-admin@FirstGmbH.example.com") + .header("current-subject", "bankaccount-admin@FirstGmbH.example.com") .port(port) .when() .get("http://localhost/api/hs/office/sepamandates/" + givenSepaMandateUuid) @@ -321,7 +321,7 @@ class HsOfficeSepaMandateControllerAcceptanceTest extends ContextBasedTestWithCl final var location = RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .contentType(ContentType.JSON) .body(""" { @@ -367,7 +367,7 @@ class HsOfficeSepaMandateControllerAcceptanceTest extends ContextBasedTestWithCl final var location = RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .contentType(ContentType.JSON) .body(""" { @@ -407,7 +407,7 @@ class HsOfficeSepaMandateControllerAcceptanceTest extends ContextBasedTestWithCl final var location = RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .contentType(ContentType.JSON) .body(""" { @@ -441,7 +441,7 @@ class HsOfficeSepaMandateControllerAcceptanceTest extends ContextBasedTestWithCl RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .port(port) .when() .delete("http://localhost/api/hs/office/sepamandates/" + givenSepaMandate.getUuid()) @@ -459,7 +459,7 @@ class HsOfficeSepaMandateControllerAcceptanceTest extends ContextBasedTestWithCl RestAssured // @formatter:off .given() - .header("current-user", "bankaccount-admin@FirstGmbH.example.com") + .header("current-subject", "bankaccount-admin@FirstGmbH.example.com") .port(port) .when() .delete("http://localhost/api/hs/office/sepamandates/" + givenSepaMandate.getUuid()) @@ -477,7 +477,7 @@ class HsOfficeSepaMandateControllerAcceptanceTest extends ContextBasedTestWithCl RestAssured // @formatter:off .given() - .header("current-user", "selfregistered-user-drew@hostsharing.org") + .header("current-subject", "selfregistered-user-drew@hostsharing.org") .port(port) .when() .delete("http://localhost/api/hs/office/sepamandates/" + givenSepaMandate.getUuid()) diff --git a/src/test/java/net/hostsharing/hsadminng/hs/office/sepamandate/HsOfficeSepaMandateRepositoryIntegrationTest.java b/src/test/java/net/hostsharing/hsadminng/hs/office/sepamandate/HsOfficeSepaMandateRepositoryIntegrationTest.java index 3fb90976..ff5ea172 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/office/sepamandate/HsOfficeSepaMandateRepositoryIntegrationTest.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/office/sepamandate/HsOfficeSepaMandateRepositoryIntegrationTest.java @@ -5,8 +5,8 @@ import net.hostsharing.hsadminng.context.Context; import net.hostsharing.hsadminng.hs.office.bankaccount.HsOfficeBankAccountRepository; import net.hostsharing.hsadminng.hs.office.debitor.HsOfficeDebitorRepository; import net.hostsharing.hsadminng.rbac.test.ContextBasedTestWithCleanup; -import net.hostsharing.hsadminng.rbac.rbacgrant.RawRbacGrantRepository; -import net.hostsharing.hsadminng.rbac.rbacrole.RawRbacRoleRepository; +import net.hostsharing.hsadminng.rbac.grant.RawRbacGrantRepository; +import net.hostsharing.hsadminng.rbac.role.RawRbacRoleRepository; import net.hostsharing.hsadminng.mapper.Array; import net.hostsharing.hsadminng.rbac.test.JpaAttempt; import org.junit.jupiter.api.Nested; @@ -24,8 +24,8 @@ import java.time.LocalDate; import java.util.Arrays; import java.util.List; -import static net.hostsharing.hsadminng.rbac.rbacgrant.RawRbacGrantEntity.distinctGrantDisplaysOf; -import static net.hostsharing.hsadminng.rbac.rbacrole.RawRbacRoleEntity.distinctRoleNamesOf; +import static net.hostsharing.hsadminng.rbac.grant.RawRbacGrantEntity.distinctGrantDisplaysOf; +import static net.hostsharing.hsadminng.rbac.role.RawRbacRoleEntity.distinctRoleNamesOf; import static net.hostsharing.hsadminng.mapper.Array.fromFormatted; import static net.hostsharing.hsadminng.rbac.test.JpaAttempt.attempt; import static org.assertj.core.api.Assertions.assertThat; @@ -128,7 +128,7 @@ class HsOfficeSepaMandateRepositoryIntegrationTest extends ContextBasedTestWithC // owner "{ grant perm:sepamandate#DE02600501010002034304-[2020-01-01,2023-01-01):DELETE to role:sepamandate#DE02600501010002034304-[2020-01-01,2023-01-01):OWNER by system and assume }", - "{ grant role:sepamandate#DE02600501010002034304-[2020-01-01,2023-01-01):OWNER to role:global#global:ADMIN by system and assume }", + "{ grant role:sepamandate#DE02600501010002034304-[2020-01-01,2023-01-01):OWNER to role:rbac.global#global:ADMIN by system and assume }", "{ grant role:sepamandate#DE02600501010002034304-[2020-01-01,2023-01-01):OWNER to user:superuser-alex@hostsharing.net by sepamandate#DE02600501010002034304-[2020-01-01,2023-01-01):OWNER and assume }", // admin @@ -380,7 +380,7 @@ class HsOfficeSepaMandateRepositoryIntegrationTest extends ContextBasedTestWithC // given final var query = em.createNativeQuery(""" select currentTask, targetTable, targetOp, targetdelta->>'reference' - from tx_journal_v + from base.tx_journal_v where targettable = 'hs_office_sepamandate'; """); diff --git a/src/test/java/net/hostsharing/hsadminng/rbac/context/ContextBasedTest.java b/src/test/java/net/hostsharing/hsadminng/rbac/context/ContextBasedTest.java index 59704ad4..455be002 100644 --- a/src/test/java/net/hostsharing/hsadminng/rbac/context/ContextBasedTest.java +++ b/src/test/java/net/hostsharing/hsadminng/rbac/context/ContextBasedTest.java @@ -1,7 +1,7 @@ package net.hostsharing.hsadminng.rbac.context; import net.hostsharing.hsadminng.context.Context; -import net.hostsharing.hsadminng.rbac.rbacgrant.RbacGrantsDiagramService; +import net.hostsharing.hsadminng.rbac.grant.RbacGrantsDiagramService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.TestInfo; import org.springframework.beans.factory.annotation.Autowired; @@ -26,7 +26,7 @@ public abstract class ContextBasedTest {
      RbacGrantsDiagramService.writeToFile(
          "title",
-         diagramService.allGrantsToCurrentUser(of(RbacGrantsDiagramService.Include.USERS, RbacGrantsDiagramService.Include.TEST_ENTITIES, RbacGrantsDiagramService.Include.NOT_ASSUMED, RbacGrantsDiagramService.Include.DETAILS, RbacGrantsDiagramService.Include.PERMISSIONS)),
+         diagramService.allGrantsTocurrentSubject(of(RbacGrantsDiagramService.Include.USERS, RbacGrantsDiagramService.Include.TEST_ENTITIES, RbacGrantsDiagramService.Include.NOT_ASSUMED, RbacGrantsDiagramService.Include.DETAILS, RbacGrantsDiagramService.Include.PERMISSIONS)),
          "filename.md
      );
     
@@ -41,12 +41,12 @@ public abstract class ContextBasedTest { this.test = testInfo; } - protected void context(final String currentUser, final String assumedRoles) { - context.define(test.getDisplayName(), null, currentUser, assumedRoles); + protected void context(final String currentSubject, final String assumedRoles) { + context.define(test.getDisplayName(), null, currentSubject, assumedRoles); } - protected void context(final String currentUser) { - context(currentUser, null); + protected void context(final String currentSubject) { + context(currentSubject, null); } protected void historicalContext(final Long txId) { diff --git a/src/test/java/net/hostsharing/hsadminng/rbac/context/ContextIntegrationTests.java b/src/test/java/net/hostsharing/hsadminng/rbac/context/ContextIntegrationTests.java index 22e1df04..1b3fded5 100644 --- a/src/test/java/net/hostsharing/hsadminng/rbac/context/ContextIntegrationTests.java +++ b/src/test/java/net/hostsharing/hsadminng/rbac/context/ContextIntegrationTests.java @@ -36,30 +36,30 @@ class ContextIntegrationTests { context.define("superuser-alex@hostsharing.net", null); - assertThat(context.getCurrentTask()) + assertThat(context.fetchCurrentTask()) .isEqualTo("ContextIntegrationTests.defineWithoutHttpServletRequestUsesCallStack"); } @Test @Transactional - void defineWithCurrentUserButWithoutAssumedRoles() { + void defineWithcurrentSubjectButWithoutAssumedRoles() { // when context.define("superuser-alex@hostsharing.net"); // then - assertThat(context.getCurrentUser()). + assertThat(context.fetchCurrentSubject()). isEqualTo("superuser-alex@hostsharing.net"); - assertThat(context.getCurrentUserUUid()).isNotNull(); + assertThat(context.fetchCurrentSubjectUuid()).isNotNull(); - assertThat(context.getAssumedRoles()).isEmpty(); + assertThat(context.fetchAssumedRoles()).isEmpty(); - assertThat(context.currentSubjectsUuids()) - .containsExactly(context.getCurrentUserUUid()); + assertThat(context.fetchCurrentSubjectOrAssumedRolesUuids()) + .containsExactly(context.fetchCurrentSubjectUuid()); } @Test - void defineWithoutCurrentUserButWithAssumedRoles() { + void defineWithoutcurrentSubjectButWithAssumedRoles() { // when final var result = jpaAttempt.transacted(() -> context.define(null, "test_package#yyy00:ADMIN") @@ -72,7 +72,7 @@ class ContextIntegrationTests { } @Test - void defineWithUnknownCurrentUser() { + void defineWithUnknowncurrentSubject() { // when final var result = jpaAttempt.transacted(() -> context.define("unknown@example.org") @@ -81,27 +81,27 @@ class ContextIntegrationTests { // then result.assertExceptionWithRootCauseMessage( jakarta.persistence.PersistenceException.class, - "[401] user unknown@example.org given in `defineContext(...)` does not exist"); + "[401] subject unknown@example.org given in `base.defineContext(...)` does not exist"); } @Test @Transactional - void defineWithCurrentUserAndAssumedRoles() { + void defineWithcurrentSubjectAndAssumedRoles() { // given context.define("superuser-alex@hostsharing.net", "test_customer#xxx:OWNER;test_customer#yyy:OWNER"); // when - final var currentUser = context.getCurrentUser(); - assertThat(currentUser).isEqualTo("superuser-alex@hostsharing.net"); + final var currentSubject = context.fetchCurrentSubject(); + assertThat(currentSubject).isEqualTo("superuser-alex@hostsharing.net"); // then - assertThat(context.getAssumedRoles()) + assertThat(context.fetchAssumedRoles()) .isEqualTo(Array.of("test_customer#xxx:OWNER", "test_customer#yyy:OWNER")); - assertThat(context.currentSubjectsUuids()).hasSize(2); + assertThat(context.fetchCurrentSubjectOrAssumedRolesUuids()).hasSize(2); } @Test - public void defineContextWithCurrentUserAndAssumeInaccessibleRole() { + public void defineContextWithcurrentSubjectAndAssumeInaccessibleRole() { // when final var result = jpaAttempt.transacted(() -> context.define("customer-admin@xxx.example.com", "test_package#yyy00:ADMIN") @@ -110,6 +110,6 @@ class ContextIntegrationTests { // then result.assertExceptionWithRootCauseMessage( jakarta.persistence.PersistenceException.class, - "ERROR: [403] user customer-admin@xxx.example.com has no permission to assume role test_package#yyy00:ADMIN"); + "ERROR: [403] subject customer-admin@xxx.example.com has no permission to assume role test_package#yyy00:ADMIN"); } } diff --git a/src/test/java/net/hostsharing/hsadminng/rbac/context/ContextUnitTest.java b/src/test/java/net/hostsharing/hsadminng/rbac/context/ContextUnitTest.java index ae64d8c1..6a6d690f 100644 --- a/src/test/java/net/hostsharing/hsadminng/rbac/context/ContextUnitTest.java +++ b/src/test/java/net/hostsharing/hsadminng/rbac/context/ContextUnitTest.java @@ -28,10 +28,10 @@ import static org.mockito.Mockito.verify; class ContextUnitTest { private static final String DEFINE_CONTEXT_QUERY_STRING = """ - call defineContext( + call base.defineContext( cast(:currentTask as varchar(127)), cast(:currentRequest as text), - cast(:currentUser as varchar(63)), + cast(:currentSubject as varchar(63)), cast(:assumedRoles as varchar(1023))); """; @@ -57,7 +57,7 @@ class ContextUnitTest { void registerWithoutHttpServletRequestUsesCallStackForTask() { given(em.createNativeQuery(any())).willReturn(nativeQuery); - context.define("current-user"); + context.define("current-subject"); verify(em).createNativeQuery(DEFINE_CONTEXT_QUERY_STRING); verify(nativeQuery).setParameter( @@ -69,7 +69,7 @@ class ContextUnitTest { void registerWithoutHttpServletRequestUsesEmptyStringForRequest() { given(em.createNativeQuery(any())).willReturn(nativeQuery); - context.define("current-user"); + context.define("current-subject"); verify(em).createNativeQuery(DEFINE_CONTEXT_QUERY_STRING); verify(nativeQuery).setParameter("currentRequest", null); @@ -109,12 +109,12 @@ class ContextUnitTest { @Test void registerWithHttpServletRequestUsesRequest() throws IOException { givenRequest("POST", "http://localhost:9999/api/endpoint", Map.ofEntries( - Map.entry("current-user", "given-user"), + Map.entry("current-subject", "given-user"), Map.entry("content-type", "application/json"), Map.entry("user-agent", "given-user-agent")), "{}"); - context.define("current-user"); + context.define("current-subject"); verify(em).createNativeQuery(DEFINE_CONTEXT_QUERY_STRING); verify(nativeQuery).setParameter("currentTask", "POST http://localhost:9999/api/endpoint"); @@ -123,20 +123,20 @@ class ContextUnitTest { @Test void registerWithHttpServletRequestForwardsRequestAsCurl() throws IOException { givenRequest("POST", "http://localhost:9999/api/endpoint", Map.ofEntries( - Map.entry("current-user", "given-user"), + Map.entry("current-subject", "given-user"), Map.entry("content-type", "application/json"), Map.entry("user-agent", "given-user-agent")), "{}"); - context.define("current-user"); + context.define("current-subject"); verify(em).createNativeQuery(DEFINE_CONTEXT_QUERY_STRING); verify(nativeQuery).setParameter("currentRequest", """ curl -0 -v -X POST http://localhost:9999/api/endpoint \\ - -H 'current-user:given-user' \\ -H 'content-type:application/json' \\ + -H 'current-subject:given-user' \\ --data-binary @- << EOF - + {} EOF """.trim()); @@ -146,12 +146,12 @@ class ContextUnitTest { void shortensCurrentTaskToMaxLength() throws IOException { givenRequest("GET", "http://localhost:9999/api/endpoint/" + "0123456789".repeat(13), Map.ofEntries( - Map.entry("current-user", "given-user"), + Map.entry("current-subject", "given-user"), Map.entry("content-type", "application/json"), Map.entry("user-agent", "given-user-agent")), "{}"); - context.define("current-user"); + context.define("current-subject"); verify(em).createNativeQuery(DEFINE_CONTEXT_QUERY_STRING); verify(nativeQuery).setParameter(eq("currentTask"), argThat((String t) -> t.length() == 127)); diff --git a/src/test/java/net/hostsharing/hsadminng/rbac/rbacgrant/RbacGrantControllerAcceptanceTest.java b/src/test/java/net/hostsharing/hsadminng/rbac/grant/RbacGrantControllerAcceptanceTest.java similarity index 74% rename from src/test/java/net/hostsharing/hsadminng/rbac/rbacgrant/RbacGrantControllerAcceptanceTest.java rename to src/test/java/net/hostsharing/hsadminng/rbac/grant/RbacGrantControllerAcceptanceTest.java index aa2f0afb..16a08fdc 100644 --- a/src/test/java/net/hostsharing/hsadminng/rbac/rbacgrant/RbacGrantControllerAcceptanceTest.java +++ b/src/test/java/net/hostsharing/hsadminng/rbac/grant/RbacGrantControllerAcceptanceTest.java @@ -1,14 +1,14 @@ -package net.hostsharing.hsadminng.rbac.rbacgrant; +package net.hostsharing.hsadminng.rbac.grant; import io.restassured.RestAssured; import io.restassured.http.ContentType; import io.restassured.response.ValidatableResponse; import net.hostsharing.hsadminng.HsadminNgApplication; import net.hostsharing.hsadminng.rbac.context.ContextBasedTest; -import net.hostsharing.hsadminng.rbac.rbacrole.RbacRoleEntity; -import net.hostsharing.hsadminng.rbac.rbacrole.RbacRoleRepository; -import net.hostsharing.hsadminng.rbac.rbacuser.RbacUserEntity; -import net.hostsharing.hsadminng.rbac.rbacuser.RbacUserRepository; +import net.hostsharing.hsadminng.rbac.role.RbacRoleEntity; +import net.hostsharing.hsadminng.rbac.role.RbacRoleRepository; +import net.hostsharing.hsadminng.rbac.subject.RbacSubjectEntity; +import net.hostsharing.hsadminng.rbac.subject.RbacSubjectRepository; import net.hostsharing.hsadminng.rbac.test.JpaAttempt; import org.apache.commons.lang3.RandomStringUtils; import org.junit.jupiter.api.Nested; @@ -43,7 +43,7 @@ class RbacGrantControllerAcceptanceTest extends ContextBasedTest { EntityManager em; @Autowired - RbacUserRepository rbacUserRepository; + RbacSubjectRepository rbacSubjectRepository; @Autowired RbacRoleRepository rbacRoleRepository; @@ -61,7 +61,7 @@ class RbacGrantControllerAcceptanceTest extends ContextBasedTest { void globalAdmin_withoutAssumedRole_canViewAllGrants() { RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .port(port) .when() .get("http://localhost/api/rbac/grants") @@ -73,7 +73,7 @@ class RbacGrantControllerAcceptanceTest extends ContextBasedTest { // TODO: should there be a grantedByRole or just a grantedByTrigger? hasEntry("grantedByRoleIdName", "test_customer#xxx:OWNER"), hasEntry("grantedRoleIdName", "test_customer#xxx:ADMIN"), - hasEntry("granteeUserName", "customer-admin@xxx.example.com") + hasEntry("granteeSubjectName", "customer-admin@xxx.example.com") ) )) .body("", hasItem( @@ -81,28 +81,28 @@ class RbacGrantControllerAcceptanceTest extends ContextBasedTest { // TODO: should there be a grantedByRole or just a grantedByTrigger? hasEntry("grantedByRoleIdName", "test_customer#yyy:OWNER"), hasEntry("grantedRoleIdName", "test_customer#yyy:ADMIN"), - hasEntry("granteeUserName", "customer-admin@yyy.example.com") + hasEntry("granteeSubjectName", "customer-admin@yyy.example.com") ) )) .body("", hasItem( allOf( - hasEntry("grantedByRoleIdName", "global#global:ADMIN"), - hasEntry("grantedRoleIdName", "global#global:ADMIN"), - hasEntry("granteeUserName", "superuser-fran@hostsharing.net") + hasEntry("grantedByRoleIdName", "rbac.global#global:ADMIN"), + hasEntry("grantedRoleIdName", "rbac.global#global:ADMIN"), + hasEntry("granteeSubjectName", "superuser-fran@hostsharing.net") ) )) .body("", hasItem( allOf( hasEntry("grantedByRoleIdName", "test_customer#xxx:ADMIN"), hasEntry("grantedRoleIdName", "test_package#xxx00:ADMIN"), - hasEntry("granteeUserName", "pac-admin-xxx00@xxx.example.com") + hasEntry("granteeSubjectName", "pac-admin-xxx00@xxx.example.com") ) )) .body("", hasItem( allOf( hasEntry("grantedByRoleIdName", "test_customer#zzz:ADMIN"), hasEntry("grantedRoleIdName", "test_package#zzz02:ADMIN"), - hasEntry("granteeUserName", "pac-admin-zzz02@zzz.example.com") + hasEntry("granteeSubjectName", "pac-admin-zzz02@zzz.example.com") ) )) .body("size()", greaterThanOrEqualTo(14)); @@ -113,7 +113,7 @@ class RbacGrantControllerAcceptanceTest extends ContextBasedTest { void globalAdmin_withAssumedPackageAdminRole_canViewPacketRelatedGrants() { RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .header("assumed-roles", "test_package#yyy00:ADMIN") .port(port) .when() @@ -125,7 +125,7 @@ class RbacGrantControllerAcceptanceTest extends ContextBasedTest { allOf( hasEntry("grantedByRoleIdName", "test_customer#yyy:ADMIN"), hasEntry("grantedRoleIdName", "test_package#yyy00:ADMIN"), - hasEntry("granteeUserName", "pac-admin-yyy00@yyy.example.com") + hasEntry("granteeSubjectName", "pac-admin-yyy00@yyy.example.com") ) )) .body("size()", is(1)); @@ -136,7 +136,7 @@ class RbacGrantControllerAcceptanceTest extends ContextBasedTest { void packageAdmin_withoutAssumedRole_canViewPacketRelatedGrants() { RestAssured // @formatter:off .given() - .header("current-user", "pac-admin-yyy00@yyy.example.com") + .header("current-subject", "pac-admin-yyy00@yyy.example.com") .port(port) .when() .get("http://localhost/api/rbac/grants") @@ -147,12 +147,12 @@ class RbacGrantControllerAcceptanceTest extends ContextBasedTest { allOf( hasEntry("grantedByRoleIdName", "test_customer#yyy:ADMIN"), hasEntry("grantedRoleIdName", "test_package#yyy00:ADMIN"), - hasEntry("granteeUserName", "pac-admin-yyy00@yyy.example.com") + hasEntry("granteeSubjectName", "pac-admin-yyy00@yyy.example.com") ) )) .body("[0].grantedByRoleIdName", is("test_customer#yyy:ADMIN")) .body("[0].grantedRoleIdName", is("test_package#yyy00:ADMIN")) - .body("[0].granteeUserName", is("pac-admin-yyy00@yyy.example.com")); + .body("[0].granteeSubjectName", is("pac-admin-yyy00@yyy.example.com")); // @formatter:on } } @@ -163,12 +163,12 @@ class RbacGrantControllerAcceptanceTest extends ContextBasedTest { @Test void customerAdmin_withAssumedPacketAdminRole_canReadPacketAdminsGrantById() { // given - final var givenCurrentUserAsPackageAdmin = new Subject("customer-admin@xxx.example.com"); - final var givenGranteeUser = findRbacUserByName("pac-admin-xxx00@xxx.example.com"); + final var givencurrentSubjectAsPackageAdmin = new Subject("customer-admin@xxx.example.com"); + final var givenGranteeUser = findRbacSubjectByName("pac-admin-xxx00@xxx.example.com"); final var givenGrantedRole = getRbacRoleByName("test_package#xxx00:ADMIN"); // when - final var grant = givenCurrentUserAsPackageAdmin.getGrantById() + final var grant = givencurrentSubjectAsPackageAdmin.getGrantById() .forGrantedRole(givenGrantedRole).toGranteeUser(givenGranteeUser); // then @@ -176,18 +176,18 @@ class RbacGrantControllerAcceptanceTest extends ContextBasedTest { .statusCode(200) .body("grantedByRoleIdName", is("test_customer#xxx:ADMIN")) .body("grantedRoleIdName", is("test_package#xxx00:ADMIN")) - .body("granteeUserName", is("pac-admin-xxx00@xxx.example.com")); + .body("granteeSubjectName", is("pac-admin-xxx00@xxx.example.com")); } @Test void packageAdmin_withoutAssumedRole_canReadItsOwnGrantById() { // given - final var givenCurrentUserAsPackageAdmin = new Subject("pac-admin-xxx00@xxx.example.com"); - final var givenGranteeUser = findRbacUserByName("pac-admin-xxx00@xxx.example.com"); + final var givencurrentSubjectAsPackageAdmin = new Subject("pac-admin-xxx00@xxx.example.com"); + final var givenGranteeUser = findRbacSubjectByName("pac-admin-xxx00@xxx.example.com"); final var givenGrantedRole = getRbacRoleByName("test_package#xxx00:ADMIN"); // when - final var grant = givenCurrentUserAsPackageAdmin.getGrantById() + final var grant = givencurrentSubjectAsPackageAdmin.getGrantById() .forGrantedRole(givenGrantedRole).toGranteeUser(givenGranteeUser); // then @@ -195,20 +195,20 @@ class RbacGrantControllerAcceptanceTest extends ContextBasedTest { .statusCode(200) .body("grantedByRoleIdName", is("test_customer#xxx:ADMIN")) .body("grantedRoleIdName", is("test_package#xxx00:ADMIN")) - .body("granteeUserName", is("pac-admin-xxx00@xxx.example.com")); + .body("granteeSubjectName", is("pac-admin-xxx00@xxx.example.com")); } @Test void packageAdmin_withAssumedPackageAdmin_canStillReadItsOwnGrantById() { // given - final var givenCurrentUserAsPackageAdmin = new Subject( + final var givencurrentSubjectAsPackageAdmin = new Subject( "pac-admin-xxx00@xxx.example.com", "test_package#xxx00:ADMIN"); - final var givenGranteeUser = findRbacUserByName("pac-admin-xxx00@xxx.example.com"); + final var givenGranteeUser = findRbacSubjectByName("pac-admin-xxx00@xxx.example.com"); final var givenGrantedRole = getRbacRoleByName("test_package#xxx00:ADMIN"); // when - final var grant = givenCurrentUserAsPackageAdmin.getGrantById() + final var grant = givencurrentSubjectAsPackageAdmin.getGrantById() .forGrantedRole(givenGrantedRole).toGranteeUser(givenGranteeUser); // then @@ -216,19 +216,19 @@ class RbacGrantControllerAcceptanceTest extends ContextBasedTest { .statusCode(200) .body("grantedByRoleIdName", is("test_customer#xxx:ADMIN")) .body("grantedRoleIdName", is("test_package#xxx00:ADMIN")) - .body("granteeUserName", is("pac-admin-xxx00@xxx.example.com")); + .body("granteeSubjectName", is("pac-admin-xxx00@xxx.example.com")); } @Test void packageAdmin_withAssumedPackageTenantRole_canNotReadItsOwnGrantByIdAnymore() { // given - final var givenCurrentUserAsPackageAdmin = new Subject( + final var givencurrentSubjectAsPackageAdmin = new Subject( "pac-admin-xxx00@xxx.example.com", "test_package#xxx00:TENANT"); - final var givenGranteeUser = findRbacUserByName("pac-admin-xxx00@xxx.example.com"); + final var givenGranteeUser = findRbacSubjectByName("pac-admin-xxx00@xxx.example.com"); final var givenGrantedRole = getRbacRoleByName("test_package#xxx00:ADMIN"); - final var grant = givenCurrentUserAsPackageAdmin.getGrantById() + final var grant = givencurrentSubjectAsPackageAdmin.getGrantById() .forGrantedRole(givenGrantedRole).toGranteeUser(givenGranteeUser); // then @@ -238,20 +238,20 @@ class RbacGrantControllerAcceptanceTest extends ContextBasedTest { } @Nested - class GrantRoleToUser { + class GrantRoleToSubject { @Test void packageAdmin_canGrantOwnPackageAdminRole_toArbitraryUser() { // given - final var givenNewUser = createRBacUser(); + final var givenNewUser = createRbacSubject(); final var givenRoleToGrant = "test_package#xxx00:ADMIN"; - final var givenCurrentUserAsPackageAdmin = new Subject("pac-admin-xxx00@xxx.example.com", givenRoleToGrant); + final var givencurrentSubjectAsPackageAdmin = new Subject("pac-admin-xxx00@xxx.example.com", givenRoleToGrant); final var givenOwnPackageAdminRole = - getRbacRoleByName(givenCurrentUserAsPackageAdmin.assumedRole); + getRbacRoleByName(givencurrentSubjectAsPackageAdmin.assumedRole); // when - final var response = givenCurrentUserAsPackageAdmin + final var response = givencurrentSubjectAsPackageAdmin .grantsRole(givenOwnPackageAdminRole).assumed() .toUser(givenNewUser); @@ -261,8 +261,8 @@ class RbacGrantControllerAcceptanceTest extends ContextBasedTest { .body("grantedByRoleIdName", is("test_package#xxx00:ADMIN")) .body("assumed", is(true)) .body("grantedRoleIdName", is("test_package#xxx00:ADMIN")) - .body("granteeUserName", is(givenNewUser.getName())); - assertThat(findAllGrantsOf(givenCurrentUserAsPackageAdmin)) + .body("granteeSubjectName", is(givenNewUser.getName())); + assertThat(findAllGrantsOf(givencurrentSubjectAsPackageAdmin)) .extracting(RbacGrantEntity::toDisplay) .contains("{ grant role:" + givenOwnPackageAdminRole.getRoleName() + " to user:" + givenNewUser.getName() + @@ -273,13 +273,13 @@ class RbacGrantControllerAcceptanceTest extends ContextBasedTest { void packageAdmin_canNotGrantAlienPackageAdminRole_toArbitraryUser() { // given - final var givenNewUser = createRBacUser(); + final var givenNewUser = createRbacSubject(); final var givenRoleToGrant = "test_package#xxx00:ADMIN"; - final var givenCurrentUserAsPackageAdmin = new Subject("pac-admin-xxx00@xxx.example.com", givenRoleToGrant); + final var givencurrentSubjectAsPackageAdmin = new Subject("pac-admin-xxx00@xxx.example.com", givenRoleToGrant); final var givenAlienPackageAdminRole = getRbacRoleByName("test_package#yyy00:ADMIN"); // when - final var result = givenCurrentUserAsPackageAdmin + final var result = givencurrentSubjectAsPackageAdmin .grantsRole(givenAlienPackageAdminRole).assumed() .toUser(givenNewUser); @@ -288,45 +288,45 @@ class RbacGrantControllerAcceptanceTest extends ContextBasedTest { .statusCode(403) .body("message", containsString("Access to granted role")) .body("message", containsString("forbidden for test_package#xxx00:ADMIN")); - assertThat(findAllGrantsOf(givenCurrentUserAsPackageAdmin)) - .extracting(RbacGrantEntity::getGranteeUserName) + assertThat(findAllGrantsOf(givencurrentSubjectAsPackageAdmin)) + .extracting(RbacGrantEntity::getGranteeSubjectName) .doesNotContain(givenNewUser.getName()); } } @Nested - class RevokeRoleFromUser { + class RevokeRoleFromSubject { @Test @Transactional(propagation = Propagation.NEVER) void packageAdmin_canRevokePackageAdminRole_grantedByPackageAdmin_fromArbitraryUser() { // given - final var givenArbitraryUser = createRBacUser(); + final var givenArbitraryUser = createRbacSubject(); final var givenRoleToGrant = "test_package#xxx00:ADMIN"; - final var givenCurrentUserAsPackageAdmin = new Subject("pac-admin-xxx00@xxx.example.com", givenRoleToGrant); + final var givenCurrentSubjectAsPackageAdmin = new Subject("pac-admin-xxx00@xxx.example.com", givenRoleToGrant); final var givenOwnPackageAdminRole = getRbacRoleByName("test_package#xxx00:ADMIN"); // and given an existing grant - assumeCreated(givenCurrentUserAsPackageAdmin + assumeCreated(givenCurrentSubjectAsPackageAdmin .grantsRole(givenOwnPackageAdminRole).assumed() .toUser(givenArbitraryUser)); assumeGrantExists( - givenCurrentUserAsPackageAdmin, + givenCurrentSubjectAsPackageAdmin, "{ grant role:%s to user:%s by role:%s and assume }".formatted( givenOwnPackageAdminRole.getRoleName(), givenArbitraryUser.getName(), - givenCurrentUserAsPackageAdmin.assumedRole)); + givenCurrentSubjectAsPackageAdmin.assumedRole)); // when - final var revokeResponse = givenCurrentUserAsPackageAdmin + final var revokeResponse = givenCurrentSubjectAsPackageAdmin .revokesRole(givenOwnPackageAdminRole) .fromUser(givenArbitraryUser); // then revokeResponse.assertThat().statusCode(204); - assertThat(findAllGrantsOf(givenCurrentUserAsPackageAdmin)) - .extracting(RbacGrantEntity::getGranteeUserName) + assertThat(findAllGrantsOf(givenCurrentSubjectAsPackageAdmin)) + .extracting(RbacGrantEntity::getGranteeSubjectName) .doesNotContain(givenArbitraryUser.getName()); } } @@ -337,16 +337,16 @@ class RbacGrantControllerAcceptanceTest extends ContextBasedTest { class Subject { - final String currentUser; + final String currentSubject; final String assumedRole; - public Subject(final String currentUser, final String assumedRole) { - this.currentUser = currentUser; + public Subject(final String currentSubject, final String assumedRole) { + this.currentSubject = currentSubject; this.assumedRole = assumedRole; } - public Subject(final String currentUser) { - this(currentUser, ""); + public Subject(final String currentSubject) { + this(currentSubject, ""); } GrantFixture grantsRole(final RbacRoleEntity givenOwnPackageAdminRole) { @@ -366,7 +366,7 @@ class RbacGrantControllerAcceptanceTest extends ContextBasedTest { private Subject grantingSubject = Subject.this; private final RbacRoleEntity grantedRole; private boolean assumed; - private RbacUserEntity granteeUser; + private RbacSubjectEntity granteeUser; public GrantFixture(final RbacRoleEntity roleToGrant) { this.grantedRole = roleToGrant; @@ -377,19 +377,19 @@ class RbacGrantControllerAcceptanceTest extends ContextBasedTest { return this; } - ValidatableResponse toUser(final RbacUserEntity granteeUser) { + ValidatableResponse toUser(final RbacSubjectEntity granteeUser) { this.granteeUser = granteeUser; return RestAssured // @formatter:ff .given() - .header("current-user", grantingSubject.currentUser) + .header("current-subject", grantingSubject.currentSubject) .header("assumed-roles", grantingSubject.assumedRole) .contentType(ContentType.JSON) .body(""" { "assumed": true, "grantedRoleUuid": "%s", - "granteeUserUuid": "%s" + "granteeSubjectUuid": "%s" } """.formatted( grantedRole.getUuid(), @@ -407,25 +407,25 @@ class RbacGrantControllerAcceptanceTest extends ContextBasedTest { private Subject currentSubject = Subject.this; private final RbacRoleEntity grantedRole; private boolean assumed; - private RbacUserEntity granteeUser; + private RbacSubjectEntity granteeUser; public RevokeFixture(final RbacRoleEntity roleToGrant) { this.grantedRole = roleToGrant; } - ValidatableResponse fromUser(final RbacUserEntity granteeUser) { + ValidatableResponse fromUser(final RbacSubjectEntity granteeUser) { this.granteeUser = granteeUser; return RestAssured // @formatter:ff .given() - .header("current-user", currentSubject.currentUser) + .header("current-subject", currentSubject.currentSubject) .header("assumed-roles", currentSubject.assumedRole) .contentType(ContentType.JSON) .body(""" { "assumed": true, "grantedRoleUuid": "%s", - "granteeUserUuid": "%s" + "granteeSubjectUuid": "%s" } """.formatted( grantedRole.getUuid(), @@ -450,11 +450,11 @@ class RbacGrantControllerAcceptanceTest extends ContextBasedTest { return this; } - ValidatableResponse toGranteeUser(final RbacUserEntity granteeUser) { + ValidatableResponse toGranteeUser(final RbacSubjectEntity granteeUser) { return RestAssured // @formatter:ff .given() - .header("current-user", currentSubject.currentUser) + .header("current-subject", currentSubject.currentSubject) .header("assumed-roles", currentSubject.assumedRole) .port(port) .when() @@ -475,23 +475,23 @@ class RbacGrantControllerAcceptanceTest extends ContextBasedTest { List findAllGrantsOf(final Subject grantingSubject) { return jpaAttempt.transacted(() -> { - context(grantingSubject.currentUser, null); + context(grantingSubject.currentSubject, null); return rbacGrantRepository.findAll(); }).returnedValue(); } - RbacUserEntity createRBacUser() { + RbacSubjectEntity createRbacSubject() { return jpaAttempt.transacted(() -> { final String newUserName = "test-user-" + RandomStringUtils.randomAlphabetic(8) + "@example.com"; context(null); - return rbacUserRepository.create(new RbacUserEntity(UUID.randomUUID(), newUserName)); + return rbacSubjectRepository.create(new RbacSubjectEntity(UUID.randomUUID(), newUserName)); }).returnedValue(); } - RbacUserEntity findRbacUserByName(final String userName) { + RbacSubjectEntity findRbacSubjectByName(final String userName) { return jpaAttempt.transacted(() -> { context("superuser-alex@hostsharing.net", null); - return rbacUserRepository.findByName(userName); + return rbacSubjectRepository.findByName(userName); }).assertNotNull().returnedValue(); } diff --git a/src/test/java/net/hostsharing/hsadminng/rbac/rbacgrant/RbacGrantEntityUnitTest.java b/src/test/java/net/hostsharing/hsadminng/rbac/grant/RbacGrantEntityUnitTest.java similarity index 84% rename from src/test/java/net/hostsharing/hsadminng/rbac/rbacgrant/RbacGrantEntityUnitTest.java rename to src/test/java/net/hostsharing/hsadminng/rbac/grant/RbacGrantEntityUnitTest.java index c0bd82cc..78b80553 100644 --- a/src/test/java/net/hostsharing/hsadminng/rbac/rbacgrant/RbacGrantEntityUnitTest.java +++ b/src/test/java/net/hostsharing/hsadminng/rbac/grant/RbacGrantEntityUnitTest.java @@ -1,6 +1,6 @@ -package net.hostsharing.hsadminng.rbac.rbacgrant; +package net.hostsharing.hsadminng.rbac.grant; -import net.hostsharing.hsadminng.rbac.rbacrole.RbacRoleType; +import net.hostsharing.hsadminng.rbac.role.RbacRoleType; import org.junit.jupiter.api.Test; import java.util.UUID; @@ -13,16 +13,16 @@ class RbacGrantEntityUnitTest { void getRbacGrantId() { // given final var grantedRoleUuid = UUID.randomUUID(); - final var granteeUserUuid = UUID.randomUUID(); + final var granteeSubjectUuid = UUID.randomUUID(); final var entity = new RbacGrantEntity(); entity.setGrantedRoleUuid(grantedRoleUuid); - entity.setGranteeUserUuid(granteeUserUuid); + entity.setGranteeSubjectUuid(granteeSubjectUuid); // when final var grantId = entity.getRbacGrantId(); // then - assertThat(grantId).isEqualTo(new RbacGrantId(granteeUserUuid, grantedRoleUuid)); + assertThat(grantId).isEqualTo(new RbacGrantId(granteeSubjectUuid, grantedRoleUuid)); } @Test diff --git a/src/test/java/net/hostsharing/hsadminng/rbac/rbacgrant/RbacGrantRepositoryIntegrationTest.java b/src/test/java/net/hostsharing/hsadminng/rbac/grant/RbacGrantRepositoryIntegrationTest.java similarity index 86% rename from src/test/java/net/hostsharing/hsadminng/rbac/rbacgrant/RbacGrantRepositoryIntegrationTest.java rename to src/test/java/net/hostsharing/hsadminng/rbac/grant/RbacGrantRepositoryIntegrationTest.java index 804a564e..e9c29afe 100644 --- a/src/test/java/net/hostsharing/hsadminng/rbac/rbacgrant/RbacGrantRepositoryIntegrationTest.java +++ b/src/test/java/net/hostsharing/hsadminng/rbac/grant/RbacGrantRepositoryIntegrationTest.java @@ -1,10 +1,10 @@ -package net.hostsharing.hsadminng.rbac.rbacgrant; +package net.hostsharing.hsadminng.rbac.grant; import net.hostsharing.hsadminng.context.Context; import net.hostsharing.hsadminng.rbac.context.ContextBasedTest; -import net.hostsharing.hsadminng.rbac.rbacrole.RbacRoleRepository; -import net.hostsharing.hsadminng.rbac.rbacuser.RbacUserEntity; -import net.hostsharing.hsadminng.rbac.rbacuser.RbacUserRepository; +import net.hostsharing.hsadminng.rbac.role.RbacRoleRepository; +import net.hostsharing.hsadminng.rbac.subject.RbacSubjectEntity; +import net.hostsharing.hsadminng.rbac.subject.RbacSubjectRepository; import net.hostsharing.hsadminng.rbac.test.JpaAttempt; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; @@ -42,7 +42,7 @@ class RbacGrantRepositoryIntegrationTest extends ContextBasedTest { RawRbacGrantRepository rawRbacGrantRepository; @Autowired - RbacUserRepository rbacUserRepository; + RbacSubjectRepository rbacSubjectRepository; @Autowired RbacRoleRepository rbacRoleRepository; @@ -103,18 +103,18 @@ class RbacGrantRepositoryIntegrationTest extends ContextBasedTest { } @Nested - class GrantRoleToUser { + class GrantRoleToSubject { @Test public void customerAdmin_canGrantOwnPackageAdminRole_toArbitraryUser() { // given context("customer-admin@xxx.example.com", "test_customer#xxx:ADMIN"); - final var givenArbitraryUserUuid = rbacUserRepository.findByName("pac-admin-zzz00@zzz.example.com").getUuid(); + final var givenArbitrarySubjectUuid = rbacSubjectRepository.findByName("pac-admin-zzz00@zzz.example.com").getUuid(); final var givenOwnPackageRoleUuid = rbacRoleRepository.findByRoleName("test_package#xxx00:ADMIN").getUuid(); // when final var grant = RbacGrantEntity.builder() - .granteeUserUuid(givenArbitraryUserUuid).grantedRoleUuid(givenOwnPackageRoleUuid) + .granteeSubjectUuid(givenArbitrarySubjectUuid).grantedRoleUuid(givenOwnPackageRoleUuid) .assumed(true) .build(); final var attempt = attempt(em, () -> @@ -133,7 +133,7 @@ class RbacGrantRepositoryIntegrationTest extends ContextBasedTest { @Transactional(propagation = Propagation.NEVER) public void packageAdmin_canNotGrantPackageOwnerRole() { // given - record Given(RbacUserEntity arbitraryUser, UUID packageOwnerRoleUuid) {} + record Given(RbacSubjectEntity arbitraryUser, UUID packageOwnerRoleUuid) {} final var given = jpaAttempt.transacted(() -> { // to find the uuids of we need to have access rights to these context("customer-admin@xxx.example.com", null); @@ -148,7 +148,7 @@ class RbacGrantRepositoryIntegrationTest extends ContextBasedTest { // now we try to use these uuids as a less privileged user context("pac-admin-xxx00@xxx.example.com", "test_package#xxx00:ADMIN"); final var grant = RbacGrantEntity.builder() - .granteeUserUuid(given.arbitraryUser.getUuid()) + .granteeSubjectUuid(given.arbitraryUser.getUuid()) .grantedRoleUuid(given.packageOwnerRoleUuid) .assumed(true) .build(); @@ -170,7 +170,7 @@ class RbacGrantRepositoryIntegrationTest extends ContextBasedTest { } @Nested - class RevokeRoleFromUser { + class revokeRoleFromSubject { @Test public void customerAdmin_canRevokeSelfGrantedPackageAdminRole() { @@ -188,7 +188,7 @@ class RbacGrantRepositoryIntegrationTest extends ContextBasedTest { context("customer-admin@xxx.example.com", "test_customer#xxx:ADMIN"); assertThat(revokeAttempt.caughtExceptionsRootCause()).isNull(); assertThat(rbacGrantRepository.findAll()) - .extracting(RbacGrantEntity::getGranteeUserName) + .extracting(RbacGrantEntity::getGranteeSubjectName) .doesNotContain("pac-admin-zzz00@zzz.example.com"); } @@ -209,7 +209,7 @@ class RbacGrantRepositoryIntegrationTest extends ContextBasedTest { assertThat(revokeAttempt.caughtExceptionsRootCause()).isNull(); context("customer-admin@xxx.example.com", "test_customer#xxx:ADMIN"); assertThat(rbacGrantRepository.findAll()) - .extracting(RbacGrantEntity::getGranteeUserName) + .extracting(RbacGrantEntity::getGranteeSubjectName) .doesNotContain("pac-admin-zzz00@zzz.example.com"); } @@ -236,11 +236,11 @@ class RbacGrantRepositoryIntegrationTest extends ContextBasedTest { private RbacGrantEntity create(GrantBuilder with) { context(with.byUserName, with.assumedRole); - final var givenArbitraryUserUuid = rbacUserRepository.findByName(with.granteeUserName).getUuid(); + final var givenArbitrarySubjectUuid = rbacSubjectRepository.findByName(with.granteeSubjectName).getUuid(); final var givenOwnPackageRoleUuid = rbacRoleRepository.findByRoleName(with.grantedRole).getUuid(); final var grant = RbacGrantEntity.builder() - .granteeUserUuid(givenArbitraryUserUuid).grantedRoleUuid(givenOwnPackageRoleUuid) + .granteeSubjectUuid(givenArbitrarySubjectUuid).grantedRoleUuid(givenOwnPackageRoleUuid) .assumed(true) .build(); final var grantAttempt = attempt(em, () -> @@ -251,7 +251,7 @@ class RbacGrantRepositoryIntegrationTest extends ContextBasedTest { assertThat(rawRbacGrantRepository.findAll()) .extracting(RawRbacGrantEntity::toDisplay) .contains("{ grant role:%s to user:%s by %s and assume }".formatted( - with.grantedRole, with.granteeUserName, with.assumedRole + with.grantedRole, with.granteeSubjectName, with.assumedRole )); return grant; @@ -266,7 +266,7 @@ class RbacGrantRepositoryIntegrationTest extends ContextBasedTest { String byUserName; String assumedRole = ""; String grantedRole; - String granteeUserName; + String granteeSubjectName; GrantBuilder byUser(final String userName) { byUserName = userName; @@ -284,28 +284,28 @@ class RbacGrantRepositoryIntegrationTest extends ContextBasedTest { } GrantBuilder toUser(final String toUser) { - this.granteeUserName = toUser; + this.granteeSubjectName = toUser; return this; } } } - private RbacUserEntity createNewUserTransacted() { + private RbacSubjectEntity createNewUserTransacted() { return jpaAttempt.transacted(() -> { final var newUserName = "test-user-" + System.currentTimeMillis() + "@example.com"; context(null); - return rbacUserRepository.create(new RbacUserEntity(null, newUserName)); + return rbacSubjectRepository.create(new RbacSubjectEntity(null, newUserName)); }).assumeSuccessful().returnedValue(); } - private RbacUserEntity createNewUser() { - return rbacUserRepository.create( - new RbacUserEntity(null, "test-user-" + System.currentTimeMillis() + "@example.com")); + private RbacSubjectEntity createNewUser() { + return rbacSubjectRepository.create( + new RbacSubjectEntity(null, "test-user-" + System.currentTimeMillis() + "@example.com")); } void exactlyTheseRbacGrantsAreReturned(final List actualResult, final String... expectedGrant) { assertThat(actualResult) - .filteredOn(g -> !g.getGranteeUserName().startsWith("test-user-")) // ignore test-users created by other tests + .filteredOn(g -> !g.getGranteeSubjectName().startsWith("test-user-")) // ignore test-users created by other tests .extracting(RbacGrantEntity::toDisplay) .containsExactlyInAnyOrder(expectedGrant); } diff --git a/src/test/java/net/hostsharing/hsadminng/rbac/rbacgrant/RbacGrantsDiagramServiceIntegrationTest.java b/src/test/java/net/hostsharing/hsadminng/rbac/grant/RbacGrantsDiagramServiceIntegrationTest.java similarity index 77% rename from src/test/java/net/hostsharing/hsadminng/rbac/rbacgrant/RbacGrantsDiagramServiceIntegrationTest.java rename to src/test/java/net/hostsharing/hsadminng/rbac/grant/RbacGrantsDiagramServiceIntegrationTest.java index 7f183ba3..46dd8333 100644 --- a/src/test/java/net/hostsharing/hsadminng/rbac/rbacgrant/RbacGrantsDiagramServiceIntegrationTest.java +++ b/src/test/java/net/hostsharing/hsadminng/rbac/grant/RbacGrantsDiagramServiceIntegrationTest.java @@ -1,8 +1,8 @@ -package net.hostsharing.hsadminng.rbac.rbacgrant; +package net.hostsharing.hsadminng.rbac.grant; import net.hostsharing.hsadminng.context.Context; import net.hostsharing.hsadminng.rbac.test.ContextBasedTestWithCleanup; -import net.hostsharing.hsadminng.rbac.rbacgrant.RbacGrantsDiagramService.Include; +import net.hostsharing.hsadminng.rbac.grant.RbacGrantsDiagramService.Include; import net.hostsharing.hsadminng.rbac.test.JpaAttempt; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; @@ -44,18 +44,18 @@ class RbacGrantsDiagramServiceIntegrationTest extends ContextBasedTestWithCleanu this.test = testInfo; } - protected void context(final String currentUser, final String assumedRoles) { - context.define(test.getDisplayName(), null, currentUser, assumedRoles); + protected void context(final String currentSubject, final String assumedRoles) { + context.define(test.getDisplayName(), null, currentSubject, assumedRoles); } - protected void context(final String currentUser) { - context(currentUser, null); + protected void context(final String currentSubject) { + context(currentSubject, null); } @Test - void allGrantsToCurrentUser() { + void allGrantsTocurrentSubject() { context("superuser-alex@hostsharing.net", "test_domain#xxx00-aaaa:OWNER"); - final var graph = grantsMermaidService.allGrantsToCurrentUser(EnumSet.of(Include.TEST_ENTITIES)); + final var graph = grantsMermaidService.allGrantsTocurrentSubject(EnumSet.of(Include.TEST_ENTITIES)); assertThat(graph).isEqualTo(""" flowchart TB @@ -68,9 +68,9 @@ class RbacGrantsDiagramServiceIntegrationTest extends ContextBasedTestWithCleanu } @Test - void allGrantsToCurrentUserIncludingPermissions() { + void allGrantsTocurrentSubjectIncludingPermissions() { context("superuser-alex@hostsharing.net", "test_domain#xxx00-aaaa:OWNER"); - final var graph = grantsMermaidService.allGrantsToCurrentUser(EnumSet.of(Include.TEST_ENTITIES, Include.PERMISSIONS)); + final var graph = grantsMermaidService.allGrantsTocurrentSubject(EnumSet.of(Include.TEST_ENTITIES, Include.PERMISSIONS)); assertThat(graph).isEqualTo(""" flowchart TB @@ -93,11 +93,11 @@ class RbacGrantsDiagramServiceIntegrationTest extends ContextBasedTestWithCleanu //context("superuser-alex@hostsharing.net", "hs_office_person#FirbySusan:ADMIN"); context("superuser-alex@hostsharing.net"); - //final var graph = grantsMermaidService.allGrantsToCurrentUser(EnumSet.of(Include.NON_TEST_ENTITIES, Include.PERMISSIONS)); + //final var graph = grantsMermaidService.allGrantsTocurrentSubject(EnumSet.of(Include.NON_TEST_ENTITIES, Include.PERMISSIONS)); final var targetObject = (UUID) em.createNativeQuery("SELECT uuid FROM hs_office_coopassetstransaction WHERE reference='ref 1000101-1'").getSingleResult(); final var graph = grantsMermaidService.allGrantsFrom(targetObject, "view", EnumSet.of(Include.USERS)); - RbacGrantsDiagramService.writeToFile(join(";", context.getAssumedRoles()), graph, "doc/all-grants.md"); + RbacGrantsDiagramService.writeToFile(join(";", context.fetchAssumedRoles()), graph, "doc/all-grants.md"); } } diff --git a/src/test/java/net/hostsharing/hsadminng/rbac/rbacuser/TestRbacUser.java b/src/test/java/net/hostsharing/hsadminng/rbac/rbacuser/TestRbacUser.java deleted file mode 100644 index bd096c9e..00000000 --- a/src/test/java/net/hostsharing/hsadminng/rbac/rbacuser/TestRbacUser.java +++ /dev/null @@ -1,14 +0,0 @@ -package net.hostsharing.hsadminng.rbac.rbacuser; - - -import static java.util.UUID.randomUUID; - -public class TestRbacUser { - - static final RbacUserEntity userxxx = rbacRole("customer-admin@xxx.example.com"); - static final RbacUserEntity userBbb = rbacRole("customer-admin@bbb.example.com"); - - static public RbacUserEntity rbacRole(final String userName) { - return new RbacUserEntity(randomUUID(), userName); - } -} diff --git a/src/test/java/net/hostsharing/hsadminng/rbac/rbacrole/RawRbacObjectEntity.java b/src/test/java/net/hostsharing/hsadminng/rbac/role/RawRbacObjectEntity.java similarity index 82% rename from src/test/java/net/hostsharing/hsadminng/rbac/rbacrole/RawRbacObjectEntity.java rename to src/test/java/net/hostsharing/hsadminng/rbac/role/RawRbacObjectEntity.java index d4256e56..084a1752 100644 --- a/src/test/java/net/hostsharing/hsadminng/rbac/rbacrole/RawRbacObjectEntity.java +++ b/src/test/java/net/hostsharing/hsadminng/rbac/role/RawRbacObjectEntity.java @@ -1,4 +1,4 @@ -package net.hostsharing.hsadminng.rbac.rbacrole; +package net.hostsharing.hsadminng.rbac.role; import lombok.*; import org.jetbrains.annotations.NotNull; @@ -9,7 +9,7 @@ import java.util.List; import java.util.UUID; @Entity -@Table(name = "rbacobject") // TODO: create view rbacobject_ev +@Table(schema = "rbac", name = "object") // TODO.impl: create view rbacobject_ev @Getter @Setter @ToString diff --git a/src/test/java/net/hostsharing/hsadminng/rbac/rbacrole/RawRbacObjectRepository.java b/src/test/java/net/hostsharing/hsadminng/rbac/role/RawRbacObjectRepository.java similarity index 82% rename from src/test/java/net/hostsharing/hsadminng/rbac/rbacrole/RawRbacObjectRepository.java rename to src/test/java/net/hostsharing/hsadminng/rbac/role/RawRbacObjectRepository.java index ab645316..bda22795 100644 --- a/src/test/java/net/hostsharing/hsadminng/rbac/rbacrole/RawRbacObjectRepository.java +++ b/src/test/java/net/hostsharing/hsadminng/rbac/role/RawRbacObjectRepository.java @@ -1,4 +1,4 @@ -package net.hostsharing.hsadminng.rbac.rbacrole; +package net.hostsharing.hsadminng.rbac.role; import org.springframework.data.repository.Repository; diff --git a/src/test/java/net/hostsharing/hsadminng/rbac/rbacrole/RawRbacRoleEntity.java b/src/test/java/net/hostsharing/hsadminng/rbac/role/RawRbacRoleEntity.java similarity index 92% rename from src/test/java/net/hostsharing/hsadminng/rbac/rbacrole/RawRbacRoleEntity.java rename to src/test/java/net/hostsharing/hsadminng/rbac/role/RawRbacRoleEntity.java index e80f8ce6..ab957e1f 100644 --- a/src/test/java/net/hostsharing/hsadminng/rbac/rbacrole/RawRbacRoleEntity.java +++ b/src/test/java/net/hostsharing/hsadminng/rbac/role/RawRbacRoleEntity.java @@ -1,4 +1,4 @@ -package net.hostsharing.hsadminng.rbac.rbacrole; +package net.hostsharing.hsadminng.rbac.role; import lombok.*; import org.hibernate.annotations.Formula; @@ -10,7 +10,7 @@ import java.util.List; import java.util.UUID; @Entity -@Table(name = "rbacrole_ev") +@Table(schema = "rbac", name = "role_ev") @Getter @Setter @ToString diff --git a/src/test/java/net/hostsharing/hsadminng/rbac/rbacrole/RawRbacRoleRepository.java b/src/test/java/net/hostsharing/hsadminng/rbac/role/RawRbacRoleRepository.java similarity index 82% rename from src/test/java/net/hostsharing/hsadminng/rbac/rbacrole/RawRbacRoleRepository.java rename to src/test/java/net/hostsharing/hsadminng/rbac/role/RawRbacRoleRepository.java index c86f88a7..029e1360 100644 --- a/src/test/java/net/hostsharing/hsadminng/rbac/rbacrole/RawRbacRoleRepository.java +++ b/src/test/java/net/hostsharing/hsadminng/rbac/role/RawRbacRoleRepository.java @@ -1,4 +1,4 @@ -package net.hostsharing.hsadminng.rbac.rbacrole; +package net.hostsharing.hsadminng.rbac.role; import org.springframework.data.repository.Repository; diff --git a/src/test/java/net/hostsharing/hsadminng/rbac/rbacrole/RbacRoleControllerAcceptanceTest.java b/src/test/java/net/hostsharing/hsadminng/rbac/role/RbacRoleControllerAcceptanceTest.java similarity index 90% rename from src/test/java/net/hostsharing/hsadminng/rbac/rbacrole/RbacRoleControllerAcceptanceTest.java rename to src/test/java/net/hostsharing/hsadminng/rbac/role/RbacRoleControllerAcceptanceTest.java index 5f20b0ab..d9e2b248 100644 --- a/src/test/java/net/hostsharing/hsadminng/rbac/rbacrole/RbacRoleControllerAcceptanceTest.java +++ b/src/test/java/net/hostsharing/hsadminng/rbac/role/RbacRoleControllerAcceptanceTest.java @@ -1,9 +1,9 @@ -package net.hostsharing.hsadminng.rbac.rbacrole; +package net.hostsharing.hsadminng.rbac.role; import io.restassured.RestAssured; import net.hostsharing.hsadminng.HsadminNgApplication; import net.hostsharing.hsadminng.context.Context; -import net.hostsharing.hsadminng.rbac.rbacuser.RbacUserRepository; +import net.hostsharing.hsadminng.rbac.subject.RbacSubjectRepository; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @@ -24,7 +24,7 @@ class RbacRoleControllerAcceptanceTest { Context context; @Autowired - RbacUserRepository rbacUserRepository; + RbacSubjectRepository rbacSubjectRepository; @Autowired RbacRoleRepository rbacRoleRepository; @@ -35,7 +35,7 @@ class RbacRoleControllerAcceptanceTest { // @formatter:off RestAssured .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .port(port) .when() .get("http://localhost/api/rbac/roles") @@ -46,7 +46,7 @@ class RbacRoleControllerAcceptanceTest { .body("", hasItem(hasEntry("roleName", "test_customer#xxx:OWNER"))) .body("", hasItem(hasEntry("roleName", "test_customer#xxx:TENANT"))) // ... - .body("", hasItem(hasEntry("roleName", "global#global:ADMIN"))) + .body("", hasItem(hasEntry("roleName", "rbac.global#global:ADMIN"))) .body("", hasItem(hasEntry("roleName", "test_customer#yyy:ADMIN"))) .body("", hasItem(hasEntry("roleName", "test_package#yyy00:ADMIN"))) .body("", hasItem(hasEntry("roleName", "test_domain#yyy00-aaaa:OWNER"))) @@ -60,7 +60,7 @@ class RbacRoleControllerAcceptanceTest { // @formatter:off RestAssured .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .header("assumed-roles", "test_package#yyy00:ADMIN") .port(port) .when() @@ -93,7 +93,7 @@ class RbacRoleControllerAcceptanceTest { // @formatter:off RestAssured .given() - .header("current-user", "pac-admin-zzz00@zzz.example.com") + .header("current-subject", "pac-admin-zzz00@zzz.example.com") .port(port) .when() .get("http://localhost/api/rbac/roles") diff --git a/src/test/java/net/hostsharing/hsadminng/rbac/rbacrole/RbacRoleControllerRestTest.java b/src/test/java/net/hostsharing/hsadminng/rbac/role/RbacRoleControllerRestTest.java similarity index 91% rename from src/test/java/net/hostsharing/hsadminng/rbac/rbacrole/RbacRoleControllerRestTest.java rename to src/test/java/net/hostsharing/hsadminng/rbac/role/RbacRoleControllerRestTest.java index 44b3885e..1eb41370 100644 --- a/src/test/java/net/hostsharing/hsadminng/rbac/rbacrole/RbacRoleControllerRestTest.java +++ b/src/test/java/net/hostsharing/hsadminng/rbac/role/RbacRoleControllerRestTest.java @@ -1,4 +1,4 @@ -package net.hostsharing.hsadminng.rbac.rbacrole; +package net.hostsharing.hsadminng.rbac.role; import net.hostsharing.hsadminng.context.Context; import net.hostsharing.hsadminng.mapper.Mapper; @@ -21,7 +21,7 @@ import jakarta.persistence.SynchronizationType; import java.util.Map; import static java.util.Arrays.asList; -import static net.hostsharing.hsadminng.rbac.rbacrole.TestRbacRole.*; +import static net.hostsharing.hsadminng.rbac.role.TestRbacRole.*; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; import static org.mockito.ArgumentMatchers.any; @@ -67,13 +67,13 @@ class RbacRoleControllerRestTest { // when mockMvc.perform(MockMvcRequestBuilders .get("/api/rbac/roles") - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .accept(MediaType.APPLICATION_JSON)) // then .andExpect(status().isOk()) .andExpect(jsonPath("$", hasSize(3))) - .andExpect(jsonPath("$[0].roleName", is("global#global:ADMIN"))) + .andExpect(jsonPath("$[0].roleName", is("rbac.global#global:ADMIN"))) .andExpect(jsonPath("$[1].roleName", is("test_customer#xxx:OWNER"))) .andExpect(jsonPath("$[2].roleName", is("test_customer#xxx:ADMIN"))) .andExpect(jsonPath("$[2].uuid", is(customerXxxAdmin.getUuid().toString()))) diff --git a/src/test/java/net/hostsharing/hsadminng/rbac/rbacrole/RbacRoleRepositoryIntegrationTest.java b/src/test/java/net/hostsharing/hsadminng/rbac/role/RbacRoleRepositoryIntegrationTest.java similarity index 94% rename from src/test/java/net/hostsharing/hsadminng/rbac/rbacrole/RbacRoleRepositoryIntegrationTest.java rename to src/test/java/net/hostsharing/hsadminng/rbac/role/RbacRoleRepositoryIntegrationTest.java index e7a28261..d8b0cb80 100644 --- a/src/test/java/net/hostsharing/hsadminng/rbac/rbacrole/RbacRoleRepositoryIntegrationTest.java +++ b/src/test/java/net/hostsharing/hsadminng/rbac/role/RbacRoleRepositoryIntegrationTest.java @@ -1,4 +1,4 @@ -package net.hostsharing.hsadminng.rbac.rbacrole; +package net.hostsharing.hsadminng.rbac.role; import net.hostsharing.hsadminng.context.Context; import net.hostsharing.hsadminng.mapper.Array; @@ -38,8 +38,8 @@ class RbacRoleRepositoryIntegrationTest { class FindAllRbacRoles { private static final String[] ALL_TEST_DATA_ROLES = Array.of( - // @formatter:off - "global#global:ADMIN", + // @formatter:off + "rbac.global#global:ADMIN", "test_customer#xxx:ADMIN", "test_customer#xxx:OWNER", "test_customer#xxx:TENANT", "test_package#xxx00:ADMIN", "test_package#xxx00:OWNER", "test_package#xxx00:TENANT", "test_package#xxx01:ADMIN", "test_package#xxx01:OWNER", "test_package#xxx01:TENANT", @@ -70,7 +70,7 @@ class RbacRoleRepositoryIntegrationTest { @Test public void globalAdmin_withAssumedglobalAdminRole_canViewAllRbacRoles() { given: - context.define("superuser-alex@hostsharing.net", "global#global:ADMIN"); + context.define("superuser-alex@hostsharing.net", "rbac.global#global:ADMIN"); // when final var result = rbacRoleRepository.findAll(); @@ -110,7 +110,7 @@ class RbacRoleRepositoryIntegrationTest { noneOfTheseRbacRolesIsReturned( result, // @formatter:off - "global#global:ADMIN", + "rbac.global#global:ADMIN", "test_customer#xxx:OWNER", "test_package#yyy00:ADMIN", "test_package#yyy00:OWNER", @@ -146,7 +146,7 @@ class RbacRoleRepositoryIntegrationTest { result.assertExceptionWithRootCauseMessage( JpaSystemException.class, - "[401] currentSubjectsUuids cannot be determined, please call `defineContext(...)` with a valid user"); + "[401] currentSubjectOrAssumedRolesUuids cannot be determined, please call `base.defineContext(...)` with a valid subject"); } } diff --git a/src/test/java/net/hostsharing/hsadminng/rbac/rbacrole/TestRbacRole.java b/src/test/java/net/hostsharing/hsadminng/rbac/role/TestRbacRole.java similarity index 87% rename from src/test/java/net/hostsharing/hsadminng/rbac/rbacrole/TestRbacRole.java rename to src/test/java/net/hostsharing/hsadminng/rbac/role/TestRbacRole.java index 73e30a1b..8a8214cf 100644 --- a/src/test/java/net/hostsharing/hsadminng/rbac/rbacrole/TestRbacRole.java +++ b/src/test/java/net/hostsharing/hsadminng/rbac/role/TestRbacRole.java @@ -1,10 +1,10 @@ -package net.hostsharing.hsadminng.rbac.rbacrole; +package net.hostsharing.hsadminng.rbac.role; import static java.util.UUID.randomUUID; public class TestRbacRole { - public static final RbacRoleEntity hostmasterRole = rbacRole("global", "global", RbacRoleType.ADMIN); + public static final RbacRoleEntity hostmasterRole = rbacRole("rbac.global", "global", RbacRoleType.ADMIN); static final RbacRoleEntity customerXxxOwner = rbacRole("test_customer", "xxx", RbacRoleType.OWNER); static final RbacRoleEntity customerXxxAdmin = rbacRole("test_customer", "xxx", RbacRoleType.ADMIN); diff --git a/src/test/java/net/hostsharing/hsadminng/rbac/rbacuser/RbacUserControllerAcceptanceTest.java b/src/test/java/net/hostsharing/hsadminng/rbac/subject/RbacSubjectControllerAcceptanceTest.java similarity index 74% rename from src/test/java/net/hostsharing/hsadminng/rbac/rbacuser/RbacUserControllerAcceptanceTest.java rename to src/test/java/net/hostsharing/hsadminng/rbac/subject/RbacSubjectControllerAcceptanceTest.java index 601fadad..e62d39c4 100644 --- a/src/test/java/net/hostsharing/hsadminng/rbac/rbacuser/RbacUserControllerAcceptanceTest.java +++ b/src/test/java/net/hostsharing/hsadminng/rbac/subject/RbacSubjectControllerAcceptanceTest.java @@ -1,4 +1,4 @@ -package net.hostsharing.hsadminng.rbac.rbacuser; +package net.hostsharing.hsadminng.rbac.subject; import io.restassured.RestAssured; import io.restassured.http.ContentType; @@ -22,7 +22,7 @@ import static org.hamcrest.Matchers.*; classes = { HsadminNgApplication.class, JpaAttempt.class } ) @Transactional -class RbacUserControllerAcceptanceTest { +class RbacSubjectControllerAcceptanceTest { @LocalServerPort private Integer port; @@ -34,10 +34,10 @@ class RbacUserControllerAcceptanceTest { Context context; @Autowired - RbacUserRepository rbacUserRepository; + RbacSubjectRepository rbacSubjectRepository; @Nested - class CreateRbacUser { + class CreateRbacSubject { @Test void anybody_canCreateANewUser() { @@ -53,7 +53,7 @@ class RbacUserControllerAcceptanceTest { """) .port(port) .when() - .post("http://localhost/api/rbac/users") + .post("http://localhost/api/rbac/subjects") .then().assertThat() .statusCode(201) .contentType(ContentType.JSON) @@ -63,28 +63,28 @@ class RbacUserControllerAcceptanceTest { // @formatter:on // finally, the user can view its own record - final var newUserUuid = UUID.fromString( + final var newSubjectUuid = UUID.fromString( location.substring(location.lastIndexOf('/') + 1)); context.define("new-user@example.com"); - assertThat(rbacUserRepository.findByUuid(newUserUuid)) - .extracting(RbacUserEntity::getName).isEqualTo("new-user@example.com"); + assertThat(rbacSubjectRepository.findByUuid(newSubjectUuid)) + .extracting(RbacSubjectEntity::getName).isEqualTo("new-user@example.com"); } } @Nested - class GetRbacUser { + class GetRbacSubject { @Test void globalAdmin_withoutAssumedRole_canGetArbitraryUser() { - final var givenUser = findRbacUserByName("pac-admin-xxx00@xxx.example.com"); + final var givenUser = findRbacSubjectByName("pac-admin-xxx00@xxx.example.com"); // @formatter:off RestAssured .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .port(port) .when() - .get("http://localhost/api/rbac/users/" + givenUser.getUuid()) + .get("http://localhost/api/rbac/subjects/" + givenUser.getUuid()) .then().log().body().assertThat() .statusCode(200) .contentType("application/json") @@ -94,16 +94,16 @@ class RbacUserControllerAcceptanceTest { @Test void globalAdmin_withAssumedCustomerAdminRole_canGetUserWithinInItsRealm() { - final var givenUser = findRbacUserByName("pac-admin-yyy00@yyy.example.com"); + final var givenUser = findRbacSubjectByName("pac-admin-yyy00@yyy.example.com"); // @formatter:off RestAssured .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .header("assumed-roles", "test_customer#yyy:ADMIN") .port(port) .when() - .get("http://localhost/api/rbac/users/" + givenUser.getUuid()) + .get("http://localhost/api/rbac/subjects/" + givenUser.getUuid()) .then().log().body().assertThat() .statusCode(200) .contentType("application/json") @@ -113,15 +113,15 @@ class RbacUserControllerAcceptanceTest { @Test void customerAdmin_withoutAssumedRole_canGetUserWithinInItsRealm() { - final var givenUser = findRbacUserByName("pac-admin-yyy00@yyy.example.com"); + final var givenUser = findRbacSubjectByName("pac-admin-yyy00@yyy.example.com"); // @formatter:off RestAssured .given() - .header("current-user", "customer-admin@yyy.example.com") + .header("current-subject", "customer-admin@yyy.example.com") .port(port) .when() - .get("http://localhost/api/rbac/users/" + givenUser.getUuid()) + .get("http://localhost/api/rbac/subjects/" + givenUser.getUuid()) .then().log().body().assertThat() .statusCode(200) .contentType("application/json") @@ -131,15 +131,15 @@ class RbacUserControllerAcceptanceTest { @Test void customerAdmin_withoutAssumedRole_canNotGetUserOutsideOfItsRealm() { - final var givenUser = findRbacUserByName("pac-admin-yyy00@yyy.example.com"); + final var givenUser = findRbacSubjectByName("pac-admin-yyy00@yyy.example.com"); // @formatter:off RestAssured .given() - .header("current-user", "customer-admin@xxx.example.com") + .header("current-subject", "customer-admin@xxx.example.com") .port(port) .when() - .get("http://localhost/api/rbac/users/" + givenUser.getUuid()) + .get("http://localhost/api/rbac/subjects/" + givenUser.getUuid()) .then().log().body().assertThat() .statusCode(404); // @formatter:on @@ -147,7 +147,7 @@ class RbacUserControllerAcceptanceTest { } @Nested - class ListRbacUsers { + class ListRbacSubjects { @Test void globalAdmin_withoutAssumedRole_canViewAllUsers() { @@ -155,10 +155,10 @@ class RbacUserControllerAcceptanceTest { // @formatter:off RestAssured .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .port(port) .when() - .get("http://localhost/api/rbac/users") + .get("http://localhost/api/rbac/subjects") .then().log().body().assertThat() .statusCode(200) .contentType("application/json") @@ -180,10 +180,10 @@ class RbacUserControllerAcceptanceTest { // @formatter:off RestAssured .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .port(port) .when() - .get("http://localhost/api/rbac/users?name=pac-admin-zzz0") + .get("http://localhost/api/rbac/subjects?name=pac-admin-zzz0") .then().log().body().assertThat() .statusCode(200) .contentType("application/json") @@ -200,11 +200,11 @@ class RbacUserControllerAcceptanceTest { // @formatter:off RestAssured .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .header("assumed-roles", "test_customer#yyy:ADMIN") .port(port) .when() - .get("http://localhost/api/rbac/users") + .get("http://localhost/api/rbac/subjects") .then().assertThat() .statusCode(200) .contentType("application/json") @@ -222,10 +222,10 @@ class RbacUserControllerAcceptanceTest { // @formatter:off RestAssured .given() - .header("current-user", "customer-admin@yyy.example.com") + .header("current-subject", "customer-admin@yyy.example.com") .port(port) .when() - .get("http://localhost/api/rbac/users") + .get("http://localhost/api/rbac/subjects") .then().assertThat() .statusCode(200) .contentType("application/json") @@ -243,10 +243,10 @@ class RbacUserControllerAcceptanceTest { // @formatter:off RestAssured .given() - .header("current-user", "pac-admin-xxx01@xxx.example.com") + .header("current-subject", "pac-admin-xxx01@xxx.example.com") .port(port) .when() - .get("http://localhost/api/rbac/users") + .get("http://localhost/api/rbac/subjects") .then().assertThat() .statusCode(200) .contentType("application/json") @@ -257,19 +257,19 @@ class RbacUserControllerAcceptanceTest { } @Nested - class ListRbacUserPermissions { + class ListRbacSubjectPermissions { @Test void globalAdmin_withoutAssumedRole_canViewArbitraryUsersPermissions() { - final var givenUser = findRbacUserByName("pac-admin-yyy00@yyy.example.com"); + final var givenUser = findRbacSubjectByName("pac-admin-yyy00@yyy.example.com"); // @formatter:off RestAssured .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .port(port) .when() - .get("http://localhost/api/rbac/users/" + givenUser.getUuid() + "/permissions") + .get("http://localhost/api/rbac/subjects/" + givenUser.getUuid() + "/permissions") .then().log().body().assertThat() .statusCode(200) .contentType("application/json") @@ -290,16 +290,16 @@ class RbacUserControllerAcceptanceTest { @Test void globalAdmin_withAssumedCustomerAdminRole_canViewArbitraryUsersPermissions() { - final var givenUser = findRbacUserByName("pac-admin-yyy00@yyy.example.com"); + final var givenUser = findRbacSubjectByName("pac-admin-yyy00@yyy.example.com"); // @formatter:off RestAssured .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .header("assumed-roles", "test_customer#yyy:ADMIN") .port(port) .when() - .get("http://localhost/api/rbac/users/" + givenUser.getUuid() + "/permissions") + .get("http://localhost/api/rbac/subjects/" + givenUser.getUuid() + "/permissions") .then().log().body().assertThat() .statusCode(200) .contentType("application/json") @@ -320,15 +320,15 @@ class RbacUserControllerAcceptanceTest { @Test void packageAdmin_withoutAssumedRole_canViewPermissionsOfUsersInItsRealm() { - final var givenUser = findRbacUserByName("pac-admin-yyy00@yyy.example.com"); + final var givenUser = findRbacSubjectByName("pac-admin-yyy00@yyy.example.com"); // @formatter:off RestAssured .given() - .header("current-user", "pac-admin-yyy00@yyy.example.com") + .header("current-subject", "pac-admin-yyy00@yyy.example.com") .port(port) .when() - .get("http://localhost/api/rbac/users/" + givenUser.getUuid() + "/permissions") + .get("http://localhost/api/rbac/subjects/" + givenUser.getUuid() + "/permissions") .then().log().body().assertThat() .statusCode(200) .contentType("application/json") @@ -349,15 +349,15 @@ class RbacUserControllerAcceptanceTest { @Test void packageAdmin_canViewPermissionsOfUsersOutsideOfItsRealm() { - final var givenUser = findRbacUserByName("pac-admin-xxx00@xxx.example.com"); + final var givenUser = findRbacSubjectByName("pac-admin-xxx00@xxx.example.com"); // @formatter:off RestAssured .given() - .header("current-user", "pac-admin-yyy00@yyy.example.com") + .header("current-subject", "pac-admin-yyy00@yyy.example.com") .port(port) .when() - .get("http://localhost/api/rbac/users/" + givenUser.getUuid() + "/permissions") + .get("http://localhost/api/rbac/subjects/" + givenUser.getUuid() + "/permissions") .then().log().body().assertThat() .statusCode(200) .contentType("application/json") @@ -367,7 +367,7 @@ class RbacUserControllerAcceptanceTest { } @Nested - class DeleteRbacUser { + class DeleteRbacSubject { @Test void anybody_canDeleteTheirOwnUser() { @@ -378,16 +378,16 @@ class RbacUserControllerAcceptanceTest { // @formatter:off final var location = RestAssured .given() - .header("current-user", givenUser.getName()) + .header("current-subject", givenUser.getName()) .port(port) .when() - .delete("http://localhost/api/rbac/users/" + givenUser.getUuid()) + .delete("http://localhost/api/rbac/subjects/" + givenUser.getUuid()) .then().log().all().assertThat() .statusCode(204); // @formatter:on // finally, the user is actually deleted - assertThat(rbacUserRepository.findByName(givenUser.getName())).isNull(); + assertThat(rbacSubjectRepository.findByName(givenUser.getName())).isNull(); } @Test @@ -399,17 +399,17 @@ class RbacUserControllerAcceptanceTest { // @formatter:off final var location = RestAssured .given() - .header("current-user", "customer-admin@xxx.example.com") + .header("current-subject", "customer-admin@xxx.example.com") .port(port) .when() - .delete("http://localhost/api/rbac/users/" + givenUser.getUuid()) + .delete("http://localhost/api/rbac/subjects/" + givenUser.getUuid()) .then().log().all().assertThat() // that user cannot even see other users, thus the system won't even try to delete .statusCode(204); // @formatter:on // finally, the user is still there - assertThat(rbacUserRepository.findByName(givenUser.getName())).isNotNull(); + assertThat(rbacSubjectRepository.findByName(givenUser.getName())).isNotNull(); } @Test @@ -421,33 +421,33 @@ class RbacUserControllerAcceptanceTest { // @formatter:off final var location = RestAssured .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .port(port) .when() - .delete("http://localhost/api/rbac/users/" + givenUser.getUuid()) + .delete("http://localhost/api/rbac/subjects/" + givenUser.getUuid()) .then().log().all().assertThat() .statusCode(204); // @formatter:on // finally, the user is actually deleted - assertThat(rbacUserRepository.findByName(givenUser.getName())).isNull(); + assertThat(rbacSubjectRepository.findByName(givenUser.getName())).isNull(); } } - RbacUserEntity findRbacUserByName(final String userName) { + RbacSubjectEntity findRbacSubjectByName(final String userName) { return jpaAttempt.transacted(() -> { context.define("superuser-alex@hostsharing.net"); - return rbacUserRepository.findByName(userName); + return rbacSubjectRepository.findByName(userName); }).returnedValue(); } - RbacUserEntity givenANewUser() { + RbacSubjectEntity givenANewUser() { final var givenUserName = "test-user-" + System.currentTimeMillis() + "@example.com"; final var givenUser = jpaAttempt.transacted(() -> { context.define(null); - return rbacUserRepository.create(new RbacUserEntity(UUID.randomUUID(), givenUserName)); + return rbacSubjectRepository.create(new RbacSubjectEntity(UUID.randomUUID(), givenUserName)); }).assumeSuccessful().returnedValue(); - assertThat(rbacUserRepository.findByName(givenUser.getName())).isNotNull(); + assertThat(rbacSubjectRepository.findByName(givenUser.getName())).isNotNull(); return givenUser; } diff --git a/src/test/java/net/hostsharing/hsadminng/rbac/rbacuser/RbacUserControllerRestTest.java b/src/test/java/net/hostsharing/hsadminng/rbac/subject/RbacSubjectControllerRestTest.java similarity index 83% rename from src/test/java/net/hostsharing/hsadminng/rbac/rbacuser/RbacUserControllerRestTest.java rename to src/test/java/net/hostsharing/hsadminng/rbac/subject/RbacSubjectControllerRestTest.java index 6e59f38a..d23a8394 100644 --- a/src/test/java/net/hostsharing/hsadminng/rbac/rbacuser/RbacUserControllerRestTest.java +++ b/src/test/java/net/hostsharing/hsadminng/rbac/subject/RbacSubjectControllerRestTest.java @@ -1,4 +1,4 @@ -package net.hostsharing.hsadminng.rbac.rbacuser; +package net.hostsharing.hsadminng.rbac.subject; import net.hostsharing.hsadminng.context.Context; import net.hostsharing.hsadminng.mapper.Mapper; @@ -30,10 +30,10 @@ import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -@WebMvcTest(RbacUserController.class) +@WebMvcTest(RbacSubjectController.class) @Import(Mapper.class) @RunWith(SpringRunner.class) -class RbacUserControllerRestTest { +class RbacSubjectControllerRestTest { @Autowired MockMvc mockMvc; @@ -42,7 +42,7 @@ class RbacUserControllerRestTest { Context contextMock; @MockBean - RbacUserRepository rbacUserRepository; + RbacSubjectRepository rbacSubjectRepository; @Mock EntityManager em; @@ -59,13 +59,13 @@ class RbacUserControllerRestTest { } @Test - void createUserUsesGivenUuid() throws Exception { + void createSubjectUsesGivenUuid() throws Exception { // given final var givenUuid = UUID.randomUUID(); // when mockMvc.perform(MockMvcRequestBuilders - .post("/api/rbac/users") + .post("/api/rbac/subjects") .contentType(MediaType.APPLICATION_JSON) .content(""" { @@ -79,14 +79,14 @@ class RbacUserControllerRestTest { .andExpect(jsonPath("uuid", is(givenUuid.toString()))); // then - verify(rbacUserRepository).create(argThat(entity -> entity.getUuid().equals(givenUuid))); + verify(rbacSubjectRepository).create(argThat(entity -> entity.getUuid().equals(givenUuid))); } @Test - void createUserGeneratesRandomUuidIfNotGiven() throws Exception { + void createSubjectGeneratesRandomUuidIfNotGiven() throws Exception { // when mockMvc.perform(MockMvcRequestBuilders - .post("/api/rbac/users") + .post("/api/rbac/subjects") .contentType(MediaType.APPLICATION_JSON) .content("{}") .accept(MediaType.APPLICATION_JSON)) @@ -96,6 +96,6 @@ class RbacUserControllerRestTest { .andExpect(jsonPath("uuid", isUuidValid())); // then - verify(rbacUserRepository).create(argThat(entity -> entity.getUuid() != null)); + verify(rbacSubjectRepository).create(argThat(entity -> entity.getUuid() != null)); } } diff --git a/src/test/java/net/hostsharing/hsadminng/rbac/rbacuser/RbacUserEntityUnitTest.java b/src/test/java/net/hostsharing/hsadminng/rbac/subject/RbacSubjectEntityUnitTest.java similarity index 91% rename from src/test/java/net/hostsharing/hsadminng/rbac/rbacuser/RbacUserEntityUnitTest.java rename to src/test/java/net/hostsharing/hsadminng/rbac/subject/RbacSubjectEntityUnitTest.java index b1cff68e..44dde522 100644 --- a/src/test/java/net/hostsharing/hsadminng/rbac/rbacuser/RbacUserEntityUnitTest.java +++ b/src/test/java/net/hostsharing/hsadminng/rbac/subject/RbacSubjectEntityUnitTest.java @@ -1,4 +1,4 @@ -package net.hostsharing.hsadminng.rbac.rbacuser; +package net.hostsharing.hsadminng.rbac.subject; import org.junit.jupiter.api.Test; @@ -9,9 +9,9 @@ import java.util.UUID; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -class RbacUserEntityUnitTest { +class RbacSubjectEntityUnitTest { - RbacUserEntity givenUser = new RbacUserEntity(UUID.randomUUID(), "test@example.org"); + RbacSubjectEntity givenUser = new RbacSubjectEntity(UUID.randomUUID(), "test@example.org"); @Test void generatedAccessCodeMatchesDefinedPattern() { diff --git a/src/test/java/net/hostsharing/hsadminng/rbac/rbacuser/RbacUserRepositoryIntegrationTest.java b/src/test/java/net/hostsharing/hsadminng/rbac/subject/RbacSubjectRepositoryIntegrationTest.java similarity index 80% rename from src/test/java/net/hostsharing/hsadminng/rbac/rbacuser/RbacUserRepositoryIntegrationTest.java rename to src/test/java/net/hostsharing/hsadminng/rbac/subject/RbacSubjectRepositoryIntegrationTest.java index be6377a0..d6e50c46 100644 --- a/src/test/java/net/hostsharing/hsadminng/rbac/rbacuser/RbacUserRepositoryIntegrationTest.java +++ b/src/test/java/net/hostsharing/hsadminng/rbac/subject/RbacSubjectRepositoryIntegrationTest.java @@ -1,4 +1,4 @@ -package net.hostsharing.hsadminng.rbac.rbacuser; +package net.hostsharing.hsadminng.rbac.subject; import net.hostsharing.hsadminng.context.Context; import net.hostsharing.hsadminng.rbac.context.ContextBasedTest; @@ -26,10 +26,10 @@ import static org.assertj.core.api.Assertions.assertThat; @DataJpaTest @Import( { Context.class, JpaAttempt.class }) -class RbacUserRepositoryIntegrationTest extends ContextBasedTest { +class RbacSubjectRepositoryIntegrationTest extends ContextBasedTest { @Autowired - RbacUserRepository rbacUserRepository; + RbacSubjectRepository rbacSubjectRepository; @Autowired JpaAttempt jpaAttempt; @@ -41,7 +41,7 @@ class RbacUserRepositoryIntegrationTest extends ContextBasedTest { HttpServletRequest request; @Nested - class CreateUser { + class CreateSubject { @Test @Transactional(propagation = Propagation.NEVER) @@ -54,35 +54,35 @@ class RbacUserRepositoryIntegrationTest extends ContextBasedTest { // when: final var result = jpaAttempt.transacted(() -> { context(null); - return rbacUserRepository.create(new RbacUserEntity(givenUuid, newUserName)); + return rbacSubjectRepository.create(new RbacSubjectEntity(givenUuid, newUserName)); }); // then: assertThat(result.wasSuccessful()).isTrue(); assertThat(result.returnedValue()).isNotNull() - .extracting(RbacUserEntity::getUuid).isEqualTo(givenUuid); - assertThat(rbacUserRepository.findByName(result.returnedValue().getName())).isNotNull(); + .extracting(RbacSubjectEntity::getUuid).isEqualTo(givenUuid); + assertThat(rbacSubjectRepository.findByName(result.returnedValue().getName())).isNotNull(); } } @Nested - class DeleteUser { + class DeleteSubject { @Test @Transactional(propagation = Propagation.NEVER) public void anyoneCanDeleteTheirOwnUser() { // given - final RbacUserEntity givenUser = givenANewUser(); + final RbacSubjectEntity givenUser = givenANewSubject(); // when final var result = jpaAttempt.transacted(() -> { context(givenUser.getName()); - rbacUserRepository.deleteByUuid(givenUser.getUuid()); + rbacSubjectRepository.deleteByUuid(givenUser.getUuid()); }); // then the user is deleted result.assertSuccessful(); - assertThat(rbacUserRepository.findByName(givenUser.getName())).isNull(); + assertThat(rbacSubjectRepository.findByName(givenUser.getName())).isNull(); } } @@ -102,27 +102,27 @@ class RbacUserRepositoryIntegrationTest extends ContextBasedTest { ); @Test - public void globalAdmin_withoutAssumedRole_canViewAllRbacUsers() { + public void globalAdmin_withoutAssumedRole_canViewAllRbacSubjects() { // given context("superuser-alex@hostsharing.net"); // when - final var result = rbacUserRepository.findByOptionalNameLike(null); + final var result = rbacSubjectRepository.findByOptionalNameLike(null); // then - allTheseRbacUsersAreReturned(result, ALL_TEST_DATA_USERS); + allTheseRbacSubjectsAreReturned(result, ALL_TEST_DATA_USERS); } @Test - public void globalAdmin_withAssumedglobalAdminRole_canViewAllRbacUsers() { + public void globalAdmin_withAssumedglobalAdminRole_canViewAllRbacSubjects() { given: - context("superuser-alex@hostsharing.net", "global#global:ADMIN"); + context("superuser-alex@hostsharing.net", "rbac.global#global:ADMIN"); // when - final var result = rbacUserRepository.findByOptionalNameLike(null); + final var result = rbacSubjectRepository.findByOptionalNameLike(null); then: - allTheseRbacUsersAreReturned(result, ALL_TEST_DATA_USERS); + allTheseRbacSubjectsAreReturned(result, ALL_TEST_DATA_USERS); } @Test @@ -131,10 +131,10 @@ class RbacUserRepositoryIntegrationTest extends ContextBasedTest { context("superuser-alex@hostsharing.net", "test_customer#xxx:ADMIN"); // when - final var result = rbacUserRepository.findByOptionalNameLike(null); + final var result = rbacSubjectRepository.findByOptionalNameLike(null); then: - exactlyTheseRbacUsersAreReturned( + exactlyTheseRbacSubjectsAreReturned( result, "customer-admin@xxx.example.com", "pac-admin-xxx00@xxx.example.com", "pac-admin-xxx01@xxx.example.com", "pac-admin-xxx02@xxx.example.com" @@ -147,10 +147,10 @@ class RbacUserRepositoryIntegrationTest extends ContextBasedTest { context("customer-admin@xxx.example.com"); // when: - final var result = rbacUserRepository.findByOptionalNameLike(null); + final var result = rbacSubjectRepository.findByOptionalNameLike(null); // then: - exactlyTheseRbacUsersAreReturned( + exactlyTheseRbacSubjectsAreReturned( result, "customer-admin@xxx.example.com", "pac-admin-xxx00@xxx.example.com", "pac-admin-xxx01@xxx.example.com", "pac-admin-xxx02@xxx.example.com" @@ -161,24 +161,24 @@ class RbacUserRepositoryIntegrationTest extends ContextBasedTest { public void customerAdmin_withAssumedOwnedPackageAdminRole_canViewOnlyUsersHavingRolesInThatPackage() { context("customer-admin@xxx.example.com", "test_package#xxx00:ADMIN"); - final var result = rbacUserRepository.findByOptionalNameLike(null); + final var result = rbacSubjectRepository.findByOptionalNameLike(null); - exactlyTheseRbacUsersAreReturned(result, "pac-admin-xxx00@xxx.example.com"); + exactlyTheseRbacSubjectsAreReturned(result, "pac-admin-xxx00@xxx.example.com"); } @Test public void packageAdmin_withoutAssumedRole_canViewOnlyUsersHavingRolesInThatPackage() { context("pac-admin-xxx00@xxx.example.com"); - final var result = rbacUserRepository.findByOptionalNameLike(null); + final var result = rbacSubjectRepository.findByOptionalNameLike(null); - exactlyTheseRbacUsersAreReturned(result, "pac-admin-xxx00@xxx.example.com"); + exactlyTheseRbacSubjectsAreReturned(result, "pac-admin-xxx00@xxx.example.com"); } } @Nested - class ListUserPermissions { + class ListSubjectPermissions { private static final String[] ALL_USER_PERMISSIONS = Array.of( // @formatter:off @@ -232,9 +232,9 @@ class RbacUserRepositoryIntegrationTest extends ContextBasedTest { context("superuser-alex@hostsharing.net"); // when - final var result = rbacUserRepository.findPermissionsOfUserByUuid(userUUID("superuser-fran@hostsharing.net")) + final var result = rbacSubjectRepository.findPermissionsOfUserByUuid(subjectUuid("superuser-fran@hostsharing.net")) .stream().filter(p -> p.getObjectTable().contains("test_")) - .sorted(comparing(RbacUserPermission::toString)).toList(); + .sorted(comparing(RbacSubjectPermission::toString)).toList(); // then allTheseRbacPermissionsAreReturned(result, ALL_USER_PERMISSIONS); @@ -246,7 +246,7 @@ class RbacUserRepositoryIntegrationTest extends ContextBasedTest { context("customer-admin@xxx.example.com"); // when - final var result = rbacUserRepository.findPermissionsOfUserByUuid(userUUID("customer-admin@xxx.example.com")); + final var result = rbacSubjectRepository.findPermissionsOfUserByUuid(subjectUuid("customer-admin@xxx.example.com")); // then allTheseRbacPermissionsAreReturned( @@ -286,17 +286,17 @@ class RbacUserRepositoryIntegrationTest extends ContextBasedTest { public void customerAdmin_withoutAssumedRole_isNotAllowedToViewGlobalAdminsPermissions() { // given context("customer-admin@xxx.example.com"); - final UUID userUuid = userUUID("superuser-alex@hostsharing.net"); + final UUID subjectUuid = subjectUuid("superuser-alex@hostsharing.net"); // when final var result = attempt(em, () -> - rbacUserRepository.findPermissionsOfUserByUuid(userUuid) + rbacSubjectRepository.findPermissionsOfUserByUuid(subjectUuid) ); // then result.assertExceptionWithRootCauseMessage( JpaSystemException.class, - "[403] permissions of user \"" + userUuid + "[403] permissions of user \"" + subjectUuid + "\" are not accessible to user \"customer-admin@xxx.example.com\""); } @@ -306,7 +306,7 @@ class RbacUserRepositoryIntegrationTest extends ContextBasedTest { context("customer-admin@xxx.example.com"); // when - final var result = rbacUserRepository.findPermissionsOfUserByUuid(userUUID("pac-admin-xxx00@xxx.example.com")); + final var result = rbacSubjectRepository.findPermissionsOfUserByUuid(subjectUuid("pac-admin-xxx00@xxx.example.com")); // then allTheseRbacPermissionsAreReturned( @@ -342,7 +342,7 @@ class RbacUserRepositoryIntegrationTest extends ContextBasedTest { context("customer-admin@xxx.example.com"); // when - final var result = rbacUserRepository.findPermissionsOfUserByUuid(userUUID("pac-admin-yyy00@yyy.example.com")); + final var result = rbacSubjectRepository.findPermissionsOfUserByUuid(subjectUuid("pac-admin-yyy00@yyy.example.com")); // then noRbacPermissionsAreReturned(result); @@ -354,7 +354,7 @@ class RbacUserRepositoryIntegrationTest extends ContextBasedTest { context("pac-admin-xxx00@xxx.example.com"); // when - final var result = rbacUserRepository.findPermissionsOfUserByUuid(userUUID("pac-admin-xxx00@xxx.example.com")); + final var result = rbacSubjectRepository.findPermissionsOfUserByUuid(subjectUuid("pac-admin-xxx00@xxx.example.com")); // then allTheseRbacPermissionsAreReturned( @@ -385,51 +385,43 @@ class RbacUserRepositoryIntegrationTest extends ContextBasedTest { } } - UUID userUUID(final String userName) { - return rbacUserRepository.findByName(userName).getUuid(); + UUID subjectUuid(final String userName) { + return rbacSubjectRepository.findByName(userName).getUuid(); } - RbacUserEntity givenANewUser() { + RbacSubjectEntity givenANewSubject() { final var givenUserName = "test-user-" + System.currentTimeMillis() + "@example.com"; final var givenUser = jpaAttempt.transacted(() -> { context(null); - return rbacUserRepository.create(new RbacUserEntity(UUID.randomUUID(), givenUserName)); + return rbacSubjectRepository.create(new RbacSubjectEntity(UUID.randomUUID(), givenUserName)); }).assumeSuccessful().returnedValue(); - assertThat(rbacUserRepository.findByName(givenUser.getName())).isNotNull(); + assertThat(rbacSubjectRepository.findByName(givenUser.getName())).isNotNull(); return givenUser; } - void exactlyTheseRbacUsersAreReturned(final List actualResult, final String... expectedUserNames) { + void exactlyTheseRbacSubjectsAreReturned(final List actualResult, final String... expectedUserNames) { assertThat(actualResult) - .extracting(RbacUserEntity::getName) + .extracting(RbacSubjectEntity::getName) .filteredOn(n -> !n.startsWith("test-user")) .containsExactlyInAnyOrder(expectedUserNames); } - void allTheseRbacUsersAreReturned(final List actualResult, final String... expectedUserNames) { + void allTheseRbacSubjectsAreReturned(final List actualResult, final String... expectedUserNames) { assertThat(actualResult) - .extracting(RbacUserEntity::getName) + .extracting(RbacSubjectEntity::getName) .filteredOn(n -> !n.startsWith("test-user")) .contains(expectedUserNames); } void noRbacPermissionsAreReturned( - final List actualResult) { + final List actualResult) { assertThat(actualResult) .extracting(p -> p.getRoleName() + " -> " + p.getObjectTable() + "#" + p.getObjectIdName() + ": " + p.getOp()) .containsExactlyInAnyOrder(); } - void exactlyTheseRbacPermissionsAreReturned( - final List actualResult, - final String... expectedRoleNames) { - assertThat(actualResult) - .extracting(p -> p.getRoleName() + " -> " + p.getObjectTable() + "#" + p.getObjectIdName() + ": " + p.getOp()) - .containsExactlyInAnyOrder(expectedRoleNames); - } - void allTheseRbacPermissionsAreReturned( - final List actualResult, + final List actualResult, final String... expectedRoleNames) { assertThat(actualResult) .extracting(p -> p.getRoleName() + " -> " + p.getObjectTable() + "#" + p.getObjectIdName() + ": " + p.getOp() @@ -438,7 +430,7 @@ class RbacUserRepositoryIntegrationTest extends ContextBasedTest { } void noneOfTheseRbacPermissionsAreReturned( - final List actualResult, + final List actualResult, final String... unexpectedRoleNames) { assertThat(actualResult) .extracting(p -> p.getRoleName() + " -> " + p.getObjectTable() + "#" + p.getObjectIdName() + ": " + p.getOp()) diff --git a/src/test/java/net/hostsharing/hsadminng/rbac/subject/TestRbacSubject.java b/src/test/java/net/hostsharing/hsadminng/rbac/subject/TestRbacSubject.java new file mode 100644 index 00000000..05388f0c --- /dev/null +++ b/src/test/java/net/hostsharing/hsadminng/rbac/subject/TestRbacSubject.java @@ -0,0 +1,14 @@ +package net.hostsharing.hsadminng.rbac.subject; + + +import static java.util.UUID.randomUUID; + +public class TestRbacSubject { + + static final RbacSubjectEntity userxxx = rbacRole("customer-admin@xxx.example.com"); + static final RbacSubjectEntity userBbb = rbacRole("customer-admin@bbb.example.com"); + + static public RbacSubjectEntity rbacRole(final String userName) { + return new RbacSubjectEntity(randomUUID(), userName); + } +} diff --git a/src/test/java/net/hostsharing/hsadminng/rbac/test/ContextBasedTestWithCleanup.java b/src/test/java/net/hostsharing/hsadminng/rbac/test/ContextBasedTestWithCleanup.java index 366e79d7..d0a5b861 100644 --- a/src/test/java/net/hostsharing/hsadminng/rbac/test/ContextBasedTestWithCleanup.java +++ b/src/test/java/net/hostsharing/hsadminng/rbac/test/ContextBasedTestWithCleanup.java @@ -1,12 +1,12 @@ package net.hostsharing.hsadminng.rbac.test; import net.hostsharing.hsadminng.rbac.context.ContextBasedTest; -import net.hostsharing.hsadminng.rbac.rbacobject.BaseEntity; -import net.hostsharing.hsadminng.rbac.rbacgrant.RbacGrantEntity; -import net.hostsharing.hsadminng.rbac.rbacgrant.RbacGrantRepository; -import net.hostsharing.hsadminng.rbac.rbacgrant.RbacGrantsDiagramService; -import net.hostsharing.hsadminng.rbac.rbacrole.RbacRoleEntity; -import net.hostsharing.hsadminng.rbac.rbacrole.RbacRoleRepository; +import net.hostsharing.hsadminng.rbac.object.BaseEntity; +import net.hostsharing.hsadminng.rbac.grant.RbacGrantEntity; +import net.hostsharing.hsadminng.rbac.grant.RbacGrantRepository; +import net.hostsharing.hsadminng.rbac.grant.RbacGrantsDiagramService; +import net.hostsharing.hsadminng.rbac.role.RbacRoleEntity; +import net.hostsharing.hsadminng.rbac.role.RbacRoleRepository; import org.apache.commons.collections4.SetUtils; import org.jetbrains.annotations.NotNull; import org.junit.jupiter.api.AfterEach; @@ -200,7 +200,7 @@ public abstract class ContextBasedTestWithCleanup extends ContextBasedTest { }); }).caughtException(); - // ... and in case of foreign key violations, we rely on the RbacObject cleanup. + // ... and in case of foreign key violations, we rely on the rbac.object cleanup. if (exception != null) { System.err.println(exception); } @@ -305,7 +305,7 @@ public abstract class ContextBasedTestWithCleanup extends ContextBasedTest { protected String[] roleNames(final String sqlLikeExpression) { final var pattern = Pattern.compile(sqlLikeExpression); //noinspection unchecked - final List rows = (List) em.createNativeQuery("select * from rbacrole_ev where roleidname like 'hs_booking_project#%'") + final List rows = (List) em.createNativeQuery("select * from rbac.role_ev where roleidname like 'hs_booking_project#%'") .getResultList(); return rows.stream() .map(row -> (row[0]).toString()) @@ -322,7 +322,7 @@ public abstract class ContextBasedTestWithCleanup extends ContextBasedTest { protected void generateRbacDiagramForCurrentSubjects(final EnumSet include, final String name) { RbacGrantsDiagramService.writeToFile( name, - diagramService.allGrantsToCurrentUser(include), + diagramService.allGrantsTocurrentSubject(include), "doc/temp/" + name + ".md" ); } @@ -362,7 +362,7 @@ interface RbacObjectRepository extends Repository { } @Entity -@Table(name = "rbacobject") +@Table(schema ="rbac", name = "object") class RbacObjectEntity { @Id diff --git a/src/test/java/net/hostsharing/hsadminng/rbac/test/EntityList.java b/src/test/java/net/hostsharing/hsadminng/rbac/test/EntityList.java index 42469ea7..09e982b9 100644 --- a/src/test/java/net/hostsharing/hsadminng/rbac/test/EntityList.java +++ b/src/test/java/net/hostsharing/hsadminng/rbac/test/EntityList.java @@ -1,6 +1,6 @@ package net.hostsharing.hsadminng.rbac.test; -import net.hostsharing.hsadminng.rbac.rbacobject.BaseEntity; +import net.hostsharing.hsadminng.rbac.object.BaseEntity; import java.util.List; diff --git a/src/test/java/net/hostsharing/hsadminng/rbac/test/PatchUnitTestBase.java b/src/test/java/net/hostsharing/hsadminng/rbac/test/PatchUnitTestBase.java index 97fa53ec..67880dec 100644 --- a/src/test/java/net/hostsharing/hsadminng/rbac/test/PatchUnitTestBase.java +++ b/src/test/java/net/hostsharing/hsadminng/rbac/test/PatchUnitTestBase.java @@ -1,6 +1,6 @@ package net.hostsharing.hsadminng.rbac.test; -import net.hostsharing.hsadminng.rbac.rbacobject.BaseEntity; +import net.hostsharing.hsadminng.rbac.object.BaseEntity; import net.hostsharing.hsadminng.mapper.EntityPatcher; import org.junit.jupiter.api.Named; import org.junit.jupiter.api.Test; diff --git a/src/test/java/net/hostsharing/hsadminng/rbac/test/cust/TestCustomerControllerAcceptanceTest.java b/src/test/java/net/hostsharing/hsadminng/rbac/test/cust/TestCustomerControllerAcceptanceTest.java index 2d6d5a70..89783f25 100644 --- a/src/test/java/net/hostsharing/hsadminng/rbac/test/cust/TestCustomerControllerAcceptanceTest.java +++ b/src/test/java/net/hostsharing/hsadminng/rbac/test/cust/TestCustomerControllerAcceptanceTest.java @@ -54,7 +54,7 @@ class TestCustomerControllerAcceptanceTest { void globalAdmin_withoutAssumedRoles_canViewAllCustomers_ifNoCriteriaGiven() { RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .port(port) .when() .get("http://localhost/api/test/customers") @@ -72,7 +72,7 @@ class TestCustomerControllerAcceptanceTest { void globalAdmin_withoutAssumedRoles_canViewMatchingCustomers_ifCriteriaGiven() { RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .port(port) .when() .get("http://localhost/api/test/customers?prefix=y") @@ -88,7 +88,7 @@ class TestCustomerControllerAcceptanceTest { void globalAdmin_withoutAssumedCustomerAdminRole_canOnlyViewOwnCustomer() { RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .header("assumed-roles", "test_customer#yyy:ADMIN") .port(port) .when() @@ -105,7 +105,7 @@ class TestCustomerControllerAcceptanceTest { void customerAdmin_withoutAssumedRole_canOnlyViewOwnCustomer() { RestAssured // @formatter:off .given() - .header("current-user", "customer-admin@yyy.example.com") + .header("current-subject", "customer-admin@yyy.example.com") .port(port) .when() .get("http://localhost/api/test/customers") @@ -126,7 +126,7 @@ class TestCustomerControllerAcceptanceTest { final var location = RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .contentType(ContentType.JSON) .body(""" { @@ -146,10 +146,10 @@ class TestCustomerControllerAcceptanceTest { .extract().header("Location"); // @formatter:on // finally, the new customer can be viewed by its own admin - final var newUserUuid = UUID.fromString( + final var newSubjectUuid = UUID.fromString( location.substring(location.lastIndexOf('/') + 1)); context.define("superuser-fran@hostsharing.net", "test_customer#uuu:ADMIN"); - assertThat(testCustomerRepository.findByUuid(newUserUuid)) + assertThat(testCustomerRepository.findByUuid(newSubjectUuid)) .hasValueSatisfying(c -> assertThat(c.getPrefix()).isEqualTo("uuu")); } @@ -158,7 +158,7 @@ class TestCustomerControllerAcceptanceTest { RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .header("assumed-roles", "test_customer#xxx:ADMIN") .contentType(ContentType.JSON) .body(""" @@ -189,7 +189,7 @@ class TestCustomerControllerAcceptanceTest { RestAssured // @formatter:off .given() - .header("current-user", "customer-admin@yyy.example.com") + .header("current-subject", "customer-admin@yyy.example.com") .contentType(ContentType.JSON) .body(""" { @@ -219,7 +219,7 @@ class TestCustomerControllerAcceptanceTest { RestAssured // @formatter:off .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .contentType(ContentType.JSON) .body("{]") // deliberately invalid JSON .port(port) diff --git a/src/test/java/net/hostsharing/hsadminng/rbac/test/cust/TestCustomerEntityUnitTest.java b/src/test/java/net/hostsharing/hsadminng/rbac/test/cust/TestCustomerEntityUnitTest.java index e7107909..2a214146 100644 --- a/src/test/java/net/hostsharing/hsadminng/rbac/test/cust/TestCustomerEntityUnitTest.java +++ b/src/test/java/net/hostsharing/hsadminng/rbac/test/cust/TestCustomerEntityUnitTest.java @@ -1,6 +1,6 @@ package net.hostsharing.hsadminng.rbac.test.cust; -import net.hostsharing.hsadminng.rbac.rbacdef.RbacViewMermaidFlowchartGenerator; +import net.hostsharing.hsadminng.rbac.generator.RbacViewMermaidFlowchartGenerator; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @@ -13,19 +13,19 @@ class TestCustomerEntityUnitTest { assertThat(rbacFlowchart).isEqualTo(""" %%{init:{'flowchart':{'htmlLabels':false}}}%% flowchart TB - + subgraph customer["`**customer**`"] direction TB style customer fill:#dd4901,stroke:#274d6e,stroke-width:8px - + subgraph customer:roles[ ] style customer:roles fill:#dd4901,stroke:white - + role:customer:OWNER[[customer:OWNER]] role:customer:ADMIN[[customer:ADMIN]] role:customer:TENANT[[customer:TENANT]] end - + subgraph customer:permissions[ ] style customer:permissions fill:#dd4901,stroke:white @@ -40,12 +40,12 @@ class TestCustomerEntityUnitTest { user:creator ==>|XX| role:customer:OWNER %% granting roles to roles - role:global:ADMIN ==>|XX| role:customer:OWNER + role:rbac.global:ADMIN ==>|XX| role:customer:OWNER role:customer:OWNER ==> role:customer:ADMIN role:customer:ADMIN ==> role:customer:TENANT %% granting permissions to roles - role:global:ADMIN ==> perm:customer:INSERT + role:rbac.global:ADMIN ==> perm:customer:INSERT role:customer:OWNER ==> perm:customer:DELETE role:customer:ADMIN ==> perm:customer:UPDATE role:customer:TENANT ==> perm:customer:SELECT diff --git a/src/test/java/net/hostsharing/hsadminng/rbac/test/pac/TestPackageControllerAcceptanceTest.java b/src/test/java/net/hostsharing/hsadminng/rbac/test/pac/TestPackageControllerAcceptanceTest.java index a5e89330..fd9ec9a0 100644 --- a/src/test/java/net/hostsharing/hsadminng/rbac/test/pac/TestPackageControllerAcceptanceTest.java +++ b/src/test/java/net/hostsharing/hsadminng/rbac/test/pac/TestPackageControllerAcceptanceTest.java @@ -43,7 +43,7 @@ class TestPackageControllerAcceptanceTest { // @formatter:off RestAssured .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .header("assumed-roles", "test_customer#xxx:ADMIN") .port(port) .when() @@ -65,7 +65,7 @@ class TestPackageControllerAcceptanceTest { // @formatter:off RestAssured .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .header("assumed-roles", "test_customer#xxx:ADMIN") .port(port) .when() @@ -94,7 +94,7 @@ class TestPackageControllerAcceptanceTest { // @formatter:off RestAssured .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .header("assumed-roles", "test_customer#xxx:ADMIN") .contentType(ContentType.JSON) .body(format(""" @@ -125,7 +125,7 @@ class TestPackageControllerAcceptanceTest { // @formatter:off RestAssured .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .header("assumed-roles", "test_customer#xxx:ADMIN") .contentType(ContentType.JSON) .body(""" @@ -155,7 +155,7 @@ class TestPackageControllerAcceptanceTest { // @formatter:off RestAssured .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .header("assumed-roles", "test_customer#xxx:ADMIN") .contentType(ContentType.JSON) .body("{}") @@ -175,7 +175,7 @@ class TestPackageControllerAcceptanceTest { // @formatter:off return UUID.fromString(RestAssured .given() - .header("current-user", "superuser-alex@hostsharing.net") + .header("current-subject", "superuser-alex@hostsharing.net") .header("assumed-roles", "test_customer#xxx:ADMIN") .port(port) .when() diff --git a/src/test/java/net/hostsharing/hsadminng/rbac/test/pac/TestPackageEntityUnitTest.java b/src/test/java/net/hostsharing/hsadminng/rbac/test/pac/TestPackageEntityUnitTest.java index 824bb1bb..f91c0d5d 100644 --- a/src/test/java/net/hostsharing/hsadminng/rbac/test/pac/TestPackageEntityUnitTest.java +++ b/src/test/java/net/hostsharing/hsadminng/rbac/test/pac/TestPackageEntityUnitTest.java @@ -1,6 +1,6 @@ package net.hostsharing.hsadminng.rbac.test.pac; -import net.hostsharing.hsadminng.rbac.rbacdef.RbacViewMermaidFlowchartGenerator; +import net.hostsharing.hsadminng.rbac.generator.RbacViewMermaidFlowchartGenerator; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @@ -50,7 +50,7 @@ class TestPackageEntityUnitTest { end %% granting roles to roles - role:global:ADMIN -.->|XX| role:customer:OWNER + role:rbac.global:ADMIN -.->|XX| role:customer:OWNER role:customer:OWNER -.-> role:customer:ADMIN role:customer:ADMIN -.-> role:customer:TENANT role:customer:ADMIN ==> role:package:OWNER diff --git a/src/test/java/net/hostsharing/hsadminng/rbac/test/pac/TestPackageRepositoryIntegrationTest.java b/src/test/java/net/hostsharing/hsadminng/rbac/test/pac/TestPackageRepositoryIntegrationTest.java index a8fd8a50..e4f0e6fb 100644 --- a/src/test/java/net/hostsharing/hsadminng/rbac/test/pac/TestPackageRepositoryIntegrationTest.java +++ b/src/test/java/net/hostsharing/hsadminng/rbac/test/pac/TestPackageRepositoryIntegrationTest.java @@ -40,7 +40,7 @@ class TestPackageRepositoryIntegrationTest extends ContextBasedTest { @Test public void globalAdmin_withoutAssumedRole_canNotViewAnyPackages_becauseThoseGrantsAreNotAssumed() { // given - // alex is not just global-admin but lso the creating user, thus we use fran + // alex is not just rbac.global-admin but lso the creating user, thus we use fran context.define("superuser-fran@hostsharing.net"); // when @@ -53,7 +53,7 @@ class TestPackageRepositoryIntegrationTest extends ContextBasedTest { @Test public void globalAdmin_withAssumedglobalAdminRole__canNotViewAnyPackages_becauseThoseGrantsAreNotAssumed() { given: - context.define("superuser-alex@hostsharing.net", "global#global:ADMIN"); + context.define("superuser-alex@hostsharing.net", "rbac.global#global:ADMIN"); // when final var result = testPackageRepository.findAllByOptionalNameLike(null); From 285e6fbeb51ab30b5613280666b93bac17be5670 Mon Sep 17 00:00:00 2001 From: Michael Hoennig Date: Tue, 17 Sep 2024 14:21:43 +0200 Subject: [PATCH 3/4] introduce separate database schema-test and amend RBAC generators for schema-generation (#104) Co-authored-by: Michael Hoennig Reviewed-on: https://dev.hostsharing.net/hostsharing/hs.hsadmin.ng/pulls/104 Reviewed-by: Marc Sandlus --- README.md | 2 +- sql/rbac-tests.sql | 10 +- sql/rbac-view-option-experiments.sql | 18 +- .../generator/InsertTriggerGenerator.java | 28 +-- .../hsadminng/rbac/generator/RbacView.java | 30 +-- .../generator/RbacViewPostgresGenerator.java | 2 +- .../RolesGrantsAndPermissionsGenerator.java | 4 +- .../rbac/generator/StringWriter.java | 6 +- .../rbac/grant/RbacGrantsDiagramService.java | 4 +- .../rbac/test/cust/TestCustomerEntity.java | 4 +- .../rbac/test/dom/TestDomainEntity.java | 4 +- .../rbac/test/pac/TestPackageEntity.java | 4 +- .../db/changelog/0-base/007-table-columns.sql | 24 ++- .../db/changelog/0-base/010-context.sql | 1 + .../0-base/011-table-schema-and-name.sql | 18 ++ .../0-base/011-table-schema-and-name.sql | 0 .../db/changelog/0-base/020-audit-log.sql | 16 +- .../db/changelog/0-base/030-historization.sql | 4 +- .../db/changelog/1-rbac/1050-rbac-base.sql | 8 +- .../changelog/1-rbac/1058-rbac-generators.sql | 54 ++++-- .../2-rbactest/200-rbactest-schema.sql | 8 + .../2010-rbactest-customer.sql} | 2 +- .../2013-rbactest-customer-rbac.md} | 0 .../2013-rbactest-customer-rbac.sql} | 56 +++--- .../2018-rbactest-customer-test-data.sql} | 6 +- .../2020-rbactest-package.sql} | 4 +- .../2023-rbactest-package-rbac.md} | 0 .../2023-rbactest-package-rbac.sql} | 88 ++++----- .../2028-rbactest-package-test-data.sql} | 14 +- .../2030-rbactest-domain.sql} | 4 +- .../2033-rbactest-domain-rbac.md} | 0 .../2033-rbactest-domain-rbac.sql} | 88 ++++----- .../2038-rbactest-domain-test-data.sql} | 10 +- .../5043-hs-office-partner-rbac.sql | 6 +- .../5044-hs-office-partner-details-rbac.sql | 6 +- .../5063-hs-office-debitor-rbac.sql | 6 +- .../5073-hs-office-sepamandate-rbac.sql | 2 +- .../5103-hs-office-membership-rbac.sql | 6 +- .../5113-hs-office-coopshares-rbac.sql | 2 +- .../5123-hs-office-coopassets-rbac.sql | 2 +- .../db/changelog/db.changelog-master.yaml | 22 ++- .../hsadminng/hs/migration/CsvDataImport.java | 6 +- .../rbac/context/ContextIntegrationTests.java | 12 +- .../RbacGrantControllerAcceptanceTest.java | 70 +++---- .../RbacGrantRepositoryIntegrationTest.java | 54 +++--- ...acGrantsDiagramServiceIntegrationTest.java | 30 +-- .../RbacRoleControllerAcceptanceTest.java | 52 +++--- .../rbac/role/RbacRoleControllerRestTest.java | 4 +- .../RbacRoleRepositoryIntegrationTest.java | 78 ++++---- .../hsadminng/rbac/role/TestRbacRole.java | 4 +- .../RbacSubjectControllerAcceptanceTest.java | 18 +- .../RbacSubjectRepositoryIntegrationTest.java | 176 +++++++++--------- .../TestCustomerControllerAcceptanceTest.java | 12 +- ...TestCustomerRepositoryIntegrationTest.java | 12 +- .../TestPackageControllerAcceptanceTest.java | 14 +- .../TestPackageRepositoryIntegrationTest.java | 8 +- src/test/resources/application.yml | 1 + 57 files changed, 599 insertions(+), 525 deletions(-) create mode 100644 src/main/resources/db/changelog/0-base/011-table-schema-and-name.sql create mode 100644 src/main/resources/db/changelog/0-base/011-table-schema-and-name.sql create mode 100644 src/main/resources/db/changelog/2-rbactest/200-rbactest-schema.sql rename src/main/resources/db/changelog/{2-test/201-test-customer/2010-test-customer.sql => 2-rbactest/201-rbactest-customer/2010-rbactest-customer.sql} (92%) rename src/main/resources/db/changelog/{2-test/201-test-customer/2013-test-customer-rbac.md => 2-rbactest/201-rbactest-customer/2013-rbactest-customer-rbac.md} (100%) rename src/main/resources/db/changelog/{2-test/201-test-customer/2013-test-customer-rbac.sql => 2-rbactest/201-rbactest-customer/2013-rbactest-customer-rbac.sql} (66%) rename src/main/resources/db/changelog/{2-test/201-test-customer/2018-test-customer-test-data.sql => 2-rbactest/201-rbactest-customer/2018-rbactest-customer-test-data.sql} (93%) rename src/main/resources/db/changelog/{2-test/202-test-package/2020-test-package.sql => 2-rbactest/202-rbactest-package/2020-rbactest-package.sql} (80%) rename src/main/resources/db/changelog/{2-test/202-test-package/2023-test-package-rbac.md => 2-rbactest/202-rbactest-package/2023-rbactest-package-rbac.md} (100%) rename src/main/resources/db/changelog/{2-test/202-test-package/2023-test-package-rbac.sql => 2-rbactest/202-rbactest-package/2023-rbactest-package-rbac.sql} (65%) rename src/main/resources/db/changelog/{2-test/202-test-package/2028-test-package-test-data.sql => 2-rbactest/202-rbactest-package/2028-rbactest-package-test-data.sql} (84%) rename src/main/resources/db/changelog/{2-test/203-test-domain/2030-test-domain.sql => 2-rbactest/203-rbactest-domain/2030-rbactest-domain.sql} (80%) rename src/main/resources/db/changelog/{2-test/203-test-domain/2033-test-domain-rbac.md => 2-rbactest/203-rbactest-domain/2033-rbactest-domain-rbac.md} (100%) rename src/main/resources/db/changelog/{2-test/203-test-domain/2033-test-domain-rbac.sql => 2-rbactest/203-rbactest-domain/2033-rbactest-domain-rbac.sql} (66%) rename src/main/resources/db/changelog/{2-test/203-test-domain/2038-test-domain-test-data.sql => 2-rbactest/203-rbactest-domain/2038-rbactest-domain-test-data.sql} (89%) diff --git a/README.md b/README.md index 9cca4fc4..37777227 100644 --- a/README.md +++ b/README.md @@ -82,7 +82,7 @@ If you have at least Docker and the Java JDK installed in appropriate versions a # the following command should return a JSON array with just all packages visible for the admin of the customer yyy: curl \ - -H 'current-subject: superuser-alex@hostsharing.net' -H 'assumed-roles: test_customer#yyy:ADMIN' \ + -H 'current-subject: superuser-alex@hostsharing.net' -H 'assumed-roles: rbactest.customer#yyy:ADMIN' \ http://localhost:8080/api/test/packages # add a new customer diff --git a/sql/rbac-tests.sql b/sql/rbac-tests.sql index 1a95add0..fd6c221e 100644 --- a/sql/rbac-tests.sql +++ b/sql/rbac-tests.sql @@ -3,14 +3,14 @@ -- -------------------------------------------------------- -select rbac.isGranted(rbac.findRoleId('administrators'), rbac.findRoleId('test.package#aaa00:OWNER')); -select rbac.isGranted(rbac.findRoleId('test.package#aaa00:OWNER'), rbac.findRoleId('administrators')); --- call rbac.grantRoleToRole(findRoleId('test.package#aaa00:OWNER'), findRoleId('administrators')); --- call rbac.grantRoleToRole(findRoleId('administrators'), findRoleId('test.package#aaa00:OWNER')); +select rbac.isGranted(rbac.findRoleId('administrators'), rbac.findRoleId('rbactest.package#aaa00:OWNER')); +select rbac.isGranted(rbac.findRoleId('rbactest.package#aaa00:OWNER'), rbac.findRoleId('administrators')); +-- call rbac.grantRoleToRole(findRoleId('rbactest.package#aaa00:OWNER'), findRoleId('administrators')); +-- call rbac.grantRoleToRole(findRoleId('administrators'), findRoleId('rbactest.package#aaa00:OWNER')); select count(*) FROM rbac.queryAllPermissionsOfSubjectIdForObjectUuids(rbac.findRbacSubject('superuser-fran@hostsharing.net'), - ARRAY(select uuid from test.customer where reference < 1100000)); + ARRAY(select uuid from rbactest.customer where reference < 1100000)); select count(*) FROM rbac.queryAllPermissionsOfSubjectId(findRbacSubject('superuser-fran@hostsharing.net')); select * diff --git a/sql/rbac-view-option-experiments.sql b/sql/rbac-view-option-experiments.sql index 75668d76..d890e309 100644 --- a/sql/rbac-view-option-experiments.sql +++ b/sql/rbac-view-option-experiments.sql @@ -20,7 +20,7 @@ CREATE POLICY customer_policy ON customer TO restricted USING ( -- id=1000 - rbac.isPermissionGrantedToSubject(rbac.findEffectivePermissionId('test.customer', id, 'SELECT'), rbac.currentSubjectUuid()) + rbac.isPermissionGrantedToSubject(rbac.findEffectivePermissionId('rbactest.customer', id, 'SELECT'), rbac.currentSubjectUuid()) ); SET SESSION AUTHORIZATION restricted; @@ -31,28 +31,28 @@ SELECT * from customer; SET SESSION SESSION AUTHORIZATION DEFAULT; DROP VIEW cust_view; CREATE VIEW cust_view AS -SELECT * FROM test.customer; +SELECT * FROM rbactest.customer; CREATE OR REPLACE RULE "_RETURN" AS ON SELECT TO cust_view DO INSTEAD - SELECT * FROM test.customer WHERE rbac.isPermissionGrantedToSubject(rbac.findEffectivePermissionId('test.customer', id, 'SELECT'), rbac.currentSubjectUuid()); + SELECT * FROM rbactest.customer WHERE rbac.isPermissionGrantedToSubject(rbac.findEffectivePermissionId('rbactest.customer', id, 'SELECT'), rbac.currentSubjectUuid()); SELECT * from cust_view LIMIT 10; select rbac.queryAllPermissionsOfSubjectId(findRbacSubject('superuser-alex@hostsharing.net')); -- access control via view-rule with join to recursive permissions - really fast (38ms for 1 million rows) SET SESSION SESSION AUTHORIZATION DEFAULT; -ALTER TABLE test.customer ENABLE ROW LEVEL SECURITY; +ALTER TABLE rbactest.customer ENABLE ROW LEVEL SECURITY; DROP VIEW IF EXISTS cust_view; CREATE OR REPLACE VIEW cust_view AS SELECT * -FROM test.customer; +FROM rbactest.customer; CREATE OR REPLACE RULE "_RETURN" AS ON SELECT TO cust_view DO INSTEAD - SELECT c.uuid, c.reference, c.prefix FROM test.customer AS c + SELECT c.uuid, c.reference, c.prefix FROM rbactest.customer AS c JOIN rbac.queryAllPermissionsOfSubjectId(rbac.currentSubjectUuid()) AS p - ON p.objectTable='test.customer' AND p.objectUuid=c.uuid; + ON p.objectTable='rbactest.customer' AND p.objectUuid=c.uuid; GRANT ALL PRIVILEGES ON cust_view TO restricted; SET SESSION SESSION AUTHORIZATION restricted; @@ -81,9 +81,9 @@ select rr.uuid, rr.type from rbac.RbacGrants g join rbac.RbacReference RR on g.ascendantUuid = RR.uuid where g.descendantUuid in ( select uuid from rbac.queryAllPermissionsOfSubjectId(findRbacSubject('alex@example.com')) - where objectTable='test.customer'); + where objectTable='rbactest.customer'); -call rbac.grantRoleToUser(rbac.findRoleId('test.customer#aaa:ADMIN'), rbac.findRbacSubject('aaaaouq@example.com')); +call rbac.grantRoleToUser(rbac.findRoleId('rbactest.customer#aaa:ADMIN'), rbac.findRbacSubject('aaaaouq@example.com')); select rbac.queryAllPermissionsOfSubjectId(findRbacSubject('aaaaouq@example.com')); diff --git a/src/main/java/net/hostsharing/hsadminng/rbac/generator/InsertTriggerGenerator.java b/src/main/java/net/hostsharing/hsadminng/rbac/generator/InsertTriggerGenerator.java index eb489038..c5bc51c4 100644 --- a/src/main/java/net/hostsharing/hsadminng/rbac/generator/InsertTriggerGenerator.java +++ b/src/main/java/net/hostsharing/hsadminng/rbac/generator/InsertTriggerGenerator.java @@ -100,7 +100,7 @@ public class InsertTriggerGenerator { /** Grants ${rawSubTable} INSERT permission to specified role of new ${rawSuperTable} rows. */ - create or replace function ${rawSuperTableSchemaName}new_${rawSubTableShortName}_grants_insert_to_${rawSuperTableShortName}_tf() + create or replace function ${rawSubTableSchemaPrefix}new_${rawSubTableShortName}_grants_insert_to_${rawSuperTableShortName}_tf() returns trigger language plpgsql strict as $$ @@ -114,10 +114,10 @@ public class InsertTriggerGenerator { end; $$; -- z_... is to put it at the end of after insert triggers, to make sure the roles exist - create trigger z_new_${rawSubTable}_grants_after_insert_tg + create trigger z_new_${rawSubTableName}_grants_after_insert_tg after insert on ${rawSuperTableWithSchema} for each row - execute procedure ${rawSuperTableSchemaName}new_${rawSubTableShortName}_grants_insert_to_${rawSuperTableShortName}_tf(); + execute procedure ${rawSubTableSchemaPrefix}new_${rawSubTableShortName}_grants_insert_to_${rawSuperTableShortName}_tf(); """, with("ifConditionThen", g.getSuperRoleDef().getEntityAlias().isCaseDependent() // TODO.impl: .type needs to be dynamically generated @@ -130,8 +130,9 @@ public class InsertTriggerGenerator { with("rawSuperTableWithSchema", g.getSuperRoleDef().getEntityAlias().getRawTableNameWithSchema()), with("rawSuperTableShortName", g.getSuperRoleDef().getEntityAlias().getRawTableShortName()), with("rawSuperTable", g.getSuperRoleDef().getEntityAlias().getRawTableName()), - with("rawSuperTableSchemaName", g.getSuperRoleDef().getEntityAlias().getRawTableSchemaPrefix()), with("rawSubTable", g.getPermDef().getEntityAlias().getRawTableNameWithSchema()), + with("rawSubTableSchemaPrefix", g.getPermDef().getEntityAlias().getRawTableSchemaPrefix()), + with("rawSubTableName", g.getPermDef().getEntityAlias().getRawTableName()), with("rawSubTableShortName", g.getPermDef().getEntityAlias().getRawTableShortName())); }); @@ -154,15 +155,16 @@ public class InsertTriggerGenerator { returns trigger language plpgsql as $$ begin - raise exception '[403] insert into ${rawSubTable} values(%) not allowed regardless of current subject, no insert permissions granted at all', NEW; + raise exception '[403] insert into ${rawSubTableWithSchema} values(%) not allowed regardless of current subject, no insert permissions granted at all', NEW; end; $$; create trigger ${rawSubTable}_insert_permission_check_tg before insert on ${rawSubTable} for each row - execute procedure ${rawSubTable}_insert_permission_missing_tf(); + execute procedure ${rawSubTableWithSchema}_insert_permission_missing_tf(); """, - with("rawSubTable", rbacDef.getRootEntityAlias().getRawTableNameWithSchema())); + with("rawSubTableWithSchema", rbacDef.getRootEntityAlias().getRawTableNameWithSchema()), + with("rawSubTable", rbacDef.getRootEntityAlias().getRawTableName())); plPgSql.writeLn("--//"); } @@ -183,7 +185,7 @@ public class InsertTriggerGenerator { private void generateInsertPermissionsCheckHeader(final StringWriter plPgSql) { plPgSql.writeLn(""" -- ============================================================================ - --changeset InsertTriggerGenerator:${rawSubTable}-rbac-CHECKING-INSERT-PERMISSION endDelimiter:--// + --changeset InsertTriggerGenerator:${liquibaseTagPrefix}-rbac-CHECKING-INSERT-PERMISSION endDelimiter:--// -- ---------------------------------------------------------------------------- /** @@ -196,6 +198,7 @@ public class InsertTriggerGenerator { superObjectUuid uuid; begin """, + with("liquibaseTagPrefix", liquibaseTagPrefix), with("rawSubTable", rbacDef.getRootEntityAlias().getRawTableNameWithSchema())); plPgSql.chopEmptyLines(); } @@ -258,17 +261,18 @@ public class InsertTriggerGenerator { private void generateInsertPermissionsChecksFooter(final StringWriter plPgSql) { plPgSql.writeLn(); plPgSql.writeLn(""" - raise exception '[403] insert into ${rawSubTable} values(%) not allowed for current subjects % (%)', + raise exception '[403] insert into ${rawSubTableWithSchema} values(%) not allowed for current subjects % (%)', NEW, base.currentSubjects(), rbac.currentSubjectOrAssumedRolesUuids(); end; $$; create trigger ${rawSubTable}_insert_permission_check_tg - before insert on ${rawSubTable} + before insert on ${rawSubTableWithSchema} for each row - execute procedure ${rawSubTable}_insert_permission_check_tf(); + execute procedure ${rawSubTableWithSchema}_insert_permission_check_tf(); --// """, - with("rawSubTable", rbacDef.getRootEntityAlias().getRawTableNameWithSchema())); + with("rawSubTableWithSchema", rbacDef.getRootEntityAlias().getRawTableNameWithSchema()), + with("rawSubTable", rbacDef.getRootEntityAlias().getRawTableName())); } private String toStringList(final Set cases) { diff --git a/src/main/java/net/hostsharing/hsadminng/rbac/generator/RbacView.java b/src/main/java/net/hostsharing/hsadminng/rbac/generator/RbacView.java index 634d4c33..179bf667 100644 --- a/src/main/java/net/hostsharing/hsadminng/rbac/generator/RbacView.java +++ b/src/main/java/net/hostsharing/hsadminng/rbac/generator/RbacView.java @@ -90,11 +90,11 @@ public class RbacView { * @param * a JPA entity class extending RbacObject */ - public static RbacView rbacViewFor(final String alias, final Class entityClass) { + public static > RbacView rbacViewFor(final String alias, final Class entityClass) { return new RbacView(alias, entityClass); } - RbacView(final String alias, final Class entityClass) { + RbacView(final String alias, final Class> entityClass) { rootEntityAlias = new EntityAlias(alias, entityClass); entityAliases.put(alias, rootEntityAlias); new RbacSubjectReference(CREATOR); @@ -121,7 +121,7 @@ public class RbacView { *

An identity view is a view which maps an objectUuid to an idName. * The idName should be a human-readable representation of the row, but as short as possible. * The idName must only consist of letters (A-Z, a-z), digits (0-9), dash (-), dot (.) and unserscore '_'. - * It's used to create the object-specific-role-names like test_customer#abc:ADMIN - here 'abc' is the idName. + * It's used to create the object-specific-role-names like rbactest.customer#abc:ADMIN - here 'abc' is the idName. * The idName not necessarily unique in a table, but it should be avoided. *

* @@ -287,9 +287,9 @@ public class RbacView { * @param * a JPA entity class extending RbacObject */ - public RbacView importRootEntityAliasProxy( + public > RbacView importRootEntityAliasProxy( final String aliasName, - final Class entityClass, + final Class> entityClass, final ColumnValue forCase, final SQL fetchSql, final Column dependsOnColum) { @@ -313,7 +313,7 @@ public class RbacView { * a JPA entity class extending RbacObject */ public RbacView importSubEntityAlias( - final String aliasName, final Class entityClass, + final String aliasName, final Class> entityClass, final SQL fetchSql, final Column dependsOnColum) { importEntityAliasImpl(aliasName, entityClass, usingDefaultCase(), fetchSql, dependsOnColum, true, NOT_NULL); return this; @@ -350,14 +350,14 @@ public class RbacView { * a JPA entity class extending RbacObject */ public RbacView importEntityAlias( - final String aliasName, final Class entityClass, final ColumnValue usingCase, + final String aliasName, final Class> entityClass, final ColumnValue usingCase, final Column dependsOnColum, final SQL fetchSql, final Nullable nullable) { importEntityAliasImpl(aliasName, entityClass, usingCase, fetchSql, dependsOnColum, false, nullable); return this; } private EntityAlias importEntityAliasImpl( - final String aliasName, final Class entityClass, final ColumnValue usingCase, + final String aliasName, final Class> entityClass, final ColumnValue usingCase, final SQL fetchSql, final Column dependsOnColum, boolean asSubEntity, final Nullable nullable) { final var entityAlias = ofNullable(entityAliases.get(aliasName)) @@ -911,13 +911,13 @@ public class RbacView { return distinctGrantDef; } - record EntityAlias(String aliasName, Class entityClass, ColumnValue usingCase, SQL fetchSql, Column dependsOnColum, boolean isSubEntity, Nullable nullable) { + record EntityAlias(String aliasName, Class> entityClass, ColumnValue usingCase, SQL fetchSql, Column dependsOnColum, boolean isSubEntity, Nullable nullable) { public EntityAlias(final String aliasName) { this(aliasName, null, null, null, null, false, null); } - public EntityAlias(final String aliasName, final Class entityClass) { + public EntityAlias(final String aliasName, final Class> entityClass) { this(aliasName, entityClass, null, null, null, false, null); } @@ -964,7 +964,7 @@ public class RbacView { if ( aliasName.equals("rbac.global")) { return "rbac.global"; // TODO: maybe we should introduce a GlobalEntity class? } - return withoutRvSuffix(entityClass.getAnnotation(Table.class).name()); + return qualifiedRealTableName(entityClass); } String getRawTableSchemaPrefix() { @@ -1010,8 +1010,12 @@ public class RbacView { } } - public static String withoutRvSuffix(final String tableName) { - return tableName.substring(0, tableName.length() - "_rv".length()); + public static String qualifiedRealTableName(final Class> entityClass) { + final var tableAnnotation = entityClass.getAnnotation(Table.class); + final var schema = tableAnnotation.schema(); + final var tableName = tableAnnotation.name(); + final var realTableName = tableName.substring(0, tableName.length() - "_rv".length()); + return (schema.isEmpty() ? "" : (schema + ".")) + realTableName; } public enum Role { diff --git a/src/main/java/net/hostsharing/hsadminng/rbac/generator/RbacViewPostgresGenerator.java b/src/main/java/net/hostsharing/hsadminng/rbac/generator/RbacViewPostgresGenerator.java index b4c6dfb4..a8a4ba3b 100644 --- a/src/main/java/net/hostsharing/hsadminng/rbac/generator/RbacViewPostgresGenerator.java +++ b/src/main/java/net/hostsharing/hsadminng/rbac/generator/RbacViewPostgresGenerator.java @@ -17,7 +17,7 @@ public class RbacViewPostgresGenerator { public RbacViewPostgresGenerator(final RbacView forRbacDef) { rbacDef = forRbacDef; - liqibaseTagPrefix = rbacDef.getRootEntityAlias().getRawTableNameWithSchema().replace("_", "-"); + liqibaseTagPrefix = rbacDef.getRootEntityAlias().getRawTableNameWithSchema().replace("_", "-").replace(".", "-"); plPgSql.writeLn(""" --liquibase formatted sql -- This code generated was by ${generator}, do not amend manually. diff --git a/src/main/java/net/hostsharing/hsadminng/rbac/generator/RolesGrantsAndPermissionsGenerator.java b/src/main/java/net/hostsharing/hsadminng/rbac/generator/RolesGrantsAndPermissionsGenerator.java index caa46eaf..d183b181 100644 --- a/src/main/java/net/hostsharing/hsadminng/rbac/generator/RolesGrantsAndPermissionsGenerator.java +++ b/src/main/java/net/hostsharing/hsadminng/rbac/generator/RolesGrantsAndPermissionsGenerator.java @@ -516,7 +516,7 @@ class RolesGrantsAndPermissionsGenerator { /* AFTER INSERT TRIGGER to create the role+grant structure for a new ${rawTableName} row. */ - + create or replace function insertTriggerFor${simpleEntityName}_tf() returns trigger language plpgsql @@ -525,7 +525,7 @@ class RolesGrantsAndPermissionsGenerator { call buildRbacSystemFor${simpleEntityName}(NEW); return NEW; end; $$; - + create trigger insertTriggerFor${simpleEntityName}_tg after insert on ${rawTableName} for each row diff --git a/src/main/java/net/hostsharing/hsadminng/rbac/generator/StringWriter.java b/src/main/java/net/hostsharing/hsadminng/rbac/generator/StringWriter.java index 346b8e4d..2b4c980e 100644 --- a/src/main/java/net/hostsharing/hsadminng/rbac/generator/StringWriter.java +++ b/src/main/java/net/hostsharing/hsadminng/rbac/generator/StringWriter.java @@ -19,9 +19,11 @@ public class StringWriter { writeLn(); } - void writeLn(final String text, final VarDef... varDefs) { - string.append( indented( new VarReplacer(varDefs).apply(text) )); + String writeLn(final String text, final VarDef... varDefs) { + final var insertText = indented(new VarReplacer(varDefs).apply(text)); + string.append(insertText); writeLn(); + return insertText; } void writeLn() { diff --git a/src/main/java/net/hostsharing/hsadminng/rbac/grant/RbacGrantsDiagramService.java b/src/main/java/net/hostsharing/hsadminng/rbac/grant/RbacGrantsDiagramService.java index 05a343dc..ef3f1b88 100644 --- a/src/main/java/net/hostsharing/hsadminng/rbac/grant/RbacGrantsDiagramService.java +++ b/src/main/java/net/hostsharing/hsadminng/rbac/grant/RbacGrantsDiagramService.java @@ -79,10 +79,10 @@ public class RbacGrantsDiagramService { return; } if ( !g.getDescendantIdName().startsWith("role:rbac.global")) { - if (!includes.contains(TEST_ENTITIES) && g.getDescendantIdName().contains(":test_")) { + if (!includes.contains(TEST_ENTITIES) && g.getDescendantIdName().contains(":rbactest.")) { return; } - if (!includes.contains(NON_TEST_ENTITIES) && !g.getDescendantIdName().contains(":test_")) { + if (!includes.contains(NON_TEST_ENTITIES) && !g.getDescendantIdName().contains(":rbactest.")) { return; } } diff --git a/src/main/java/net/hostsharing/hsadminng/rbac/test/cust/TestCustomerEntity.java b/src/main/java/net/hostsharing/hsadminng/rbac/test/cust/TestCustomerEntity.java index f60fd11d..37e45161 100644 --- a/src/main/java/net/hostsharing/hsadminng/rbac/test/cust/TestCustomerEntity.java +++ b/src/main/java/net/hostsharing/hsadminng/rbac/test/cust/TestCustomerEntity.java @@ -20,7 +20,7 @@ import static net.hostsharing.hsadminng.rbac.generator.RbacView.Role.*; import static net.hostsharing.hsadminng.rbac.generator.RbacView.rbacViewFor; @Entity -@Table(name = "test_customer_rv") +@Table(schema = "rbactest", name = "customer_rv") @Getter @Setter @NoArgsConstructor @@ -62,6 +62,6 @@ public class TestCustomerEntity implements BaseEntity { } public static void main(String[] args) throws IOException { - rbac().generateWithBaseFileName("2-test/201-test-customer/2013-test-customer-rbac"); + rbac().generateWithBaseFileName("2-rbactest/201-rbactest-customer/2013-rbactest-customer-rbac"); } } diff --git a/src/main/java/net/hostsharing/hsadminng/rbac/test/dom/TestDomainEntity.java b/src/main/java/net/hostsharing/hsadminng/rbac/test/dom/TestDomainEntity.java index 3af8bd66..4895375d 100644 --- a/src/main/java/net/hostsharing/hsadminng/rbac/test/dom/TestDomainEntity.java +++ b/src/main/java/net/hostsharing/hsadminng/rbac/test/dom/TestDomainEntity.java @@ -22,7 +22,7 @@ import static net.hostsharing.hsadminng.rbac.generator.RbacView.SQL.directlyFetc import static net.hostsharing.hsadminng.rbac.generator.RbacView.rbacViewFor; @Entity -@Table(name = "test_domain_rv") +@Table(schema = "rbactest", name = "domain_rv") @Getter @Setter @NoArgsConstructor @@ -68,6 +68,6 @@ public class TestDomainEntity implements BaseEntity { } public static void main(String[] args) throws IOException { - rbac().generateWithBaseFileName("2-test/203-test-domain/2033-test-domain-rbac"); + rbac().generateWithBaseFileName("2-rbactest/203-rbactest-domain/2033-rbactest-domain-rbac"); } } diff --git a/src/main/java/net/hostsharing/hsadminng/rbac/test/pac/TestPackageEntity.java b/src/main/java/net/hostsharing/hsadminng/rbac/test/pac/TestPackageEntity.java index 19e58733..fcbaff4f 100644 --- a/src/main/java/net/hostsharing/hsadminng/rbac/test/pac/TestPackageEntity.java +++ b/src/main/java/net/hostsharing/hsadminng/rbac/test/pac/TestPackageEntity.java @@ -22,7 +22,7 @@ import static net.hostsharing.hsadminng.rbac.generator.RbacView.SQL.*; import static net.hostsharing.hsadminng.rbac.generator.RbacView.rbacViewFor; @Entity -@Table(name = "test_package_rv") +@Table(schema = "rbactest", name = "package_rv") @Getter @Setter @NoArgsConstructor @@ -69,6 +69,6 @@ public class TestPackageEntity implements BaseEntity { } public static void main(String[] args) throws IOException { - rbac().generateWithBaseFileName("2-test/202-test-package/2023-test-package-rbac"); + rbac().generateWithBaseFileName("2-rbactest/202-rbactest-package/2023-rbactest-package-rbac"); } } diff --git a/src/main/resources/db/changelog/0-base/007-table-columns.sql b/src/main/resources/db/changelog/0-base/007-table-columns.sql index 55c744bd..49017e5d 100644 --- a/src/main/resources/db/changelog/0-base/007-table-columns.sql +++ b/src/main/resources/db/changelog/0-base/007-table-columns.sql @@ -6,15 +6,31 @@ --changeset michael.hoennig:table-columns-function endDelimiter:--// -- ---------------------------------------------------------------------------- -create or replace function base.tableColumnNames( tableName text ) +create or replace function base.tableColumnNames( ofTableName text ) returns text stable language 'plpgsql' as $$ -declare columns text[]; +declare + tableName text; + tableSchema text; + columns text[]; begin + tableSchema := CASE + WHEN position('.' in ofTableName) > 0 THEN split_part(ofTableName, '.', 1) + ELSE 'public' + END; + + tableName := CASE + WHEN position('.' in ofTableName) > 0 THEN split_part(ofTableName, '.', 2) + ELSE ofTableName + END; + columns := (select array(select column_name::text - from information_schema.columns - where table_name = tableName)); + from information_schema.columns + where table_name = tableName + and table_schema = tableSchema)); + assert cardinality(columns) > 0, 'cannot determine columns of table ' || ofTableName || + '("' || tableSchema || '"."' || tableName || '")'; return array_to_string(columns, ', '); end; $$ --// diff --git a/src/main/resources/db/changelog/0-base/010-context.sql b/src/main/resources/db/changelog/0-base/010-context.sql index 95318e9a..6340850b 100644 --- a/src/main/resources/db/changelog/0-base/010-context.sql +++ b/src/main/resources/db/changelog/0-base/010-context.sql @@ -127,6 +127,7 @@ begin end; $$; --// + -- ============================================================================ --changeset michael.hoennig:context-base.ASSUMED-ROLES endDelimiter:--// -- ---------------------------------------------------------------------------- diff --git a/src/main/resources/db/changelog/0-base/011-table-schema-and-name.sql b/src/main/resources/db/changelog/0-base/011-table-schema-and-name.sql new file mode 100644 index 00000000..baf4a87d --- /dev/null +++ b/src/main/resources/db/changelog/0-base/011-table-schema-and-name.sql @@ -0,0 +1,18 @@ +--liquibase formatted sql + + +-- ============================================================================ +--changeset michael.hoennig:base-COMBINE-TABLE-SCHEMA-AND-NAME endDelimiter:--// +-- ---------------------------------------------------------------------------- + +create or replace function base.combine_table_schema_and_name(tableSchema name, tableName name) + returns text + language plpgsql as $$ +begin + if tableSchema is null or tableSchema = 'public' or tableSchema = '' then + return tableName::text; + else + return tableSchema::text || '.' || tableName::text; + end if; +end; $$; +--// diff --git a/src/main/resources/db/changelog/0-base/011-table-schema-and-name.sql b/src/main/resources/db/changelog/0-base/011-table-schema-and-name.sql new file mode 100644 index 00000000..e69de29b diff --git a/src/main/resources/db/changelog/0-base/020-audit-log.sql b/src/main/resources/db/changelog/0-base/020-audit-log.sql index cdf5b42c..569d8826 100644 --- a/src/main/resources/db/changelog/0-base/020-audit-log.sql +++ b/src/main/resources/db/changelog/0-base/020-audit-log.sql @@ -77,9 +77,11 @@ create or replace function base.tx_journal_trigger() declare curTask text; curTxId xid8; + tableSchemaAndName text; begin curTask := base.currentTask(); curTxId := pg_current_xact_id(); + tableSchemaAndName := base.combine_table_schema_and_name(tg_table_schema, tg_table_name); insert into base.tx_context (txId, txTimestamp, currentSubject, assumedRoles, currentTask, currentRequest) @@ -90,20 +92,20 @@ begin case tg_op when 'INSERT' then insert into base.tx_journal - values (curTxId, - tg_table_name, new.uuid, tg_op::base.tx_operation, + values (curTxId, tableSchemaAndName, + new.uuid, tg_op::base.tx_operation, to_jsonb(new)); when 'UPDATE' then insert into base.tx_journal - values (curTxId, - tg_table_name, old.uuid, tg_op::base.tx_operation, + values (curTxId, tableSchemaAndName, + old.uuid, tg_op::base.tx_operation, base.jsonb_changes_delta(to_jsonb(old), to_jsonb(new))); when 'DELETE' then insert into base.tx_journal - values (curTxId, - tg_table_name, old.uuid, 'DELETE'::base.tx_operation, + values (curTxId,tableSchemaAndName, + old.uuid, 'DELETE'::base.tx_operation, null::jsonb); - else raise exception 'Trigger op % not supported for %.', tg_op, tg_table_name; + else raise exception 'Trigger op % not supported for %.', tg_op, tableSchemaAndName; end case; return null; end; $$; diff --git a/src/main/resources/db/changelog/0-base/030-historization.sql b/src/main/resources/db/changelog/0-base/030-historization.sql index 888f5be9..e61671cc 100644 --- a/src/main/resources/db/changelog/0-base/030-historization.sql +++ b/src/main/resources/db/changelog/0-base/030-historization.sql @@ -81,8 +81,8 @@ begin "alive" := false; end if; - sql := format('INSERT INTO %3$I_ex VALUES (DEFAULT, pg_current_xact_id(), %1$L, %2$L, $1.*)', TG_OP, alive, TG_TABLE_NAME); - raise notice 'sql: %', sql; + sql := format('INSERT INTO %3$I_ex VALUES (DEFAULT, pg_current_xact_id(), %1$L, %2$L, $1.*)', + TG_OP, alive, base.combine_table_schema_and_name(tg_table_schema, tg_table_name)::name); execute sql using "row"; return "row"; diff --git a/src/main/resources/db/changelog/1-rbac/1050-rbac-base.sql b/src/main/resources/db/changelog/1-rbac/1050-rbac-base.sql index 77ced6ad..b2e73ca1 100644 --- a/src/main/resources/db/changelog/1-rbac/1050-rbac-base.sql +++ b/src/main/resources/db/changelog/1-rbac/1050-rbac-base.sql @@ -3,9 +3,7 @@ -- ============================================================================ --changeset michael.hoennig:rbac-base-REFERENCE endDelimiter:--// -- ---------------------------------------------------------------------------- -/* - */ create type rbac.ReferenceType as enum ('rbac.subject', 'rbac.role', 'rbac.permission'); create table rbac.reference @@ -120,18 +118,20 @@ create or replace function rbac.insert_related_object() strict as $$ declare objectUuid uuid; + tableSchemaAndName text; begin + tableSchemaAndName := base.combine_table_schema_and_name(TG_TABLE_SCHEMA, TG_TABLE_NAME); if TG_OP = 'INSERT' then if NEW.uuid is null then insert into rbac.object (objectTable) - values (TG_TABLE_NAME) + values (tableSchemaAndName) returning uuid into objectUuid; NEW.uuid = objectUuid; else insert into rbac.object (uuid, objectTable) - values (NEW.uuid, TG_TABLE_NAME) + values (NEW.uuid, tableSchemaAndName) returning uuid into objectUuid; end if; return NEW; diff --git a/src/main/resources/db/changelog/1-rbac/1058-rbac-generators.sql b/src/main/resources/db/changelog/1-rbac/1058-rbac-generators.sql index ed114dd5..0c7b8b2e 100644 --- a/src/main/resources/db/changelog/1-rbac/1058-rbac-generators.sql +++ b/src/main/resources/db/changelog/1-rbac/1058-rbac-generators.sql @@ -8,26 +8,40 @@ create or replace procedure rbac.generateRelatedRbacObject(targetTable varchar) language plpgsql as $$ declare + targetTableName text; + targetSchemaPrefix text; createInsertTriggerSQL text; createDeleteTriggerSQL text; begin + if POSITION('.' IN targetTable) > 0 then + targetSchemaPrefix := SPLIT_PART(targetTable, '.', 1) || '.'; + targetTableName := SPLIT_PART(targetTable, '.', 2); + else + targetSchemaPrefix := ''; + targetTableName := targetTable; + end if; + + if targetSchemaPrefix = '' and targetTableName = 'customer' then + raise exception 'missing targetShemaPrefix: %', targetTable; + end if; + createInsertTriggerSQL = format($sql$ - create trigger createRbacObjectFor_%s_Trigger - before insert on %s + create trigger createRbacObjectFor_%s_insert_tg_1058_25 + before insert on %s%s for each row execute procedure rbac.insert_related_object(); - $sql$, targetTable, targetTable); + $sql$, targetTableName, targetSchemaPrefix, targetTableName); execute createInsertTriggerSQL; createDeleteTriggerSQL = format($sql$ - create trigger delete_related_rbac_rules_for_%s_tg - after delete - on %s + create trigger createRbacObjectFor_%s_delete_tg_1058_35 + after delete on %s%s for each row execute procedure rbac.delete_related_rbac_rules_tf(); - $sql$, targetTable, targetTable); + $sql$, targetTableName, targetSchemaPrefix, targetTableName); execute createDeleteTriggerSQL; -end; $$; +end; +$$; --// @@ -176,7 +190,7 @@ begin */ sql := format($sql$ create or replace view %1$s_rv as - with accessible_%1$s_uuids as ( + with accessible_uuids as ( with recursive recursive_grants as (select distinct rbac.grants.descendantuuid, @@ -209,7 +223,7 @@ begin ) select target.* from %1$s as target - where target.uuid in (select * from accessible_%1$s_uuids) + where target.uuid in (select * from accessible_uuids) order by %2$s; grant all privileges on %1$s_rv to ${HSADMINNG_POSTGRES_RESTRICTED_USERNAME}; @@ -219,9 +233,9 @@ begin /** Instead of insert trigger function for the restricted view. */ - newColumns := 'new.' || replace(columnNames, ',', ', new.'); + newColumns := 'new.' || replace(columnNames, ', ', ', new.'); sql := format($sql$ - create or replace function %1$sInsert() + create function %1$s_instead_of_insert_tf() returns trigger language plpgsql as $f$ declare @@ -240,11 +254,11 @@ begin Creates an instead of insert trigger for the restricted view. */ sql := format($sql$ - create trigger %1$sInsert_tg + create trigger instead_of_insert_tg instead of insert on %1$s_rv for each row - execute function %1$sInsert(); + execute function %1$s_instead_of_insert_tf(); $sql$, targetTable); execute sql; @@ -252,7 +266,7 @@ begin Instead of delete trigger function for the restricted view. */ sql := format($sql$ - create or replace function %1$sDelete() + create function %1$s_instead_of_delete_tf() returns trigger language plpgsql as $f$ begin @@ -269,11 +283,11 @@ begin Creates an instead of delete trigger for the restricted view. */ sql := format($sql$ - create trigger %1$sDelete_tg + create trigger instead_of_delete_tg instead of delete on %1$s_rv for each row - execute function %1$sDelete(); + execute function %1$s_instead_of_delete_tf(); $sql$, targetTable); execute sql; @@ -283,7 +297,7 @@ begin */ if columnUpdates is not null then sql := format($sql$ - create or replace function %1$sUpdate() + create function %1$s_instead_of_update_tf() returns trigger language plpgsql as $f$ begin @@ -302,11 +316,11 @@ begin Creates an instead of delete trigger for the restricted view. */ sql = format($sql$ - create trigger %1$sUpdate_tg + create trigger instead_of_update_tg instead of update on %1$s_rv for each row - execute function %1$sUpdate(); + execute function %1$s_instead_of_update_tf(); $sql$, targetTable); execute sql; end if; diff --git a/src/main/resources/db/changelog/2-rbactest/200-rbactest-schema.sql b/src/main/resources/db/changelog/2-rbactest/200-rbactest-schema.sql new file mode 100644 index 00000000..e820c2d5 --- /dev/null +++ b/src/main/resources/db/changelog/2-rbactest/200-rbactest-schema.sql @@ -0,0 +1,8 @@ +--liquibase formatted sql + + +-- ============================================================================ +--changeset michael.hoennig:rbactest-SCHEMA endDelimiter:--// +-- ---------------------------------------------------------------------------- +CREATE SCHEMA rbactest; -- just 'test' does not work, databasechangelog gets emptied or deleted +--// diff --git a/src/main/resources/db/changelog/2-test/201-test-customer/2010-test-customer.sql b/src/main/resources/db/changelog/2-rbactest/201-rbactest-customer/2010-rbactest-customer.sql similarity index 92% rename from src/main/resources/db/changelog/2-test/201-test-customer/2010-test-customer.sql rename to src/main/resources/db/changelog/2-rbactest/201-rbactest-customer/2010-rbactest-customer.sql index 4c0b2b81..80f914ae 100644 --- a/src/main/resources/db/changelog/2-test/201-test-customer/2010-test-customer.sql +++ b/src/main/resources/db/changelog/2-rbactest/201-rbactest-customer/2010-rbactest-customer.sql @@ -4,7 +4,7 @@ --changeset michael.hoennig:test-customer-MAIN-TABLE endDelimiter:--// -- ---------------------------------------------------------------------------- -create table if not exists test_customer +create table if not exists rbactest.customer ( uuid uuid unique references rbac.object (uuid), version int not null default 0, diff --git a/src/main/resources/db/changelog/2-test/201-test-customer/2013-test-customer-rbac.md b/src/main/resources/db/changelog/2-rbactest/201-rbactest-customer/2013-rbactest-customer-rbac.md similarity index 100% rename from src/main/resources/db/changelog/2-test/201-test-customer/2013-test-customer-rbac.md rename to src/main/resources/db/changelog/2-rbactest/201-rbactest-customer/2013-rbactest-customer-rbac.md diff --git a/src/main/resources/db/changelog/2-test/201-test-customer/2013-test-customer-rbac.sql b/src/main/resources/db/changelog/2-rbactest/201-rbactest-customer/2013-rbactest-customer-rbac.sql similarity index 66% rename from src/main/resources/db/changelog/2-test/201-test-customer/2013-test-customer-rbac.sql rename to src/main/resources/db/changelog/2-rbactest/201-rbactest-customer/2013-rbactest-customer-rbac.sql index 237c8179..35f64f4a 100644 --- a/src/main/resources/db/changelog/2-test/201-test-customer/2013-test-customer-rbac.sql +++ b/src/main/resources/db/changelog/2-rbactest/201-rbactest-customer/2013-rbactest-customer-rbac.sql @@ -3,21 +3,21 @@ -- ============================================================================ ---changeset RbacObjectGenerator:test-customer-rbac-OBJECT endDelimiter:--// +--changeset RbacObjectGenerator:rbactest-customer-rbac-OBJECT endDelimiter:--// -- ---------------------------------------------------------------------------- -call rbac.generateRelatedRbacObject('test_customer'); +call rbac.generateRelatedRbacObject('rbactest.customer'); --// -- ============================================================================ ---changeset RbacRoleDescriptorsGenerator:test-customer-rbac-ROLE-DESCRIPTORS endDelimiter:--// +--changeset RbacRoleDescriptorsGenerator:rbactest-customer-rbac-ROLE-DESCRIPTORS endDelimiter:--// -- ---------------------------------------------------------------------------- -call rbac.generateRbacRoleDescriptors('testCustomer', 'test_customer'); +call rbac.generateRbacRoleDescriptors('testCustomer', 'rbactest.customer'); --// -- ============================================================================ ---changeset RolesGrantsAndPermissionsGenerator:test-customer-rbac-insert-trigger endDelimiter:--// +--changeset RolesGrantsAndPermissionsGenerator:rbactest-customer-rbac-insert-trigger endDelimiter:--// -- ---------------------------------------------------------------------------- /* @@ -25,7 +25,7 @@ call rbac.generateRbacRoleDescriptors('testCustomer', 'test_customer'); */ create or replace procedure buildRbacSystemForTestCustomer( - NEW test_customer + NEW rbactest.customer ) language plpgsql as $$ @@ -57,7 +57,7 @@ begin end; $$; /* - AFTER INSERT TRIGGER to create the role+grant structure for a new test_customer row. + AFTER INSERT TRIGGER to create the role+grant structure for a new rbactest.customer row. */ create or replace function insertTriggerForTestCustomer_tf() @@ -70,68 +70,68 @@ begin end; $$; create trigger insertTriggerForTestCustomer_tg - after insert on test_customer + after insert on rbactest.customer for each row execute procedure insertTriggerForTestCustomer_tf(); --// -- ============================================================================ ---changeset InsertTriggerGenerator:test-customer-rbac-GRANTING-INSERT-PERMISSION endDelimiter:--// +--changeset InsertTriggerGenerator:rbactest-customer-rbac-GRANTING-INSERT-PERMISSION endDelimiter:--// -- ---------------------------------------------------------------------------- -- granting INSERT permission to rbac.global ---------------------------- /* - Grants INSERT INTO test_customer permissions to specified role of pre-existing rbac.global rows. + Grants INSERT INTO rbactest.customer permissions to specified role of pre-existing rbac.global rows. */ do language plpgsql $$ declare row rbac.global; begin - call base.defineContext('create INSERT INTO test_customer permissions for pre-exising rbac.global rows'); + call base.defineContext('create INSERT INTO rbactest.customer permissions for pre-exising rbac.global rows'); FOR row IN SELECT * FROM rbac.global -- unconditional for all rows in that table LOOP call rbac.grantPermissionToRole( - rbac.createPermission(row.uuid, 'INSERT', 'test_customer'), + rbac.createPermission(row.uuid, 'INSERT', 'rbactest.customer'), rbac.globalADMIN()); END LOOP; end; $$; /** - Grants test_customer INSERT permission to specified role of new global rows. + Grants rbactest.customer INSERT permission to specified role of new global rows. */ -create or replace function rbac.new_test_customer_grants_insert_to_global_tf() +create or replace function rbactest.new_customer_grants_insert_to_global_tf() returns trigger language plpgsql strict as $$ begin -- unconditional for all rows in that table call rbac.grantPermissionToRole( - rbac.createPermission(NEW.uuid, 'INSERT', 'test_customer'), + rbac.createPermission(NEW.uuid, 'INSERT', 'rbactest.customer'), rbac.globalADMIN()); -- end. return NEW; end; $$; -- z_... is to put it at the end of after insert triggers, to make sure the roles exist -create trigger z_new_test_customer_grants_after_insert_tg +create trigger z_new_customer_grants_after_insert_tg after insert on rbac.global for each row -execute procedure rbac.new_test_customer_grants_insert_to_global_tf(); +execute procedure rbactest.new_customer_grants_insert_to_global_tf(); -- ============================================================================ ---changeset InsertTriggerGenerator:test_customer-rbac-CHECKING-INSERT-PERMISSION endDelimiter:--// +--changeset InsertTriggerGenerator:rbactest-customer-rbac-CHECKING-INSERT-PERMISSION endDelimiter:--// -- ---------------------------------------------------------------------------- /** - Checks if the user respectively the assumed roles are allowed to insert a row to test_customer. + Checks if the user respectively the assumed roles are allowed to insert a row to rbactest.customer. */ -create or replace function test_customer_insert_permission_check_tf() +create or replace function rbactest.customer_insert_permission_check_tf() returns trigger language plpgsql as $$ declare @@ -142,22 +142,22 @@ begin return NEW; end if; - raise exception '[403] insert into test_customer values(%) not allowed for current subjects % (%)', + raise exception '[403] insert into rbactest.customer values(%) not allowed for current subjects % (%)', NEW, base.currentSubjects(), rbac.currentSubjectOrAssumedRolesUuids(); end; $$; -create trigger test_customer_insert_permission_check_tg - before insert on test_customer +create trigger customer_insert_permission_check_tg + before insert on rbactest.customer for each row - execute procedure test_customer_insert_permission_check_tf(); + execute procedure rbactest.customer_insert_permission_check_tf(); --// -- ============================================================================ ---changeset RbacIdentityViewGenerator:test-customer-rbac-IDENTITY-VIEW endDelimiter:--// +--changeset RbacIdentityViewGenerator:rbactest-customer-rbac-IDENTITY-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call rbac.generateRbacIdentityViewFromProjection('test_customer', +call rbac.generateRbacIdentityViewFromProjection('rbactest.customer', $idName$ prefix $idName$); @@ -165,9 +165,9 @@ call rbac.generateRbacIdentityViewFromProjection('test_customer', -- ============================================================================ ---changeset RbacRestrictedViewGenerator:test-customer-rbac-RESTRICTED-VIEW endDelimiter:--// +--changeset RbacRestrictedViewGenerator:rbactest-customer-rbac-RESTRICTED-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call rbac.generateRbacRestrictedView('test_customer', +call rbac.generateRbacRestrictedView('rbactest.customer', $orderBy$ reference $orderBy$, diff --git a/src/main/resources/db/changelog/2-test/201-test-customer/2018-test-customer-test-data.sql b/src/main/resources/db/changelog/2-rbactest/201-rbactest-customer/2018-rbactest-customer-test-data.sql similarity index 93% rename from src/main/resources/db/changelog/2-test/201-test-customer/2018-test-customer-test-data.sql rename to src/main/resources/db/changelog/2-rbactest/201-rbactest-customer/2018-rbactest-customer-test-data.sql index b1a22df4..f441522e 100644 --- a/src/main/resources/db/changelog/2-test/201-test-customer/2018-test-customer-test-data.sql +++ b/src/main/resources/db/changelog/2-rbactest/201-rbactest-customer/2018-rbactest-customer-test-data.sql @@ -28,18 +28,18 @@ declare custRowId uuid; custAdminName varchar; custAdminUuid uuid; - newCust test_customer; + newCust rbactest.customer; begin custRowId = uuid_generate_v4(); custAdminName = 'customer-admin@' || custPrefix || '.example.com'; custAdminUuid = rbac.create_subject(custAdminName); insert - into test_customer (reference, prefix, adminUserName) + into rbactest.customer (reference, prefix, adminUserName) values (custReference, custPrefix, custAdminName); select * into newCust - from test_customer where reference=custReference; + from rbactest.customer where reference=custReference; call rbac.grantRoleToSubject( rbac.getRoleId(testCustomerOwner(newCust)), rbac.getRoleId(testCustomerAdmin(newCust)), diff --git a/src/main/resources/db/changelog/2-test/202-test-package/2020-test-package.sql b/src/main/resources/db/changelog/2-rbactest/202-rbactest-package/2020-rbactest-package.sql similarity index 80% rename from src/main/resources/db/changelog/2-test/202-test-package/2020-test-package.sql rename to src/main/resources/db/changelog/2-rbactest/202-rbactest-package/2020-rbactest-package.sql index 83453f0a..152e083c 100644 --- a/src/main/resources/db/changelog/2-test/202-test-package/2020-test-package.sql +++ b/src/main/resources/db/changelog/2-rbactest/202-rbactest-package/2020-rbactest-package.sql @@ -4,11 +4,11 @@ --changeset michael.hoennig:test-package-MAIN-TABLE endDelimiter:--// -- ---------------------------------------------------------------------------- -create table if not exists test_package +create table if not exists rbactest.package ( uuid uuid unique references rbac.object (uuid), version int not null default 0, - customerUuid uuid references test_customer (uuid), + customerUuid uuid references rbactest.customer (uuid), name varchar(5), description varchar(96) ); diff --git a/src/main/resources/db/changelog/2-test/202-test-package/2023-test-package-rbac.md b/src/main/resources/db/changelog/2-rbactest/202-rbactest-package/2023-rbactest-package-rbac.md similarity index 100% rename from src/main/resources/db/changelog/2-test/202-test-package/2023-test-package-rbac.md rename to src/main/resources/db/changelog/2-rbactest/202-rbactest-package/2023-rbactest-package-rbac.md diff --git a/src/main/resources/db/changelog/2-test/202-test-package/2023-test-package-rbac.sql b/src/main/resources/db/changelog/2-rbactest/202-rbactest-package/2023-rbactest-package-rbac.sql similarity index 65% rename from src/main/resources/db/changelog/2-test/202-test-package/2023-test-package-rbac.sql rename to src/main/resources/db/changelog/2-rbactest/202-rbactest-package/2023-rbactest-package-rbac.sql index 87f5717c..6fff59c6 100644 --- a/src/main/resources/db/changelog/2-test/202-test-package/2023-test-package-rbac.sql +++ b/src/main/resources/db/changelog/2-rbactest/202-rbactest-package/2023-rbactest-package-rbac.sql @@ -3,21 +3,21 @@ -- ============================================================================ ---changeset RbacObjectGenerator:test-package-rbac-OBJECT endDelimiter:--// +--changeset RbacObjectGenerator:rbactest-package-rbac-OBJECT endDelimiter:--// -- ---------------------------------------------------------------------------- -call rbac.generateRelatedRbacObject('test_package'); +call rbac.generateRelatedRbacObject('rbactest.package'); --// -- ============================================================================ ---changeset RbacRoleDescriptorsGenerator:test-package-rbac-ROLE-DESCRIPTORS endDelimiter:--// +--changeset RbacRoleDescriptorsGenerator:rbactest-package-rbac-ROLE-DESCRIPTORS endDelimiter:--// -- ---------------------------------------------------------------------------- -call rbac.generateRbacRoleDescriptors('testPackage', 'test_package'); +call rbac.generateRbacRoleDescriptors('testPackage', 'rbactest.package'); --// -- ============================================================================ ---changeset RolesGrantsAndPermissionsGenerator:test-package-rbac-insert-trigger endDelimiter:--// +--changeset RolesGrantsAndPermissionsGenerator:rbactest-package-rbac-insert-trigger endDelimiter:--// -- ---------------------------------------------------------------------------- /* @@ -25,17 +25,17 @@ call rbac.generateRbacRoleDescriptors('testPackage', 'test_package'); */ create or replace procedure buildRbacSystemForTestPackage( - NEW test_package + NEW rbactest.package ) language plpgsql as $$ declare - newCustomer test_customer; + newCustomer rbactest.customer; begin call rbac.enterTriggerForObjectUuid(NEW.uuid); - SELECT * FROM test_customer WHERE uuid = NEW.customerUuid INTO newCustomer; + SELECT * FROM rbactest.customer WHERE uuid = NEW.customerUuid INTO newCustomer; assert newCustomer.uuid is not null, format('newCustomer must not be null for NEW.customerUuid = %s', NEW.customerUuid); @@ -61,7 +61,7 @@ begin end; $$; /* - AFTER INSERT TRIGGER to create the role+grant structure for a new test_package row. + AFTER INSERT TRIGGER to create the role+grant structure for a new rbactest.package row. */ create or replace function insertTriggerForTestPackage_tf() @@ -74,14 +74,14 @@ begin end; $$; create trigger insertTriggerForTestPackage_tg - after insert on test_package + after insert on rbactest.package for each row execute procedure insertTriggerForTestPackage_tf(); --// -- ============================================================================ ---changeset RolesGrantsAndPermissionsGenerator:test-package-rbac-update-trigger endDelimiter:--// +--changeset RolesGrantsAndPermissionsGenerator:rbactest-package-rbac-update-trigger endDelimiter:--// -- ---------------------------------------------------------------------------- /* @@ -89,22 +89,22 @@ execute procedure insertTriggerForTestPackage_tf(); */ create or replace procedure updateRbacRulesForTestPackage( - OLD test_package, - NEW test_package + OLD rbactest.package, + NEW rbactest.package ) language plpgsql as $$ declare - oldCustomer test_customer; - newCustomer test_customer; + oldCustomer rbactest.customer; + newCustomer rbactest.customer; begin call rbac.enterTriggerForObjectUuid(NEW.uuid); - SELECT * FROM test_customer WHERE uuid = OLD.customerUuid INTO oldCustomer; + SELECT * FROM rbactest.customer WHERE uuid = OLD.customerUuid INTO oldCustomer; assert oldCustomer.uuid is not null, format('oldCustomer must not be null for OLD.customerUuid = %s', OLD.customerUuid); - SELECT * FROM test_customer WHERE uuid = NEW.customerUuid INTO newCustomer; + SELECT * FROM rbactest.customer WHERE uuid = NEW.customerUuid INTO newCustomer; assert newCustomer.uuid is not null, format('newCustomer must not be null for NEW.customerUuid = %s', NEW.customerUuid); @@ -122,7 +122,7 @@ begin end; $$; /* - AFTER INSERT TRIGGER to re-wire the grant structure for a new test_package row. + AFTER INSERT TRIGGER to re-wire the grant structure for a new rbactest.package row. */ create or replace function updateTriggerForTestPackage_tf() @@ -135,94 +135,94 @@ begin end; $$; create trigger updateTriggerForTestPackage_tg - after update on test_package + after update on rbactest.package for each row execute procedure updateTriggerForTestPackage_tf(); --// -- ============================================================================ ---changeset InsertTriggerGenerator:test-package-rbac-GRANTING-INSERT-PERMISSION endDelimiter:--// +--changeset InsertTriggerGenerator:rbactest-package-rbac-GRANTING-INSERT-PERMISSION endDelimiter:--// -- ---------------------------------------------------------------------------- --- granting INSERT permission to test_customer ---------------------------- +-- granting INSERT permission to rbactest.customer ---------------------------- /* - Grants INSERT INTO test_package permissions to specified role of pre-existing test_customer rows. + Grants INSERT INTO rbactest.package permissions to specified role of pre-existing rbactest.customer rows. */ do language plpgsql $$ declare - row test_customer; + row rbactest.customer; begin - call base.defineContext('create INSERT INTO test_package permissions for pre-exising test_customer rows'); + call base.defineContext('create INSERT INTO rbactest.package permissions for pre-exising rbactest.customer rows'); - FOR row IN SELECT * FROM test_customer + FOR row IN SELECT * FROM rbactest.customer -- unconditional for all rows in that table LOOP call rbac.grantPermissionToRole( - rbac.createPermission(row.uuid, 'INSERT', 'test_package'), + rbac.createPermission(row.uuid, 'INSERT', 'rbactest.package'), testCustomerADMIN(row)); END LOOP; end; $$; /** - Grants test_package INSERT permission to specified role of new test_customer rows. + Grants rbactest.package INSERT permission to specified role of new customer rows. */ -create or replace function new_test_package_grants_insert_to_test_customer_tf() +create or replace function rbactest.new_package_grants_insert_to_customer_tf() returns trigger language plpgsql strict as $$ begin -- unconditional for all rows in that table call rbac.grantPermissionToRole( - rbac.createPermission(NEW.uuid, 'INSERT', 'test_package'), + rbac.createPermission(NEW.uuid, 'INSERT', 'rbactest.package'), testCustomerADMIN(NEW)); -- end. return NEW; end; $$; -- z_... is to put it at the end of after insert triggers, to make sure the roles exist -create trigger z_new_test_package_grants_after_insert_tg - after insert on test_customer +create trigger z_new_package_grants_after_insert_tg + after insert on rbactest.customer for each row -execute procedure new_test_package_grants_insert_to_test_customer_tf(); +execute procedure rbactest.new_package_grants_insert_to_customer_tf(); -- ============================================================================ ---changeset InsertTriggerGenerator:test_package-rbac-CHECKING-INSERT-PERMISSION endDelimiter:--// +--changeset InsertTriggerGenerator:rbactest-package-rbac-CHECKING-INSERT-PERMISSION endDelimiter:--// -- ---------------------------------------------------------------------------- /** - Checks if the user respectively the assumed roles are allowed to insert a row to test_package. + Checks if the user respectively the assumed roles are allowed to insert a row to rbactest.package. */ -create or replace function test_package_insert_permission_check_tf() +create or replace function rbactest.package_insert_permission_check_tf() returns trigger language plpgsql as $$ declare superObjectUuid uuid; begin -- check INSERT permission via direct foreign key: NEW.customerUuid - if rbac.hasInsertPermission(NEW.customerUuid, 'test_package') then + if rbac.hasInsertPermission(NEW.customerUuid, 'rbactest.package') then return NEW; end if; - raise exception '[403] insert into test_package values(%) not allowed for current subjects % (%)', + raise exception '[403] insert into rbactest.package values(%) not allowed for current subjects % (%)', NEW, base.currentSubjects(), rbac.currentSubjectOrAssumedRolesUuids(); end; $$; -create trigger test_package_insert_permission_check_tg - before insert on test_package +create trigger package_insert_permission_check_tg + before insert on rbactest.package for each row - execute procedure test_package_insert_permission_check_tf(); + execute procedure rbactest.package_insert_permission_check_tf(); --// -- ============================================================================ ---changeset RbacIdentityViewGenerator:test-package-rbac-IDENTITY-VIEW endDelimiter:--// +--changeset RbacIdentityViewGenerator:rbactest-package-rbac-IDENTITY-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call rbac.generateRbacIdentityViewFromProjection('test_package', +call rbac.generateRbacIdentityViewFromProjection('rbactest.package', $idName$ name $idName$); @@ -230,9 +230,9 @@ call rbac.generateRbacIdentityViewFromProjection('test_package', -- ============================================================================ ---changeset RbacRestrictedViewGenerator:test-package-rbac-RESTRICTED-VIEW endDelimiter:--// +--changeset RbacRestrictedViewGenerator:rbactest-package-rbac-RESTRICTED-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call rbac.generateRbacRestrictedView('test_package', +call rbac.generateRbacRestrictedView('rbactest.package', $orderBy$ name $orderBy$, diff --git a/src/main/resources/db/changelog/2-test/202-test-package/2028-test-package-test-data.sql b/src/main/resources/db/changelog/2-rbactest/202-rbactest-package/2028-rbactest-package-test-data.sql similarity index 84% rename from src/main/resources/db/changelog/2-test/202-test-package/2028-test-package-test-data.sql rename to src/main/resources/db/changelog/2-rbactest/202-rbactest-package/2028-rbactest-package-test-data.sql index 95430732..869b9cb4 100644 --- a/src/main/resources/db/changelog/2-test/202-test-package/2028-test-package-test-data.sql +++ b/src/main/resources/db/changelog/2-rbactest/202-rbactest-package/2028-rbactest-package-test-data.sql @@ -9,23 +9,23 @@ create or replace procedure createPackageTestData(customerPrefix varchar, pacCount int) language plpgsql as $$ declare - cust test_customer; + cust rbactest.customer; custAdminUser varchar; custAdminRole varchar; pacName varchar; - pac test_package; + pac rbactest.package; begin - select * from test_customer where test_customer.prefix = customerPrefix into cust; + select * from rbactest.customer where rbactest.customer.prefix = customerPrefix into cust; for t in 0..(pacCount-1) loop pacName = cust.prefix || to_char(t, 'fm00'); custAdminUser = 'customer-admin@' || cust.prefix || '.example.com'; - custAdminRole = 'test_customer#' || cust.prefix || ':ADMIN'; + custAdminRole = 'rbactest.customer#' || cust.prefix || ':ADMIN'; call base.defineContext('creating RBAC test package', null, 'superuser-fran@hostsharing.net', custAdminRole); insert - into test_package (customerUuid, name, description) + into rbactest.package (customerUuid, name, description) values (cust.uuid, pacName, 'Here you can add your own description of package ' || pacName || '.') returning * into pac; @@ -44,9 +44,9 @@ end; $$; create or replace procedure createPackageTestData() language plpgsql as $$ declare - cust test_customer; + cust rbactest.customer; begin - for cust in (select * from test_customer) + for cust in (select * from rbactest.customer) loop continue when cust.reference >= 90000; -- reserved for functional testing call createPackageTestData(cust.prefix, 3); diff --git a/src/main/resources/db/changelog/2-test/203-test-domain/2030-test-domain.sql b/src/main/resources/db/changelog/2-rbactest/203-rbactest-domain/2030-rbactest-domain.sql similarity index 80% rename from src/main/resources/db/changelog/2-test/203-test-domain/2030-test-domain.sql rename to src/main/resources/db/changelog/2-rbactest/203-rbactest-domain/2030-rbactest-domain.sql index c9db1c5e..753e4ed4 100644 --- a/src/main/resources/db/changelog/2-test/203-test-domain/2030-test-domain.sql +++ b/src/main/resources/db/changelog/2-rbactest/203-rbactest-domain/2030-rbactest-domain.sql @@ -4,10 +4,10 @@ --changeset michael.hoennig:test-domain-MAIN-TABLE endDelimiter:--// -- ---------------------------------------------------------------------------- -create table if not exists test_domain +create table if not exists rbactest.domain ( uuid uuid unique references rbac.object (uuid), - packageUuid uuid references test_package (uuid), + packageUuid uuid references rbactest.package (uuid), name character varying(253), description character varying(96) ); diff --git a/src/main/resources/db/changelog/2-test/203-test-domain/2033-test-domain-rbac.md b/src/main/resources/db/changelog/2-rbactest/203-rbactest-domain/2033-rbactest-domain-rbac.md similarity index 100% rename from src/main/resources/db/changelog/2-test/203-test-domain/2033-test-domain-rbac.md rename to src/main/resources/db/changelog/2-rbactest/203-rbactest-domain/2033-rbactest-domain-rbac.md diff --git a/src/main/resources/db/changelog/2-test/203-test-domain/2033-test-domain-rbac.sql b/src/main/resources/db/changelog/2-rbactest/203-rbactest-domain/2033-rbactest-domain-rbac.sql similarity index 66% rename from src/main/resources/db/changelog/2-test/203-test-domain/2033-test-domain-rbac.sql rename to src/main/resources/db/changelog/2-rbactest/203-rbactest-domain/2033-rbactest-domain-rbac.sql index eb657b4c..69534c50 100644 --- a/src/main/resources/db/changelog/2-test/203-test-domain/2033-test-domain-rbac.sql +++ b/src/main/resources/db/changelog/2-rbactest/203-rbactest-domain/2033-rbactest-domain-rbac.sql @@ -3,21 +3,21 @@ -- ============================================================================ ---changeset RbacObjectGenerator:test-domain-rbac-OBJECT endDelimiter:--// +--changeset RbacObjectGenerator:rbactest-domain-rbac-OBJECT endDelimiter:--// -- ---------------------------------------------------------------------------- -call rbac.generateRelatedRbacObject('test_domain'); +call rbac.generateRelatedRbacObject('rbactest.domain'); --// -- ============================================================================ ---changeset RbacRoleDescriptorsGenerator:test-domain-rbac-ROLE-DESCRIPTORS endDelimiter:--// +--changeset RbacRoleDescriptorsGenerator:rbactest-domain-rbac-ROLE-DESCRIPTORS endDelimiter:--// -- ---------------------------------------------------------------------------- -call rbac.generateRbacRoleDescriptors('testDomain', 'test_domain'); +call rbac.generateRbacRoleDescriptors('testDomain', 'rbactest.domain'); --// -- ============================================================================ ---changeset RolesGrantsAndPermissionsGenerator:test-domain-rbac-insert-trigger endDelimiter:--// +--changeset RolesGrantsAndPermissionsGenerator:rbactest-domain-rbac-insert-trigger endDelimiter:--// -- ---------------------------------------------------------------------------- /* @@ -25,17 +25,17 @@ call rbac.generateRbacRoleDescriptors('testDomain', 'test_domain'); */ create or replace procedure buildRbacSystemForTestDomain( - NEW test_domain + NEW rbactest.domain ) language plpgsql as $$ declare - newPackage test_package; + newPackage rbactest.package; begin call rbac.enterTriggerForObjectUuid(NEW.uuid); - SELECT * FROM test_package WHERE uuid = NEW.packageUuid INTO newPackage; + SELECT * FROM rbactest.package WHERE uuid = NEW.packageUuid INTO newPackage; assert newPackage.uuid is not null, format('newPackage must not be null for NEW.packageUuid = %s', NEW.packageUuid); @@ -57,7 +57,7 @@ begin end; $$; /* - AFTER INSERT TRIGGER to create the role+grant structure for a new test_domain row. + AFTER INSERT TRIGGER to create the role+grant structure for a new rbactest.domain row. */ create or replace function insertTriggerForTestDomain_tf() @@ -70,14 +70,14 @@ begin end; $$; create trigger insertTriggerForTestDomain_tg - after insert on test_domain + after insert on rbactest.domain for each row execute procedure insertTriggerForTestDomain_tf(); --// -- ============================================================================ ---changeset RolesGrantsAndPermissionsGenerator:test-domain-rbac-update-trigger endDelimiter:--// +--changeset RolesGrantsAndPermissionsGenerator:rbactest-domain-rbac-update-trigger endDelimiter:--// -- ---------------------------------------------------------------------------- /* @@ -85,22 +85,22 @@ execute procedure insertTriggerForTestDomain_tf(); */ create or replace procedure updateRbacRulesForTestDomain( - OLD test_domain, - NEW test_domain + OLD rbactest.domain, + NEW rbactest.domain ) language plpgsql as $$ declare - oldPackage test_package; - newPackage test_package; + oldPackage rbactest.package; + newPackage rbactest.package; begin call rbac.enterTriggerForObjectUuid(NEW.uuid); - SELECT * FROM test_package WHERE uuid = OLD.packageUuid INTO oldPackage; + SELECT * FROM rbactest.package WHERE uuid = OLD.packageUuid INTO oldPackage; assert oldPackage.uuid is not null, format('oldPackage must not be null for OLD.packageUuid = %s', OLD.packageUuid); - SELECT * FROM test_package WHERE uuid = NEW.packageUuid INTO newPackage; + SELECT * FROM rbactest.package WHERE uuid = NEW.packageUuid INTO newPackage; assert newPackage.uuid is not null, format('newPackage must not be null for NEW.packageUuid = %s', NEW.packageUuid); @@ -121,7 +121,7 @@ begin end; $$; /* - AFTER INSERT TRIGGER to re-wire the grant structure for a new test_domain row. + AFTER INSERT TRIGGER to re-wire the grant structure for a new rbactest.domain row. */ create or replace function updateTriggerForTestDomain_tf() @@ -134,94 +134,94 @@ begin end; $$; create trigger updateTriggerForTestDomain_tg - after update on test_domain + after update on rbactest.domain for each row execute procedure updateTriggerForTestDomain_tf(); --// -- ============================================================================ ---changeset InsertTriggerGenerator:test-domain-rbac-GRANTING-INSERT-PERMISSION endDelimiter:--// +--changeset InsertTriggerGenerator:rbactest-domain-rbac-GRANTING-INSERT-PERMISSION endDelimiter:--// -- ---------------------------------------------------------------------------- --- granting INSERT permission to test_package ---------------------------- +-- granting INSERT permission to rbactest.package ---------------------------- /* - Grants INSERT INTO test_domain permissions to specified role of pre-existing test_package rows. + Grants INSERT INTO rbactest.domain permissions to specified role of pre-existing rbactest.package rows. */ do language plpgsql $$ declare - row test_package; + row rbactest.package; begin - call base.defineContext('create INSERT INTO test_domain permissions for pre-exising test_package rows'); + call base.defineContext('create INSERT INTO rbactest.domain permissions for pre-exising rbactest.package rows'); - FOR row IN SELECT * FROM test_package + FOR row IN SELECT * FROM rbactest.package -- unconditional for all rows in that table LOOP call rbac.grantPermissionToRole( - rbac.createPermission(row.uuid, 'INSERT', 'test_domain'), + rbac.createPermission(row.uuid, 'INSERT', 'rbactest.domain'), testPackageADMIN(row)); END LOOP; end; $$; /** - Grants test_domain INSERT permission to specified role of new test_package rows. + Grants rbactest.domain INSERT permission to specified role of new package rows. */ -create or replace function new_test_domain_grants_insert_to_test_package_tf() +create or replace function rbactest.new_domain_grants_insert_to_package_tf() returns trigger language plpgsql strict as $$ begin -- unconditional for all rows in that table call rbac.grantPermissionToRole( - rbac.createPermission(NEW.uuid, 'INSERT', 'test_domain'), + rbac.createPermission(NEW.uuid, 'INSERT', 'rbactest.domain'), testPackageADMIN(NEW)); -- end. return NEW; end; $$; -- z_... is to put it at the end of after insert triggers, to make sure the roles exist -create trigger z_new_test_domain_grants_after_insert_tg - after insert on test_package +create trigger z_new_domain_grants_after_insert_tg + after insert on rbactest.package for each row -execute procedure new_test_domain_grants_insert_to_test_package_tf(); +execute procedure rbactest.new_domain_grants_insert_to_package_tf(); -- ============================================================================ ---changeset InsertTriggerGenerator:test_domain-rbac-CHECKING-INSERT-PERMISSION endDelimiter:--// +--changeset InsertTriggerGenerator:rbactest-domain-rbac-CHECKING-INSERT-PERMISSION endDelimiter:--// -- ---------------------------------------------------------------------------- /** - Checks if the user respectively the assumed roles are allowed to insert a row to test_domain. + Checks if the user respectively the assumed roles are allowed to insert a row to rbactest.domain. */ -create or replace function test_domain_insert_permission_check_tf() +create or replace function rbactest.domain_insert_permission_check_tf() returns trigger language plpgsql as $$ declare superObjectUuid uuid; begin -- check INSERT permission via direct foreign key: NEW.packageUuid - if rbac.hasInsertPermission(NEW.packageUuid, 'test_domain') then + if rbac.hasInsertPermission(NEW.packageUuid, 'rbactest.domain') then return NEW; end if; - raise exception '[403] insert into test_domain values(%) not allowed for current subjects % (%)', + raise exception '[403] insert into rbactest.domain values(%) not allowed for current subjects % (%)', NEW, base.currentSubjects(), rbac.currentSubjectOrAssumedRolesUuids(); end; $$; -create trigger test_domain_insert_permission_check_tg - before insert on test_domain +create trigger domain_insert_permission_check_tg + before insert on rbactest.domain for each row - execute procedure test_domain_insert_permission_check_tf(); + execute procedure rbactest.domain_insert_permission_check_tf(); --// -- ============================================================================ ---changeset RbacIdentityViewGenerator:test-domain-rbac-IDENTITY-VIEW endDelimiter:--// +--changeset RbacIdentityViewGenerator:rbactest-domain-rbac-IDENTITY-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call rbac.generateRbacIdentityViewFromProjection('test_domain', +call rbac.generateRbacIdentityViewFromProjection('rbactest.domain', $idName$ name $idName$); @@ -229,9 +229,9 @@ call rbac.generateRbacIdentityViewFromProjection('test_domain', -- ============================================================================ ---changeset RbacRestrictedViewGenerator:test-domain-rbac-RESTRICTED-VIEW endDelimiter:--// +--changeset RbacRestrictedViewGenerator:rbactest-domain-rbac-RESTRICTED-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call rbac.generateRbacRestrictedView('test_domain', +call rbac.generateRbacRestrictedView('rbactest.domain', $orderBy$ name $orderBy$, diff --git a/src/main/resources/db/changelog/2-test/203-test-domain/2038-test-domain-test-data.sql b/src/main/resources/db/changelog/2-rbactest/203-rbactest-domain/2038-rbactest-domain-test-data.sql similarity index 89% rename from src/main/resources/db/changelog/2-test/203-test-domain/2038-test-domain-test-data.sql rename to src/main/resources/db/changelog/2-rbactest/203-rbactest-domain/2038-rbactest-domain-test-data.sql index 5cd9b4b0..38843d1e 100644 --- a/src/main/resources/db/changelog/2-test/203-test-domain/2038-test-domain-test-data.sql +++ b/src/main/resources/db/changelog/2-rbactest/203-rbactest-domain/2038-rbactest-domain-test-data.sql @@ -13,8 +13,8 @@ declare pacAdmin varchar; begin select p.uuid, p.name, c.prefix as custPrefix - from test_package p - join test_customer c on p.customeruuid = c.uuid + from rbactest.package p + join rbactest.customer c on p.customeruuid = c.uuid where p.name = packageName into pac; @@ -24,7 +24,7 @@ begin call base.defineContext('creating RBAC test domain', null, pacAdmin, null); insert - into test_domain (name, packageUuid) + into rbactest.domain (name, packageUuid) values (pac.name || '-' || base.intToVarChar(t, 4), pac.uuid); end loop; end; $$; @@ -41,8 +41,8 @@ declare begin for pac in (select p.uuid, p.name - from test_package p - join test_customer c on p.customeruuid = c.uuid + from rbactest.package p + join rbactest.customer c on p.customeruuid = c.uuid where c.reference < 90000) -- reserved for functional testing loop call createdomainTestData(pac.name, 2); diff --git a/src/main/resources/db/changelog/5-hs-office/504-partner/5043-hs-office-partner-rbac.sql b/src/main/resources/db/changelog/5-hs-office/504-partner/5043-hs-office-partner-rbac.sql index 4c8aab39..8227db94 100644 --- a/src/main/resources/db/changelog/5-hs-office/504-partner/5043-hs-office-partner-rbac.sql +++ b/src/main/resources/db/changelog/5-hs-office/504-partner/5043-hs-office-partner-rbac.sql @@ -181,7 +181,7 @@ $$; /** Grants hs_office_partner INSERT permission to specified role of new global rows. */ -create or replace function rbac.new_hsof_partner_grants_insert_to_global_tf() +create or replace function new_hsof_partner_grants_insert_to_global_tf() returns trigger language plpgsql strict as $$ @@ -198,11 +198,11 @@ end; $$; create trigger z_new_hs_office_partner_grants_after_insert_tg after insert on rbac.global for each row -execute procedure rbac.new_hsof_partner_grants_insert_to_global_tf(); +execute procedure new_hsof_partner_grants_insert_to_global_tf(); -- ============================================================================ ---changeset InsertTriggerGenerator:hs_office_partner-rbac-CHECKING-INSERT-PERMISSION endDelimiter:--// +--changeset InsertTriggerGenerator:hs-office-partner-rbac-CHECKING-INSERT-PERMISSION endDelimiter:--// -- ---------------------------------------------------------------------------- /** diff --git a/src/main/resources/db/changelog/5-hs-office/504-partner/5044-hs-office-partner-details-rbac.sql b/src/main/resources/db/changelog/5-hs-office/504-partner/5044-hs-office-partner-details-rbac.sql index 840003e3..6c360b90 100644 --- a/src/main/resources/db/changelog/5-hs-office/504-partner/5044-hs-office-partner-details-rbac.sql +++ b/src/main/resources/db/changelog/5-hs-office/504-partner/5044-hs-office-partner-details-rbac.sql @@ -85,7 +85,7 @@ $$; /** Grants hs_office_partner_details INSERT permission to specified role of new global rows. */ -create or replace function rbac.new_hsof_partner_details_grants_insert_to_global_tf() +create or replace function new_hsof_partner_details_grants_insert_to_global_tf() returns trigger language plpgsql strict as $$ @@ -102,11 +102,11 @@ end; $$; create trigger z_new_hs_office_partner_details_grants_after_insert_tg after insert on rbac.global for each row -execute procedure rbac.new_hsof_partner_details_grants_insert_to_global_tf(); +execute procedure new_hsof_partner_details_grants_insert_to_global_tf(); -- ============================================================================ ---changeset InsertTriggerGenerator:hs_office_partner_details-rbac-CHECKING-INSERT-PERMISSION endDelimiter:--// +--changeset InsertTriggerGenerator:hs-office-partner-details-rbac-CHECKING-INSERT-PERMISSION endDelimiter:--// -- ---------------------------------------------------------------------------- /** diff --git a/src/main/resources/db/changelog/5-hs-office/506-debitor/5063-hs-office-debitor-rbac.sql b/src/main/resources/db/changelog/5-hs-office/506-debitor/5063-hs-office-debitor-rbac.sql index 6800076f..994dea2f 100644 --- a/src/main/resources/db/changelog/5-hs-office/506-debitor/5063-hs-office-debitor-rbac.sql +++ b/src/main/resources/db/changelog/5-hs-office/506-debitor/5063-hs-office-debitor-rbac.sql @@ -154,7 +154,7 @@ $$; /** Grants hs_office_debitor INSERT permission to specified role of new global rows. */ -create or replace function rbac.new_hsof_debitor_grants_insert_to_global_tf() +create or replace function new_hsof_debitor_grants_insert_to_global_tf() returns trigger language plpgsql strict as $$ @@ -171,11 +171,11 @@ end; $$; create trigger z_new_hs_office_debitor_grants_after_insert_tg after insert on rbac.global for each row -execute procedure rbac.new_hsof_debitor_grants_insert_to_global_tf(); +execute procedure new_hsof_debitor_grants_insert_to_global_tf(); -- ============================================================================ ---changeset InsertTriggerGenerator:hs_office_debitor-rbac-CHECKING-INSERT-PERMISSION endDelimiter:--// +--changeset InsertTriggerGenerator:hs-office-debitor-rbac-CHECKING-INSERT-PERMISSION endDelimiter:--// -- ---------------------------------------------------------------------------- /** diff --git a/src/main/resources/db/changelog/5-hs-office/507-sepamandate/5073-hs-office-sepamandate-rbac.sql b/src/main/resources/db/changelog/5-hs-office/507-sepamandate/5073-hs-office-sepamandate-rbac.sql index 63f139d6..76cfe166 100644 --- a/src/main/resources/db/changelog/5-hs-office/507-sepamandate/5073-hs-office-sepamandate-rbac.sql +++ b/src/main/resources/db/changelog/5-hs-office/507-sepamandate/5073-hs-office-sepamandate-rbac.sql @@ -150,7 +150,7 @@ execute procedure new_hsof_sepamandate_grants_insert_to_hsof_relation_tf(); -- ============================================================================ ---changeset InsertTriggerGenerator:hs_office_sepamandate-rbac-CHECKING-INSERT-PERMISSION endDelimiter:--// +--changeset InsertTriggerGenerator:hs-office-sepamandate-rbac-CHECKING-INSERT-PERMISSION endDelimiter:--// -- ---------------------------------------------------------------------------- /** diff --git a/src/main/resources/db/changelog/5-hs-office/510-membership/5103-hs-office-membership-rbac.sql b/src/main/resources/db/changelog/5-hs-office/510-membership/5103-hs-office-membership-rbac.sql index f7a540b4..b5239725 100644 --- a/src/main/resources/db/changelog/5-hs-office/510-membership/5103-hs-office-membership-rbac.sql +++ b/src/main/resources/db/changelog/5-hs-office/510-membership/5103-hs-office-membership-rbac.sql @@ -116,7 +116,7 @@ $$; /** Grants hs_office_membership INSERT permission to specified role of new global rows. */ -create or replace function rbac.new_hsof_membership_grants_insert_to_global_tf() +create or replace function new_hsof_membership_grants_insert_to_global_tf() returns trigger language plpgsql strict as $$ @@ -133,11 +133,11 @@ end; $$; create trigger z_new_hs_office_membership_grants_after_insert_tg after insert on rbac.global for each row -execute procedure rbac.new_hsof_membership_grants_insert_to_global_tf(); +execute procedure new_hsof_membership_grants_insert_to_global_tf(); -- ============================================================================ ---changeset InsertTriggerGenerator:hs_office_membership-rbac-CHECKING-INSERT-PERMISSION endDelimiter:--// +--changeset InsertTriggerGenerator:hs-office-membership-rbac-CHECKING-INSERT-PERMISSION endDelimiter:--// -- ---------------------------------------------------------------------------- /** diff --git a/src/main/resources/db/changelog/5-hs-office/511-coopshares/5113-hs-office-coopshares-rbac.sql b/src/main/resources/db/changelog/5-hs-office/511-coopshares/5113-hs-office-coopshares-rbac.sql index e96609e1..b77458ee 100644 --- a/src/main/resources/db/changelog/5-hs-office/511-coopshares/5113-hs-office-coopshares-rbac.sql +++ b/src/main/resources/db/changelog/5-hs-office/511-coopshares/5113-hs-office-coopshares-rbac.sql @@ -113,7 +113,7 @@ execute procedure new_hsof_coopsharetx_grants_insert_to_hsof_membership_tf(); -- ============================================================================ ---changeset InsertTriggerGenerator:hs_office_coopsharestransaction-rbac-CHECKING-INSERT-PERMISSION endDelimiter:--// +--changeset InsertTriggerGenerator:hs-office-coopsharestransaction-rbac-CHECKING-INSERT-PERMISSION endDelimiter:--// -- ---------------------------------------------------------------------------- /** diff --git a/src/main/resources/db/changelog/5-hs-office/512-coopassets/5123-hs-office-coopassets-rbac.sql b/src/main/resources/db/changelog/5-hs-office/512-coopassets/5123-hs-office-coopassets-rbac.sql index 881dc899..52b39ae3 100644 --- a/src/main/resources/db/changelog/5-hs-office/512-coopassets/5123-hs-office-coopassets-rbac.sql +++ b/src/main/resources/db/changelog/5-hs-office/512-coopassets/5123-hs-office-coopassets-rbac.sql @@ -113,7 +113,7 @@ execute procedure new_hsof_coopassettx_grants_insert_to_hsof_membership_tf(); -- ============================================================================ ---changeset InsertTriggerGenerator:hs_office_coopassetstransaction-rbac-CHECKING-INSERT-PERMISSION endDelimiter:--// +--changeset InsertTriggerGenerator:hs-office-coopassetstransaction-rbac-CHECKING-INSERT-PERMISSION endDelimiter:--// -- ---------------------------------------------------------------------------- /** diff --git a/src/main/resources/db/changelog/db.changelog-master.yaml b/src/main/resources/db/changelog/db.changelog-master.yaml index 83185337..a8029152 100644 --- a/src/main/resources/db/changelog/db.changelog-master.yaml +++ b/src/main/resources/db/changelog/db.changelog-master.yaml @@ -21,6 +21,8 @@ databaseChangeLog: file: db/changelog/0-base/009-check-environment.sql - include: file: db/changelog/0-base/010-context.sql + - include: + file: db/changelog/0-base/011-table-schema-and-name.sql - include: file: db/changelog/0-base/020-audit-log.sql - include: @@ -48,23 +50,25 @@ databaseChangeLog: - include: file: db/changelog/1-rbac/1080-rbac-global.sql - include: - file: db/changelog/2-test/201-test-customer/2010-test-customer.sql + file: db/changelog/2-rbactest/200-rbactest-schema.sql - include: - file: db/changelog/2-test/201-test-customer/2013-test-customer-rbac.sql + file: db/changelog/2-rbactest/201-rbactest-customer/2010-rbactest-customer.sql - include: - file: db/changelog/2-test/201-test-customer/2018-test-customer-test-data.sql + file: db/changelog/2-rbactest/201-rbactest-customer/2013-rbactest-customer-rbac.sql - include: - file: db/changelog/2-test/202-test-package/2020-test-package.sql + file: db/changelog/2-rbactest/201-rbactest-customer/2018-rbactest-customer-test-data.sql - include: - file: db/changelog/2-test/202-test-package/2023-test-package-rbac.sql + file: db/changelog/2-rbactest/202-rbactest-package/2020-rbactest-package.sql - include: - file: db/changelog/2-test/202-test-package/2028-test-package-test-data.sql + file: db/changelog/2-rbactest/202-rbactest-package/2023-rbactest-package-rbac.sql - include: - file: db/changelog/2-test/203-test-domain/2030-test-domain.sql + file: db/changelog/2-rbactest/202-rbactest-package/2028-rbactest-package-test-data.sql - include: - file: db/changelog/2-test/203-test-domain/2033-test-domain-rbac.sql + file: db/changelog/2-rbactest/203-rbactest-domain/2030-rbactest-domain.sql - include: - file: db/changelog/2-test/203-test-domain/2038-test-domain-test-data.sql + file: db/changelog/2-rbactest/203-rbactest-domain/2033-rbactest-domain-rbac.sql + - include: + file: db/changelog/2-rbactest/203-rbactest-domain/2038-rbactest-domain-test-data.sql - include: file: db/changelog/5-hs-office/501-contact/5010-hs-office-contact.sql - include: diff --git a/src/test/java/net/hostsharing/hsadminng/hs/migration/CsvDataImport.java b/src/test/java/net/hostsharing/hsadminng/hs/migration/CsvDataImport.java index b355706e..66cfc5e7 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/migration/CsvDataImport.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/migration/CsvDataImport.java @@ -289,9 +289,9 @@ public class CsvDataImport extends ContextBasedTest { protected void deleteFromTestTables() { jpaAttempt.transacted(() -> { context(rbacSuperuser); - em.createNativeQuery("delete from test_domain where true").executeUpdate(); - em.createNativeQuery("delete from test_package where true").executeUpdate(); - em.createNativeQuery("delete from test_customer where true").executeUpdate(); + em.createNativeQuery("delete from rbactest.domain where true").executeUpdate(); + em.createNativeQuery("delete from rbactest.package where true").executeUpdate(); + em.createNativeQuery("delete from rbactest.customer where true").executeUpdate(); }).assertSuccessful(); } diff --git a/src/test/java/net/hostsharing/hsadminng/rbac/context/ContextIntegrationTests.java b/src/test/java/net/hostsharing/hsadminng/rbac/context/ContextIntegrationTests.java index 1b3fded5..c48f782e 100644 --- a/src/test/java/net/hostsharing/hsadminng/rbac/context/ContextIntegrationTests.java +++ b/src/test/java/net/hostsharing/hsadminng/rbac/context/ContextIntegrationTests.java @@ -62,13 +62,13 @@ class ContextIntegrationTests { void defineWithoutcurrentSubjectButWithAssumedRoles() { // when final var result = jpaAttempt.transacted(() -> - context.define(null, "test_package#yyy00:ADMIN") + context.define(null, "rbactest.package#yyy00:ADMIN") ); // then result.assertExceptionWithRootCauseMessage( jakarta.persistence.PersistenceException.class, - "ERROR: [403] undefined has no permission to assume role test_package#yyy00:ADMIN"); + "ERROR: [403] undefined has no permission to assume role rbactest.package#yyy00:ADMIN"); } @Test @@ -88,7 +88,7 @@ class ContextIntegrationTests { @Transactional void defineWithcurrentSubjectAndAssumedRoles() { // given - context.define("superuser-alex@hostsharing.net", "test_customer#xxx:OWNER;test_customer#yyy:OWNER"); + context.define("superuser-alex@hostsharing.net", "rbactest.customer#xxx:OWNER;rbactest.customer#yyy:OWNER"); // when final var currentSubject = context.fetchCurrentSubject(); @@ -96,7 +96,7 @@ class ContextIntegrationTests { // then assertThat(context.fetchAssumedRoles()) - .isEqualTo(Array.of("test_customer#xxx:OWNER", "test_customer#yyy:OWNER")); + .isEqualTo(Array.of("rbactest.customer#xxx:OWNER", "rbactest.customer#yyy:OWNER")); assertThat(context.fetchCurrentSubjectOrAssumedRolesUuids()).hasSize(2); } @@ -104,12 +104,12 @@ class ContextIntegrationTests { public void defineContextWithcurrentSubjectAndAssumeInaccessibleRole() { // when final var result = jpaAttempt.transacted(() -> - context.define("customer-admin@xxx.example.com", "test_package#yyy00:ADMIN") + context.define("customer-admin@xxx.example.com", "rbactest.package#yyy00:ADMIN") ); // then result.assertExceptionWithRootCauseMessage( jakarta.persistence.PersistenceException.class, - "ERROR: [403] subject customer-admin@xxx.example.com has no permission to assume role test_package#yyy00:ADMIN"); + "ERROR: [403] subject customer-admin@xxx.example.com has no permission to assume role rbactest.package#yyy00:ADMIN"); } } diff --git a/src/test/java/net/hostsharing/hsadminng/rbac/grant/RbacGrantControllerAcceptanceTest.java b/src/test/java/net/hostsharing/hsadminng/rbac/grant/RbacGrantControllerAcceptanceTest.java index 16a08fdc..5906f3e3 100644 --- a/src/test/java/net/hostsharing/hsadminng/rbac/grant/RbacGrantControllerAcceptanceTest.java +++ b/src/test/java/net/hostsharing/hsadminng/rbac/grant/RbacGrantControllerAcceptanceTest.java @@ -71,16 +71,16 @@ class RbacGrantControllerAcceptanceTest extends ContextBasedTest { .body("", hasItem( allOf( // TODO: should there be a grantedByRole or just a grantedByTrigger? - hasEntry("grantedByRoleIdName", "test_customer#xxx:OWNER"), - hasEntry("grantedRoleIdName", "test_customer#xxx:ADMIN"), + hasEntry("grantedByRoleIdName", "rbactest.customer#xxx:OWNER"), + hasEntry("grantedRoleIdName", "rbactest.customer#xxx:ADMIN"), hasEntry("granteeSubjectName", "customer-admin@xxx.example.com") ) )) .body("", hasItem( allOf( // TODO: should there be a grantedByRole or just a grantedByTrigger? - hasEntry("grantedByRoleIdName", "test_customer#yyy:OWNER"), - hasEntry("grantedRoleIdName", "test_customer#yyy:ADMIN"), + hasEntry("grantedByRoleIdName", "rbactest.customer#yyy:OWNER"), + hasEntry("grantedRoleIdName", "rbactest.customer#yyy:ADMIN"), hasEntry("granteeSubjectName", "customer-admin@yyy.example.com") ) )) @@ -93,15 +93,15 @@ class RbacGrantControllerAcceptanceTest extends ContextBasedTest { )) .body("", hasItem( allOf( - hasEntry("grantedByRoleIdName", "test_customer#xxx:ADMIN"), - hasEntry("grantedRoleIdName", "test_package#xxx00:ADMIN"), + hasEntry("grantedByRoleIdName", "rbactest.customer#xxx:ADMIN"), + hasEntry("grantedRoleIdName", "rbactest.package#xxx00:ADMIN"), hasEntry("granteeSubjectName", "pac-admin-xxx00@xxx.example.com") ) )) .body("", hasItem( allOf( - hasEntry("grantedByRoleIdName", "test_customer#zzz:ADMIN"), - hasEntry("grantedRoleIdName", "test_package#zzz02:ADMIN"), + hasEntry("grantedByRoleIdName", "rbactest.customer#zzz:ADMIN"), + hasEntry("grantedRoleIdName", "rbactest.package#zzz02:ADMIN"), hasEntry("granteeSubjectName", "pac-admin-zzz02@zzz.example.com") ) )) @@ -114,7 +114,7 @@ class RbacGrantControllerAcceptanceTest extends ContextBasedTest { RestAssured // @formatter:off .given() .header("current-subject", "superuser-alex@hostsharing.net") - .header("assumed-roles", "test_package#yyy00:ADMIN") + .header("assumed-roles", "rbactest.package#yyy00:ADMIN") .port(port) .when() .get("http://localhost/api/rbac/grants") @@ -123,8 +123,8 @@ class RbacGrantControllerAcceptanceTest extends ContextBasedTest { .contentType("application/json") .body("", hasItem( allOf( - hasEntry("grantedByRoleIdName", "test_customer#yyy:ADMIN"), - hasEntry("grantedRoleIdName", "test_package#yyy00:ADMIN"), + hasEntry("grantedByRoleIdName", "rbactest.customer#yyy:ADMIN"), + hasEntry("grantedRoleIdName", "rbactest.package#yyy00:ADMIN"), hasEntry("granteeSubjectName", "pac-admin-yyy00@yyy.example.com") ) )) @@ -145,13 +145,13 @@ class RbacGrantControllerAcceptanceTest extends ContextBasedTest { .contentType("application/json") .body("", hasItem( allOf( - hasEntry("grantedByRoleIdName", "test_customer#yyy:ADMIN"), - hasEntry("grantedRoleIdName", "test_package#yyy00:ADMIN"), + hasEntry("grantedByRoleIdName", "rbactest.customer#yyy:ADMIN"), + hasEntry("grantedRoleIdName", "rbactest.package#yyy00:ADMIN"), hasEntry("granteeSubjectName", "pac-admin-yyy00@yyy.example.com") ) )) - .body("[0].grantedByRoleIdName", is("test_customer#yyy:ADMIN")) - .body("[0].grantedRoleIdName", is("test_package#yyy00:ADMIN")) + .body("[0].grantedByRoleIdName", is("rbactest.customer#yyy:ADMIN")) + .body("[0].grantedRoleIdName", is("rbactest.package#yyy00:ADMIN")) .body("[0].granteeSubjectName", is("pac-admin-yyy00@yyy.example.com")); // @formatter:on } @@ -165,7 +165,7 @@ class RbacGrantControllerAcceptanceTest extends ContextBasedTest { // given final var givencurrentSubjectAsPackageAdmin = new Subject("customer-admin@xxx.example.com"); final var givenGranteeUser = findRbacSubjectByName("pac-admin-xxx00@xxx.example.com"); - final var givenGrantedRole = getRbacRoleByName("test_package#xxx00:ADMIN"); + final var givenGrantedRole = getRbacRoleByName("rbactest.package#xxx00:ADMIN"); // when final var grant = givencurrentSubjectAsPackageAdmin.getGrantById() @@ -174,8 +174,8 @@ class RbacGrantControllerAcceptanceTest extends ContextBasedTest { // then grant.assertThat() .statusCode(200) - .body("grantedByRoleIdName", is("test_customer#xxx:ADMIN")) - .body("grantedRoleIdName", is("test_package#xxx00:ADMIN")) + .body("grantedByRoleIdName", is("rbactest.customer#xxx:ADMIN")) + .body("grantedRoleIdName", is("rbactest.package#xxx00:ADMIN")) .body("granteeSubjectName", is("pac-admin-xxx00@xxx.example.com")); } @@ -184,7 +184,7 @@ class RbacGrantControllerAcceptanceTest extends ContextBasedTest { // given final var givencurrentSubjectAsPackageAdmin = new Subject("pac-admin-xxx00@xxx.example.com"); final var givenGranteeUser = findRbacSubjectByName("pac-admin-xxx00@xxx.example.com"); - final var givenGrantedRole = getRbacRoleByName("test_package#xxx00:ADMIN"); + final var givenGrantedRole = getRbacRoleByName("rbactest.package#xxx00:ADMIN"); // when final var grant = givencurrentSubjectAsPackageAdmin.getGrantById() @@ -193,8 +193,8 @@ class RbacGrantControllerAcceptanceTest extends ContextBasedTest { // then grant.assertThat() .statusCode(200) - .body("grantedByRoleIdName", is("test_customer#xxx:ADMIN")) - .body("grantedRoleIdName", is("test_package#xxx00:ADMIN")) + .body("grantedByRoleIdName", is("rbactest.customer#xxx:ADMIN")) + .body("grantedRoleIdName", is("rbactest.package#xxx00:ADMIN")) .body("granteeSubjectName", is("pac-admin-xxx00@xxx.example.com")); } @@ -203,9 +203,9 @@ class RbacGrantControllerAcceptanceTest extends ContextBasedTest { // given final var givencurrentSubjectAsPackageAdmin = new Subject( "pac-admin-xxx00@xxx.example.com", - "test_package#xxx00:ADMIN"); + "rbactest.package#xxx00:ADMIN"); final var givenGranteeUser = findRbacSubjectByName("pac-admin-xxx00@xxx.example.com"); - final var givenGrantedRole = getRbacRoleByName("test_package#xxx00:ADMIN"); + final var givenGrantedRole = getRbacRoleByName("rbactest.package#xxx00:ADMIN"); // when final var grant = givencurrentSubjectAsPackageAdmin.getGrantById() @@ -214,8 +214,8 @@ class RbacGrantControllerAcceptanceTest extends ContextBasedTest { // then grant.assertThat() .statusCode(200) - .body("grantedByRoleIdName", is("test_customer#xxx:ADMIN")) - .body("grantedRoleIdName", is("test_package#xxx00:ADMIN")) + .body("grantedByRoleIdName", is("rbactest.customer#xxx:ADMIN")) + .body("grantedRoleIdName", is("rbactest.package#xxx00:ADMIN")) .body("granteeSubjectName", is("pac-admin-xxx00@xxx.example.com")); } @@ -225,9 +225,9 @@ class RbacGrantControllerAcceptanceTest extends ContextBasedTest { // given final var givencurrentSubjectAsPackageAdmin = new Subject( "pac-admin-xxx00@xxx.example.com", - "test_package#xxx00:TENANT"); + "rbactest.package#xxx00:TENANT"); final var givenGranteeUser = findRbacSubjectByName("pac-admin-xxx00@xxx.example.com"); - final var givenGrantedRole = getRbacRoleByName("test_package#xxx00:ADMIN"); + final var givenGrantedRole = getRbacRoleByName("rbactest.package#xxx00:ADMIN"); final var grant = givencurrentSubjectAsPackageAdmin.getGrantById() .forGrantedRole(givenGrantedRole).toGranteeUser(givenGranteeUser); @@ -245,7 +245,7 @@ class RbacGrantControllerAcceptanceTest extends ContextBasedTest { // given final var givenNewUser = createRbacSubject(); - final var givenRoleToGrant = "test_package#xxx00:ADMIN"; + final var givenRoleToGrant = "rbactest.package#xxx00:ADMIN"; final var givencurrentSubjectAsPackageAdmin = new Subject("pac-admin-xxx00@xxx.example.com", givenRoleToGrant); final var givenOwnPackageAdminRole = getRbacRoleByName(givencurrentSubjectAsPackageAdmin.assumedRole); @@ -258,9 +258,9 @@ class RbacGrantControllerAcceptanceTest extends ContextBasedTest { // then response.assertThat() .statusCode(201) - .body("grantedByRoleIdName", is("test_package#xxx00:ADMIN")) + .body("grantedByRoleIdName", is("rbactest.package#xxx00:ADMIN")) .body("assumed", is(true)) - .body("grantedRoleIdName", is("test_package#xxx00:ADMIN")) + .body("grantedRoleIdName", is("rbactest.package#xxx00:ADMIN")) .body("granteeSubjectName", is(givenNewUser.getName())); assertThat(findAllGrantsOf(givencurrentSubjectAsPackageAdmin)) .extracting(RbacGrantEntity::toDisplay) @@ -274,9 +274,9 @@ class RbacGrantControllerAcceptanceTest extends ContextBasedTest { // given final var givenNewUser = createRbacSubject(); - final var givenRoleToGrant = "test_package#xxx00:ADMIN"; + final var givenRoleToGrant = "rbactest.package#xxx00:ADMIN"; final var givencurrentSubjectAsPackageAdmin = new Subject("pac-admin-xxx00@xxx.example.com", givenRoleToGrant); - final var givenAlienPackageAdminRole = getRbacRoleByName("test_package#yyy00:ADMIN"); + final var givenAlienPackageAdminRole = getRbacRoleByName("rbactest.package#yyy00:ADMIN"); // when final var result = givencurrentSubjectAsPackageAdmin @@ -287,7 +287,7 @@ class RbacGrantControllerAcceptanceTest extends ContextBasedTest { result.assertThat() .statusCode(403) .body("message", containsString("Access to granted role")) - .body("message", containsString("forbidden for test_package#xxx00:ADMIN")); + .body("message", containsString("forbidden for rbactest.package#xxx00:ADMIN")); assertThat(findAllGrantsOf(givencurrentSubjectAsPackageAdmin)) .extracting(RbacGrantEntity::getGranteeSubjectName) .doesNotContain(givenNewUser.getName()); @@ -303,9 +303,9 @@ class RbacGrantControllerAcceptanceTest extends ContextBasedTest { // given final var givenArbitraryUser = createRbacSubject(); - final var givenRoleToGrant = "test_package#xxx00:ADMIN"; + final var givenRoleToGrant = "rbactest.package#xxx00:ADMIN"; final var givenCurrentSubjectAsPackageAdmin = new Subject("pac-admin-xxx00@xxx.example.com", givenRoleToGrant); - final var givenOwnPackageAdminRole = getRbacRoleByName("test_package#xxx00:ADMIN"); + final var givenOwnPackageAdminRole = getRbacRoleByName("rbactest.package#xxx00:ADMIN"); // and given an existing grant assumeCreated(givenCurrentSubjectAsPackageAdmin diff --git a/src/test/java/net/hostsharing/hsadminng/rbac/grant/RbacGrantRepositoryIntegrationTest.java b/src/test/java/net/hostsharing/hsadminng/rbac/grant/RbacGrantRepositoryIntegrationTest.java index e9c29afe..f4df3c6d 100644 --- a/src/test/java/net/hostsharing/hsadminng/rbac/grant/RbacGrantRepositoryIntegrationTest.java +++ b/src/test/java/net/hostsharing/hsadminng/rbac/grant/RbacGrantRepositoryIntegrationTest.java @@ -67,7 +67,7 @@ class RbacGrantRepositoryIntegrationTest extends ContextBasedTest { // then exactlyTheseRbacGrantsAreReturned( result, - "{ grant role:test_package#xxx00:ADMIN to user:pac-admin-xxx00@xxx.example.com by role:test_customer#xxx:ADMIN and assume }"); + "{ grant role:rbactest.package#xxx00:ADMIN to user:pac-admin-xxx00@xxx.example.com by role:rbactest.customer#xxx:ADMIN and assume }"); } @Test @@ -81,16 +81,16 @@ class RbacGrantRepositoryIntegrationTest extends ContextBasedTest { // then exactlyTheseRbacGrantsAreReturned( result, - "{ grant role:test_customer#xxx:ADMIN to user:customer-admin@xxx.example.com by role:test_customer#xxx:OWNER and assume }", - "{ grant role:test_package#xxx00:ADMIN to user:pac-admin-xxx00@xxx.example.com by role:test_customer#xxx:ADMIN and assume }", - "{ grant role:test_package#xxx01:ADMIN to user:pac-admin-xxx01@xxx.example.com by role:test_customer#xxx:ADMIN and assume }", - "{ grant role:test_package#xxx02:ADMIN to user:pac-admin-xxx02@xxx.example.com by role:test_customer#xxx:ADMIN and assume }"); + "{ grant role:rbactest.customer#xxx:ADMIN to user:customer-admin@xxx.example.com by role:rbactest.customer#xxx:OWNER and assume }", + "{ grant role:rbactest.package#xxx00:ADMIN to user:pac-admin-xxx00@xxx.example.com by role:rbactest.customer#xxx:ADMIN and assume }", + "{ grant role:rbactest.package#xxx01:ADMIN to user:pac-admin-xxx01@xxx.example.com by role:rbactest.customer#xxx:ADMIN and assume }", + "{ grant role:rbactest.package#xxx02:ADMIN to user:pac-admin-xxx02@xxx.example.com by role:rbactest.customer#xxx:ADMIN and assume }"); } @Test public void customerAdmin_withAssumedRole_canOnlyViewRbacGrantsVisibleByAssumedRole() { // given: - context("customer-admin@xxx.example.com", "test_package#xxx00:ADMIN"); + context("customer-admin@xxx.example.com", "rbactest.package#xxx00:ADMIN"); // when final var result = rbacGrantRepository.findAll(); @@ -98,7 +98,7 @@ class RbacGrantRepositoryIntegrationTest extends ContextBasedTest { // then exactlyTheseRbacGrantsAreReturned( result, - "{ grant role:test_package#xxx00:ADMIN to user:pac-admin-xxx00@xxx.example.com by role:test_customer#xxx:ADMIN and assume }"); + "{ grant role:rbactest.package#xxx00:ADMIN to user:pac-admin-xxx00@xxx.example.com by role:rbactest.customer#xxx:ADMIN and assume }"); } } @@ -108,9 +108,9 @@ class RbacGrantRepositoryIntegrationTest extends ContextBasedTest { @Test public void customerAdmin_canGrantOwnPackageAdminRole_toArbitraryUser() { // given - context("customer-admin@xxx.example.com", "test_customer#xxx:ADMIN"); + context("customer-admin@xxx.example.com", "rbactest.customer#xxx:ADMIN"); final var givenArbitrarySubjectUuid = rbacSubjectRepository.findByName("pac-admin-zzz00@zzz.example.com").getUuid(); - final var givenOwnPackageRoleUuid = rbacRoleRepository.findByRoleName("test_package#xxx00:ADMIN").getUuid(); + final var givenOwnPackageRoleUuid = rbacRoleRepository.findByRoleName("rbactest.package#xxx00:ADMIN").getUuid(); // when final var grant = RbacGrantEntity.builder() @@ -126,7 +126,7 @@ class RbacGrantRepositoryIntegrationTest extends ContextBasedTest { assertThat(rbacGrantRepository.findAll()) .extracting(RbacGrantEntity::toDisplay) .contains( - "{ grant role:test_package#xxx00:ADMIN to user:pac-admin-zzz00@zzz.example.com by role:test_customer#xxx:ADMIN and assume }"); + "{ grant role:rbactest.package#xxx00:ADMIN to user:pac-admin-zzz00@zzz.example.com by role:rbactest.customer#xxx:ADMIN and assume }"); } @Test @@ -139,14 +139,14 @@ class RbacGrantRepositoryIntegrationTest extends ContextBasedTest { context("customer-admin@xxx.example.com", null); return new Given( createNewUser(), - rbacRoleRepository.findByRoleName("test_package#xxx00:OWNER").getUuid() + rbacRoleRepository.findByRoleName("rbactest.package#xxx00:OWNER").getUuid() ); }).assumeSuccessful().returnedValue(); // when final var attempt = jpaAttempt.transacted(() -> { // now we try to use these uuids as a less privileged user - context("pac-admin-xxx00@xxx.example.com", "test_package#xxx00:ADMIN"); + context("pac-admin-xxx00@xxx.example.com", "rbactest.package#xxx00:ADMIN"); final var grant = RbacGrantEntity.builder() .granteeSubjectUuid(given.arbitraryUser.getUuid()) .grantedRoleUuid(given.packageOwnerRoleUuid) @@ -158,8 +158,8 @@ class RbacGrantRepositoryIntegrationTest extends ContextBasedTest { // then attempt.assertExceptionWithRootCauseMessage( JpaSystemException.class, - "ERROR: [403] Access to granted role test_package#xxx00:OWNER", - "forbidden for test_package#xxx00:ADMIN"); + "ERROR: [403] Access to granted role rbactest.package#xxx00:OWNER", + "forbidden for rbactest.package#xxx00:ADMIN"); jpaAttempt.transacted(() -> { // finally, we use the new user to make sure, no roles were granted context(given.arbitraryUser.getName(), null); @@ -176,16 +176,16 @@ class RbacGrantRepositoryIntegrationTest extends ContextBasedTest { public void customerAdmin_canRevokeSelfGrantedPackageAdminRole() { // given final var grant = create(grant() - .byUser("customer-admin@xxx.example.com").withAssumedRole("test_customer#xxx:ADMIN") - .grantingRole("test_package#xxx00:ADMIN").toUser("pac-admin-zzz00@zzz.example.com")); + .byUser("customer-admin@xxx.example.com").withAssumedRole("rbactest.customer#xxx:ADMIN") + .grantingRole("rbactest.package#xxx00:ADMIN").toUser("pac-admin-zzz00@zzz.example.com")); // when - context("customer-admin@xxx.example.com", "test_customer#xxx:ADMIN"); + context("customer-admin@xxx.example.com", "rbactest.customer#xxx:ADMIN"); final var revokeAttempt = attempt(em, () -> rbacGrantRepository.deleteByRbacGrantId(grant.getRbacGrantId())); // then - context("customer-admin@xxx.example.com", "test_customer#xxx:ADMIN"); + context("customer-admin@xxx.example.com", "rbactest.customer#xxx:ADMIN"); assertThat(revokeAttempt.caughtExceptionsRootCause()).isNull(); assertThat(rbacGrantRepository.findAll()) .extracting(RbacGrantEntity::getGranteeSubjectName) @@ -197,17 +197,17 @@ class RbacGrantRepositoryIntegrationTest extends ContextBasedTest { // given final var newUser = createNewUserTransacted(); final var grant = create(grant() - .byUser("customer-admin@xxx.example.com").withAssumedRole("test_package#xxx00:ADMIN") - .grantingRole("test_package#xxx00:ADMIN").toUser(newUser.getName())); + .byUser("customer-admin@xxx.example.com").withAssumedRole("rbactest.package#xxx00:ADMIN") + .grantingRole("rbactest.package#xxx00:ADMIN").toUser(newUser.getName())); // when - context("pac-admin-xxx00@xxx.example.com", "test_package#xxx00:ADMIN"); + context("pac-admin-xxx00@xxx.example.com", "rbactest.package#xxx00:ADMIN"); final var revokeAttempt = attempt(em, () -> rbacGrantRepository.deleteByRbacGrantId(grant.getRbacGrantId())); // then assertThat(revokeAttempt.caughtExceptionsRootCause()).isNull(); - context("customer-admin@xxx.example.com", "test_customer#xxx:ADMIN"); + context("customer-admin@xxx.example.com", "rbactest.customer#xxx:ADMIN"); assertThat(rbacGrantRepository.findAll()) .extracting(RbacGrantEntity::getGranteeSubjectName) .doesNotContain("pac-admin-zzz00@zzz.example.com"); @@ -217,19 +217,19 @@ class RbacGrantRepositoryIntegrationTest extends ContextBasedTest { public void packageAdmin_canNotRevokeOwnPackageAdminRoleGrantedByOwnerRoleOfThatPackage() { // given final var grant = create(grant() - .byUser("customer-admin@xxx.example.com").withAssumedRole("test_package#xxx00:OWNER") - .grantingRole("test_package#xxx00:ADMIN").toUser("pac-admin-zzz00@zzz.example.com")); - final var grantedByRole = rbacRoleRepository.findByRoleName("test_package#xxx00:OWNER"); + .byUser("customer-admin@xxx.example.com").withAssumedRole("rbactest.package#xxx00:OWNER") + .grantingRole("rbactest.package#xxx00:ADMIN").toUser("pac-admin-zzz00@zzz.example.com")); + final var grantedByRole = rbacRoleRepository.findByRoleName("rbactest.package#xxx00:OWNER"); // when - context("pac-admin-xxx00@xxx.example.com", "test_package#xxx00:ADMIN"); + context("pac-admin-xxx00@xxx.example.com", "rbactest.package#xxx00:ADMIN"); final var revokeAttempt = attempt(em, () -> rbacGrantRepository.deleteByRbacGrantId(grant.getRbacGrantId())); // then revokeAttempt.assertExceptionWithRootCauseMessage( JpaSystemException.class, - "ERROR: [403] Revoking role created by %s is forbidden for {test_package#xxx00:ADMIN}.".formatted( + "ERROR: [403] Revoking role created by %s is forbidden for {rbactest.package#xxx00:ADMIN}.".formatted( grantedByRole.getUuid() )); } diff --git a/src/test/java/net/hostsharing/hsadminng/rbac/grant/RbacGrantsDiagramServiceIntegrationTest.java b/src/test/java/net/hostsharing/hsadminng/rbac/grant/RbacGrantsDiagramServiceIntegrationTest.java index 46dd8333..2f6dc3a9 100644 --- a/src/test/java/net/hostsharing/hsadminng/rbac/grant/RbacGrantsDiagramServiceIntegrationTest.java +++ b/src/test/java/net/hostsharing/hsadminng/rbac/grant/RbacGrantsDiagramServiceIntegrationTest.java @@ -54,36 +54,36 @@ class RbacGrantsDiagramServiceIntegrationTest extends ContextBasedTestWithCleanu @Test void allGrantsTocurrentSubject() { - context("superuser-alex@hostsharing.net", "test_domain#xxx00-aaaa:OWNER"); + context("superuser-alex@hostsharing.net", "rbactest.domain#xxx00-aaaa:OWNER"); final var graph = grantsMermaidService.allGrantsTocurrentSubject(EnumSet.of(Include.TEST_ENTITIES)); assertThat(graph).isEqualTo(""" flowchart TB - role:test_domain#xxx00-aaaa:ADMIN --> role:test_package#xxx00:TENANT - role:test_domain#xxx00-aaaa:OWNER --> role:test_domain#xxx00-aaaa:ADMIN - role:test_domain#xxx00-aaaa:OWNER --> role:test_package#xxx00:TENANT - role:test_package#xxx00:TENANT --> role:test_customer#xxx:TENANT + role:rbactest.domain#xxx00-aaaa:ADMIN --> role:rbactest.package#xxx00:TENANT + role:rbactest.domain#xxx00-aaaa:OWNER --> role:rbactest.domain#xxx00-aaaa:ADMIN + role:rbactest.domain#xxx00-aaaa:OWNER --> role:rbactest.package#xxx00:TENANT + role:rbactest.package#xxx00:TENANT --> role:rbactest.customer#xxx:TENANT """.trim()); } @Test void allGrantsTocurrentSubjectIncludingPermissions() { - context("superuser-alex@hostsharing.net", "test_domain#xxx00-aaaa:OWNER"); + context("superuser-alex@hostsharing.net", "rbactest.domain#xxx00-aaaa:OWNER"); final var graph = grantsMermaidService.allGrantsTocurrentSubject(EnumSet.of(Include.TEST_ENTITIES, Include.PERMISSIONS)); assertThat(graph).isEqualTo(""" flowchart TB - role:test_customer#xxx:TENANT --> perm:test_customer#xxx:SELECT - role:test_domain#xxx00-aaaa:ADMIN --> perm:test_domain#xxx00-aaaa:SELECT - role:test_domain#xxx00-aaaa:ADMIN --> role:test_package#xxx00:TENANT - role:test_domain#xxx00-aaaa:OWNER --> perm:test_domain#xxx00-aaaa:DELETE - role:test_domain#xxx00-aaaa:OWNER --> perm:test_domain#xxx00-aaaa:UPDATE - role:test_domain#xxx00-aaaa:OWNER --> role:test_domain#xxx00-aaaa:ADMIN - role:test_domain#xxx00-aaaa:OWNER --> role:test_package#xxx00:TENANT - role:test_package#xxx00:TENANT --> perm:test_package#xxx00:SELECT - role:test_package#xxx00:TENANT --> role:test_customer#xxx:TENANT + role:rbactest.customer#xxx:TENANT --> perm:rbactest.customer#xxx:SELECT + role:rbactest.domain#xxx00-aaaa:ADMIN --> perm:rbactest.domain#xxx00-aaaa:SELECT + role:rbactest.domain#xxx00-aaaa:ADMIN --> role:rbactest.package#xxx00:TENANT + role:rbactest.domain#xxx00-aaaa:OWNER --> perm:rbactest.domain#xxx00-aaaa:DELETE + role:rbactest.domain#xxx00-aaaa:OWNER --> perm:rbactest.domain#xxx00-aaaa:UPDATE + role:rbactest.domain#xxx00-aaaa:OWNER --> role:rbactest.domain#xxx00-aaaa:ADMIN + role:rbactest.domain#xxx00-aaaa:OWNER --> role:rbactest.package#xxx00:TENANT + role:rbactest.package#xxx00:TENANT --> perm:rbactest.package#xxx00:SELECT + role:rbactest.package#xxx00:TENANT --> role:rbactest.customer#xxx:TENANT """.trim()); } diff --git a/src/test/java/net/hostsharing/hsadminng/rbac/role/RbacRoleControllerAcceptanceTest.java b/src/test/java/net/hostsharing/hsadminng/rbac/role/RbacRoleControllerAcceptanceTest.java index d9e2b248..43ff21ab 100644 --- a/src/test/java/net/hostsharing/hsadminng/rbac/role/RbacRoleControllerAcceptanceTest.java +++ b/src/test/java/net/hostsharing/hsadminng/rbac/role/RbacRoleControllerAcceptanceTest.java @@ -42,14 +42,14 @@ class RbacRoleControllerAcceptanceTest { .then().assertThat() .statusCode(200) .contentType("application/json") - .body("", hasItem(hasEntry("roleName", "test_customer#xxx:ADMIN"))) - .body("", hasItem(hasEntry("roleName", "test_customer#xxx:OWNER"))) - .body("", hasItem(hasEntry("roleName", "test_customer#xxx:TENANT"))) + .body("", hasItem(hasEntry("roleName", "rbactest.customer#xxx:ADMIN"))) + .body("", hasItem(hasEntry("roleName", "rbactest.customer#xxx:OWNER"))) + .body("", hasItem(hasEntry("roleName", "rbactest.customer#xxx:TENANT"))) // ... .body("", hasItem(hasEntry("roleName", "rbac.global#global:ADMIN"))) - .body("", hasItem(hasEntry("roleName", "test_customer#yyy:ADMIN"))) - .body("", hasItem(hasEntry("roleName", "test_package#yyy00:ADMIN"))) - .body("", hasItem(hasEntry("roleName", "test_domain#yyy00-aaaa:OWNER"))) + .body("", hasItem(hasEntry("roleName", "rbactest.customer#yyy:ADMIN"))) + .body("", hasItem(hasEntry("roleName", "rbactest.package#yyy00:ADMIN"))) + .body("", hasItem(hasEntry("roleName", "rbactest.domain#yyy00-aaaa:OWNER"))) .body( "size()", greaterThanOrEqualTo(73)); // increases with new test data // @formatter:on } @@ -61,7 +61,7 @@ class RbacRoleControllerAcceptanceTest { RestAssured .given() .header("current-subject", "superuser-alex@hostsharing.net") - .header("assumed-roles", "test_package#yyy00:ADMIN") + .header("assumed-roles", "rbactest.package#yyy00:ADMIN") .port(port) .when() .get("http://localhost/api/rbac/roles") @@ -71,18 +71,18 @@ class RbacRoleControllerAcceptanceTest { .statusCode(200) .contentType("application/json") - .body("", hasItem(hasEntry("roleName", "test_customer#yyy:TENANT"))) - .body("", hasItem(hasEntry("roleName", "test_domain#yyy00-aaaa:OWNER"))) - .body("", hasItem(hasEntry("roleName", "test_domain#yyy00-aaaa:ADMIN"))) - .body("", hasItem(hasEntry("roleName", "test_domain#yyy00-aaab:OWNER"))) - .body("", hasItem(hasEntry("roleName", "test_domain#yyy00-aaab:ADMIN"))) - .body("", hasItem(hasEntry("roleName", "test_package#yyy00:ADMIN"))) - .body("", hasItem(hasEntry("roleName", "test_package#yyy00:TENANT"))) + .body("", hasItem(hasEntry("roleName", "rbactest.customer#yyy:TENANT"))) + .body("", hasItem(hasEntry("roleName", "rbactest.domain#yyy00-aaaa:OWNER"))) + .body("", hasItem(hasEntry("roleName", "rbactest.domain#yyy00-aaaa:ADMIN"))) + .body("", hasItem(hasEntry("roleName", "rbactest.domain#yyy00-aaab:OWNER"))) + .body("", hasItem(hasEntry("roleName", "rbactest.domain#yyy00-aaab:ADMIN"))) + .body("", hasItem(hasEntry("roleName", "rbactest.package#yyy00:ADMIN"))) + .body("", hasItem(hasEntry("roleName", "rbactest.package#yyy00:TENANT"))) - .body("", not(hasItem(hasEntry("roleName", "test_customer#xxx:TENANT")))) - .body("", not(hasItem(hasEntry("roleName", "test_domain#xxx00-aaaa:ADMIN")))) - .body("", not(hasItem(hasEntry("roleName", "test_package#xxx00:ADMIN")))) - .body("", not(hasItem(hasEntry("roleName", "test_package#xxx00:TENANT")))) + .body("", not(hasItem(hasEntry("roleName", "rbactest.customer#xxx:TENANT")))) + .body("", not(hasItem(hasEntry("roleName", "rbactest.domain#xxx00-aaaa:ADMIN")))) + .body("", not(hasItem(hasEntry("roleName", "rbactest.package#xxx00:ADMIN")))) + .body("", not(hasItem(hasEntry("roleName", "rbactest.package#xxx00:TENANT")))) ; // @formatter:on } @@ -101,15 +101,15 @@ class RbacRoleControllerAcceptanceTest { .statusCode(200) .contentType("application/json") - .body("", hasItem(hasEntry("roleName", "test_customer#zzz:TENANT"))) - .body("", hasItem(hasEntry("roleName", "test_domain#zzz00-aaaa:ADMIN"))) - .body("", hasItem(hasEntry("roleName", "test_package#zzz00:ADMIN"))) - .body("", hasItem(hasEntry("roleName", "test_package#zzz00:TENANT"))) + .body("", hasItem(hasEntry("roleName", "rbactest.customer#zzz:TENANT"))) + .body("", hasItem(hasEntry("roleName", "rbactest.domain#zzz00-aaaa:ADMIN"))) + .body("", hasItem(hasEntry("roleName", "rbactest.package#zzz00:ADMIN"))) + .body("", hasItem(hasEntry("roleName", "rbactest.package#zzz00:TENANT"))) - .body("", not(hasItem(hasEntry("roleName", "test_customer#yyy:TENANT")))) - .body("", not(hasItem(hasEntry("roleName", "test_domain#yyy00-aaaa:ADMIN")))) - .body("", not(hasItem(hasEntry("roleName", "test_package#yyy00:ADMIN")))) - .body("", not(hasItem(hasEntry("roleName", "test_package#yyy00:TENANT")))); + .body("", not(hasItem(hasEntry("roleName", "rbactest.customer#yyy:TENANT")))) + .body("", not(hasItem(hasEntry("roleName", "rbactest.domain#yyy00-aaaa:ADMIN")))) + .body("", not(hasItem(hasEntry("roleName", "rbactest.package#yyy00:ADMIN")))) + .body("", not(hasItem(hasEntry("roleName", "rbactest.package#yyy00:TENANT")))); // @formatter:on } } diff --git a/src/test/java/net/hostsharing/hsadminng/rbac/role/RbacRoleControllerRestTest.java b/src/test/java/net/hostsharing/hsadminng/rbac/role/RbacRoleControllerRestTest.java index 1eb41370..2d3d74c7 100644 --- a/src/test/java/net/hostsharing/hsadminng/rbac/role/RbacRoleControllerRestTest.java +++ b/src/test/java/net/hostsharing/hsadminng/rbac/role/RbacRoleControllerRestTest.java @@ -74,8 +74,8 @@ class RbacRoleControllerRestTest { .andExpect(status().isOk()) .andExpect(jsonPath("$", hasSize(3))) .andExpect(jsonPath("$[0].roleName", is("rbac.global#global:ADMIN"))) - .andExpect(jsonPath("$[1].roleName", is("test_customer#xxx:OWNER"))) - .andExpect(jsonPath("$[2].roleName", is("test_customer#xxx:ADMIN"))) + .andExpect(jsonPath("$[1].roleName", is("rbactest.customer#xxx:OWNER"))) + .andExpect(jsonPath("$[2].roleName", is("rbactest.customer#xxx:ADMIN"))) .andExpect(jsonPath("$[2].uuid", is(customerXxxAdmin.getUuid().toString()))) .andExpect(jsonPath("$[2].objectUuid", is(customerXxxAdmin.getObjectUuid().toString()))) .andExpect(jsonPath("$[2].objectTable", is(customerXxxAdmin.getObjectTable().toString()))) diff --git a/src/test/java/net/hostsharing/hsadminng/rbac/role/RbacRoleRepositoryIntegrationTest.java b/src/test/java/net/hostsharing/hsadminng/rbac/role/RbacRoleRepositoryIntegrationTest.java index d8b0cb80..7540777a 100644 --- a/src/test/java/net/hostsharing/hsadminng/rbac/role/RbacRoleRepositoryIntegrationTest.java +++ b/src/test/java/net/hostsharing/hsadminng/rbac/role/RbacRoleRepositoryIntegrationTest.java @@ -40,18 +40,18 @@ class RbacRoleRepositoryIntegrationTest { private static final String[] ALL_TEST_DATA_ROLES = Array.of( // @formatter:off "rbac.global#global:ADMIN", - "test_customer#xxx:ADMIN", "test_customer#xxx:OWNER", "test_customer#xxx:TENANT", - "test_package#xxx00:ADMIN", "test_package#xxx00:OWNER", "test_package#xxx00:TENANT", - "test_package#xxx01:ADMIN", "test_package#xxx01:OWNER", "test_package#xxx01:TENANT", - "test_package#xxx02:ADMIN", "test_package#xxx02:OWNER", "test_package#xxx02:TENANT", - "test_customer#yyy:ADMIN", "test_customer#yyy:OWNER", "test_customer#yyy:TENANT", - "test_package#yyy00:ADMIN", "test_package#yyy00:OWNER", "test_package#yyy00:TENANT", - "test_package#yyy01:ADMIN", "test_package#yyy01:OWNER", "test_package#yyy01:TENANT", - "test_package#yyy02:ADMIN", "test_package#yyy02:OWNER", "test_package#yyy02:TENANT", - "test_customer#zzz:ADMIN", "test_customer#zzz:OWNER", "test_customer#zzz:TENANT", - "test_package#zzz00:ADMIN", "test_package#zzz00:OWNER", "test_package#zzz00:TENANT", - "test_package#zzz01:ADMIN", "test_package#zzz01:OWNER", "test_package#zzz01:TENANT", - "test_package#zzz02:ADMIN", "test_package#zzz02:OWNER", "test_package#zzz02:TENANT" + "rbactest.customer#xxx:ADMIN", "rbactest.customer#xxx:OWNER", "rbactest.customer#xxx:TENANT", + "rbactest.package#xxx00:ADMIN", "rbactest.package#xxx00:OWNER", "rbactest.package#xxx00:TENANT", + "rbactest.package#xxx01:ADMIN", "rbactest.package#xxx01:OWNER", "rbactest.package#xxx01:TENANT", + "rbactest.package#xxx02:ADMIN", "rbactest.package#xxx02:OWNER", "rbactest.package#xxx02:TENANT", + "rbactest.customer#yyy:ADMIN", "rbactest.customer#yyy:OWNER", "rbactest.customer#yyy:TENANT", + "rbactest.package#yyy00:ADMIN", "rbactest.package#yyy00:OWNER", "rbactest.package#yyy00:TENANT", + "rbactest.package#yyy01:ADMIN", "rbactest.package#yyy01:OWNER", "rbactest.package#yyy01:TENANT", + "rbactest.package#yyy02:ADMIN", "rbactest.package#yyy02:OWNER", "rbactest.package#yyy02:TENANT", + "rbactest.customer#zzz:ADMIN", "rbactest.customer#zzz:OWNER", "rbactest.customer#zzz:TENANT", + "rbactest.package#zzz00:ADMIN", "rbactest.package#zzz00:OWNER", "rbactest.package#zzz00:TENANT", + "rbactest.package#zzz01:ADMIN", "rbactest.package#zzz01:OWNER", "rbactest.package#zzz01:TENANT", + "rbactest.package#zzz02:ADMIN", "rbactest.package#zzz02:OWNER", "rbactest.package#zzz02:TENANT" // @formatter:on ); @@ -91,49 +91,49 @@ class RbacRoleRepositoryIntegrationTest { allTheseRbacRolesAreReturned( result, // @formatter:off - "test_customer#xxx:ADMIN", - "test_customer#xxx:TENANT", - "test_package#xxx00:ADMIN", - "test_package#xxx00:OWNER", - "test_package#xxx00:TENANT", - "test_package#xxx01:ADMIN", - "test_package#xxx01:OWNER", - "test_package#xxx01:TENANT", + "rbactest.customer#xxx:ADMIN", + "rbactest.customer#xxx:TENANT", + "rbactest.package#xxx00:ADMIN", + "rbactest.package#xxx00:OWNER", + "rbactest.package#xxx00:TENANT", + "rbactest.package#xxx01:ADMIN", + "rbactest.package#xxx01:OWNER", + "rbactest.package#xxx01:TENANT", // ... - "test_domain#xxx00-aaaa:ADMIN", - "test_domain#xxx00-aaaa:OWNER", + "rbactest.domain#xxx00-aaaa:ADMIN", + "rbactest.domain#xxx00-aaaa:OWNER", // .. - "test_domain#xxx01-aaab:ADMIN", - "test_domain#xxx01-aaab:OWNER" + "rbactest.domain#xxx01-aaab:ADMIN", + "rbactest.domain#xxx01-aaab:OWNER" // @formatter:on ); noneOfTheseRbacRolesIsReturned( result, // @formatter:off "rbac.global#global:ADMIN", - "test_customer#xxx:OWNER", - "test_package#yyy00:ADMIN", - "test_package#yyy00:OWNER", - "test_package#yyy00:TENANT" + "rbactest.customer#xxx:OWNER", + "rbactest.package#yyy00:ADMIN", + "rbactest.package#yyy00:OWNER", + "rbactest.package#yyy00:TENANT" // @formatter:on ); } @Test public void customerAdmin_withAssumedOwnedPackageAdminRole_canViewOnlyItsOwnRbacRole() { - context.define("customer-admin@xxx.example.com", "test_package#xxx00:ADMIN"); + context.define("customer-admin@xxx.example.com", "rbactest.package#xxx00:ADMIN"); final var result = rbacRoleRepository.findAll(); exactlyTheseRbacRolesAreReturned( result, - "test_customer#xxx:TENANT", - "test_package#xxx00:ADMIN", - "test_package#xxx00:TENANT", - "test_domain#xxx00-aaaa:ADMIN", - "test_domain#xxx00-aaaa:OWNER", - "test_domain#xxx00-aaab:ADMIN", - "test_domain#xxx00-aaab:OWNER"); + "rbactest.customer#xxx:TENANT", + "rbactest.package#xxx00:ADMIN", + "rbactest.package#xxx00:TENANT", + "rbactest.domain#xxx00-aaaa:ADMIN", + "rbactest.domain#xxx00-aaaa:OWNER", + "rbactest.domain#xxx00-aaab:ADMIN", + "rbactest.domain#xxx00-aaab:OWNER"); } @Test @@ -157,10 +157,10 @@ class RbacRoleRepositoryIntegrationTest { void customerAdmin_withoutAssumedRole_canFindItsOwnRolesByName() { context.define("customer-admin@xxx.example.com"); - final var result = rbacRoleRepository.findByRoleName("test_customer#xxx:ADMIN"); + final var result = rbacRoleRepository.findByRoleName("rbactest.customer#xxx:ADMIN"); assertThat(result).isNotNull(); - assertThat(result.getObjectTable()).isEqualTo("test_customer"); + assertThat(result.getObjectTable()).isEqualTo("rbactest.customer"); assertThat(result.getObjectIdName()).isEqualTo("xxx"); assertThat(result.getRoleType()).isEqualTo(RbacRoleType.ADMIN); } @@ -169,7 +169,7 @@ class RbacRoleRepositoryIntegrationTest { void customerAdmin_withoutAssumedRole_canNotFindAlienRolesByName() { context.define("customer-admin@xxx.example.com"); - final var result = rbacRoleRepository.findByRoleName("test_customer#bbb:ADMIN"); + final var result = rbacRoleRepository.findByRoleName("rbactest.customer#bbb:ADMIN"); assertThat(result).isNull(); } diff --git a/src/test/java/net/hostsharing/hsadminng/rbac/role/TestRbacRole.java b/src/test/java/net/hostsharing/hsadminng/rbac/role/TestRbacRole.java index 8a8214cf..0307f9d4 100644 --- a/src/test/java/net/hostsharing/hsadminng/rbac/role/TestRbacRole.java +++ b/src/test/java/net/hostsharing/hsadminng/rbac/role/TestRbacRole.java @@ -5,8 +5,8 @@ import static java.util.UUID.randomUUID; public class TestRbacRole { public static final RbacRoleEntity hostmasterRole = rbacRole("rbac.global", "global", RbacRoleType.ADMIN); - static final RbacRoleEntity customerXxxOwner = rbacRole("test_customer", "xxx", RbacRoleType.OWNER); - static final RbacRoleEntity customerXxxAdmin = rbacRole("test_customer", "xxx", RbacRoleType.ADMIN); + static final RbacRoleEntity customerXxxOwner = rbacRole("rbactest.customer", "xxx", RbacRoleType.OWNER); + static final RbacRoleEntity customerXxxAdmin = rbacRole("rbactest.customer", "xxx", RbacRoleType.ADMIN); static public RbacRoleEntity rbacRole(final String objectTable, final String objectIdName, final RbacRoleType roleType) { return new RbacRoleEntity(randomUUID(), randomUUID(), objectTable, objectIdName, roleType, objectTable+'#'+objectIdName+':'+roleType); diff --git a/src/test/java/net/hostsharing/hsadminng/rbac/subject/RbacSubjectControllerAcceptanceTest.java b/src/test/java/net/hostsharing/hsadminng/rbac/subject/RbacSubjectControllerAcceptanceTest.java index e62d39c4..aa1bac97 100644 --- a/src/test/java/net/hostsharing/hsadminng/rbac/subject/RbacSubjectControllerAcceptanceTest.java +++ b/src/test/java/net/hostsharing/hsadminng/rbac/subject/RbacSubjectControllerAcceptanceTest.java @@ -100,7 +100,7 @@ class RbacSubjectControllerAcceptanceTest { RestAssured .given() .header("current-subject", "superuser-alex@hostsharing.net") - .header("assumed-roles", "test_customer#yyy:ADMIN") + .header("assumed-roles", "rbactest.customer#yyy:ADMIN") .port(port) .when() .get("http://localhost/api/rbac/subjects/" + givenUser.getUuid()) @@ -201,7 +201,7 @@ class RbacSubjectControllerAcceptanceTest { RestAssured .given() .header("current-subject", "superuser-alex@hostsharing.net") - .header("assumed-roles", "test_customer#yyy:ADMIN") + .header("assumed-roles", "rbactest.customer#yyy:ADMIN") .port(port) .when() .get("http://localhost/api/rbac/subjects") @@ -275,12 +275,12 @@ class RbacSubjectControllerAcceptanceTest { .contentType("application/json") .body("", hasItem( allOf( - hasEntry("roleName", "test_customer#yyy:TENANT"), + hasEntry("roleName", "rbactest.customer#yyy:TENANT"), hasEntry("op", "SELECT")) )) .body("", hasItem( allOf( - hasEntry("roleName", "test_domain#yyy00-aaaa:OWNER"), + hasEntry("roleName", "rbactest.domain#yyy00-aaaa:OWNER"), hasEntry("op", "DELETE")) )) // actual content tested in integration test, so this is enough for here: @@ -296,7 +296,7 @@ class RbacSubjectControllerAcceptanceTest { RestAssured .given() .header("current-subject", "superuser-alex@hostsharing.net") - .header("assumed-roles", "test_customer#yyy:ADMIN") + .header("assumed-roles", "rbactest.customer#yyy:ADMIN") .port(port) .when() .get("http://localhost/api/rbac/subjects/" + givenUser.getUuid() + "/permissions") @@ -305,12 +305,12 @@ class RbacSubjectControllerAcceptanceTest { .contentType("application/json") .body("", hasItem( allOf( - hasEntry("roleName", "test_customer#yyy:TENANT"), + hasEntry("roleName", "rbactest.customer#yyy:TENANT"), hasEntry("op", "SELECT")) )) .body("", hasItem( allOf( - hasEntry("roleName", "test_domain#yyy00-aaaa:OWNER"), + hasEntry("roleName", "rbactest.domain#yyy00-aaaa:OWNER"), hasEntry("op", "DELETE")) )) // actual content tested in integration test, so this is enough for here: @@ -334,12 +334,12 @@ class RbacSubjectControllerAcceptanceTest { .contentType("application/json") .body("", hasItem( allOf( - hasEntry("roleName", "test_customer#yyy:TENANT"), + hasEntry("roleName", "rbactest.customer#yyy:TENANT"), hasEntry("op", "SELECT")) )) .body("", hasItem( allOf( - hasEntry("roleName", "test_domain#yyy00-aaaa:OWNER"), + hasEntry("roleName", "rbactest.domain#yyy00-aaaa:OWNER"), hasEntry("op", "DELETE")) )) // actual content tested in integration test, so this is enough for here: diff --git a/src/test/java/net/hostsharing/hsadminng/rbac/subject/RbacSubjectRepositoryIntegrationTest.java b/src/test/java/net/hostsharing/hsadminng/rbac/subject/RbacSubjectRepositoryIntegrationTest.java index d6e50c46..c60142d5 100644 --- a/src/test/java/net/hostsharing/hsadminng/rbac/subject/RbacSubjectRepositoryIntegrationTest.java +++ b/src/test/java/net/hostsharing/hsadminng/rbac/subject/RbacSubjectRepositoryIntegrationTest.java @@ -128,7 +128,7 @@ class RbacSubjectRepositoryIntegrationTest extends ContextBasedTest { @Test public void globalAdmin_withAssumedCustomerAdminRole_canViewOnlyUsersHavingRolesInThatCustomersRealm() { given: - context("superuser-alex@hostsharing.net", "test_customer#xxx:ADMIN"); + context("superuser-alex@hostsharing.net", "rbactest.customer#xxx:ADMIN"); // when final var result = rbacSubjectRepository.findByOptionalNameLike(null); @@ -159,7 +159,7 @@ class RbacSubjectRepositoryIntegrationTest extends ContextBasedTest { @Test public void customerAdmin_withAssumedOwnedPackageAdminRole_canViewOnlyUsersHavingRolesInThatPackage() { - context("customer-admin@xxx.example.com", "test_package#xxx00:ADMIN"); + context("customer-admin@xxx.example.com", "rbactest.package#xxx00:ADMIN"); final var result = rbacSubjectRepository.findByOptionalNameLike(null); @@ -182,47 +182,47 @@ class RbacSubjectRepositoryIntegrationTest extends ContextBasedTest { private static final String[] ALL_USER_PERMISSIONS = Array.of( // @formatter:off - "test_customer#xxx:ADMIN -> test_customer#xxx: SELECT", - "test_customer#xxx:OWNER -> test_customer#xxx: DELETE", - "test_customer#xxx:TENANT -> test_customer#xxx: SELECT", - "test_customer#xxx:ADMIN -> test_customer#xxx: INSERT:test_package", - "test_package#xxx00:ADMIN -> test_package#xxx00: INSERT:test_domain", - "test_package#xxx00:ADMIN -> test_package#xxx00: INSERT:test_domain", - "test_package#xxx00:TENANT -> test_package#xxx00: SELECT", - "test_package#xxx01:ADMIN -> test_package#xxx01: INSERT:test_domain", - "test_package#xxx01:ADMIN -> test_package#xxx01: INSERT:test_domain", - "test_package#xxx01:TENANT -> test_package#xxx01: SELECT", - "test_package#xxx02:ADMIN -> test_package#xxx02: INSERT:test_domain", - "test_package#xxx02:ADMIN -> test_package#xxx02: INSERT:test_domain", - "test_package#xxx02:TENANT -> test_package#xxx02: SELECT", + "rbactest.customer#xxx:ADMIN -> rbactest.customer#xxx: SELECT", + "rbactest.customer#xxx:OWNER -> rbactest.customer#xxx: DELETE", + "rbactest.customer#xxx:TENANT -> rbactest.customer#xxx: SELECT", + "rbactest.customer#xxx:ADMIN -> rbactest.customer#xxx: INSERT:rbactest.package", + "rbactest.package#xxx00:ADMIN -> rbactest.package#xxx00: INSERT:rbactest.domain", + "rbactest.package#xxx00:ADMIN -> rbactest.package#xxx00: INSERT:rbactest.domain", + "rbactest.package#xxx00:TENANT -> rbactest.package#xxx00: SELECT", + "rbactest.package#xxx01:ADMIN -> rbactest.package#xxx01: INSERT:rbactest.domain", + "rbactest.package#xxx01:ADMIN -> rbactest.package#xxx01: INSERT:rbactest.domain", + "rbactest.package#xxx01:TENANT -> rbactest.package#xxx01: SELECT", + "rbactest.package#xxx02:ADMIN -> rbactest.package#xxx02: INSERT:rbactest.domain", + "rbactest.package#xxx02:ADMIN -> rbactest.package#xxx02: INSERT:rbactest.domain", + "rbactest.package#xxx02:TENANT -> rbactest.package#xxx02: SELECT", - "test_customer#yyy:ADMIN -> test_customer#yyy: SELECT", - "test_customer#yyy:OWNER -> test_customer#yyy: DELETE", - "test_customer#yyy:TENANT -> test_customer#yyy: SELECT", - "test_customer#yyy:ADMIN -> test_customer#yyy: INSERT:test_package", - "test_package#yyy00:ADMIN -> test_package#yyy00: INSERT:test_domain", - "test_package#yyy00:ADMIN -> test_package#yyy00: INSERT:test_domain", - "test_package#yyy00:TENANT -> test_package#yyy00: SELECT", - "test_package#yyy01:ADMIN -> test_package#yyy01: INSERT:test_domain", - "test_package#yyy01:ADMIN -> test_package#yyy01: INSERT:test_domain", - "test_package#yyy01:TENANT -> test_package#yyy01: SELECT", - "test_package#yyy02:ADMIN -> test_package#yyy02: INSERT:test_domain", - "test_package#yyy02:ADMIN -> test_package#yyy02: INSERT:test_domain", - "test_package#yyy02:TENANT -> test_package#yyy02: SELECT", + "rbactest.customer#yyy:ADMIN -> rbactest.customer#yyy: SELECT", + "rbactest.customer#yyy:OWNER -> rbactest.customer#yyy: DELETE", + "rbactest.customer#yyy:TENANT -> rbactest.customer#yyy: SELECT", + "rbactest.customer#yyy:ADMIN -> rbactest.customer#yyy: INSERT:rbactest.package", + "rbactest.package#yyy00:ADMIN -> rbactest.package#yyy00: INSERT:rbactest.domain", + "rbactest.package#yyy00:ADMIN -> rbactest.package#yyy00: INSERT:rbactest.domain", + "rbactest.package#yyy00:TENANT -> rbactest.package#yyy00: SELECT", + "rbactest.package#yyy01:ADMIN -> rbactest.package#yyy01: INSERT:rbactest.domain", + "rbactest.package#yyy01:ADMIN -> rbactest.package#yyy01: INSERT:rbactest.domain", + "rbactest.package#yyy01:TENANT -> rbactest.package#yyy01: SELECT", + "rbactest.package#yyy02:ADMIN -> rbactest.package#yyy02: INSERT:rbactest.domain", + "rbactest.package#yyy02:ADMIN -> rbactest.package#yyy02: INSERT:rbactest.domain", + "rbactest.package#yyy02:TENANT -> rbactest.package#yyy02: SELECT", - "test_customer#zzz:ADMIN -> test_customer#zzz: SELECT", - "test_customer#zzz:OWNER -> test_customer#zzz: DELETE", - "test_customer#zzz:TENANT -> test_customer#zzz: SELECT", - "test_customer#zzz:ADMIN -> test_customer#zzz: INSERT:test_package", - "test_package#zzz00:ADMIN -> test_package#zzz00: INSERT:test_domain", - "test_package#zzz00:ADMIN -> test_package#zzz00: INSERT:test_domain", - "test_package#zzz00:TENANT -> test_package#zzz00: SELECT", - "test_package#zzz01:ADMIN -> test_package#zzz01: INSERT:test_domain", - "test_package#zzz01:ADMIN -> test_package#zzz01: INSERT:test_domain", - "test_package#zzz01:TENANT -> test_package#zzz01: SELECT", - "test_package#zzz02:ADMIN -> test_package#zzz02: INSERT:test_domain", - "test_package#zzz02:ADMIN -> test_package#zzz02: INSERT:test_domain", - "test_package#zzz02:TENANT -> test_package#zzz02: SELECT" + "rbactest.customer#zzz:ADMIN -> rbactest.customer#zzz: SELECT", + "rbactest.customer#zzz:OWNER -> rbactest.customer#zzz: DELETE", + "rbactest.customer#zzz:TENANT -> rbactest.customer#zzz: SELECT", + "rbactest.customer#zzz:ADMIN -> rbactest.customer#zzz: INSERT:rbactest.package", + "rbactest.package#zzz00:ADMIN -> rbactest.package#zzz00: INSERT:rbactest.domain", + "rbactest.package#zzz00:ADMIN -> rbactest.package#zzz00: INSERT:rbactest.domain", + "rbactest.package#zzz00:TENANT -> rbactest.package#zzz00: SELECT", + "rbactest.package#zzz01:ADMIN -> rbactest.package#zzz01: INSERT:rbactest.domain", + "rbactest.package#zzz01:ADMIN -> rbactest.package#zzz01: INSERT:rbactest.domain", + "rbactest.package#zzz01:TENANT -> rbactest.package#zzz01: SELECT", + "rbactest.package#zzz02:ADMIN -> rbactest.package#zzz02: INSERT:rbactest.domain", + "rbactest.package#zzz02:ADMIN -> rbactest.package#zzz02: INSERT:rbactest.domain", + "rbactest.package#zzz02:TENANT -> rbactest.package#zzz02: SELECT" // @formatter:on ); @@ -233,7 +233,7 @@ class RbacSubjectRepositoryIntegrationTest extends ContextBasedTest { // when final var result = rbacSubjectRepository.findPermissionsOfUserByUuid(subjectUuid("superuser-fran@hostsharing.net")) - .stream().filter(p -> p.getObjectTable().contains("test_")) + .stream().filter(p -> p.getObjectTable().contains("rbactest.")) .sorted(comparing(RbacSubjectPermission::toString)).toList(); // then @@ -252,32 +252,32 @@ class RbacSubjectRepositoryIntegrationTest extends ContextBasedTest { allTheseRbacPermissionsAreReturned( result, // @formatter:off - "test_customer#xxx:ADMIN -> test_customer#xxx: INSERT:test_package", - "test_customer#xxx:ADMIN -> test_customer#xxx: SELECT", - "test_customer#xxx:TENANT -> test_customer#xxx: SELECT", + "rbactest.customer#xxx:ADMIN -> rbactest.customer#xxx: INSERT:rbactest.package", + "rbactest.customer#xxx:ADMIN -> rbactest.customer#xxx: SELECT", + "rbactest.customer#xxx:TENANT -> rbactest.customer#xxx: SELECT", - "test_package#xxx00:ADMIN -> test_package#xxx00: INSERT:test_domain", - "test_package#xxx00:ADMIN -> test_package#xxx00: INSERT:test_domain", - "test_package#xxx00:TENANT -> test_package#xxx00: SELECT", - "test_domain#xxx00-aaaa:OWNER -> test_domain#xxx00-aaaa: DELETE", + "rbactest.package#xxx00:ADMIN -> rbactest.package#xxx00: INSERT:rbactest.domain", + "rbactest.package#xxx00:ADMIN -> rbactest.package#xxx00: INSERT:rbactest.domain", + "rbactest.package#xxx00:TENANT -> rbactest.package#xxx00: SELECT", + "rbactest.domain#xxx00-aaaa:OWNER -> rbactest.domain#xxx00-aaaa: DELETE", - "test_package#xxx01:ADMIN -> test_package#xxx01: INSERT:test_domain", - "test_package#xxx01:ADMIN -> test_package#xxx01: INSERT:test_domain", - "test_package#xxx01:TENANT -> test_package#xxx01: SELECT", - "test_domain#xxx01-aaaa:OWNER -> test_domain#xxx01-aaaa: DELETE", + "rbactest.package#xxx01:ADMIN -> rbactest.package#xxx01: INSERT:rbactest.domain", + "rbactest.package#xxx01:ADMIN -> rbactest.package#xxx01: INSERT:rbactest.domain", + "rbactest.package#xxx01:TENANT -> rbactest.package#xxx01: SELECT", + "rbactest.domain#xxx01-aaaa:OWNER -> rbactest.domain#xxx01-aaaa: DELETE", - "test_package#xxx02:ADMIN -> test_package#xxx02: INSERT:test_domain", - "test_package#xxx02:ADMIN -> test_package#xxx02: INSERT:test_domain", - "test_package#xxx02:TENANT -> test_package#xxx02: SELECT", - "test_domain#xxx02-aaaa:OWNER -> test_domain#xxx02-aaaa: DELETE" + "rbactest.package#xxx02:ADMIN -> rbactest.package#xxx02: INSERT:rbactest.domain", + "rbactest.package#xxx02:ADMIN -> rbactest.package#xxx02: INSERT:rbactest.domain", + "rbactest.package#xxx02:TENANT -> rbactest.package#xxx02: SELECT", + "rbactest.domain#xxx02-aaaa:OWNER -> rbactest.domain#xxx02-aaaa: DELETE" // @formatter:on ); noneOfTheseRbacPermissionsAreReturned( result, // @formatter:off - "test_customer#yyy:ADMIN -> test_customer#yyy: INSERT:test_package", - "test_customer#yyy:ADMIN -> test_customer#yyy: SELECT", - "test_customer#yyy:TENANT -> test_customer#yyy: SELECT" + "rbactest.customer#yyy:ADMIN -> rbactest.customer#yyy: INSERT:rbactest.package", + "rbactest.customer#yyy:ADMIN -> rbactest.customer#yyy: SELECT", + "rbactest.customer#yyy:TENANT -> rbactest.customer#yyy: SELECT" // @formatter:on ); } @@ -312,26 +312,26 @@ class RbacSubjectRepositoryIntegrationTest extends ContextBasedTest { allTheseRbacPermissionsAreReturned( result, // @formatter:off - "test_customer#xxx:TENANT -> test_customer#xxx: SELECT", - // "test_customer#xxx:ADMIN -> test_customer#xxx: view" - Not permissions through the customer admin! - "test_package#xxx00:ADMIN -> test_package#xxx00: INSERT:test_domain", - "test_package#xxx00:ADMIN -> test_package#xxx00: INSERT:test_domain", - "test_package#xxx00:TENANT -> test_package#xxx00: SELECT", - "test_domain#xxx00-aaaa:OWNER -> test_domain#xxx00-aaaa: DELETE", - "test_domain#xxx00-aaab:OWNER -> test_domain#xxx00-aaab: DELETE" + "rbactest.customer#xxx:TENANT -> rbactest.customer#xxx: SELECT", + // "rbactest.customer#xxx:ADMIN -> rbactest.customer#xxx: view" - Not permissions through the customer admin! + "rbactest.package#xxx00:ADMIN -> rbactest.package#xxx00: INSERT:rbactest.domain", + "rbactest.package#xxx00:ADMIN -> rbactest.package#xxx00: INSERT:rbactest.domain", + "rbactest.package#xxx00:TENANT -> rbactest.package#xxx00: SELECT", + "rbactest.domain#xxx00-aaaa:OWNER -> rbactest.domain#xxx00-aaaa: DELETE", + "rbactest.domain#xxx00-aaab:OWNER -> rbactest.domain#xxx00-aaab: DELETE" // @formatter:on ); noneOfTheseRbacPermissionsAreReturned( result, // @formatter:off - "test_customer#yyy:ADMIN -> test_customer#yyy: INSERT:test_package", - "test_customer#yyy:ADMIN -> test_customer#yyy: SELECT", - "test_customer#yyy:TENANT -> test_customer#yyy: SELECT", - "test_package#yyy00:ADMIN -> test_package#yyy00: INSERT:test_domain", - "test_package#yyy00:ADMIN -> test_package#yyy00: INSERT:test_domain", - "test_package#yyy00:TENANT -> test_package#yyy00: SELECT", - "test_domain#yyy00-aaaa:OWNER -> test_domain#yyy00-aaaa: DELETE", - "test_domain#yyy00-aaab:OWNER -> test_domain#yyy00-aaab: DELETE" + "rbactest.customer#yyy:ADMIN -> rbactest.customer#yyy: INSERT:rbactest.package", + "rbactest.customer#yyy:ADMIN -> rbactest.customer#yyy: SELECT", + "rbactest.customer#yyy:TENANT -> rbactest.customer#yyy: SELECT", + "rbactest.package#yyy00:ADMIN -> rbactest.package#yyy00: INSERT:rbactest.domain", + "rbactest.package#yyy00:ADMIN -> rbactest.package#yyy00: INSERT:rbactest.domain", + "rbactest.package#yyy00:TENANT -> rbactest.package#yyy00: SELECT", + "rbactest.domain#yyy00-aaaa:OWNER -> rbactest.domain#yyy00-aaaa: DELETE", + "rbactest.domain#yyy00-aaab:OWNER -> rbactest.domain#yyy00-aaab: DELETE" // @formatter:on ); } @@ -360,26 +360,26 @@ class RbacSubjectRepositoryIntegrationTest extends ContextBasedTest { allTheseRbacPermissionsAreReturned( result, // @formatter:off - "test_customer#xxx:TENANT -> test_customer#xxx: SELECT", - // "test_customer#xxx:ADMIN -> test_customer#xxx: view" - Not permissions through the customer admin! - "test_package#xxx00:ADMIN -> test_package#xxx00: INSERT:test_domain", - "test_package#xxx00:TENANT -> test_package#xxx00: SELECT" + "rbactest.customer#xxx:TENANT -> rbactest.customer#xxx: SELECT", + // "rbactest.customer#xxx:ADMIN -> rbactest.customer#xxx: view" - Not permissions through the customer admin! + "rbactest.package#xxx00:ADMIN -> rbactest.package#xxx00: INSERT:rbactest.domain", + "rbactest.package#xxx00:TENANT -> rbactest.package#xxx00: SELECT" // @formatter:on ); noneOfTheseRbacPermissionsAreReturned( result, // @formatter:off // no customer admin permissions - "test_customer#xxx:ADMIN -> test_customer#xxx: add-package", + "rbactest.customer#xxx:ADMIN -> rbactest.customer#xxx: add-package", // no permissions on other customer's objects - "test_customer#yyy:ADMIN -> test_customer#yyy: add-package", - "test_customer#yyy:ADMIN -> test_customer#yyy: SELECT", - "test_customer#yyy:TENANT -> test_customer#yyy: SELECT", - "test_package#yyy00:ADMIN -> test_package#yyy00: INSERT:test_domain", - "test_package#yyy00:ADMIN -> test_package#yyy00: INSERT:test_domain", - "test_package#yyy00:TENANT -> test_package#yyy00: SELECT", - "test_domain#yyy00-aaaa:OWNER -> test_domain#yyy00-aaaa: DELETE", - "test_domain#yyy00-xxxb:OWNER -> test_domain#yyy00-xxxb: DELETE" + "rbactest.customer#yyy:ADMIN -> rbactest.customer#yyy: add-package", + "rbactest.customer#yyy:ADMIN -> rbactest.customer#yyy: SELECT", + "rbactest.customer#yyy:TENANT -> rbactest.customer#yyy: SELECT", + "rbactest.package#yyy00:ADMIN -> rbactest.package#yyy00: INSERT:rbactest.domain", + "rbactest.package#yyy00:ADMIN -> rbactest.package#yyy00: INSERT:rbactest.domain", + "rbactest.package#yyy00:TENANT -> rbactest.package#yyy00: SELECT", + "rbactest.domain#yyy00-aaaa:OWNER -> rbactest.domain#yyy00-aaaa: DELETE", + "rbactest.domain#yyy00-xxxb:OWNER -> rbactest.domain#yyy00-xxxb: DELETE" // @formatter:on ); } diff --git a/src/test/java/net/hostsharing/hsadminng/rbac/test/cust/TestCustomerControllerAcceptanceTest.java b/src/test/java/net/hostsharing/hsadminng/rbac/test/cust/TestCustomerControllerAcceptanceTest.java index 89783f25..cf61003f 100644 --- a/src/test/java/net/hostsharing/hsadminng/rbac/test/cust/TestCustomerControllerAcceptanceTest.java +++ b/src/test/java/net/hostsharing/hsadminng/rbac/test/cust/TestCustomerControllerAcceptanceTest.java @@ -89,7 +89,7 @@ class TestCustomerControllerAcceptanceTest { RestAssured // @formatter:off .given() .header("current-subject", "superuser-alex@hostsharing.net") - .header("assumed-roles", "test_customer#yyy:ADMIN") + .header("assumed-roles", "rbactest.customer#yyy:ADMIN") .port(port) .when() .get("http://localhost/api/test/customers") @@ -148,7 +148,7 @@ class TestCustomerControllerAcceptanceTest { // finally, the new customer can be viewed by its own admin final var newSubjectUuid = UUID.fromString( location.substring(location.lastIndexOf('/') + 1)); - context.define("superuser-fran@hostsharing.net", "test_customer#uuu:ADMIN"); + context.define("superuser-fran@hostsharing.net", "rbactest.customer#uuu:ADMIN"); assertThat(testCustomerRepository.findByUuid(newSubjectUuid)) .hasValueSatisfying(c -> assertThat(c.getPrefix()).isEqualTo("uuu")); } @@ -159,7 +159,7 @@ class TestCustomerControllerAcceptanceTest { RestAssured // @formatter:off .given() .header("current-subject", "superuser-alex@hostsharing.net") - .header("assumed-roles", "test_customer#xxx:ADMIN") + .header("assumed-roles", "rbactest.customer#xxx:ADMIN") .contentType(ContentType.JSON) .body(""" { @@ -175,8 +175,8 @@ class TestCustomerControllerAcceptanceTest { .statusCode(403) .contentType(ContentType.JSON) .statusCode(403) - .body("message", containsString("ERROR: [403] insert into test_customer ")) - .body("message", containsString(" not allowed for current subjects {test_customer#xxx:ADMIN}")); + .body("message", containsString("ERROR: [403] insert into rbactest.customer ")) + .body("message", containsString(" not allowed for current subjects {rbactest.customer#xxx:ADMIN}")); // @formatter:on // finally, the new customer was not created @@ -205,7 +205,7 @@ class TestCustomerControllerAcceptanceTest { .statusCode(403) .contentType(ContentType.JSON) .statusCode(403) - .body("message", containsString("ERROR: [403] insert into test_customer ")) + .body("message", containsString("ERROR: [403] insert into rbactest.customer ")) .body("message", containsString(" not allowed for current subjects")); // @formatter:on diff --git a/src/test/java/net/hostsharing/hsadminng/rbac/test/cust/TestCustomerRepositoryIntegrationTest.java b/src/test/java/net/hostsharing/hsadminng/rbac/test/cust/TestCustomerRepositoryIntegrationTest.java index 831a2976..245278da 100644 --- a/src/test/java/net/hostsharing/hsadminng/rbac/test/cust/TestCustomerRepositoryIntegrationTest.java +++ b/src/test/java/net/hostsharing/hsadminng/rbac/test/cust/TestCustomerRepositoryIntegrationTest.java @@ -54,7 +54,7 @@ class TestCustomerRepositoryIntegrationTest extends ContextBasedTest { @Test public void globalAdmin_withAssumedCustomerRole_cannotCreateNewCustomer() { // given - context("superuser-alex@hostsharing.net", "test_customer#xxx:ADMIN"); + context("superuser-alex@hostsharing.net", "rbactest.customer#xxx:ADMIN"); // when final var result = attempt(em, () -> { @@ -66,8 +66,8 @@ class TestCustomerRepositoryIntegrationTest extends ContextBasedTest { // then result.assertExceptionWithRootCauseMessage( PersistenceException.class, - "ERROR: [403] insert into test_customer ", - "not allowed for current subjects {test_customer#xxx:ADMIN}"); + "ERROR: [403] insert into rbactest.customer ", + "not allowed for current subjects {rbactest.customer#xxx:ADMIN}"); } @Test @@ -85,7 +85,7 @@ class TestCustomerRepositoryIntegrationTest extends ContextBasedTest { // then result.assertExceptionWithRootCauseMessage( PersistenceException.class, - "ERROR: [403] insert into test_customer ", + "ERROR: [403] insert into rbactest.customer ", " not allowed for current subjects {customer-admin@xxx.example.com}"); } @@ -114,7 +114,7 @@ class TestCustomerRepositoryIntegrationTest extends ContextBasedTest { @Test public void globalAdmin_withAssumedCustomerOwnerRole_canViewExactlyThatCustomer() { given: - context("superuser-alex@hostsharing.net", "test_customer#yyy:OWNER"); + context("superuser-alex@hostsharing.net", "rbactest.customer#yyy:OWNER"); // when final var result = testCustomerRepository.findCustomerByOptionalPrefixLike(null); @@ -139,7 +139,7 @@ class TestCustomerRepositoryIntegrationTest extends ContextBasedTest { public void customerAdmin_withAssumedOwnedPackageAdminRole_canViewOnlyItsOwnCustomer() { context("customer-admin@xxx.example.com"); - context("customer-admin@xxx.example.com", "test_package#xxx00:ADMIN"); + context("customer-admin@xxx.example.com", "rbactest.package#xxx00:ADMIN"); final var result = testCustomerRepository.findCustomerByOptionalPrefixLike(null); diff --git a/src/test/java/net/hostsharing/hsadminng/rbac/test/pac/TestPackageControllerAcceptanceTest.java b/src/test/java/net/hostsharing/hsadminng/rbac/test/pac/TestPackageControllerAcceptanceTest.java index fd9ec9a0..b76cc849 100644 --- a/src/test/java/net/hostsharing/hsadminng/rbac/test/pac/TestPackageControllerAcceptanceTest.java +++ b/src/test/java/net/hostsharing/hsadminng/rbac/test/pac/TestPackageControllerAcceptanceTest.java @@ -44,7 +44,7 @@ class TestPackageControllerAcceptanceTest { RestAssured .given() .header("current-subject", "superuser-alex@hostsharing.net") - .header("assumed-roles", "test_customer#xxx:ADMIN") + .header("assumed-roles", "rbactest.customer#xxx:ADMIN") .port(port) .when() .get("http://localhost/api/test/packages") @@ -66,7 +66,7 @@ class TestPackageControllerAcceptanceTest { RestAssured .given() .header("current-subject", "superuser-alex@hostsharing.net") - .header("assumed-roles", "test_customer#xxx:ADMIN") + .header("assumed-roles", "rbactest.customer#xxx:ADMIN") .port(port) .when() .get("http://localhost/api/test/packages?name=xxx01") @@ -95,7 +95,7 @@ class TestPackageControllerAcceptanceTest { RestAssured .given() .header("current-subject", "superuser-alex@hostsharing.net") - .header("assumed-roles", "test_customer#xxx:ADMIN") + .header("assumed-roles", "rbactest.customer#xxx:ADMIN") .contentType(ContentType.JSON) .body(format(""" { @@ -126,7 +126,7 @@ class TestPackageControllerAcceptanceTest { RestAssured .given() .header("current-subject", "superuser-alex@hostsharing.net") - .header("assumed-roles", "test_customer#xxx:ADMIN") + .header("assumed-roles", "rbactest.customer#xxx:ADMIN") .contentType(ContentType.JSON) .body(""" { @@ -156,7 +156,7 @@ class TestPackageControllerAcceptanceTest { RestAssured .given() .header("current-subject", "superuser-alex@hostsharing.net") - .header("assumed-roles", "test_customer#xxx:ADMIN") + .header("assumed-roles", "rbactest.customer#xxx:ADMIN") .contentType(ContentType.JSON) .body("{}") .port(port) @@ -176,7 +176,7 @@ class TestPackageControllerAcceptanceTest { return UUID.fromString(RestAssured .given() .header("current-subject", "superuser-alex@hostsharing.net") - .header("assumed-roles", "test_customer#xxx:ADMIN") + .header("assumed-roles", "rbactest.customer#xxx:ADMIN") .port(port) .when() .get("http://localhost/api/test/packages?name={packageName}", packageName) @@ -188,7 +188,7 @@ class TestPackageControllerAcceptanceTest { } String getDescriptionOfPackage(final String packageName) { - context.define("superuser-alex@hostsharing.net","test_customer#xxx:ADMIN"); + context.define("superuser-alex@hostsharing.net","rbactest.customer#xxx:ADMIN"); return testPackageRepository.findAllByOptionalNameLike(packageName).get(0).getDescription(); } } diff --git a/src/test/java/net/hostsharing/hsadminng/rbac/test/pac/TestPackageRepositoryIntegrationTest.java b/src/test/java/net/hostsharing/hsadminng/rbac/test/pac/TestPackageRepositoryIntegrationTest.java index e4f0e6fb..aea12049 100644 --- a/src/test/java/net/hostsharing/hsadminng/rbac/test/pac/TestPackageRepositoryIntegrationTest.java +++ b/src/test/java/net/hostsharing/hsadminng/rbac/test/pac/TestPackageRepositoryIntegrationTest.java @@ -76,7 +76,7 @@ class TestPackageRepositoryIntegrationTest extends ContextBasedTest { @Test public void customerAdmin_withAssumedOwnedPackageAdminRole_canViewOnlyItsOwnPackages() { - context.define("customer-admin@xxx.example.com", "test_package#xxx00:ADMIN"); + context.define("customer-admin@xxx.example.com", "rbactest.package#xxx00:ADMIN"); final var result = testPackageRepository.findAllByOptionalNameLike(null); @@ -90,17 +90,17 @@ class TestPackageRepositoryIntegrationTest extends ContextBasedTest { @Test public void supportsOptimisticLocking() { // given - globalAdminWithAssumedRole("test_package#xxx00:ADMIN"); + globalAdminWithAssumedRole("rbactest.package#xxx00:ADMIN"); final var pac = testPackageRepository.findAllByOptionalNameLike("%").get(0); // when final var result1 = jpaAttempt.transacted(() -> { - globalAdminWithAssumedRole("test_package#xxx00:OWNER"); + globalAdminWithAssumedRole("rbactest.package#xxx00:OWNER"); pac.setDescription("description set by thread 1"); testPackageRepository.save(pac); }); final var result2 = jpaAttempt.transacted(() -> { - globalAdminWithAssumedRole("test_package#xxx00:OWNER"); + globalAdminWithAssumedRole("rbactest.package#xxx00:OWNER"); pac.setDescription("description set by thread 2"); testPackageRepository.save(pac); sleep(1500); diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml index 7c3d2cff..923c62e9 100644 --- a/src/test/resources/application.yml +++ b/src/test/resources/application.yml @@ -5,6 +5,7 @@ spring: datasource: url-tc: jdbc:tc:postgresql:15.5-bookworm:///spring_boot_testcontainers + url-tcx: jdbc:tc:postgresql:15.5-bookworm:///spring_boot_testcontainers?TC_REUSABLE=true&TC_DAEMON=true url-local: jdbc:postgresql://localhost:5432/postgres url: ${spring.datasource.url-tc} username: postgres From 23b60641e38e9299eec49c1aa525bccc2148c2b3 Mon Sep 17 00:00:00 2001 From: Michael Hoennig Date: Wed, 18 Sep 2024 10:28:21 +0200 Subject: [PATCH 4/4] introduce-separate-database-schema-hs-office-and-amend-generators (#105) Co-authored-by: Michael Hoennig Reviewed-on: https://dev.hostsharing.net/hostsharing/hs.hsadmin.ng/pulls/105 Reviewed-by: Marc Sandlus --- doc/rbac-performance-analysis.md | 38 +++--- .../booking/item/HsBookingItemRbacEntity.java | 4 +- .../hs/booking/project/HsBookingProject.java | 8 +- .../project/HsBookingProjectRbacEntity.java | 6 +- .../asset/HsHostingAssetRbacEntity.java | 4 +- .../HsOfficeBankAccountEntity.java | 2 +- .../contact/HsOfficeContactRbacEntity.java | 2 +- .../contact/HsOfficeContactRealEntity.java | 2 +- .../HsOfficeCoopAssetsTransactionEntity.java | 2 +- .../HsOfficeCoopSharesTransactionEntity.java | 2 +- .../office/debitor/HsOfficeDebitorEntity.java | 20 +-- .../membership/HsOfficeMembershipEntity.java | 10 +- .../partner/HsOfficePartnerDetailsEntity.java | 8 +- .../office/partner/HsOfficePartnerEntity.java | 2 +- .../office/person/HsOfficePersonEntity.java | 2 +- .../relation/HsOfficeRelationRbacEntity.java | 8 +- .../HsOfficeRelationRbacRepository.java | 4 +- .../relation/HsOfficeRelationRealEntity.java | 2 +- .../HsOfficeRelationRealRepository.java | 4 +- .../HsOfficeSepaMandateEntity.java | 10 +- .../generator/InsertTriggerGenerator.java | 4 +- .../hsadminng/rbac/generator/RbacView.java | 12 +- .../RolesGrantsAndPermissionsGenerator.java | 73 ++++++----- .../db/changelog/1-rbac/1050-rbac-base.sql | 2 +- .../2013-rbactest-customer-rbac.sql | 12 +- .../2023-rbactest-package-rbac.sql | 22 ++-- .../2033-rbactest-domain-rbac.sql | 22 ++-- .../5-hs-office/500-hs-office-schema.sql | 8 ++ .../501-contact/5010-hs-office-contact.sql | 4 +- .../5013-hs-office-contact-rbac.sql | 36 +++--- .../5016-hs-office-contact-migration.sql | 26 ++-- .../5018-hs-office-contact-test-data.sql | 2 +- .../502-person/5020-hs-office-person.sql | 4 +- .../502-person/5023-hs-office-person-rbac.sql | 24 ++-- .../5028-hs-office-person-test-data.sql | 2 +- .../503-relation/5030-hs-office-relation.sql | 10 +- .../5033-hs-office-relation-rbac.sql | 120 +++++++++--------- .../5038-hs-office-relation-test-data.sql | 22 ++-- .../504-partner/5040-hs-office-partner.sql | 24 ++-- .../5043-hs-office-partner-rbac.sql | 96 +++++++------- .../5044-hs-office-partner-details-rbac.sql | 60 ++++----- .../5046-hs-office-partner-migration.sql | 26 ++-- .../5048-hs-office-partner-test-data.sql | 18 +-- .../5050-hs-office-bankaccount.sql | 4 +- .../5053-hs-office-bankaccount-rbac.sql | 24 ++-- .../5058-hs-office-bankaccount-test-data.sql | 2 +- .../506-debitor/5060-hs-office-debitor.sql | 20 +-- .../5063-hs-office-debitor-rbac.sql | 96 +++++++------- .../5068-hs-office-debitor-test-data.sql | 8 +- .../5070-hs-office-sepamandate.sql | 8 +- .../5073-hs-office-sepamandate-rbac.sql | 82 ++++++------ .../5076-hs-office-sepamandate-migration.sql | 26 ++-- .../5078-hs-office-sepamandate-test-data.sql | 16 +-- .../5100-hs-office-membership.sql | 6 +- .../5103-hs-office-membership-rbac.sql | 64 +++++----- .../5108-hs-office-membership-test-data.sql | 6 +- .../5110-hs-office-coopshares.sql | 18 +-- .../5113-hs-office-coopshares-rbac.sql | 66 +++++----- .../5116-hs-office-coopshares-migration.sql | 26 ++-- .../5118-hs-office-coopshares-test-data.sql | 8 +- .../5120-hs-office-coopassets.sql | 18 +-- .../5123-hs-office-coopassets-rbac.sql | 66 +++++----- .../5126-hs-office-coopassets-migration.sql | 26 ++-- .../5128-hs-office-coopassets-test-data.sql | 8 +- .../6100-hs-booking-debitor.sql | 8 +- .../6200-hs-booking-project.sql | 2 +- .../6203-hs-booking-project-rbac.sql | 60 ++++----- .../6208-hs-booking-project-test-data.sql | 10 +- .../6303-hs-booking-item-rbac.sql | 56 ++++---- .../7010-hs-hosting-asset.sql | 2 +- .../7013-hs-hosting-asset-rbac.sql | 44 +++---- .../7018-hs-hosting-asset-test-data.sql | 4 +- .../db/changelog/db.changelog-master.yaml | 2 + ...okingProjectRepositoryIntegrationTest.java | 4 +- .../hs/migration/BaseOfficeDataImport.java | 14 +- .../hsadminng/hs/migration/CsvDataImport.java | 38 +++--- ...eBankAccountRepositoryIntegrationTest.java | 28 ++-- ...eContactRbacRepositoryIntegrationTest.java | 30 ++--- ...tsTransactionControllerAcceptanceTest.java | 4 +- ...sTransactionRepositoryIntegrationTest.java | 32 ++--- ...esTransactionControllerAcceptanceTest.java | 4 +- ...sTransactionRepositoryIntegrationTest.java | 32 ++--- ...OfficeDebitorControllerAcceptanceTest.java | 4 +- ...fficeDebitorRepositoryIntegrationTest.java | 66 +++++----- ...iceMembershipControllerAcceptanceTest.java | 6 +- ...ceMembershipRepositoryIntegrationTest.java | 28 ++-- ...fficePartnerRepositoryIntegrationTest.java | 44 +++---- ...OfficePersonRepositoryIntegrationTest.java | 32 ++--- ...ficeRelationRepositoryIntegrationTest.java | 62 ++++----- ...eSepaMandateRepositoryIntegrationTest.java | 30 ++--- ...acGrantsDiagramServiceIntegrationTest.java | 4 +- 91 files changed, 1015 insertions(+), 1002 deletions(-) create mode 100644 src/main/resources/db/changelog/5-hs-office/500-hs-office-schema.sql diff --git a/doc/rbac-performance-analysis.md b/doc/rbac-performance-analysis.md index 6cfcdf47..a37f24db 100644 --- a/doc/rbac-performance-analysis.md +++ b/doc/rbac-performance-analysis.md @@ -206,14 +206,14 @@ Limit (cost=6549.08..6549.35 rows=54 width=16) ```SQL SELECT hore1_0.uuid,a1_0.uuid,a1_0.familyname,a1_0.givenname,a1_0.persontype,a1_0.salutation,a1_0.title,a1_0.tradename,a1_0.version,c1_0.uuid,c1_0.caption,c1_0.emailaddresses,c1_0.phonenumbers,c1_0.postaladdress,c1_0.version,h1_0.uuid,h1_0.familyname,h1_0.givenname,h1_0.persontype,h1_0.salutation,h1_0.title,h1_0.tradename,h1_0.version,hore1_0.mark,hore1_0.type,hore1_0.version - FROM hs_office_relation_rv hore1_0 - LEFT JOIN hs_office_person_rv a1_0 ON a1_0.uuid=hore1_0.anchoruuid - LEFT JOIN hs_office_contact_rv c1_0 ON c1_0.uuid=hore1_0.contactuuid - LEFT JOIN hs_office_person_rv h1_0 ON h1_0.uuid=hore1_0.holderuuid + FROM hs_office.relation_rv hore1_0 + LEFT JOIN hs_office.person_rv a1_0 ON a1_0.uuid=hore1_0.anchoruuid + LEFT JOIN hs_office.contact_rv c1_0 ON c1_0.uuid=hore1_0.contactuuid + LEFT JOIN hs_office.person_rv h1_0 ON h1_0.uuid=hore1_0.holderuuid WHERE hore1_0.uuid=$1 ``` -That query on the `hs_office_relation_rv`-table joins the three references anchor-person, holder-person and contact. +That query on the `hs_office.relation_rv`-table joins the three references anchor-person, holder-person and contact. ### Total-Query-Time > Total-Import-Runtime @@ -270,16 +270,16 @@ At this point, the import took 21mins with these statistics: | query | calls | total_m | mean_ms | |-------|-------|---------|---------| -| select hore1_0.uuid,a1_0.uuid,a1_0.familyname,a1_0.givenname,a1_0.persontype,a1_0.salutation,a1_0.title,a1_0.tradename,a1_0.version,c1_0.uuid,c1_0.caption,c1_0.emailaddresses,c1_0.phonenumbers,c1_0.postaladdress, c1_0.version,h1_0.uuid,h1_0.familyname,h1_0.givenname,h1_0.persontype,h1_0.salutation,h1_0.title,h1_0.tradename,h1_0.version,hore1_0.mark,hore1_0.type,hore1_0.version from public.hs_office_relation_rv hore1_0 left join public.hs_office_person_rv a1_0 on a1_0.uuid=hore1_0.anchoruuid left join public.hs_office_contact_rv c1_0 on c1_0.uuid=hore1_0.contactuuid left join public.hs_office_person_rv h1_0 on h1_0.uuid=hore1_0.holderuuid where hore1_0.uuid=$1 | 517 | 11 | 1282 | -| select hope1_0.uuid,hope1_0.familyname,hope1_0.givenname,hope1_0.persontype,hope1_0.salutation,hope1_0.title,hope1_0.tradename,hope1_0.version from public.hs_office_person_rv hope1_0 where hope1_0.uuid=$1 | 973 | 4 | 254 | -| select hoce1_0.uuid,hoce1_0.caption,hoce1_0.emailaddresses,hoce1_0.phonenumbers,hoce1_0.postaladdress,hoce1_0.version from public.hs_office_contact_rv hoce1_0 where hoce1_0.uuid=$1 | 973 | 4 | 253 | +| select hore1_0.uuid,a1_0.uuid,a1_0.familyname,a1_0.givenname,a1_0.persontype,a1_0.salutation,a1_0.title,a1_0.tradename,a1_0.version,c1_0.uuid,c1_0.caption,c1_0.emailaddresses,c1_0.phonenumbers,c1_0.postaladdress, c1_0.version,h1_0.uuid,h1_0.familyname,h1_0.givenname,h1_0.persontype,h1_0.salutation,h1_0.title,h1_0.tradename,h1_0.version,hore1_0.mark,hore1_0.type,hore1_0.version from public.hs_office.relation_rv hore1_0 left join public.hs_office.person_rv a1_0 on a1_0.uuid=hore1_0.anchoruuid left join public.hs_office.contact_rv c1_0 on c1_0.uuid=hore1_0.contactuuid left join public.hs_office.person_rv h1_0 on h1_0.uuid=hore1_0.holderuuid where hore1_0.uuid=$1 | 517 | 11 | 1282 | +| select hope1_0.uuid,hope1_0.familyname,hope1_0.givenname,hope1_0.persontype,hope1_0.salutation,hope1_0.title,hope1_0.tradename,hope1_0.version from public.hs_office.person_rv hope1_0 where hope1_0.uuid=$1 | 973 | 4 | 254 | +| select hoce1_0.uuid,hoce1_0.caption,hoce1_0.emailaddresses,hoce1_0.phonenumbers,hoce1_0.postaladdress,hoce1_0.version from public.hs_office.contact_rv hoce1_0 where hoce1_0.uuid=$1 | 973 | 4 | 253 | | call rbac.grantRoleToRole(roleUuid, superRoleUuid, superRoleDesc.assumed) | 31316 | 0 | 1 | | call buildRbacSystemForHsHostingAsset(NEW) | 2258 | 0 | 7 | | select * from rbac.isGranted(array[granteeId], grantedId) | 44613 | 0 | 0 | | insert into public.hs_hosting_asset_rv (alarmcontactuuid,assignedtoassetuuid,bookingitemuuid,caption,config,identifier,parentassetuuid,type,version,uuid) values ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10) | 2207 | 0 | 7 | | insert into hs_hosting_asset (alarmcontactuuid, version, bookingitemuuid, type, parentassetuuid, assignedtoassetuuid, config, uuid, identifier, caption) values (new.alarmcontactuuid, new. version, new. bookingitemuuid, new. type, new. parentassetuuid, new. assignedtoassetuuid, new. config, new. uuid, new. identifier, new. caption) returning * | 2207 | 0 | 7 | -| insert into public.hs_office_relation_rv (anchoruuid,contactuuid,holderuuid,mark,type,version,uuid) values ($1,$2,$3,$4,$5,$6,$7) | 1261 | 0 | 9 | -| insert into hs_office_relation (uuid, version, anchoruuid, holderuuid, contactuuid, type, mark) values (new.uuid, new. version, new. anchoruuid, new. holderuuid, new. contactuuid, new. type, new. mark) returning * | 1261 | 0 | 9 | +| insert into public.hs_office.relation_rv (anchoruuid,contactuuid,holderuuid,mark,type,version,uuid) values ($1,$2,$3,$4,$5,$6,$7) | 1261 | 0 | 9 | +| insert into hs_office.relation (uuid, version, anchoruuid, holderuuid, contactuuid, type, mark) values (new.uuid, new. version, new. anchoruuid, new. holderuuid, new. contactuuid, new. type, new. mark) returning * | 1261 | 0 | 9 | | call buildRbacSystemForHsOfficeRelation(NEW) | 1276 | 0 | 8 | | with recursive grants as ( select descendantUuid, ascendantUuid from RbacGrants where descendantUuid = grantedId union all select ""grant"".descendantUuid, ""grant"".ascendantUuid from RbacGrants ""grant"" inner join grants recur on recur.ascendantUuid = ""grant"".descendantUuid ) select exists ( select $3 from grants where ascendantUuid = any(granteeIds) ) or grantedId = any(granteeIds) | 47540 | 0 | 0 | | insert into RbacGrants (grantedByTriggerOf, ascendantuuid, descendantUuid, assumed) values (currentTriggerObjectUuid(), superRoleId, subRoleId, doAssume) on conflict do nothing" | 40472 | 0 | 0 | @@ -294,17 +294,17 @@ We changed these mappings from `EAGER` (default) to `LAZY` to `@ManyToOne(fetch :::small | query | calls | total (min) | mean (ms) | |-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------|-------------|----------| -| select hope1_0.uuid,hope1_0.familyname,hope1_0.givenname,hope1_0.persontype,hope1_0.salutation,hope1_0.title,hope1_0.tradename,hope1_0.version from public.hs_office_person_rv hope1_0 where hope1_0.uuid=$1 | 1015 | 4 | 238 | -| select hore1_0.uuid,hore1_0.anchoruuid,hore1_0.contactuuid,hore1_0.holderuuid,hore1_0.mark,hore1_0.type,hore1_0.version from public.hs_office_relation_rv hore1_0 where hore1_0.uuid=$1 | 517 | 4 | 439 | -| select hoce1_0.uuid,hoce1_0.caption,hoce1_0.emailaddresses,hoce1_0.phonenumbers,hoce1_0.postaladdress,hoce1_0.version from public.hs_office_contact_rv hoce1_0 where hoce1_0.uuid=$1 | 497 | 2 | 213 | +| select hope1_0.uuid,hope1_0.familyname,hope1_0.givenname,hope1_0.persontype,hope1_0.salutation,hope1_0.title,hope1_0.tradename,hope1_0.version from public.hs_office.person_rv hope1_0 where hope1_0.uuid=$1 | 1015 | 4 | 238 | +| select hore1_0.uuid,hore1_0.anchoruuid,hore1_0.contactuuid,hore1_0.holderuuid,hore1_0.mark,hore1_0.type,hore1_0.version from public.hs_office.relation_rv hore1_0 where hore1_0.uuid=$1 | 517 | 4 | 439 | +| select hoce1_0.uuid,hoce1_0.caption,hoce1_0.emailaddresses,hoce1_0.phonenumbers,hoce1_0.postaladdress,hoce1_0.version from public.hs_office.contact_rv hoce1_0 where hoce1_0.uuid=$1 | 497 | 2 | 213 | | call rbac.grantRoleToRole(roleUuid, superRoleUuid, superRoleDesc.assumed) | 31316 | 0 | 1 | | select * from rbac.isGranted(array[granteeId], grantedId) | 44613 | 0 | 0 | | call buildRbacSystemForHsHostingAsset(NEW) | 2258 | 0 | 7 | | insert into public.hs_hosting_asset_rv (alarmcontactuuid,assignedtoassetuuid,bookingitemuuid,caption,config,identifier,parentassetuuid,type,version,uuid) values ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10) | 2207 | 0 | 7 | | insert into hs_hosting_asset (alarmcontactuuid, version, bookingitemuuid, type, parentassetuuid, assignedtoassetuuid, config, uuid, identifier, caption) values (new.alarmcontactuuid, new. version, new. bookingitemuuid, new. type, new. parentassetuuid, new. assignedtoassetuuid, new. config, new. uuid, new. identifier, new. caption) returning * | 2207 | 0 | 7 | | with recursive grants as ( select descendantUuid, ascendantUuid from RbacGrants where descendantUuid = grantedId union all select ""grant"".descendantUuid, ""grant"".ascendantUuid from RbacGrants ""grant"" inner join grants recur on recur.ascendantUuid = ""grant"".descendantUuid ) select exists ( select $3 from grants where ascendantUuid = any(granteeIds) ) or grantedId = any(granteeIds) | 47538 | 0 | 0 | - insert into public.hs_office_relation_rv (anchoruuid,contactuuid,holderuuid,mark,type,version,uuid) values ($1,$2,$3,$4,$5,$6,$7) | 1261 | 0 | 8 | -| insert into hs_office_relation (uuid, version, anchoruuid, holderuuid, contactuuid, type, mark) values (new.uuid, new. version, new. anchoruuid, new. holderuuid, new. contactuuid, new. type, new. mark) returning * | 1261 | 0 | 8 | + insert into public.hs_office.relation_rv (anchoruuid,contactuuid,holderuuid,mark,type,version,uuid) values ($1,$2,$3,$4,$5,$6,$7) | 1261 | 0 | 8 | +| insert into hs_office.relation (uuid, version, anchoruuid, holderuuid, contactuuid, type, mark) values (new.uuid, new. version, new. anchoruuid, new. holderuuid, new. contactuuid, new. type, new. mark) returning * | 1261 | 0 | 8 | | call buildRbacSystemForHsOfficeRelation(NEW) | 1276 | 0 | 7 | | insert into public.hs_booking_item_rv (caption,parentitemuuid,projectuuid,resources,type,validity,version,uuid) values ($1,$2,$3,$4,$5,$6,$7,$8) | 926 | 0 | 7 | | insert into hs_booking_item (resources, version, projectuuid, type, parentitemuuid, validity, uuid, caption) values (new.resources, new. version, new. projectuuid, new. type, new. parentitemuuid, new. validity, new. uuid, new. caption) returning * | 926 | 0 | 7 | @@ -331,13 +331,13 @@ Now, the longest running queries are these: | No.| calls | total_m | mean_ms | query | |---:|---------|--------:|--------:|:-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | 1 | 13.093 | 4 | 21 | insert into hs_hosting_asset( uuid, type, bookingitemuuid, parentassetuuid, assignedtoassetuuid, alarmcontactuuid, identifier, caption, config, version) values ( $1, $2, $3, $4, $5, $6, $7, $8, cast($9 as jsonb), $10) | -| 2 | 517 | 4 | 502 | select hore1_0.uuid,hore1_0.anchoruuid,hore1_0.contactuuid,hore1_0.holderuuid,hore1_0.mark,hore1_0.type,hore1_0.version from public.hs_office_relation_rv hore1_0 where hore1_0.uuid=$1 | +| 2 | 517 | 4 | 502 | select hore1_0.uuid,hore1_0.anchoruuid,hore1_0.contactuuid,hore1_0.holderuuid,hore1_0.mark,hore1_0.type,hore1_0.version from public.hs_office.relation_rv hore1_0 where hore1_0.uuid=$1 | | 3 | 13.144 | 4 | 21 | call buildRbacSystemForHsHostingAsset(NEW) | | 4 | 96.632 | 3 | 2 | call rbac.grantRoleToRole(roleUuid, superRoleUuid, superRoleDesc.assumed) | | 5 | 120.815 | 3 | 2 | select * from rbac.isGranted(array[granteeId], grantedId) | | 6 | 123.740 | 3 | 2 | with recursive grants as ( select descendantUuid, ascendantUuid from RbacGrants where descendantUuid = grantedId union all select "grant".descendantUuid, "grant".ascendantUuid from RbacGrants "grant" inner join grants recur on recur.ascendantUuid = "grant".descendantUuid ) select exists ( select $3 from grants where ascendantUuid = any(granteeIds) ) or grantedId = any(granteeIds) | -| 7 | 497 | 2 | 259 | select hoce1_0.uuid,hoce1_0.caption,hoce1_0.emailaddresses,hoce1_0.phonenumbers,hoce1_0.postaladdress,hoce1_0.version from public.hs_office_contact_rv hoce1_0 where hoce1_0.uuid=$1 | -| 8 | 497 | 2 | 255 | select hope1_0.uuid,hope1_0.familyname,hope1_0.givenname,hope1_0.persontype,hope1_0.salutation,hope1_0.title,hope1_0.tradename,hope1_0.version from public.hs_office_person_rv hope1_0 where hope1_0.uuid=$1 | +| 7 | 497 | 2 | 259 | select hoce1_0.uuid,hoce1_0.caption,hoce1_0.emailaddresses,hoce1_0.phonenumbers,hoce1_0.postaladdress,hoce1_0.version from public.hs_office.contact_rv hoce1_0 where hoce1_0.uuid=$1 | +| 8 | 497 | 2 | 255 | select hope1_0.uuid,hope1_0.familyname,hope1_0.givenname,hope1_0.persontype,hope1_0.salutation,hope1_0.title,hope1_0.tradename,hope1_0.version from public.hs_office.person_rv hope1_0 where hope1_0.uuid=$1 | | 9 | 13.144 | 1 | 8 | SELECT createRoleWithGrants( hsHostingAssetTENANT(NEW), permissions => array[$7], incomingSuperRoles => array[ hsHostingAssetAGENT(NEW), hsOfficeContactADMIN(newAlarmContact)], outgoingSubRoles => array[ hsBookingItemTENANT(newBookingItem), hsHostingAssetTENANT(newParentAsset)] ) | | 10 | 13.144 | 1 | 5 | SELECT createRoleWithGrants( hsHostingAssetADMIN(NEW), permissions => array[$7], incomingSuperRoles => array[ hsBookingItemAGENT(newBookingItem), hsHostingAssetAGENT(newParentAsset), hsHostingAssetOWNER(NEW)] ) | @@ -345,7 +345,7 @@ That the `INSERT into hs_hosting_asset` (No. 1) takes up the most time, seems to It seems that the trigger effects (eg. No. 3 and No. 4) are included in the measure for the causing INSERT, otherwise summing up the totals would exceed the actual total time of the whole import. And it was to be expected that building the RBAC rules for new business objects takes most of the time. -In production, the `SELECT ... FROM hs_office_relation_rv` (No. 2) with about 0.5 seconds could still be a problem. But once we apply the improvements from the hosting asset area also to the office area, this should not be a problem for the import anymore. +In production, the `SELECT ... FROM hs_office.relation_rv` (No. 2) with about 0.5 seconds could still be a problem. But once we apply the improvements from the hosting asset area also to the office area, this should not be a problem for the import anymore. ## Further Options To Explore diff --git a/src/main/java/net/hostsharing/hsadminng/hs/booking/item/HsBookingItemRbacEntity.java b/src/main/java/net/hostsharing/hsadminng/hs/booking/item/HsBookingItemRbacEntity.java index b4f40cb2..250b65ef 100644 --- a/src/main/java/net/hostsharing/hsadminng/hs/booking/item/HsBookingItemRbacEntity.java +++ b/src/main/java/net/hostsharing/hsadminng/hs/booking/item/HsBookingItemRbacEntity.java @@ -4,7 +4,7 @@ import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.experimental.SuperBuilder; -import net.hostsharing.hsadminng.hs.booking.project.HsBookingProject; +import net.hostsharing.hsadminng.hs.booking.project.HsBookingProjectRbacEntity; import net.hostsharing.hsadminng.rbac.generator.RbacView; import net.hostsharing.hsadminng.rbac.generator.RbacView.SQL; @@ -49,7 +49,7 @@ public class HsBookingItemRbacEntity extends HsBookingItem { .toRole(GLOBAL, ADMIN).grantPermission(INSERT) // TODO.impl: Why is this necessary to insert test data? .toRole(GLOBAL, ADMIN).grantPermission(DELETE) - .importEntityAlias("project", HsBookingProject.class, usingDefaultCase(), + .importEntityAlias("project", HsBookingProjectRbacEntity.class, usingDefaultCase(), dependsOnColumn("projectUuid"), directlyFetchedByDependsOnColumn(), NULLABLE) diff --git a/src/main/java/net/hostsharing/hsadminng/hs/booking/project/HsBookingProject.java b/src/main/java/net/hostsharing/hsadminng/hs/booking/project/HsBookingProject.java index 935051fe..ae997f07 100644 --- a/src/main/java/net/hostsharing/hsadminng/hs/booking/project/HsBookingProject.java +++ b/src/main/java/net/hostsharing/hsadminng/hs/booking/project/HsBookingProject.java @@ -68,11 +68,11 @@ public abstract class HsBookingProject implements Stringifyable, BaseEntity, value = """ ( SELECT DISTINCT partner.uuid - FROM hs_office_partner_rv partner - JOIN hs_office_relation_rv dRel + FROM hs_office.partner_rv partner + JOIN hs_office.relation_rv dRel ON dRel.uuid = debitorreluuid AND dRel.type = 'DEBITOR' - JOIN hs_office_relation_rv pRel + JOIN hs_office.relation_rv pRel ON pRel.uuid = partner.partnerRelUuid AND pRel.type = 'PARTNER' WHERE pRel.holderUuid = dRel.anchorUuid ) @@ -170,14 +170,14 @@ public class HsOfficeDebitorEntity implements BaseEntity, .withIdentityView(SQL.query(""" SELECT debitor.uuid AS uuid, 'D-' || (SELECT partner.partnerNumber - FROM hs_office_partner partner - JOIN hs_office_relation partnerRel + FROM hs_office.partner partner + JOIN hs_office.relation partnerRel ON partnerRel.uuid = partner.partnerRelUUid AND partnerRel.type = 'PARTNER' - JOIN hs_office_relation debitorRel + JOIN hs_office.relation debitorRel ON debitorRel.anchorUuid = partnerRel.holderUuid AND debitorRel.type = 'DEBITOR' WHERE debitorRel.uuid = debitor.debitorRelUuid) || debitorNumberSuffix as idName - FROM hs_office_debitor AS debitor + FROM hs_office.debitor AS debitor """)) .withRestrictedViewOrderBy(SQL.projection("defaultPrefix")) .withUpdatableColumns( @@ -209,8 +209,8 @@ public class HsOfficeDebitorEntity implements BaseEntity, dependsOnColumn("debitorRelUuid"), fetchedBySql(""" SELECT ${columns} - FROM hs_office_relation AS partnerRel - JOIN hs_office_relation AS debitorRel + FROM hs_office.relation AS partnerRel + JOIN hs_office.relation AS debitorRel ON debitorRel.type = 'DEBITOR' AND debitorRel.anchorUuid = partnerRel.holderUuid WHERE partnerRel.type = 'PARTNER' AND ${REF}.debitorRelUuid = debitorRel.uuid diff --git a/src/main/java/net/hostsharing/hsadminng/hs/office/membership/HsOfficeMembershipEntity.java b/src/main/java/net/hostsharing/hsadminng/hs/office/membership/HsOfficeMembershipEntity.java index dae389f8..b8c238c1 100644 --- a/src/main/java/net/hostsharing/hsadminng/hs/office/membership/HsOfficeMembershipEntity.java +++ b/src/main/java/net/hostsharing/hsadminng/hs/office/membership/HsOfficeMembershipEntity.java @@ -56,7 +56,7 @@ import static net.hostsharing.hsadminng.rbac.generator.RbacView.rbacViewFor; import static net.hostsharing.hsadminng.stringify.Stringify.stringify; @Entity -@Table(name = "hs_office_membership_rv") +@Table(schema = "hs_office", name = "membership_rv") @Getter @Setter @Builder @@ -160,8 +160,8 @@ public class HsOfficeMembershipEntity implements BaseEntity findRelationRelatedToPersonUuid(@NotNull UUID personUuid); @Query(value = """ - SELECT p.* FROM hs_office_relation_rv AS p + SELECT p.* FROM hs_office.relation_rv AS p WHERE (:relationType IS NULL OR p.type = cast(:relationType AS HsOfficeRelationType)) AND ( p.anchorUuid = :personUuid OR p.holderUuid = :personUuid) """, nativeQuery = true) diff --git a/src/main/java/net/hostsharing/hsadminng/hs/office/relation/HsOfficeRelationRealEntity.java b/src/main/java/net/hostsharing/hsadminng/hs/office/relation/HsOfficeRelationRealEntity.java index 3c6c71a9..0c7c3e4d 100644 --- a/src/main/java/net/hostsharing/hsadminng/hs/office/relation/HsOfficeRelationRealEntity.java +++ b/src/main/java/net/hostsharing/hsadminng/hs/office/relation/HsOfficeRelationRealEntity.java @@ -11,7 +11,7 @@ import jakarta.persistence.Table; @Entity -@Table(name = "hs_office_relation") +@Table(schema = "hs_office", name = "relation") @NoArgsConstructor @Getter @Setter diff --git a/src/main/java/net/hostsharing/hsadminng/hs/office/relation/HsOfficeRelationRealRepository.java b/src/main/java/net/hostsharing/hsadminng/hs/office/relation/HsOfficeRelationRealRepository.java index 6a24ad02..220ea6f4 100644 --- a/src/main/java/net/hostsharing/hsadminng/hs/office/relation/HsOfficeRelationRealRepository.java +++ b/src/main/java/net/hostsharing/hsadminng/hs/office/relation/HsOfficeRelationRealRepository.java @@ -17,13 +17,13 @@ public interface HsOfficeRelationRealRepository extends Repository findRelationRelatedToPersonUuid(@NotNull UUID personUuid); @Query(value = """ - SELECT p.* FROM hs_office_relation AS p + SELECT p.* FROM hs_office.relation AS p WHERE (:relationType IS NULL OR p.type = cast(:relationType AS HsOfficeRelationType)) AND ( p.anchorUuid = :personUuid OR p.holderUuid = :personUuid) """, nativeQuery = true) diff --git a/src/main/java/net/hostsharing/hsadminng/hs/office/sepamandate/HsOfficeSepaMandateEntity.java b/src/main/java/net/hostsharing/hsadminng/hs/office/sepamandate/HsOfficeSepaMandateEntity.java index e984ce3b..bd91c44d 100644 --- a/src/main/java/net/hostsharing/hsadminng/hs/office/sepamandate/HsOfficeSepaMandateEntity.java +++ b/src/main/java/net/hostsharing/hsadminng/hs/office/sepamandate/HsOfficeSepaMandateEntity.java @@ -33,7 +33,7 @@ import static net.hostsharing.hsadminng.rbac.generator.RbacView.rbacViewFor; import static net.hostsharing.hsadminng.stringify.Stringify.stringify; @Entity -@Table(name = "hs_office_sepamandate_rv") +@Table(schema = "hs_office", name = "sepamandate_rv") @Getter @Setter @Builder @@ -104,8 +104,8 @@ public class HsOfficeSepaMandateEntity implements Stringifyable, BaseEntity hsof.coopsharetx + // maybe we should shorten the table name e.g. hs_office.coopsharestransaction -> hsof.coopsharetx // this is just a workaround: return getRawTableName() - .replace("hs_office_", "hsof_") + .replace("hs_office.", "hsof.") .replace("hs_booking_", "hsbk_") .replace("hs_hosting_", "hsho_") .replace("coopsharestransaction", "coopsharetx") @@ -1274,13 +1273,14 @@ public class RbacView { public static Set> findRbacEntityClasses(String packageName) { final var reflections = new Reflections(packageName, TypeAnnotationsScanner.class); - return reflections.getTypesAnnotatedWith(Entity.class).stream() - .filter(c -> stream(c.getInterfaces()).anyMatch(i -> i== BaseEntity.class)) + final Set> rbacEntityClasses = reflections.getTypesAnnotatedWith(Entity.class).stream() + .filter(BaseEntity.class::isAssignableFrom) .filter(c -> stream(c.getDeclaredMethods()) - .anyMatch(m -> m.getName().equals("rbac") && Modifier.isStatic(m.getModifiers())) + .anyMatch(m -> m.getName().equals("rbac") && isStatic(m.getModifiers())) ) .map(RbacView::castToSubclassOfBaseEntity) .collect(Collectors.toSet()); + return rbacEntityClasses; } @SuppressWarnings("unchecked") diff --git a/src/main/java/net/hostsharing/hsadminng/rbac/generator/RolesGrantsAndPermissionsGenerator.java b/src/main/java/net/hostsharing/hsadminng/rbac/generator/RolesGrantsAndPermissionsGenerator.java index d183b181..22a9b9d3 100644 --- a/src/main/java/net/hostsharing/hsadminng/rbac/generator/RolesGrantsAndPermissionsGenerator.java +++ b/src/main/java/net/hostsharing/hsadminng/rbac/generator/RolesGrantsAndPermissionsGenerator.java @@ -29,7 +29,7 @@ class RolesGrantsAndPermissionsGenerator { private final String liquibaseTagPrefix; private final String simpleEntityName; private final String simpleEntityVarName; - private final String rawTableName; + private final String qualifiedRawTableName; RolesGrantsAndPermissionsGenerator(final RbacView rbacDef, final String liquibaseTagPrefix) { this.rbacDef = rbacDef; @@ -40,7 +40,7 @@ class RolesGrantsAndPermissionsGenerator { simpleEntityVarName = rbacDef.getRootEntityAlias().simpleName(); simpleEntityName = capitalize(simpleEntityVarName); - rawTableName = rbacDef.getRootEntityAlias().getRawTableNameWithSchema(); + qualifiedRawTableName = rbacDef.getRootEntityAlias().getRawTableNameWithSchema(); } void generateTo(final StringWriter plPgSql) { @@ -66,13 +66,12 @@ class RolesGrantsAndPermissionsGenerator { Creates the roles, grants and permission for the AFTER INSERT TRIGGER. */ - create or replace procedure buildRbacSystemFor${simpleEntityName}( - NEW ${rawTableName} + create or replace procedure ${rawTableQualifiedName}_build_rbac_system( + NEW ${rawTableQualifiedName} ) language plpgsql as $$ """ - .replace("${simpleEntityName}", simpleEntityName) - .replace("${rawTableName}", rawTableName)); + .replace("${rawTableQualifiedName}", qualifiedRawTableName)); plPgSql.writeLn("declare"); plPgSql.indented(() -> { @@ -106,21 +105,21 @@ class RolesGrantsAndPermissionsGenerator { Called from the AFTER UPDATE TRIGGER to re-wire the grants. */ - create or replace procedure updateRbacRulesFor${simpleEntityName}( - OLD ${rawTableName}, - NEW ${rawTableName} + create or replace procedure ${rawTableQualifiedName}_update_rbac_system( + OLD ${rawTableQualifiedName}, + NEW ${rawTableQualifiedName} ) language plpgsql as $$ begin if ${updateConditions} then delete from rbac.grants g where g.grantedbytriggerof = OLD.uuid; - call buildRbacSystemFor${simpleEntityName}(NEW); + call ${rawTableQualifiedName}_build_rbac_system(NEW); end if; end; $$; """, with("simpleEntityName", simpleEntityName), - with("rawTableName", rawTableName), + with("rawTableQualifiedName", qualifiedRawTableName), with("updateConditions", updateConditions)); } @@ -130,16 +129,15 @@ class RolesGrantsAndPermissionsGenerator { Called from the AFTER UPDATE TRIGGER to re-wire the grants. */ - create or replace procedure updateRbacRulesFor${simpleEntityName}( - OLD ${rawTableName}, - NEW ${rawTableName} + create or replace procedure ${rawTableQualifiedName}_update_rbac_system( + OLD ${rawTableQualifiedName}, + NEW ${rawTableQualifiedName} ) language plpgsql as $$ declare - """ - .replace("${simpleEntityName}", simpleEntityName) - .replace("${rawTableName}", rawTableName)); + """, + with("rawTableQualifiedName", qualifiedRawTableName)); plPgSql.chopEmptyLines(); plPgSql.indented(() -> { @@ -514,25 +512,25 @@ class RolesGrantsAndPermissionsGenerator { plPgSql.writeLn(""" /* - AFTER INSERT TRIGGER to create the role+grant structure for a new ${rawTableName} row. + AFTER INSERT TRIGGER to create the role+grant structure for a new ${rawTableQualifiedName} row. */ - create or replace function insertTriggerFor${simpleEntityName}_tf() + create or replace function ${rawTableQualifiedName}_build_rbac_system_after_insert_tf() returns trigger language plpgsql strict as $$ begin - call buildRbacSystemFor${simpleEntityName}(NEW); + call ${rawTableQualifiedName}_build_rbac_system(NEW); return NEW; end; $$; - create trigger insertTriggerFor${simpleEntityName}_tg - after insert on ${rawTableName} + create trigger build_rbac_system_after_insert_tg + after insert on ${rawTableQualifiedName} for each row - execute procedure insertTriggerFor${simpleEntityName}_tf(); + execute procedure ${rawTableQualifiedName}_build_rbac_system_after_insert_tf(); """ - .replace("${simpleEntityName}", simpleEntityName) - .replace("${rawTableName}", rawTableName) + .replace("${schemaPrefix}", schemaPrefix(qualifiedRawTableName)) + .replace("${rawTableQualifiedName}", qualifiedRawTableName) ); generateFooter(plPgSql); @@ -549,30 +547,35 @@ class RolesGrantsAndPermissionsGenerator { plPgSql.writeLn(""" /* - AFTER INSERT TRIGGER to re-wire the grant structure for a new ${rawTableName} row. + AFTER UPDATE TRIGGER to re-wire the grant structure for a new ${rawTableQualifiedName} row. */ - - create or replace function updateTriggerFor${simpleEntityName}_tf() + + create or replace function ${rawTableQualifiedName}_update_rbac_system_after_update_tf() returns trigger language plpgsql strict as $$ begin - call updateRbacRulesFor${simpleEntityName}(OLD, NEW); + call ${rawTableQualifiedName}_update_rbac_system(OLD, NEW); return NEW; end; $$; - - create trigger updateTriggerFor${simpleEntityName}_tg - after update on ${rawTableName} + + create trigger update_rbac_system_after_update_tg + after update on ${rawTableQualifiedName} for each row - execute procedure updateTriggerFor${simpleEntityName}_tf(); + execute procedure ${rawTableQualifiedName}_update_rbac_system_after_update_tf(); """ - .replace("${simpleEntityName}", simpleEntityName) - .replace("${rawTableName}", rawTableName) + .replace("${rawTableQualifiedName}", qualifiedRawTableName) ); generateFooter(plPgSql); } + private String schemaPrefix(final String qualifiedIdentifier) { + return qualifiedIdentifier.contains(".") + ? qualifiedIdentifier.split("\\.")[0] + "." + : ""; + } + private static void generateFooter(final StringWriter plPgSql) { plPgSql.writeLn("--//"); plPgSql.writeLn(); diff --git a/src/main/resources/db/changelog/1-rbac/1050-rbac-base.sql b/src/main/resources/db/changelog/1-rbac/1050-rbac-base.sql index b2e73ca1..6a403e08 100644 --- a/src/main/resources/db/changelog/1-rbac/1050-rbac-base.sql +++ b/src/main/resources/db/changelog/1-rbac/1050-rbac-base.sql @@ -384,7 +384,7 @@ create index on rbac.permission (objectUuid, op); create index on rbac.permission (opTableName, op); ALTER TABLE rbac.permission - ADD CONSTRAINT RbacPermission_uc UNIQUE NULLS NOT DISTINCT (objectUuid, op, opTableName); + ADD CONSTRAINT unique_including_null_values UNIQUE NULLS NOT DISTINCT (objectUuid, op, opTableName); call base.create_journal('rbac.permission'); diff --git a/src/main/resources/db/changelog/2-rbactest/201-rbactest-customer/2013-rbactest-customer-rbac.sql b/src/main/resources/db/changelog/2-rbactest/201-rbactest-customer/2013-rbactest-customer-rbac.sql index 35f64f4a..d7104eff 100644 --- a/src/main/resources/db/changelog/2-rbactest/201-rbactest-customer/2013-rbactest-customer-rbac.sql +++ b/src/main/resources/db/changelog/2-rbactest/201-rbactest-customer/2013-rbactest-customer-rbac.sql @@ -24,7 +24,7 @@ call rbac.generateRbacRoleDescriptors('testCustomer', 'rbactest.customer'); Creates the roles, grants and permission for the AFTER INSERT TRIGGER. */ -create or replace procedure buildRbacSystemForTestCustomer( +create or replace procedure rbactest.customer_build_rbac_system( NEW rbactest.customer ) language plpgsql as $$ @@ -60,19 +60,19 @@ end; $$; AFTER INSERT TRIGGER to create the role+grant structure for a new rbactest.customer row. */ -create or replace function insertTriggerForTestCustomer_tf() +create or replace function rbactest.customer_build_rbac_system_after_insert_tf() returns trigger language plpgsql strict as $$ begin - call buildRbacSystemForTestCustomer(NEW); + call rbactest.customer_build_rbac_system(NEW); return NEW; end; $$; -create trigger insertTriggerForTestCustomer_tg +create trigger build_rbac_system_after_insert_tg after insert on rbactest.customer for each row -execute procedure insertTriggerForTestCustomer_tf(); +execute procedure rbactest.customer_build_rbac_system_after_insert_tf(); --// @@ -137,7 +137,7 @@ create or replace function rbactest.customer_insert_permission_check_tf() declare superObjectUuid uuid; begin - -- check INSERT INSERT if rbac.global ADMIN + -- check INSERT permission if rbac.global ADMIN if rbac.isGlobalAdmin() then return NEW; end if; diff --git a/src/main/resources/db/changelog/2-rbactest/202-rbactest-package/2023-rbactest-package-rbac.sql b/src/main/resources/db/changelog/2-rbactest/202-rbactest-package/2023-rbactest-package-rbac.sql index 6fff59c6..91dd207b 100644 --- a/src/main/resources/db/changelog/2-rbactest/202-rbactest-package/2023-rbactest-package-rbac.sql +++ b/src/main/resources/db/changelog/2-rbactest/202-rbactest-package/2023-rbactest-package-rbac.sql @@ -24,7 +24,7 @@ call rbac.generateRbacRoleDescriptors('testPackage', 'rbactest.package'); Creates the roles, grants and permission for the AFTER INSERT TRIGGER. */ -create or replace procedure buildRbacSystemForTestPackage( +create or replace procedure rbactest.package_build_rbac_system( NEW rbactest.package ) language plpgsql as $$ @@ -64,19 +64,19 @@ end; $$; AFTER INSERT TRIGGER to create the role+grant structure for a new rbactest.package row. */ -create or replace function insertTriggerForTestPackage_tf() +create or replace function rbactest.package_build_rbac_system_after_insert_tf() returns trigger language plpgsql strict as $$ begin - call buildRbacSystemForTestPackage(NEW); + call rbactest.package_build_rbac_system(NEW); return NEW; end; $$; -create trigger insertTriggerForTestPackage_tg +create trigger build_rbac_system_after_insert_tg after insert on rbactest.package for each row -execute procedure insertTriggerForTestPackage_tf(); +execute procedure rbactest.package_build_rbac_system_after_insert_tf(); --// @@ -88,7 +88,7 @@ execute procedure insertTriggerForTestPackage_tf(); Called from the AFTER UPDATE TRIGGER to re-wire the grants. */ -create or replace procedure updateRbacRulesForTestPackage( +create or replace procedure rbactest.package_update_rbac_system( OLD rbactest.package, NEW rbactest.package ) @@ -122,22 +122,22 @@ begin end; $$; /* - AFTER INSERT TRIGGER to re-wire the grant structure for a new rbactest.package row. + AFTER UPDATE TRIGGER to re-wire the grant structure for a new rbactest.package row. */ -create or replace function updateTriggerForTestPackage_tf() +create or replace function rbactest.package_update_rbac_system_after_update_tf() returns trigger language plpgsql strict as $$ begin - call updateRbacRulesForTestPackage(OLD, NEW); + call rbactest.package_update_rbac_system(OLD, NEW); return NEW; end; $$; -create trigger updateTriggerForTestPackage_tg +create trigger update_rbac_system_after_update_tg after update on rbactest.package for each row -execute procedure updateTriggerForTestPackage_tf(); +execute procedure rbactest.package_update_rbac_system_after_update_tf(); --// diff --git a/src/main/resources/db/changelog/2-rbactest/203-rbactest-domain/2033-rbactest-domain-rbac.sql b/src/main/resources/db/changelog/2-rbactest/203-rbactest-domain/2033-rbactest-domain-rbac.sql index 69534c50..b20d12d6 100644 --- a/src/main/resources/db/changelog/2-rbactest/203-rbactest-domain/2033-rbactest-domain-rbac.sql +++ b/src/main/resources/db/changelog/2-rbactest/203-rbactest-domain/2033-rbactest-domain-rbac.sql @@ -24,7 +24,7 @@ call rbac.generateRbacRoleDescriptors('testDomain', 'rbactest.domain'); Creates the roles, grants and permission for the AFTER INSERT TRIGGER. */ -create or replace procedure buildRbacSystemForTestDomain( +create or replace procedure rbactest.domain_build_rbac_system( NEW rbactest.domain ) language plpgsql as $$ @@ -60,19 +60,19 @@ end; $$; AFTER INSERT TRIGGER to create the role+grant structure for a new rbactest.domain row. */ -create or replace function insertTriggerForTestDomain_tf() +create or replace function rbactest.domain_build_rbac_system_after_insert_tf() returns trigger language plpgsql strict as $$ begin - call buildRbacSystemForTestDomain(NEW); + call rbactest.domain_build_rbac_system(NEW); return NEW; end; $$; -create trigger insertTriggerForTestDomain_tg +create trigger build_rbac_system_after_insert_tg after insert on rbactest.domain for each row -execute procedure insertTriggerForTestDomain_tf(); +execute procedure rbactest.domain_build_rbac_system_after_insert_tf(); --// @@ -84,7 +84,7 @@ execute procedure insertTriggerForTestDomain_tf(); Called from the AFTER UPDATE TRIGGER to re-wire the grants. */ -create or replace procedure updateRbacRulesForTestDomain( +create or replace procedure rbactest.domain_update_rbac_system( OLD rbactest.domain, NEW rbactest.domain ) @@ -121,22 +121,22 @@ begin end; $$; /* - AFTER INSERT TRIGGER to re-wire the grant structure for a new rbactest.domain row. + AFTER UPDATE TRIGGER to re-wire the grant structure for a new rbactest.domain row. */ -create or replace function updateTriggerForTestDomain_tf() +create or replace function rbactest.domain_update_rbac_system_after_update_tf() returns trigger language plpgsql strict as $$ begin - call updateRbacRulesForTestDomain(OLD, NEW); + call rbactest.domain_update_rbac_system(OLD, NEW); return NEW; end; $$; -create trigger updateTriggerForTestDomain_tg +create trigger update_rbac_system_after_update_tg after update on rbactest.domain for each row -execute procedure updateTriggerForTestDomain_tf(); +execute procedure rbactest.domain_update_rbac_system_after_update_tf(); --// diff --git a/src/main/resources/db/changelog/5-hs-office/500-hs-office-schema.sql b/src/main/resources/db/changelog/5-hs-office/500-hs-office-schema.sql new file mode 100644 index 00000000..80e09179 --- /dev/null +++ b/src/main/resources/db/changelog/5-hs-office/500-hs-office-schema.sql @@ -0,0 +1,8 @@ +--liquibase formatted sql + + +-- ============================================================================ +--changeset michael.hoennig:hs-office-SCHEMA endDelimiter:--// +-- ---------------------------------------------------------------------------- +CREATE SCHEMA hs_office; +--// diff --git a/src/main/resources/db/changelog/5-hs-office/501-contact/5010-hs-office-contact.sql b/src/main/resources/db/changelog/5-hs-office/501-contact/5010-hs-office-contact.sql index 305d80d1..eeb33f4d 100644 --- a/src/main/resources/db/changelog/5-hs-office/501-contact/5010-hs-office-contact.sql +++ b/src/main/resources/db/changelog/5-hs-office/501-contact/5010-hs-office-contact.sql @@ -4,7 +4,7 @@ --changeset michael.hoennig:hs-office-contact-MAIN-TABLE endDelimiter:--// -- ---------------------------------------------------------------------------- -create table if not exists hs_office_contact +create table if not exists hs_office.contact ( uuid uuid unique references rbac.object (uuid) initially deferred, version int not null default 0, @@ -20,5 +20,5 @@ create table if not exists hs_office_contact --changeset michael.hoennig:hs-office-contact-MAIN-TABLE-JOURNAL endDelimiter:--// -- ---------------------------------------------------------------------------- -call base.create_journal('hs_office_contact'); +call base.create_journal('hs_office.contact'); --// diff --git a/src/main/resources/db/changelog/5-hs-office/501-contact/5013-hs-office-contact-rbac.sql b/src/main/resources/db/changelog/5-hs-office/501-contact/5013-hs-office-contact-rbac.sql index eb83c6e7..39976f0e 100644 --- a/src/main/resources/db/changelog/5-hs-office/501-contact/5013-hs-office-contact-rbac.sql +++ b/src/main/resources/db/changelog/5-hs-office/501-contact/5013-hs-office-contact-rbac.sql @@ -3,29 +3,29 @@ -- ============================================================================ ---changeset michael.hoennig:hs-office-contact-rbac-OBJECT endDelimiter:--// +--changeset RbacObjectGenerator:hs-office-contact-rbac-OBJECT endDelimiter:--// -- ---------------------------------------------------------------------------- -call rbac.generateRelatedRbacObject('hs_office_contact'); +call rbac.generateRelatedRbacObject('hs_office.contact'); --// -- ============================================================================ ---changeset michael.hoennig:hs-office-contact-rbac-ROLE-DESCRIPTORS endDelimiter:--// +--changeset RbacRoleDescriptorsGenerator:hs-office-contact-rbac-ROLE-DESCRIPTORS endDelimiter:--// -- ---------------------------------------------------------------------------- -call rbac.generateRbacRoleDescriptors('hsOfficeContact', 'hs_office_contact'); +call rbac.generateRbacRoleDescriptors('hsOfficeContact', 'hs_office.contact'); --// -- ============================================================================ ---changeset michael.hoennig:hs-office-contact-rbac-insert-trigger endDelimiter:--// +--changeset RolesGrantsAndPermissionsGenerator:hs-office-contact-rbac-insert-trigger endDelimiter:--// -- ---------------------------------------------------------------------------- /* Creates the roles, grants and permission for the AFTER INSERT TRIGGER. */ -create or replace procedure buildRbacSystemForHsOfficeContact( - NEW hs_office_contact +create or replace procedure hs_office.contact_build_rbac_system( + NEW hs_office.contact ) language plpgsql as $$ @@ -37,7 +37,7 @@ begin perform rbac.defineRoleWithGrants( hsOfficeContactOWNER(NEW), permissions => array['DELETE'], - incomingSuperRoles => array[rbac.globalAdmin()], + incomingSuperRoles => array[rbac.globalADMIN()], subjectUuids => array[rbac.currentSubjectUuid()] ); @@ -57,30 +57,30 @@ begin end; $$; /* - AFTER INSERT TRIGGER to create the role+grant structure for a new hs_office_contact row. + AFTER INSERT TRIGGER to create the role+grant structure for a new hs_office.contact row. */ -create or replace function insertTriggerForHsOfficeContact_tf() +create or replace function hs_office.contact_build_rbac_system_after_insert_tf() returns trigger language plpgsql strict as $$ begin - call buildRbacSystemForHsOfficeContact(NEW); + call hs_office.contact_build_rbac_system(NEW); return NEW; end; $$; -create trigger insertTriggerForHsOfficeContact_tg - after insert on hs_office_contact +create trigger build_rbac_system_after_insert_tg + after insert on hs_office.contact for each row -execute procedure insertTriggerForHsOfficeContact_tf(); +execute procedure hs_office.contact_build_rbac_system_after_insert_tf(); --// -- ============================================================================ ---changeset michael.hoennig:hs-office-contact-rbac-IDENTITY-VIEW endDelimiter:--// +--changeset RbacIdentityViewGenerator:hs-office-contact-rbac-IDENTITY-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call rbac.generateRbacIdentityViewFromProjection('hs_office_contact', +call rbac.generateRbacIdentityViewFromProjection('hs_office.contact', $idName$ caption $idName$); @@ -88,9 +88,9 @@ call rbac.generateRbacIdentityViewFromProjection('hs_office_contact', -- ============================================================================ ---changeset michael.hoennig:hs-office-contact-rbac-RESTRICTED-VIEW endDelimiter:--// +--changeset RbacRestrictedViewGenerator:hs-office-contact-rbac-RESTRICTED-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call rbac.generateRbacRestrictedView('hs_office_contact', +call rbac.generateRbacRestrictedView('hs_office.contact', $orderBy$ caption $orderBy$, diff --git a/src/main/resources/db/changelog/5-hs-office/501-contact/5016-hs-office-contact-migration.sql b/src/main/resources/db/changelog/5-hs-office/501-contact/5016-hs-office-contact-migration.sql index fe0f1553..ae41ee0f 100644 --- a/src/main/resources/db/changelog/5-hs-office/501-contact/5016-hs-office-contact-migration.sql +++ b/src/main/resources/db/changelog/5-hs-office/501-contact/5016-hs-office-contact-migration.sql @@ -7,9 +7,9 @@ --changeset michael.hoennig:hs-office-contact-MIGRATION-mapping endDelimiter:--// -- ---------------------------------------------------------------------------- -CREATE TABLE hs_office_contact_legacy_id +CREATE TABLE hs_office.contact_legacy_id ( - uuid uuid NOT NULL REFERENCES hs_office_contact(uuid), + uuid uuid NOT NULL REFERENCES hs_office.contact(uuid), contact_id integer NOT NULL ); --// @@ -19,10 +19,10 @@ CREATE TABLE hs_office_contact_legacy_id --changeset michael.hoennig:hs-office-contact-MIGRATION-sequence endDelimiter:--// -- ---------------------------------------------------------------------------- -CREATE SEQUENCE IF NOT EXISTS hs_office_contact_legacy_id_seq +CREATE SEQUENCE IF NOT EXISTS hs_office.contact_legacy_id_seq AS integer START 1000000000 - OWNED BY hs_office_contact_legacy_id.contact_id; + OWNED BY hs_office.contact_legacy_id.contact_id; --// @@ -30,9 +30,9 @@ CREATE SEQUENCE IF NOT EXISTS hs_office_contact_legacy_id_seq --changeset michael.hoennig:hs-office-contact-MIGRATION-default endDelimiter:--// -- ---------------------------------------------------------------------------- -ALTER TABLE hs_office_contact_legacy_id +ALTER TABLE hs_office.contact_legacy_id ALTER COLUMN contact_id - SET DEFAULT nextVal('hs_office_contact_legacy_id_seq'); + SET DEFAULT nextVal('hs_office.contact_legacy_id_seq'); --/ @@ -41,8 +41,8 @@ ALTER TABLE hs_office_contact_legacy_id -- ---------------------------------------------------------------------------- CALL base.defineContext('schema-migration'); -INSERT INTO hs_office_contact_legacy_id(uuid, contact_id) - SELECT uuid, nextVal('hs_office_contact_legacy_id_seq') FROM hs_office_contact; +INSERT INTO hs_office.contact_legacy_id(uuid, contact_id) + SELECT uuid, nextVal('hs_office.contact_legacy_id_seq') FROM hs_office.contact; --/ @@ -58,14 +58,14 @@ begin raise exception 'invalid usage of trigger'; end if; - INSERT INTO hs_office_contact_legacy_id VALUES - (NEW.uuid, nextVal('hs_office_contact_legacy_id_seq')); + INSERT INTO hs_office.contact_legacy_id VALUES + (NEW.uuid, nextVal('hs_office.contact_legacy_id_seq')); return NEW; end; $$; create trigger createContactLegacyIdMapping - after insert on hs_office_contact + after insert on hs_office.contact for each row execute procedure insertContactLegacyIdMapping(); --/ @@ -83,14 +83,14 @@ begin raise exception 'invalid usage of trigger'; end if; - DELETE FROM hs_office_contact_legacy_id + DELETE FROM hs_office.contact_legacy_id WHERE uuid = OLD.uuid; return OLD; end; $$; create trigger removeContactLegacyIdMapping - before delete on hs_office_contact + before delete on hs_office.contact for each row execute procedure deleteContactLegacyIdMapping(); --/ diff --git a/src/main/resources/db/changelog/5-hs-office/501-contact/5018-hs-office-contact-test-data.sql b/src/main/resources/db/changelog/5-hs-office/501-contact/5018-hs-office-contact-test-data.sql index 7e77c396..40f9e065 100644 --- a/src/main/resources/db/changelog/5-hs-office/501-contact/5018-hs-office-contact-test-data.sql +++ b/src/main/resources/db/changelog/5-hs-office/501-contact/5018-hs-office-contact-test-data.sql @@ -23,7 +23,7 @@ begin raise notice 'creating test contact: %', contCaption; insert - into hs_office_contact (caption, postaladdress, emailaddresses, phonenumbers) + into hs_office.contact (caption, postaladdress, emailaddresses, phonenumbers) values ( contCaption, postalAddr, diff --git a/src/main/resources/db/changelog/5-hs-office/502-person/5020-hs-office-person.sql b/src/main/resources/db/changelog/5-hs-office/502-person/5020-hs-office-person.sql index 30fa1477..428df466 100644 --- a/src/main/resources/db/changelog/5-hs-office/502-person/5020-hs-office-person.sql +++ b/src/main/resources/db/changelog/5-hs-office/502-person/5020-hs-office-person.sql @@ -14,7 +14,7 @@ CREATE TYPE HsOfficePersonType AS ENUM ( CREATE CAST (character varying as HsOfficePersonType) WITH INOUT AS IMPLICIT; -create table if not exists hs_office_person +create table if not exists hs_office.person ( uuid uuid unique references rbac.object (uuid) initially deferred, version int not null default 0, @@ -31,5 +31,5 @@ create table if not exists hs_office_person --changeset michael.hoennig:hs-office-person-MAIN-TABLE-JOURNAL endDelimiter:--// -- ---------------------------------------------------------------------------- -call base.create_journal('hs_office_person'); +call base.create_journal('hs_office.person'); --// diff --git a/src/main/resources/db/changelog/5-hs-office/502-person/5023-hs-office-person-rbac.sql b/src/main/resources/db/changelog/5-hs-office/502-person/5023-hs-office-person-rbac.sql index f652529f..8e0d7a31 100644 --- a/src/main/resources/db/changelog/5-hs-office/502-person/5023-hs-office-person-rbac.sql +++ b/src/main/resources/db/changelog/5-hs-office/502-person/5023-hs-office-person-rbac.sql @@ -5,14 +5,14 @@ -- ============================================================================ --changeset RbacObjectGenerator:hs-office-person-rbac-OBJECT endDelimiter:--// -- ---------------------------------------------------------------------------- -call rbac.generateRelatedRbacObject('hs_office_person'); +call rbac.generateRelatedRbacObject('hs_office.person'); --// -- ============================================================================ --changeset RbacRoleDescriptorsGenerator:hs-office-person-rbac-ROLE-DESCRIPTORS endDelimiter:--// -- ---------------------------------------------------------------------------- -call rbac.generateRbacRoleDescriptors('hsOfficePerson', 'hs_office_person'); +call rbac.generateRbacRoleDescriptors('hsOfficePerson', 'hs_office.person'); --// @@ -24,8 +24,8 @@ call rbac.generateRbacRoleDescriptors('hsOfficePerson', 'hs_office_person'); Creates the roles, grants and permission for the AFTER INSERT TRIGGER. */ -create or replace procedure buildRbacSystemForHsOfficePerson( - NEW hs_office_person +create or replace procedure hs_office.person_build_rbac_system( + NEW hs_office.person ) language plpgsql as $$ @@ -57,22 +57,22 @@ begin end; $$; /* - AFTER INSERT TRIGGER to create the role+grant structure for a new hs_office_person row. + AFTER INSERT TRIGGER to create the role+grant structure for a new hs_office.person row. */ -create or replace function insertTriggerForHsOfficePerson_tf() +create or replace function hs_office.person_build_rbac_system_after_insert_tf() returns trigger language plpgsql strict as $$ begin - call buildRbacSystemForHsOfficePerson(NEW); + call hs_office.person_build_rbac_system(NEW); return NEW; end; $$; -create trigger insertTriggerForHsOfficePerson_tg - after insert on hs_office_person +create trigger build_rbac_system_after_insert_tg + after insert on hs_office.person for each row -execute procedure insertTriggerForHsOfficePerson_tf(); +execute procedure hs_office.person_build_rbac_system_after_insert_tf(); --// @@ -80,7 +80,7 @@ execute procedure insertTriggerForHsOfficePerson_tf(); --changeset RbacIdentityViewGenerator:hs-office-person-rbac-IDENTITY-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call rbac.generateRbacIdentityViewFromProjection('hs_office_person', +call rbac.generateRbacIdentityViewFromProjection('hs_office.person', $idName$ concat(tradeName, familyName, givenName) $idName$); @@ -90,7 +90,7 @@ call rbac.generateRbacIdentityViewFromProjection('hs_office_person', -- ============================================================================ --changeset RbacRestrictedViewGenerator:hs-office-person-rbac-RESTRICTED-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call rbac.generateRbacRestrictedView('hs_office_person', +call rbac.generateRbacRestrictedView('hs_office.person', $orderBy$ concat(tradeName, familyName, givenName) $orderBy$, diff --git a/src/main/resources/db/changelog/5-hs-office/502-person/5028-hs-office-person-test-data.sql b/src/main/resources/db/changelog/5-hs-office/502-person/5028-hs-office-person-test-data.sql index c9b078e2..9ba8dd37 100644 --- a/src/main/resources/db/changelog/5-hs-office/502-person/5028-hs-office-person-test-data.sql +++ b/src/main/resources/db/changelog/5-hs-office/502-person/5028-hs-office-person-test-data.sql @@ -27,7 +27,7 @@ begin raise notice 'creating test person: % by %', fullName, emailAddr; insert - into hs_office_person (persontype, tradename, givenname, familyname) + into hs_office.person (persontype, tradename, givenname, familyname) values (newPersonType, newTradeName, newGivenName, newFamilyName); end; $$; --// diff --git a/src/main/resources/db/changelog/5-hs-office/503-relation/5030-hs-office-relation.sql b/src/main/resources/db/changelog/5-hs-office/503-relation/5030-hs-office-relation.sql index 387bacd3..1c17aa78 100644 --- a/src/main/resources/db/changelog/5-hs-office/503-relation/5030-hs-office-relation.sql +++ b/src/main/resources/db/changelog/5-hs-office/503-relation/5030-hs-office-relation.sql @@ -16,13 +16,13 @@ CREATE TYPE HsOfficeRelationType AS ENUM ( CREATE CAST (character varying as HsOfficeRelationType) WITH INOUT AS IMPLICIT; -create table if not exists hs_office_relation +create table if not exists hs_office.relation ( uuid uuid unique references rbac.object (uuid) initially deferred, -- on delete cascade version int not null default 0, - anchorUuid uuid not null references hs_office_person(uuid), - holderUuid uuid not null references hs_office_person(uuid), - contactUuid uuid references hs_office_contact(uuid), + anchorUuid uuid not null references hs_office.person(uuid), + holderUuid uuid not null references hs_office.person(uuid), + contactUuid uuid references hs_office.contact(uuid), type HsOfficeRelationType not null, mark varchar(24) ); @@ -33,5 +33,5 @@ create table if not exists hs_office_relation --changeset michael.hoennig:hs-office-relation-MAIN-TABLE-JOURNAL endDelimiter:--// -- ---------------------------------------------------------------------------- -call base.create_journal('hs_office_relation'); +call base.create_journal('hs_office.relation'); --// diff --git a/src/main/resources/db/changelog/5-hs-office/503-relation/5033-hs-office-relation-rbac.sql b/src/main/resources/db/changelog/5-hs-office/503-relation/5033-hs-office-relation-rbac.sql index d6f36ad5..85301c32 100644 --- a/src/main/resources/db/changelog/5-hs-office/503-relation/5033-hs-office-relation-rbac.sql +++ b/src/main/resources/db/changelog/5-hs-office/503-relation/5033-hs-office-relation-rbac.sql @@ -3,54 +3,54 @@ -- ============================================================================ ---changeset michael.hoennig:hs-office-relation-rbac-OBJECT endDelimiter:--// +--changeset RbacObjectGenerator:hs-office-relation-rbac-OBJECT endDelimiter:--// -- ---------------------------------------------------------------------------- -call rbac.generateRelatedRbacObject('hs_office_relation'); +call rbac.generateRelatedRbacObject('hs_office.relation'); --// -- ============================================================================ ---changeset michael.hoennig:hs-office-relation-rbac-ROLE-DESCRIPTORS endDelimiter:--// +--changeset RbacRoleDescriptorsGenerator:hs-office-relation-rbac-ROLE-DESCRIPTORS endDelimiter:--// -- ---------------------------------------------------------------------------- -call rbac.generateRbacRoleDescriptors('hsOfficeRelation', 'hs_office_relation'); +call rbac.generateRbacRoleDescriptors('hsOfficeRelation', 'hs_office.relation'); --// -- ============================================================================ ---changeset michael.hoennig:hs-office-relation-rbac-insert-trigger endDelimiter:--// +--changeset RolesGrantsAndPermissionsGenerator:hs-office-relation-rbac-insert-trigger endDelimiter:--// -- ---------------------------------------------------------------------------- /* Creates the roles, grants and permission for the AFTER INSERT TRIGGER. */ -create or replace procedure buildRbacSystemForHsOfficeRelation( - NEW hs_office_relation +create or replace procedure hs_office.relation_build_rbac_system( + NEW hs_office.relation ) language plpgsql as $$ declare - newHolderPerson hs_office_person; - newAnchorPerson hs_office_person; - newContact hs_office_contact; + newHolderPerson hs_office.person; + newAnchorPerson hs_office.person; + newContact hs_office.contact; begin call rbac.enterTriggerForObjectUuid(NEW.uuid); - SELECT * FROM hs_office_person WHERE uuid = NEW.holderUuid INTO newHolderPerson; + SELECT * FROM hs_office.person WHERE uuid = NEW.holderUuid INTO newHolderPerson; assert newHolderPerson.uuid is not null, format('newHolderPerson must not be null for NEW.holderUuid = %s', NEW.holderUuid); - SELECT * FROM hs_office_person WHERE uuid = NEW.anchorUuid INTO newAnchorPerson; + SELECT * FROM hs_office.person WHERE uuid = NEW.anchorUuid INTO newAnchorPerson; assert newAnchorPerson.uuid is not null, format('newAnchorPerson must not be null for NEW.anchorUuid = %s', NEW.anchorUuid); - SELECT * FROM hs_office_contact WHERE uuid = NEW.contactUuid INTO newContact; + SELECT * FROM hs_office.contact WHERE uuid = NEW.contactUuid INTO newContact; assert newContact.uuid is not null, format('newContact must not be null for NEW.contactUuid = %s', NEW.contactUuid); perform rbac.defineRoleWithGrants( hsOfficeRelationOWNER(NEW), permissions => array['DELETE'], - incomingSuperRoles => array[rbac.globalAdmin()], + incomingSuperRoles => array[rbac.globalADMIN()], subjectUuids => array[rbac.currentSubjectUuid()] ); @@ -90,162 +90,162 @@ begin end; $$; /* - AFTER INSERT TRIGGER to create the role+grant structure for a new hs_office_relation row. + AFTER INSERT TRIGGER to create the role+grant structure for a new hs_office.relation row. */ -create or replace function insertTriggerForHsOfficeRelation_tf() +create or replace function hs_office.relation_build_rbac_system_after_insert_tf() returns trigger language plpgsql strict as $$ begin - call buildRbacSystemForHsOfficeRelation(NEW); + call hs_office.relation_build_rbac_system(NEW); return NEW; end; $$; -create trigger insertTriggerForHsOfficeRelation_tg - after insert on hs_office_relation +create trigger build_rbac_system_after_insert_tg + after insert on hs_office.relation for each row -execute procedure insertTriggerForHsOfficeRelation_tf(); +execute procedure hs_office.relation_build_rbac_system_after_insert_tf(); --// -- ============================================================================ ---changeset michael.hoennig:hs-office-relation-rbac-update-trigger endDelimiter:--// +--changeset RolesGrantsAndPermissionsGenerator:hs-office-relation-rbac-update-trigger endDelimiter:--// -- ---------------------------------------------------------------------------- /* Called from the AFTER UPDATE TRIGGER to re-wire the grants. */ -create or replace procedure updateRbacRulesForHsOfficeRelation( - OLD hs_office_relation, - NEW hs_office_relation +create or replace procedure hs_office.relation_update_rbac_system( + OLD hs_office.relation, + NEW hs_office.relation ) language plpgsql as $$ begin if NEW.contactUuid is distinct from OLD.contactUuid then delete from rbac.grants g where g.grantedbytriggerof = OLD.uuid; - call buildRbacSystemForHsOfficeRelation(NEW); + call hs_office.relation_build_rbac_system(NEW); end if; end; $$; /* - AFTER INSERT TRIGGER to re-wire the grant structure for a new hs_office_relation row. + AFTER UPDATE TRIGGER to re-wire the grant structure for a new hs_office.relation row. */ -create or replace function updateTriggerForHsOfficeRelation_tf() +create or replace function hs_office.relation_update_rbac_system_after_update_tf() returns trigger language plpgsql strict as $$ begin - call updateRbacRulesForHsOfficeRelation(OLD, NEW); + call hs_office.relation_update_rbac_system(OLD, NEW); return NEW; end; $$; -create trigger updateTriggerForHsOfficeRelation_tg - after update on hs_office_relation +create trigger update_rbac_system_after_update_tg + after update on hs_office.relation for each row -execute procedure updateTriggerForHsOfficeRelation_tf(); +execute procedure hs_office.relation_update_rbac_system_after_update_tf(); --// -- ============================================================================ ---changeset michael.hoennig:hs-office-relation-rbac-GRANTING-INSERT-PERMISSION endDelimiter:--// +--changeset InsertTriggerGenerator:hs-office-relation-rbac-GRANTING-INSERT-PERMISSION endDelimiter:--// -- ---------------------------------------------------------------------------- --- granting INSERT permission to hs_office_person ---------------------------- +-- granting INSERT permission to hs_office.person ---------------------------- /* - Grants INSERT INTO hs_office_relation permissions to specified role of pre-existing hs_office_person rows. + Grants INSERT INTO hs_office.relation permissions to specified role of pre-existing hs_office.person rows. */ do language plpgsql $$ declare - row hs_office_person; + row hs_office.person; begin - call base.defineContext('create INSERT INTO hs_office_relation permissions for pre-exising hs_office_person rows'); + call base.defineContext('create INSERT INTO hs_office.relation permissions for pre-exising hs_office.person rows'); - FOR row IN SELECT * FROM hs_office_person + FOR row IN SELECT * FROM hs_office.person -- unconditional for all rows in that table LOOP call rbac.grantPermissionToRole( - rbac.createPermission(row.uuid, 'INSERT', 'hs_office_relation'), + rbac.createPermission(row.uuid, 'INSERT', 'hs_office.relation'), hsOfficePersonADMIN(row)); END LOOP; end; $$; /** - Grants hs_office_relation INSERT permission to specified role of new hs_office_person rows. + Grants hs_office.relation INSERT permission to specified role of new person rows. */ -create or replace function new_hs_office_relation_grants_insert_to_hs_office_person_tf() +create or replace function hs_office.new_relation_grants_insert_to_person_tf() returns trigger language plpgsql strict as $$ begin -- unconditional for all rows in that table call rbac.grantPermissionToRole( - rbac.createPermission(NEW.uuid, 'INSERT', 'hs_office_relation'), + rbac.createPermission(NEW.uuid, 'INSERT', 'hs_office.relation'), hsOfficePersonADMIN(NEW)); -- end. return NEW; end; $$; -- z_... is to put it at the end of after insert triggers, to make sure the roles exist -create trigger z_new_hs_office_relation_grants_insert_to_hs_office_person_tg - after insert on hs_office_person +create trigger z_new_relation_grants_after_insert_tg + after insert on hs_office.person for each row -execute procedure new_hs_office_relation_grants_insert_to_hs_office_person_tf(); +execute procedure hs_office.new_relation_grants_insert_to_person_tf(); -- ============================================================================ ---changeset michael.hoennig:hs_office_relation-rbac-CHECKING-INSERT-PERMISSION endDelimiter:--// +--changeset InsertTriggerGenerator:hs-office-relation-rbac-CHECKING-INSERT-PERMISSION endDelimiter:--// -- ---------------------------------------------------------------------------- /** - Checks if the user respectively the assumed roles are allowed to insert a row to hs_office_relation. + Checks if the user respectively the assumed roles are allowed to insert a row to hs_office.relation. */ -create or replace function hs_office_relation_insert_permission_check_tf() +create or replace function hs_office.relation_insert_permission_check_tf() returns trigger language plpgsql as $$ declare superObjectUuid uuid; begin -- check INSERT permission via direct foreign key: NEW.anchorUuid - if rbac.hasInsertPermission(NEW.anchorUuid, 'hs_office_relation') then + if rbac.hasInsertPermission(NEW.anchorUuid, 'hs_office.relation') then return NEW; end if; - raise exception '[403] insert into hs_office_relation not allowed for current subjects % (%)', - base.currentSubjects(), rbac.currentSubjectOrAssumedRolesUuids(); + raise exception '[403] insert into hs_office.relation values(%) not allowed for current subjects % (%)', + NEW, base.currentSubjects(), rbac.currentSubjectOrAssumedRolesUuids(); end; $$; -create trigger hs_office_relation_insert_permission_check_tg - before insert on hs_office_relation +create trigger relation_insert_permission_check_tg + before insert on hs_office.relation for each row - execute procedure hs_office_relation_insert_permission_check_tf(); + execute procedure hs_office.relation_insert_permission_check_tf(); --// -- ============================================================================ ---changeset michael.hoennig:hs-office-relation-rbac-IDENTITY-VIEW endDelimiter:--// +--changeset RbacIdentityViewGenerator:hs-office-relation-rbac-IDENTITY-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call rbac.generateRbacIdentityViewFromProjection('hs_office_relation', +call rbac.generateRbacIdentityViewFromProjection('hs_office.relation', $idName$ - (select idName from hs_office_person_iv p where p.uuid = anchorUuid) + (select idName from hs_office.person_iv p where p.uuid = anchorUuid) || '-with-' || target.type || '-' - || (select idName from hs_office_person_iv p where p.uuid = holderUuid) + || (select idName from hs_office.person_iv p where p.uuid = holderUuid) $idName$); --// -- ============================================================================ ---changeset michael.hoennig:hs-office-relation-rbac-RESTRICTED-VIEW endDelimiter:--// +--changeset RbacRestrictedViewGenerator:hs-office-relation-rbac-RESTRICTED-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call rbac.generateRbacRestrictedView('hs_office_relation', +call rbac.generateRbacRestrictedView('hs_office.relation', $orderBy$ - (select idName from hs_office_person_iv p where p.uuid = target.holderUuid) + (select idName from hs_office.person_iv p where p.uuid = target.holderUuid) $orderBy$, $updates$ contactUuid = new.contactUuid diff --git a/src/main/resources/db/changelog/5-hs-office/503-relation/5038-hs-office-relation-test-data.sql b/src/main/resources/db/changelog/5-hs-office/503-relation/5038-hs-office-relation-test-data.sql index 39c204a9..3cb64e13 100644 --- a/src/main/resources/db/changelog/5-hs-office/503-relation/5038-hs-office-relation-test-data.sql +++ b/src/main/resources/db/changelog/5-hs-office/503-relation/5038-hs-office-relation-test-data.sql @@ -17,16 +17,16 @@ create or replace procedure createHsOfficeRelationTestData( language plpgsql as $$ declare idName varchar; - anchorPerson hs_office_person; - holderPerson hs_office_person; - contact hs_office_contact; + anchorPerson hs_office.person; + holderPerson hs_office.person; + contact hs_office.contact; begin idName := base.cleanIdentifier( anchorPersonName || '-' || holderPersonName); select p.* into anchorPerson - from hs_office_person p + from hs_office.person p where p.tradeName = anchorPersonName or p.familyName = anchorPersonName; if anchorPerson is null then raise exception 'anchorPerson "%" not found', anchorPersonName; @@ -34,13 +34,13 @@ begin select p.* into holderPerson - from hs_office_person p + from hs_office.person p where p.tradeName = holderPersonName or p.familyName = holderPersonName; if holderPerson is null then raise exception 'holderPerson "%" not found', holderPersonName; end if; - select c.* into contact from hs_office_contact c where c.caption = contactCaption; + select c.* into contact from hs_office.contact c where c.caption = contactCaption; if contact is null then raise exception 'contact "%" not found', contactCaption; end if; @@ -50,7 +50,7 @@ begin raise notice '- using holder person (%): %', holderPerson.uuid, holderPerson; raise notice '- using contact (%): %', contact.uuid, contact; insert - into hs_office_relation (uuid, anchoruuid, holderuuid, type, mark, contactUuid) + into hs_office.relation (uuid, anchoruuid, holderuuid, type, mark, contactUuid) values (uuid_generate_v4(), anchorPerson.uuid, holderPerson.uuid, relationType, mark, contact.uuid); end; $$; --// @@ -64,13 +64,13 @@ create or replace procedure createHsOfficeRelationTestData( ) language plpgsql as $$ declare - person hs_office_person; - contact hs_office_contact; + person hs_office.person; + contact hs_office.contact; begin for t in startCount..endCount loop - select p.* from hs_office_person p where tradeName = base.intToVarChar(t, 4) into person; - select c.* from hs_office_contact c where c.caption = base.intToVarChar(t, 4) || '#' || t into contact; + select p.* from hs_office.person p where tradeName = base.intToVarChar(t, 4) into person; + select c.* from hs_office.contact c where c.caption = base.intToVarChar(t, 4) || '#' || t into contact; call createHsOfficeRelationTestData(person.uuid, contact.uuid, 'REPRESENTATIVE'); commit; diff --git a/src/main/resources/db/changelog/5-hs-office/504-partner/5040-hs-office-partner.sql b/src/main/resources/db/changelog/5-hs-office/504-partner/5040-hs-office-partner.sql index eae97773..f696d310 100644 --- a/src/main/resources/db/changelog/5-hs-office/504-partner/5040-hs-office-partner.sql +++ b/src/main/resources/db/changelog/5-hs-office/504-partner/5040-hs-office-partner.sql @@ -5,7 +5,7 @@ --changeset michael.hoennig:hs-office-partner-DETAILS-TABLE endDelimiter:--// -- ---------------------------------------------------------------------------- -create table hs_office_partner_details +create table hs_office.partner_details ( uuid uuid unique references rbac.object (uuid) initially deferred, version int not null default 0, @@ -23,20 +23,20 @@ create table hs_office_partner_details --changeset michael.hoennig:hs-office-partner-DETAILS-TABLE-JOURNAL endDelimiter:--// -- ---------------------------------------------------------------------------- -call base.create_journal('hs_office_partner_details'); +call base.create_journal('hs_office.partner_details'); --// -- ============================================================================ --changeset michael.hoennig:hs-office-partner-MAIN-TABLE endDelimiter:--// -- ---------------------------------------------------------------------------- -create table hs_office_partner +create table hs_office.partner ( uuid uuid unique references rbac.object (uuid) initially deferred, version int not null default 0, partnerNumber numeric(5) unique not null, - partnerRelUuid uuid not null references hs_office_relation(uuid), -- deleted in after delete trigger - detailsUuid uuid not null references hs_office_partner_details(uuid) -- deleted in after delete trigger + partnerRelUuid uuid not null references hs_office.relation(uuid), -- deleted in after delete trigger + detailsUuid uuid not null references hs_office.partner_details(uuid) -- deleted in after delete trigger ); --// @@ -48,20 +48,20 @@ create table hs_office_partner /** Trigger function to delete related details of a partner to delete. */ -create or replace function deleteHsOfficeDependentsOnPartnerDelete() +create or replace function hs_office.partner_delete_dependents_tf() returns trigger language PLPGSQL as $$ declare counter integer; begin - DELETE FROM hs_office_partner_details d WHERE d.uuid = OLD.detailsUuid; + DELETE FROM hs_office.partner_details d WHERE d.uuid = OLD.detailsUuid; GET DIAGNOSTICS counter = ROW_COUNT; if counter = 0 then raise exception 'partner details % could not be deleted', OLD.detailsUuid; end if; - DELETE FROM hs_office_relation r WHERE r.uuid = OLD.partnerRelUuid; + DELETE FROM hs_office.relation r WHERE r.uuid = OLD.partnerRelUuid; GET DIAGNOSTICS counter = ROW_COUNT; if counter = 0 then raise exception 'partner relation % could not be deleted', OLD.partnerRelUuid; @@ -73,15 +73,15 @@ end; $$; /** Triggers deletion of related rows of a partner to delete. */ -create trigger hs_office_partner_delete_dependents_trigger +create trigger delete_dependents_tg after delete - on hs_office_partner + on hs_office.partner for each row - execute procedure deleteHsOfficeDependentsOnPartnerDelete(); + execute procedure hs_office.partner_delete_dependents_tf(); -- ============================================================================ --changeset michael.hoennig:hs-office-partner-MAIN-TABLE-JOURNAL endDelimiter:--// -- ---------------------------------------------------------------------------- -call base.create_journal('hs_office_partner'); +call base.create_journal('hs_office.partner'); --// diff --git a/src/main/resources/db/changelog/5-hs-office/504-partner/5043-hs-office-partner-rbac.sql b/src/main/resources/db/changelog/5-hs-office/504-partner/5043-hs-office-partner-rbac.sql index 8227db94..7ead6151 100644 --- a/src/main/resources/db/changelog/5-hs-office/504-partner/5043-hs-office-partner-rbac.sql +++ b/src/main/resources/db/changelog/5-hs-office/504-partner/5043-hs-office-partner-rbac.sql @@ -5,14 +5,14 @@ -- ============================================================================ --changeset RbacObjectGenerator:hs-office-partner-rbac-OBJECT endDelimiter:--// -- ---------------------------------------------------------------------------- -call rbac.generateRelatedRbacObject('hs_office_partner'); +call rbac.generateRelatedRbacObject('hs_office.partner'); --// -- ============================================================================ --changeset RbacRoleDescriptorsGenerator:hs-office-partner-rbac-ROLE-DESCRIPTORS endDelimiter:--// -- ---------------------------------------------------------------------------- -call rbac.generateRbacRoleDescriptors('hsOfficePartner', 'hs_office_partner'); +call rbac.generateRbacRoleDescriptors('hsOfficePartner', 'hs_office.partner'); --// @@ -24,22 +24,22 @@ call rbac.generateRbacRoleDescriptors('hsOfficePartner', 'hs_office_partner'); Creates the roles, grants and permission for the AFTER INSERT TRIGGER. */ -create or replace procedure buildRbacSystemForHsOfficePartner( - NEW hs_office_partner +create or replace procedure hs_office.partner_build_rbac_system( + NEW hs_office.partner ) language plpgsql as $$ declare - newPartnerRel hs_office_relation; - newPartnerDetails hs_office_partner_details; + newPartnerRel hs_office.relation; + newPartnerDetails hs_office.partner_details; begin call rbac.enterTriggerForObjectUuid(NEW.uuid); - SELECT * FROM hs_office_relation WHERE uuid = NEW.partnerRelUuid INTO newPartnerRel; + SELECT * FROM hs_office.relation WHERE uuid = NEW.partnerRelUuid INTO newPartnerRel; assert newPartnerRel.uuid is not null, format('newPartnerRel must not be null for NEW.partnerRelUuid = %s', NEW.partnerRelUuid); - SELECT * FROM hs_office_partner_details WHERE uuid = NEW.detailsUuid INTO newPartnerDetails; + SELECT * FROM hs_office.partner_details WHERE uuid = NEW.detailsUuid INTO newPartnerDetails; assert newPartnerDetails.uuid is not null, format('newPartnerDetails must not be null for NEW.detailsUuid = %s', NEW.detailsUuid); call rbac.grantPermissionToRole(rbac.createPermission(NEW.uuid, 'DELETE'), hsOfficeRelationOWNER(newPartnerRel)); @@ -53,22 +53,22 @@ begin end; $$; /* - AFTER INSERT TRIGGER to create the role+grant structure for a new hs_office_partner row. + AFTER INSERT TRIGGER to create the role+grant structure for a new hs_office.partner row. */ -create or replace function insertTriggerForHsOfficePartner_tf() +create or replace function hs_office.partner_build_rbac_system_after_insert_tf() returns trigger language plpgsql strict as $$ begin - call buildRbacSystemForHsOfficePartner(NEW); + call hs_office.partner_build_rbac_system(NEW); return NEW; end; $$; -create trigger insertTriggerForHsOfficePartner_tg - after insert on hs_office_partner +create trigger build_rbac_system_after_insert_tg + after insert on hs_office.partner for each row -execute procedure insertTriggerForHsOfficePartner_tf(); +execute procedure hs_office.partner_build_rbac_system_after_insert_tf(); --// @@ -80,31 +80,31 @@ execute procedure insertTriggerForHsOfficePartner_tf(); Called from the AFTER UPDATE TRIGGER to re-wire the grants. */ -create or replace procedure updateRbacRulesForHsOfficePartner( - OLD hs_office_partner, - NEW hs_office_partner +create or replace procedure hs_office.partner_update_rbac_system( + OLD hs_office.partner, + NEW hs_office.partner ) language plpgsql as $$ declare - oldPartnerRel hs_office_relation; - newPartnerRel hs_office_relation; - oldPartnerDetails hs_office_partner_details; - newPartnerDetails hs_office_partner_details; + oldPartnerRel hs_office.relation; + newPartnerRel hs_office.relation; + oldPartnerDetails hs_office.partner_details; + newPartnerDetails hs_office.partner_details; begin call rbac.enterTriggerForObjectUuid(NEW.uuid); - SELECT * FROM hs_office_relation WHERE uuid = OLD.partnerRelUuid INTO oldPartnerRel; + SELECT * FROM hs_office.relation WHERE uuid = OLD.partnerRelUuid INTO oldPartnerRel; assert oldPartnerRel.uuid is not null, format('oldPartnerRel must not be null for OLD.partnerRelUuid = %s', OLD.partnerRelUuid); - SELECT * FROM hs_office_relation WHERE uuid = NEW.partnerRelUuid INTO newPartnerRel; + SELECT * FROM hs_office.relation WHERE uuid = NEW.partnerRelUuid INTO newPartnerRel; assert newPartnerRel.uuid is not null, format('newPartnerRel must not be null for NEW.partnerRelUuid = %s', NEW.partnerRelUuid); - SELECT * FROM hs_office_partner_details WHERE uuid = OLD.detailsUuid INTO oldPartnerDetails; + SELECT * FROM hs_office.partner_details WHERE uuid = OLD.detailsUuid INTO oldPartnerDetails; assert oldPartnerDetails.uuid is not null, format('oldPartnerDetails must not be null for OLD.detailsUuid = %s', OLD.detailsUuid); - SELECT * FROM hs_office_partner_details WHERE uuid = NEW.detailsUuid INTO newPartnerDetails; + SELECT * FROM hs_office.partner_details WHERE uuid = NEW.detailsUuid INTO newPartnerDetails; assert newPartnerDetails.uuid is not null, format('newPartnerDetails must not be null for NEW.detailsUuid = %s', NEW.detailsUuid); @@ -134,22 +134,22 @@ begin end; $$; /* - AFTER INSERT TRIGGER to re-wire the grant structure for a new hs_office_partner row. + AFTER UPDATE TRIGGER to re-wire the grant structure for a new hs_office.partner row. */ -create or replace function updateTriggerForHsOfficePartner_tf() +create or replace function hs_office.partner_update_rbac_system_after_update_tf() returns trigger language plpgsql strict as $$ begin - call updateRbacRulesForHsOfficePartner(OLD, NEW); + call hs_office.partner_update_rbac_system(OLD, NEW); return NEW; end; $$; -create trigger updateTriggerForHsOfficePartner_tg - after update on hs_office_partner +create trigger update_rbac_system_after_update_tg + after update on hs_office.partner for each row -execute procedure updateTriggerForHsOfficePartner_tf(); +execute procedure hs_office.partner_update_rbac_system_after_update_tf(); --// @@ -160,45 +160,45 @@ execute procedure updateTriggerForHsOfficePartner_tf(); -- granting INSERT permission to rbac.global ---------------------------- /* - Grants INSERT INTO hs_office_partner permissions to specified role of pre-existing rbac.global rows. + Grants INSERT INTO hs_office.partner permissions to specified role of pre-existing rbac.global rows. */ do language plpgsql $$ declare row rbac.global; begin - call base.defineContext('create INSERT INTO hs_office_partner permissions for pre-exising rbac.global rows'); + call base.defineContext('create INSERT INTO hs_office.partner permissions for pre-exising rbac.global rows'); FOR row IN SELECT * FROM rbac.global -- unconditional for all rows in that table LOOP call rbac.grantPermissionToRole( - rbac.createPermission(row.uuid, 'INSERT', 'hs_office_partner'), + rbac.createPermission(row.uuid, 'INSERT', 'hs_office.partner'), rbac.globalADMIN()); END LOOP; end; $$; /** - Grants hs_office_partner INSERT permission to specified role of new global rows. + Grants hs_office.partner INSERT permission to specified role of new global rows. */ -create or replace function new_hsof_partner_grants_insert_to_global_tf() +create or replace function hs_office.new_partner_grants_insert_to_global_tf() returns trigger language plpgsql strict as $$ begin -- unconditional for all rows in that table call rbac.grantPermissionToRole( - rbac.createPermission(NEW.uuid, 'INSERT', 'hs_office_partner'), + rbac.createPermission(NEW.uuid, 'INSERT', 'hs_office.partner'), rbac.globalADMIN()); -- end. return NEW; end; $$; -- z_... is to put it at the end of after insert triggers, to make sure the roles exist -create trigger z_new_hs_office_partner_grants_after_insert_tg +create trigger z_new_partner_grants_after_insert_tg after insert on rbac.global for each row -execute procedure new_hsof_partner_grants_insert_to_global_tf(); +execute procedure hs_office.new_partner_grants_insert_to_global_tf(); -- ============================================================================ @@ -206,27 +206,27 @@ execute procedure new_hsof_partner_grants_insert_to_global_tf(); -- ---------------------------------------------------------------------------- /** - Checks if the user respectively the assumed roles are allowed to insert a row to hs_office_partner. + Checks if the user respectively the assumed roles are allowed to insert a row to hs_office.partner. */ -create or replace function hs_office_partner_insert_permission_check_tf() +create or replace function hs_office.partner_insert_permission_check_tf() returns trigger language plpgsql as $$ declare superObjectUuid uuid; begin - -- check INSERT INSERT if rbac.global ADMIN + -- check INSERT permission if rbac.global ADMIN if rbac.isGlobalAdmin() then return NEW; end if; - raise exception '[403] insert into hs_office_partner values(%) not allowed for current subjects % (%)', + raise exception '[403] insert into hs_office.partner values(%) not allowed for current subjects % (%)', NEW, base.currentSubjects(), rbac.currentSubjectOrAssumedRolesUuids(); end; $$; -create trigger hs_office_partner_insert_permission_check_tg - before insert on hs_office_partner +create trigger partner_insert_permission_check_tg + before insert on hs_office.partner for each row - execute procedure hs_office_partner_insert_permission_check_tf(); + execute procedure hs_office.partner_insert_permission_check_tf(); --// @@ -234,7 +234,7 @@ create trigger hs_office_partner_insert_permission_check_tg --changeset RbacIdentityViewGenerator:hs-office-partner-rbac-IDENTITY-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call rbac.generateRbacIdentityViewFromProjection('hs_office_partner', +call rbac.generateRbacIdentityViewFromProjection('hs_office.partner', $idName$ 'P-' || partnerNumber $idName$); @@ -244,7 +244,7 @@ call rbac.generateRbacIdentityViewFromProjection('hs_office_partner', -- ============================================================================ --changeset RbacRestrictedViewGenerator:hs-office-partner-rbac-RESTRICTED-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call rbac.generateRbacRestrictedView('hs_office_partner', +call rbac.generateRbacRestrictedView('hs_office.partner', $orderBy$ 'P-' || partnerNumber $orderBy$, diff --git a/src/main/resources/db/changelog/5-hs-office/504-partner/5044-hs-office-partner-details-rbac.sql b/src/main/resources/db/changelog/5-hs-office/504-partner/5044-hs-office-partner-details-rbac.sql index 6c360b90..a6209110 100644 --- a/src/main/resources/db/changelog/5-hs-office/504-partner/5044-hs-office-partner-details-rbac.sql +++ b/src/main/resources/db/changelog/5-hs-office/504-partner/5044-hs-office-partner-details-rbac.sql @@ -5,14 +5,14 @@ -- ============================================================================ --changeset RbacObjectGenerator:hs-office-partner-details-rbac-OBJECT endDelimiter:--// -- ---------------------------------------------------------------------------- -call rbac.generateRelatedRbacObject('hs_office_partner_details'); +call rbac.generateRelatedRbacObject('hs_office.partner_details'); --// -- ============================================================================ --changeset RbacRoleDescriptorsGenerator:hs-office-partner-details-rbac-ROLE-DESCRIPTORS endDelimiter:--// -- ---------------------------------------------------------------------------- -call rbac.generateRbacRoleDescriptors('hsOfficePartnerDetails', 'hs_office_partner_details'); +call rbac.generateRbacRoleDescriptors('hsOfficePartnerDetails', 'hs_office.partner_details'); --// @@ -24,8 +24,8 @@ call rbac.generateRbacRoleDescriptors('hsOfficePartnerDetails', 'hs_office_partn Creates the roles, grants and permission for the AFTER INSERT TRIGGER. */ -create or replace procedure buildRbacSystemForHsOfficePartnerDetails( - NEW hs_office_partner_details +create or replace procedure hs_office.partner_details_build_rbac_system( + NEW hs_office.partner_details ) language plpgsql as $$ @@ -38,22 +38,22 @@ begin end; $$; /* - AFTER INSERT TRIGGER to create the role+grant structure for a new hs_office_partner_details row. + AFTER INSERT TRIGGER to create the role+grant structure for a new hs_office.partner_details row. */ -create or replace function insertTriggerForHsOfficePartnerDetails_tf() +create or replace function hs_office.partner_details_build_rbac_system_after_insert_tf() returns trigger language plpgsql strict as $$ begin - call buildRbacSystemForHsOfficePartnerDetails(NEW); + call hs_office.partner_details_build_rbac_system(NEW); return NEW; end; $$; -create trigger insertTriggerForHsOfficePartnerDetails_tg - after insert on hs_office_partner_details +create trigger build_rbac_system_after_insert_tg + after insert on hs_office.partner_details for each row -execute procedure insertTriggerForHsOfficePartnerDetails_tf(); +execute procedure hs_office.partner_details_build_rbac_system_after_insert_tf(); --// @@ -64,45 +64,45 @@ execute procedure insertTriggerForHsOfficePartnerDetails_tf(); -- granting INSERT permission to rbac.global ---------------------------- /* - Grants INSERT INTO hs_office_partner_details permissions to specified role of pre-existing rbac.global rows. + Grants INSERT INTO hs_office.partner_details permissions to specified role of pre-existing rbac.global rows. */ do language plpgsql $$ declare row rbac.global; begin - call base.defineContext('create INSERT INTO hs_office_partner_details permissions for pre-exising rbac.global rows'); + call base.defineContext('create INSERT INTO hs_office.partner_details permissions for pre-exising rbac.global rows'); FOR row IN SELECT * FROM rbac.global -- unconditional for all rows in that table LOOP call rbac.grantPermissionToRole( - rbac.createPermission(row.uuid, 'INSERT', 'hs_office_partner_details'), + rbac.createPermission(row.uuid, 'INSERT', 'hs_office.partner_details'), rbac.globalADMIN()); END LOOP; end; $$; /** - Grants hs_office_partner_details INSERT permission to specified role of new global rows. + Grants hs_office.partner_details INSERT permission to specified role of new global rows. */ -create or replace function new_hsof_partner_details_grants_insert_to_global_tf() +create or replace function hs_office.new_partner_details_grants_insert_to_global_tf() returns trigger language plpgsql strict as $$ begin -- unconditional for all rows in that table call rbac.grantPermissionToRole( - rbac.createPermission(NEW.uuid, 'INSERT', 'hs_office_partner_details'), + rbac.createPermission(NEW.uuid, 'INSERT', 'hs_office.partner_details'), rbac.globalADMIN()); -- end. return NEW; end; $$; -- z_... is to put it at the end of after insert triggers, to make sure the roles exist -create trigger z_new_hs_office_partner_details_grants_after_insert_tg +create trigger z_new_partner_details_grants_after_insert_tg after insert on rbac.global for each row -execute procedure new_hsof_partner_details_grants_insert_to_global_tf(); +execute procedure hs_office.new_partner_details_grants_insert_to_global_tf(); -- ============================================================================ @@ -110,27 +110,27 @@ execute procedure new_hsof_partner_details_grants_insert_to_global_tf(); -- ---------------------------------------------------------------------------- /** - Checks if the user respectively the assumed roles are allowed to insert a row to hs_office_partner_details. + Checks if the user respectively the assumed roles are allowed to insert a row to hs_office.partner_details. */ -create or replace function hs_office_partner_details_insert_permission_check_tf() +create or replace function hs_office.partner_details_insert_permission_check_tf() returns trigger language plpgsql as $$ declare superObjectUuid uuid; begin - -- check INSERT INSERT if rbac.global ADMIN + -- check INSERT permission if rbac.global ADMIN if rbac.isGlobalAdmin() then return NEW; end if; - raise exception '[403] insert into hs_office_partner_details values(%) not allowed for current subjects % (%)', + raise exception '[403] insert into hs_office.partner_details values(%) not allowed for current subjects % (%)', NEW, base.currentSubjects(), rbac.currentSubjectOrAssumedRolesUuids(); end; $$; -create trigger hs_office_partner_details_insert_permission_check_tg - before insert on hs_office_partner_details +create trigger partner_details_insert_permission_check_tg + before insert on hs_office.partner_details for each row - execute procedure hs_office_partner_details_insert_permission_check_tf(); + execute procedure hs_office.partner_details_insert_permission_check_tf(); --// @@ -138,12 +138,12 @@ create trigger hs_office_partner_details_insert_permission_check_tg --changeset RbacIdentityViewGenerator:hs-office-partner-details-rbac-IDENTITY-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call rbac.generateRbacIdentityViewFromQuery('hs_office_partner_details', +call rbac.generateRbacIdentityViewFromQuery('hs_office.partner_details', $idName$ SELECT partnerDetails.uuid as uuid, partner_iv.idName as idName - FROM hs_office_partner_details AS partnerDetails - JOIN hs_office_partner partner ON partner.detailsUuid = partnerDetails.uuid - JOIN hs_office_partner_iv partner_iv ON partner_iv.uuid = partner.uuid + FROM hs_office.partner_details AS partnerDetails + JOIN hs_office.partner partner ON partner.detailsUuid = partnerDetails.uuid + JOIN hs_office.partner_iv partner_iv ON partner_iv.uuid = partner.uuid $idName$); --// @@ -151,7 +151,7 @@ call rbac.generateRbacIdentityViewFromQuery('hs_office_partner_details', -- ============================================================================ --changeset RbacRestrictedViewGenerator:hs-office-partner-details-rbac-RESTRICTED-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call rbac.generateRbacRestrictedView('hs_office_partner_details', +call rbac.generateRbacRestrictedView('hs_office.partner_details', $orderBy$ uuid $orderBy$, diff --git a/src/main/resources/db/changelog/5-hs-office/504-partner/5046-hs-office-partner-migration.sql b/src/main/resources/db/changelog/5-hs-office/504-partner/5046-hs-office-partner-migration.sql index 9facdb93..5e79ecf8 100644 --- a/src/main/resources/db/changelog/5-hs-office/504-partner/5046-hs-office-partner-migration.sql +++ b/src/main/resources/db/changelog/5-hs-office/504-partner/5046-hs-office-partner-migration.sql @@ -7,9 +7,9 @@ --changeset michael.hoennig:hs-office-partner-MIGRATION-mapping endDelimiter:--// -- ---------------------------------------------------------------------------- -CREATE TABLE hs_office_partner_legacy_id +CREATE TABLE hs_office.partner_legacy_id ( - uuid uuid NOT NULL REFERENCES hs_office_partner(uuid), + uuid uuid NOT NULL REFERENCES hs_office.partner(uuid), bp_id integer NOT NULL ); --// @@ -19,10 +19,10 @@ CREATE TABLE hs_office_partner_legacy_id --changeset michael.hoennig:hs-office-partner-MIGRATION-sequence endDelimiter:--// -- ---------------------------------------------------------------------------- -CREATE SEQUENCE IF NOT EXISTS hs_office_partner_legacy_id_seq +CREATE SEQUENCE IF NOT EXISTS hs_office.partner_legacy_id_seq AS integer START 1000000000 - OWNED BY hs_office_partner_legacy_id.bp_id; + OWNED BY hs_office.partner_legacy_id.bp_id; --// @@ -30,9 +30,9 @@ CREATE SEQUENCE IF NOT EXISTS hs_office_partner_legacy_id_seq --changeset michael.hoennig:hs-office-partner-MIGRATION-default endDelimiter:--// -- ---------------------------------------------------------------------------- -ALTER TABLE hs_office_partner_legacy_id +ALTER TABLE hs_office.partner_legacy_id ALTER COLUMN bp_id - SET DEFAULT nextVal('hs_office_partner_legacy_id_seq'); + SET DEFAULT nextVal('hs_office.partner_legacy_id_seq'); --/ -- ============================================================================ @@ -40,8 +40,8 @@ ALTER TABLE hs_office_partner_legacy_id -- ---------------------------------------------------------------------------- CALL base.defineContext('schema-migration'); -INSERT INTO hs_office_partner_legacy_id(uuid, bp_id) - SELECT uuid, nextVal('hs_office_partner_legacy_id_seq') FROM hs_office_partner; +INSERT INTO hs_office.partner_legacy_id(uuid, bp_id) + SELECT uuid, nextVal('hs_office.partner_legacy_id_seq') FROM hs_office.partner; --/ @@ -57,14 +57,14 @@ begin raise exception 'invalid usage of trigger'; end if; - INSERT INTO hs_office_partner_legacy_id VALUES - (NEW.uuid, nextVal('hs_office_partner_legacy_id_seq')); + INSERT INTO hs_office.partner_legacy_id VALUES + (NEW.uuid, nextVal('hs_office.partner_legacy_id_seq')); return NEW; end; $$; create trigger createPartnerLegacyIdMapping - after insert on hs_office_partner + after insert on hs_office.partner for each row execute procedure insertPartnerLegacyIdMapping(); --/ @@ -82,14 +82,14 @@ begin raise exception 'invalid usage of trigger'; end if; - DELETE FROM hs_office_partner_legacy_id + DELETE FROM hs_office.partner_legacy_id WHERE uuid = OLD.uuid; return OLD; end; $$; create trigger removePartnerLegacyIdMapping - before delete on hs_office_partner + before delete on hs_office.partner for each row execute procedure deletePartnerLegacyIdMapping(); --/ diff --git a/src/main/resources/db/changelog/5-hs-office/504-partner/5048-hs-office-partner-test-data.sql b/src/main/resources/db/changelog/5-hs-office/504-partner/5048-hs-office-partner-test-data.sql index c28192b3..114158c5 100644 --- a/src/main/resources/db/changelog/5-hs-office/504-partner/5048-hs-office-partner-test-data.sql +++ b/src/main/resources/db/changelog/5-hs-office/504-partner/5048-hs-office-partner-test-data.sql @@ -16,25 +16,25 @@ create or replace procedure createHsOfficePartnerTestData( language plpgsql as $$ declare idName varchar; - mandantPerson hs_office_person; - partnerRel hs_office_relation; - relatedPerson hs_office_person; + mandantPerson hs_office.person; + partnerRel hs_office.relation; + relatedPerson hs_office.person; relatedDetailsUuid uuid; begin idName := base.cleanIdentifier( partnerPersonName|| '-' || contactCaption); - select p.* from hs_office_person p + select p.* from hs_office.person p where p.tradeName = mandantTradeName into mandantPerson; if mandantPerson is null then raise exception 'mandant "%" not found', mandantTradeName; end if; - select p.* from hs_office_person p + select p.* from hs_office.person p where p.tradeName = partnerPersonName or p.familyName = partnerPersonName into relatedPerson; - select r.* from hs_office_relation r + select r.* from hs_office.relation r where r.type = 'PARTNER' and r.anchoruuid = mandantPerson.uuid and r.holderuuid = relatedPerson.uuid into partnerRel; @@ -48,18 +48,18 @@ begin if relatedPerson.persontype = 'NP' then insert - into hs_office_partner_details (uuid, birthName, birthday, birthPlace) + into hs_office.partner_details (uuid, birthName, birthday, birthPlace) values (uuid_generate_v4(), 'Meyer', '1987-10-31', 'Hamburg') returning uuid into relatedDetailsUuid; else insert - into hs_office_partner_details (uuid, registrationOffice, registrationNumber) + into hs_office.partner_details (uuid, registrationOffice, registrationNumber) values (uuid_generate_v4(), 'Hamburg', 'RegNo123456789') returning uuid into relatedDetailsUuid; end if; insert - into hs_office_partner (uuid, partnerNumber, partnerRelUuid, detailsUuid) + into hs_office.partner (uuid, partnerNumber, partnerRelUuid, detailsUuid) values (uuid_generate_v4(), newPartnerNumber, partnerRel.uuid, relatedDetailsUuid); end; $$; --// diff --git a/src/main/resources/db/changelog/5-hs-office/505-bankaccount/5050-hs-office-bankaccount.sql b/src/main/resources/db/changelog/5-hs-office/505-bankaccount/5050-hs-office-bankaccount.sql index 8b27cbe9..f651faaa 100644 --- a/src/main/resources/db/changelog/5-hs-office/505-bankaccount/5050-hs-office-bankaccount.sql +++ b/src/main/resources/db/changelog/5-hs-office/505-bankaccount/5050-hs-office-bankaccount.sql @@ -3,7 +3,7 @@ --changeset michael.hoennig:hs-office-bankaccount-MAIN-TABLE endDelimiter:--// -- ---------------------------------------------------------------------------- -create table hs_office_bankaccount +create table hs_office.bankaccount ( uuid uuid unique references rbac.object (uuid) initially deferred, version int not null default 0, @@ -18,5 +18,5 @@ create table hs_office_bankaccount --changeset michael.hoennig:hs-office-bankaccount-MAIN-TABLE-JOURNAL endDelimiter:--// -- ---------------------------------------------------------------------------- -call base.create_journal('hs_office_bankaccount'); +call base.create_journal('hs_office.bankaccount'); --// diff --git a/src/main/resources/db/changelog/5-hs-office/505-bankaccount/5053-hs-office-bankaccount-rbac.sql b/src/main/resources/db/changelog/5-hs-office/505-bankaccount/5053-hs-office-bankaccount-rbac.sql index 4b8895d7..02775bf1 100644 --- a/src/main/resources/db/changelog/5-hs-office/505-bankaccount/5053-hs-office-bankaccount-rbac.sql +++ b/src/main/resources/db/changelog/5-hs-office/505-bankaccount/5053-hs-office-bankaccount-rbac.sql @@ -5,14 +5,14 @@ -- ============================================================================ --changeset RbacObjectGenerator:hs-office-bankaccount-rbac-OBJECT endDelimiter:--// -- ---------------------------------------------------------------------------- -call rbac.generateRelatedRbacObject('hs_office_bankaccount'); +call rbac.generateRelatedRbacObject('hs_office.bankaccount'); --// -- ============================================================================ --changeset RbacRoleDescriptorsGenerator:hs-office-bankaccount-rbac-ROLE-DESCRIPTORS endDelimiter:--// -- ---------------------------------------------------------------------------- -call rbac.generateRbacRoleDescriptors('hsOfficeBankAccount', 'hs_office_bankaccount'); +call rbac.generateRbacRoleDescriptors('hsOfficeBankAccount', 'hs_office.bankaccount'); --// @@ -24,8 +24,8 @@ call rbac.generateRbacRoleDescriptors('hsOfficeBankAccount', 'hs_office_bankacco Creates the roles, grants and permission for the AFTER INSERT TRIGGER. */ -create or replace procedure buildRbacSystemForHsOfficeBankAccount( - NEW hs_office_bankaccount +create or replace procedure hs_office.bankaccount_build_rbac_system( + NEW hs_office.bankaccount ) language plpgsql as $$ @@ -57,22 +57,22 @@ begin end; $$; /* - AFTER INSERT TRIGGER to create the role+grant structure for a new hs_office_bankaccount row. + AFTER INSERT TRIGGER to create the role+grant structure for a new hs_office.bankaccount row. */ -create or replace function insertTriggerForHsOfficeBankAccount_tf() +create or replace function hs_office.bankaccount_build_rbac_system_after_insert_tf() returns trigger language plpgsql strict as $$ begin - call buildRbacSystemForHsOfficeBankAccount(NEW); + call hs_office.bankaccount_build_rbac_system(NEW); return NEW; end; $$; -create trigger insertTriggerForHsOfficeBankAccount_tg - after insert on hs_office_bankaccount +create trigger build_rbac_system_after_insert_tg + after insert on hs_office.bankaccount for each row -execute procedure insertTriggerForHsOfficeBankAccount_tf(); +execute procedure hs_office.bankaccount_build_rbac_system_after_insert_tf(); --// @@ -80,7 +80,7 @@ execute procedure insertTriggerForHsOfficeBankAccount_tf(); --changeset RbacIdentityViewGenerator:hs-office-bankaccount-rbac-IDENTITY-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call rbac.generateRbacIdentityViewFromProjection('hs_office_bankaccount', +call rbac.generateRbacIdentityViewFromProjection('hs_office.bankaccount', $idName$ iban $idName$); @@ -90,7 +90,7 @@ call rbac.generateRbacIdentityViewFromProjection('hs_office_bankaccount', -- ============================================================================ --changeset RbacRestrictedViewGenerator:hs-office-bankaccount-rbac-RESTRICTED-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call rbac.generateRbacRestrictedView('hs_office_bankaccount', +call rbac.generateRbacRestrictedView('hs_office.bankaccount', $orderBy$ iban $orderBy$, diff --git a/src/main/resources/db/changelog/5-hs-office/505-bankaccount/5058-hs-office-bankaccount-test-data.sql b/src/main/resources/db/changelog/5-hs-office/505-bankaccount/5058-hs-office-bankaccount-test-data.sql index aa28bdf4..0a8123eb 100644 --- a/src/main/resources/db/changelog/5-hs-office/505-bankaccount/5058-hs-office-bankaccount-test-data.sql +++ b/src/main/resources/db/changelog/5-hs-office/505-bankaccount/5058-hs-office-bankaccount-test-data.sql @@ -19,7 +19,7 @@ begin raise notice 'creating test bankaccount: %', givenHolder; insert - into hs_office_bankaccount(uuid, holder, iban, bic) + into hs_office.bankaccount(uuid, holder, iban, bic) values (uuid_generate_v4(), givenHolder, givenIBAN, givenBIC); end; $$; --// diff --git a/src/main/resources/db/changelog/5-hs-office/506-debitor/5060-hs-office-debitor.sql b/src/main/resources/db/changelog/5-hs-office/506-debitor/5060-hs-office-debitor.sql index 3ea372f7..f9639533 100644 --- a/src/main/resources/db/changelog/5-hs-office/506-debitor/5060-hs-office-debitor.sql +++ b/src/main/resources/db/changelog/5-hs-office/506-debitor/5060-hs-office-debitor.sql @@ -4,18 +4,18 @@ --changeset michael.hoennig:hs-office-debitor-MAIN-TABLE endDelimiter:--// -- ---------------------------------------------------------------------------- -create table hs_office_debitor +create table hs_office.debitor ( uuid uuid unique references rbac.object (uuid) initially deferred, version int not null default 0, debitorNumberSuffix char(2) not null check (debitorNumberSuffix::text ~ '^[0-9][0-9]$'), - debitorRelUuid uuid not null references hs_office_relation(uuid), + debitorRelUuid uuid not null references hs_office.relation(uuid), billable boolean not null default true, vatId varchar(24), vatCountryCode varchar(2), vatBusiness boolean not null, vatReverseCharge boolean not null, - refundBankAccountUuid uuid references hs_office_bankaccount(uuid), + refundBankAccountUuid uuid references hs_office.bankaccount(uuid), defaultPrefix char(3) not null unique constraint check_default_prefix check ( defaultPrefix::text ~ '^([a-z]{3}|al0|bh1|c4s|f3k|k8i|l3d|mh1|o13|p2m|s80|t4w)$' @@ -29,16 +29,16 @@ create table hs_office_debitor -- ---------------------------------------------------------------------------- /** - Trigger function to delete related rows of a debitor to delete. + Trigger function to delete related relations of a debitor to delete. */ -create or replace function deleteHsOfficeDependentsOnDebitorDelete() +create or replace function hs_office.debitor_delete_dependents_tf() returns trigger language PLPGSQL as $$ declare counter integer; begin - DELETE FROM hs_office_relation r WHERE r.uuid = OLD.debitorRelUuid; + DELETE FROM hs_office.relation r WHERE r.uuid = OLD.debitorRelUuid; GET DIAGNOSTICS counter = ROW_COUNT; if counter = 0 then raise exception 'debitor relation % could not be deleted', OLD.debitorRelUuid; @@ -50,16 +50,16 @@ end; $$; /** Triggers deletion of related details of a debitor to delete. */ -create trigger hs_office_debitor_delete_dependents_trigger +create trigger debitor_delete_dependents_tg after delete - on hs_office_debitor + on hs_office.debitor for each row -execute procedure deleteHsOfficeDependentsOnDebitorDelete(); +execute procedure hs_office.debitor_delete_dependents_tf(); -- ============================================================================ --changeset michael.hoennig:hs-office-debitor-MAIN-TABLE-JOURNAL endDelimiter:--// -- ---------------------------------------------------------------------------- -call base.create_journal('hs_office_debitor'); +call base.create_journal('hs_office.debitor'); --// diff --git a/src/main/resources/db/changelog/5-hs-office/506-debitor/5063-hs-office-debitor-rbac.sql b/src/main/resources/db/changelog/5-hs-office/506-debitor/5063-hs-office-debitor-rbac.sql index 994dea2f..dd3abfa8 100644 --- a/src/main/resources/db/changelog/5-hs-office/506-debitor/5063-hs-office-debitor-rbac.sql +++ b/src/main/resources/db/changelog/5-hs-office/506-debitor/5063-hs-office-debitor-rbac.sql @@ -5,14 +5,14 @@ -- ============================================================================ --changeset RbacObjectGenerator:hs-office-debitor-rbac-OBJECT endDelimiter:--// -- ---------------------------------------------------------------------------- -call rbac.generateRelatedRbacObject('hs_office_debitor'); +call rbac.generateRelatedRbacObject('hs_office.debitor'); --// -- ============================================================================ --changeset RbacRoleDescriptorsGenerator:hs-office-debitor-rbac-ROLE-DESCRIPTORS endDelimiter:--// -- ---------------------------------------------------------------------------- -call rbac.generateRbacRoleDescriptors('hsOfficeDebitor', 'hs_office_debitor'); +call rbac.generateRbacRoleDescriptors('hsOfficeDebitor', 'hs_office.debitor'); --// @@ -24,32 +24,32 @@ call rbac.generateRbacRoleDescriptors('hsOfficeDebitor', 'hs_office_debitor'); Creates the roles, grants and permission for the AFTER INSERT TRIGGER. */ -create or replace procedure buildRbacSystemForHsOfficeDebitor( - NEW hs_office_debitor +create or replace procedure hs_office.debitor_build_rbac_system( + NEW hs_office.debitor ) language plpgsql as $$ declare - newPartnerRel hs_office_relation; - newDebitorRel hs_office_relation; - newRefundBankAccount hs_office_bankaccount; + newPartnerRel hs_office.relation; + newDebitorRel hs_office.relation; + newRefundBankAccount hs_office.bankaccount; begin call rbac.enterTriggerForObjectUuid(NEW.uuid); SELECT partnerRel.* - FROM hs_office_relation AS partnerRel - JOIN hs_office_relation AS debitorRel + FROM hs_office.relation AS partnerRel + JOIN hs_office.relation AS debitorRel ON debitorRel.type = 'DEBITOR' AND debitorRel.anchorUuid = partnerRel.holderUuid WHERE partnerRel.type = 'PARTNER' AND NEW.debitorRelUuid = debitorRel.uuid INTO newPartnerRel; assert newPartnerRel.uuid is not null, format('newPartnerRel must not be null for NEW.debitorRelUuid = %s', NEW.debitorRelUuid); - SELECT * FROM hs_office_relation WHERE uuid = NEW.debitorRelUuid INTO newDebitorRel; + SELECT * FROM hs_office.relation WHERE uuid = NEW.debitorRelUuid INTO newDebitorRel; assert newDebitorRel.uuid is not null, format('newDebitorRel must not be null for NEW.debitorRelUuid = %s', NEW.debitorRelUuid); - SELECT * FROM hs_office_bankaccount WHERE uuid = NEW.refundBankAccountUuid INTO newRefundBankAccount; + SELECT * FROM hs_office.bankaccount WHERE uuid = NEW.refundBankAccountUuid INTO newRefundBankAccount; call rbac.grantRoleToRole(hsOfficeBankAccountREFERRER(newRefundBankAccount), hsOfficeRelationAGENT(newDebitorRel)); call rbac.grantRoleToRole(hsOfficeRelationADMIN(newDebitorRel), hsOfficeRelationADMIN(newPartnerRel)); @@ -65,22 +65,22 @@ begin end; $$; /* - AFTER INSERT TRIGGER to create the role+grant structure for a new hs_office_debitor row. + AFTER INSERT TRIGGER to create the role+grant structure for a new hs_office.debitor row. */ -create or replace function insertTriggerForHsOfficeDebitor_tf() +create or replace function hs_office.debitor_build_rbac_system_after_insert_tf() returns trigger language plpgsql strict as $$ begin - call buildRbacSystemForHsOfficeDebitor(NEW); + call hs_office.debitor_build_rbac_system(NEW); return NEW; end; $$; -create trigger insertTriggerForHsOfficeDebitor_tg - after insert on hs_office_debitor +create trigger build_rbac_system_after_insert_tg + after insert on hs_office.debitor for each row -execute procedure insertTriggerForHsOfficeDebitor_tf(); +execute procedure hs_office.debitor_build_rbac_system_after_insert_tf(); --// @@ -92,9 +92,9 @@ execute procedure insertTriggerForHsOfficeDebitor_tf(); Called from the AFTER UPDATE TRIGGER to re-wire the grants. */ -create or replace procedure updateRbacRulesForHsOfficeDebitor( - OLD hs_office_debitor, - NEW hs_office_debitor +create or replace procedure hs_office.debitor_update_rbac_system( + OLD hs_office.debitor, + NEW hs_office.debitor ) language plpgsql as $$ begin @@ -102,27 +102,27 @@ begin if NEW.debitorRelUuid is distinct from OLD.debitorRelUuid or NEW.refundBankAccountUuid is distinct from OLD.refundBankAccountUuid then delete from rbac.grants g where g.grantedbytriggerof = OLD.uuid; - call buildRbacSystemForHsOfficeDebitor(NEW); + call hs_office.debitor_build_rbac_system(NEW); end if; end; $$; /* - AFTER INSERT TRIGGER to re-wire the grant structure for a new hs_office_debitor row. + AFTER UPDATE TRIGGER to re-wire the grant structure for a new hs_office.debitor row. */ -create or replace function updateTriggerForHsOfficeDebitor_tf() +create or replace function hs_office.debitor_update_rbac_system_after_update_tf() returns trigger language plpgsql strict as $$ begin - call updateRbacRulesForHsOfficeDebitor(OLD, NEW); + call hs_office.debitor_update_rbac_system(OLD, NEW); return NEW; end; $$; -create trigger updateTriggerForHsOfficeDebitor_tg - after update on hs_office_debitor +create trigger update_rbac_system_after_update_tg + after update on hs_office.debitor for each row -execute procedure updateTriggerForHsOfficeDebitor_tf(); +execute procedure hs_office.debitor_update_rbac_system_after_update_tf(); --// @@ -133,45 +133,45 @@ execute procedure updateTriggerForHsOfficeDebitor_tf(); -- granting INSERT permission to rbac.global ---------------------------- /* - Grants INSERT INTO hs_office_debitor permissions to specified role of pre-existing rbac.global rows. + Grants INSERT INTO hs_office.debitor permissions to specified role of pre-existing rbac.global rows. */ do language plpgsql $$ declare row rbac.global; begin - call base.defineContext('create INSERT INTO hs_office_debitor permissions for pre-exising rbac.global rows'); + call base.defineContext('create INSERT INTO hs_office.debitor permissions for pre-exising rbac.global rows'); FOR row IN SELECT * FROM rbac.global -- unconditional for all rows in that table LOOP call rbac.grantPermissionToRole( - rbac.createPermission(row.uuid, 'INSERT', 'hs_office_debitor'), + rbac.createPermission(row.uuid, 'INSERT', 'hs_office.debitor'), rbac.globalADMIN()); END LOOP; end; $$; /** - Grants hs_office_debitor INSERT permission to specified role of new global rows. + Grants hs_office.debitor INSERT permission to specified role of new global rows. */ -create or replace function new_hsof_debitor_grants_insert_to_global_tf() +create or replace function hs_office.new_debitor_grants_insert_to_global_tf() returns trigger language plpgsql strict as $$ begin -- unconditional for all rows in that table call rbac.grantPermissionToRole( - rbac.createPermission(NEW.uuid, 'INSERT', 'hs_office_debitor'), + rbac.createPermission(NEW.uuid, 'INSERT', 'hs_office.debitor'), rbac.globalADMIN()); -- end. return NEW; end; $$; -- z_... is to put it at the end of after insert triggers, to make sure the roles exist -create trigger z_new_hs_office_debitor_grants_after_insert_tg +create trigger z_new_debitor_grants_after_insert_tg after insert on rbac.global for each row -execute procedure new_hsof_debitor_grants_insert_to_global_tf(); +execute procedure hs_office.new_debitor_grants_insert_to_global_tf(); -- ============================================================================ @@ -179,27 +179,27 @@ execute procedure new_hsof_debitor_grants_insert_to_global_tf(); -- ---------------------------------------------------------------------------- /** - Checks if the user respectively the assumed roles are allowed to insert a row to hs_office_debitor. + Checks if the user respectively the assumed roles are allowed to insert a row to hs_office.debitor. */ -create or replace function hs_office_debitor_insert_permission_check_tf() +create or replace function hs_office.debitor_insert_permission_check_tf() returns trigger language plpgsql as $$ declare superObjectUuid uuid; begin - -- check INSERT INSERT if rbac.global ADMIN + -- check INSERT permission if rbac.global ADMIN if rbac.isGlobalAdmin() then return NEW; end if; - raise exception '[403] insert into hs_office_debitor values(%) not allowed for current subjects % (%)', + raise exception '[403] insert into hs_office.debitor values(%) not allowed for current subjects % (%)', NEW, base.currentSubjects(), rbac.currentSubjectOrAssumedRolesUuids(); end; $$; -create trigger hs_office_debitor_insert_permission_check_tg - before insert on hs_office_debitor +create trigger debitor_insert_permission_check_tg + before insert on hs_office.debitor for each row - execute procedure hs_office_debitor_insert_permission_check_tf(); + execute procedure hs_office.debitor_insert_permission_check_tf(); --// @@ -207,18 +207,18 @@ create trigger hs_office_debitor_insert_permission_check_tg --changeset RbacIdentityViewGenerator:hs-office-debitor-rbac-IDENTITY-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call rbac.generateRbacIdentityViewFromQuery('hs_office_debitor', +call rbac.generateRbacIdentityViewFromQuery('hs_office.debitor', $idName$ SELECT debitor.uuid AS uuid, 'D-' || (SELECT partner.partnerNumber - FROM hs_office_partner partner - JOIN hs_office_relation partnerRel + FROM hs_office.partner partner + JOIN hs_office.relation partnerRel ON partnerRel.uuid = partner.partnerRelUUid AND partnerRel.type = 'PARTNER' - JOIN hs_office_relation debitorRel + JOIN hs_office.relation debitorRel ON debitorRel.anchorUuid = partnerRel.holderUuid AND debitorRel.type = 'DEBITOR' WHERE debitorRel.uuid = debitor.debitorRelUuid) || debitorNumberSuffix as idName - FROM hs_office_debitor AS debitor + FROM hs_office.debitor AS debitor $idName$); --// @@ -226,7 +226,7 @@ call rbac.generateRbacIdentityViewFromQuery('hs_office_debitor', -- ============================================================================ --changeset RbacRestrictedViewGenerator:hs-office-debitor-rbac-RESTRICTED-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call rbac.generateRbacRestrictedView('hs_office_debitor', +call rbac.generateRbacRestrictedView('hs_office.debitor', $orderBy$ defaultPrefix $orderBy$, diff --git a/src/main/resources/db/changelog/5-hs-office/506-debitor/5068-hs-office-debitor-test-data.sql b/src/main/resources/db/changelog/5-hs-office/506-debitor/5068-hs-office-debitor-test-data.sql index a648bace..df82033d 100644 --- a/src/main/resources/db/changelog/5-hs-office/506-debitor/5068-hs-office-debitor-test-data.sql +++ b/src/main/resources/db/changelog/5-hs-office/506-debitor/5068-hs-office-debitor-test-data.sql @@ -24,21 +24,21 @@ begin select debitorRel.uuid into relatedDebitorRelUuid - from hs_office_relation debitorRel - join hs_office_person person on person.uuid = debitorRel.holderUuid + from hs_office.relation debitorRel + join hs_office.person person on person.uuid = debitorRel.holderUuid and (person.tradeName = forPartnerPersonName or person.familyName = forPartnerPersonName) where debitorRel.type = 'DEBITOR'; select b.uuid into relatedBankAccountUuid - from hs_office_bankaccount b + from hs_office.bankaccount b where b.holder = forPartnerPersonName; raise notice 'creating test debitor: % (#%)', idName, withDebitorNumberSuffix; -- raise exception 'creating test debitor: (uuid=%, debitorRelUuid=%, debitornumbersuffix=%, billable=%, vatbusiness=%, vatreversecharge=%, refundbankaccountuuid=%, defaultprefix=%)', -- uuid_generate_v4(), relatedDebitorRelUuid, withDebitorNumberSuffix, true, true, false, relatedBankAccountUuid, withDefaultPrefix; insert - into hs_office_debitor (uuid, debitorRelUuid, debitornumbersuffix, billable, vatbusiness, vatreversecharge, refundbankaccountuuid, defaultprefix) + into hs_office.debitor (uuid, debitorRelUuid, debitornumbersuffix, billable, vatbusiness, vatreversecharge, refundbankaccountuuid, defaultprefix) values (uuid_generate_v4(), relatedDebitorRelUuid, withDebitorNumberSuffix, true, true, false, relatedBankAccountUuid, withDefaultPrefix); end; $$; --// diff --git a/src/main/resources/db/changelog/5-hs-office/507-sepamandate/5070-hs-office-sepamandate.sql b/src/main/resources/db/changelog/5-hs-office/507-sepamandate/5070-hs-office-sepamandate.sql index 16714cda..684ecb7a 100644 --- a/src/main/resources/db/changelog/5-hs-office/507-sepamandate/5070-hs-office-sepamandate.sql +++ b/src/main/resources/db/changelog/5-hs-office/507-sepamandate/5070-hs-office-sepamandate.sql @@ -4,12 +4,12 @@ --changeset michael.hoennig:hs-office-sepamandate-MAIN-TABLE endDelimiter:--// -- ---------------------------------------------------------------------------- -create table if not exists hs_office_sepamandate +create table if not exists hs_office.sepamandate ( uuid uuid unique references rbac.object (uuid) initially deferred, version int not null default 0, - debitorUuid uuid not null references hs_office_debitor(uuid), - bankAccountUuid uuid not null references hs_office_bankaccount(uuid), + debitorUuid uuid not null references hs_office.debitor(uuid), + bankAccountUuid uuid not null references hs_office.bankaccount(uuid), reference varchar(96) not null, agreement date not null, validity daterange not null @@ -21,5 +21,5 @@ create table if not exists hs_office_sepamandate --changeset michael.hoennig:hs-office-sepamandate-MAIN-TABLE-JOURNAL endDelimiter:--// -- ---------------------------------------------------------------------------- -call base.create_journal('hs_office_sepamandate'); +call base.create_journal('hs_office.sepamandate'); --// diff --git a/src/main/resources/db/changelog/5-hs-office/507-sepamandate/5073-hs-office-sepamandate-rbac.sql b/src/main/resources/db/changelog/5-hs-office/507-sepamandate/5073-hs-office-sepamandate-rbac.sql index 76cfe166..f9e4ef66 100644 --- a/src/main/resources/db/changelog/5-hs-office/507-sepamandate/5073-hs-office-sepamandate-rbac.sql +++ b/src/main/resources/db/changelog/5-hs-office/507-sepamandate/5073-hs-office-sepamandate-rbac.sql @@ -5,14 +5,14 @@ -- ============================================================================ --changeset RbacObjectGenerator:hs-office-sepamandate-rbac-OBJECT endDelimiter:--// -- ---------------------------------------------------------------------------- -call rbac.generateRelatedRbacObject('hs_office_sepamandate'); +call rbac.generateRelatedRbacObject('hs_office.sepamandate'); --// -- ============================================================================ --changeset RbacRoleDescriptorsGenerator:hs-office-sepamandate-rbac-ROLE-DESCRIPTORS endDelimiter:--// -- ---------------------------------------------------------------------------- -call rbac.generateRbacRoleDescriptors('hsOfficeSepaMandate', 'hs_office_sepamandate'); +call rbac.generateRbacRoleDescriptors('hsOfficeSepaMandate', 'hs_office.sepamandate'); --// @@ -24,24 +24,24 @@ call rbac.generateRbacRoleDescriptors('hsOfficeSepaMandate', 'hs_office_sepamand Creates the roles, grants and permission for the AFTER INSERT TRIGGER. */ -create or replace procedure buildRbacSystemForHsOfficeSepaMandate( - NEW hs_office_sepamandate +create or replace procedure hs_office.sepamandate_build_rbac_system( + NEW hs_office.sepamandate ) language plpgsql as $$ declare - newBankAccount hs_office_bankaccount; - newDebitorRel hs_office_relation; + newBankAccount hs_office.bankaccount; + newDebitorRel hs_office.relation; begin call rbac.enterTriggerForObjectUuid(NEW.uuid); - SELECT * FROM hs_office_bankaccount WHERE uuid = NEW.bankAccountUuid INTO newBankAccount; + SELECT * FROM hs_office.bankaccount WHERE uuid = NEW.bankAccountUuid INTO newBankAccount; assert newBankAccount.uuid is not null, format('newBankAccount must not be null for NEW.bankAccountUuid = %s', NEW.bankAccountUuid); SELECT debitorRel.* - FROM hs_office_relation debitorRel - JOIN hs_office_debitor debitor ON debitor.debitorRelUuid = debitorRel.uuid + FROM hs_office.relation debitorRel + JOIN hs_office.debitor debitor ON debitor.debitorRelUuid = debitorRel.uuid WHERE debitor.uuid = NEW.debitorUuid INTO newDebitorRel; assert newDebitorRel.uuid is not null, format('newDebitorRel must not be null for NEW.debitorUuid = %s', NEW.debitorUuid); @@ -82,22 +82,22 @@ begin end; $$; /* - AFTER INSERT TRIGGER to create the role+grant structure for a new hs_office_sepamandate row. + AFTER INSERT TRIGGER to create the role+grant structure for a new hs_office.sepamandate row. */ -create or replace function insertTriggerForHsOfficeSepaMandate_tf() +create or replace function hs_office.sepamandate_build_rbac_system_after_insert_tf() returns trigger language plpgsql strict as $$ begin - call buildRbacSystemForHsOfficeSepaMandate(NEW); + call hs_office.sepamandate_build_rbac_system(NEW); return NEW; end; $$; -create trigger insertTriggerForHsOfficeSepaMandate_tg - after insert on hs_office_sepamandate +create trigger build_rbac_system_after_insert_tg + after insert on hs_office.sepamandate for each row -execute procedure insertTriggerForHsOfficeSepaMandate_tf(); +execute procedure hs_office.sepamandate_build_rbac_system_after_insert_tf(); --// @@ -105,48 +105,48 @@ execute procedure insertTriggerForHsOfficeSepaMandate_tf(); --changeset InsertTriggerGenerator:hs-office-sepamandate-rbac-GRANTING-INSERT-PERMISSION endDelimiter:--// -- ---------------------------------------------------------------------------- --- granting INSERT permission to hs_office_relation ---------------------------- +-- granting INSERT permission to hs_office.relation ---------------------------- /* - Grants INSERT INTO hs_office_sepamandate permissions to specified role of pre-existing hs_office_relation rows. + Grants INSERT INTO hs_office.sepamandate permissions to specified role of pre-existing hs_office.relation rows. */ do language plpgsql $$ declare - row hs_office_relation; + row hs_office.relation; begin - call base.defineContext('create INSERT INTO hs_office_sepamandate permissions for pre-exising hs_office_relation rows'); + call base.defineContext('create INSERT INTO hs_office.sepamandate permissions for pre-exising hs_office.relation rows'); - FOR row IN SELECT * FROM hs_office_relation + FOR row IN SELECT * FROM hs_office.relation WHERE type = 'DEBITOR' LOOP call rbac.grantPermissionToRole( - rbac.createPermission(row.uuid, 'INSERT', 'hs_office_sepamandate'), + rbac.createPermission(row.uuid, 'INSERT', 'hs_office.sepamandate'), hsOfficeRelationADMIN(row)); END LOOP; end; $$; /** - Grants hs_office_sepamandate INSERT permission to specified role of new hs_office_relation rows. + Grants hs_office.sepamandate INSERT permission to specified role of new relation rows. */ -create or replace function new_hsof_sepamandate_grants_insert_to_hsof_relation_tf() +create or replace function hs_office.new_sepamandate_grants_insert_to_relation_tf() returns trigger language plpgsql strict as $$ begin if NEW.type = 'DEBITOR' then call rbac.grantPermissionToRole( - rbac.createPermission(NEW.uuid, 'INSERT', 'hs_office_sepamandate'), + rbac.createPermission(NEW.uuid, 'INSERT', 'hs_office.sepamandate'), hsOfficeRelationADMIN(NEW)); end if; return NEW; end; $$; -- z_... is to put it at the end of after insert triggers, to make sure the roles exist -create trigger z_new_hs_office_sepamandate_grants_after_insert_tg - after insert on hs_office_relation +create trigger z_new_sepamandate_grants_after_insert_tg + after insert on hs_office.relation for each row -execute procedure new_hsof_sepamandate_grants_insert_to_hsof_relation_tf(); +execute procedure hs_office.new_sepamandate_grants_insert_to_relation_tf(); -- ============================================================================ @@ -154,9 +154,9 @@ execute procedure new_hsof_sepamandate_grants_insert_to_hsof_relation_tf(); -- ---------------------------------------------------------------------------- /** - Checks if the user respectively the assumed roles are allowed to insert a row to hs_office_sepamandate. + Checks if the user respectively the assumed roles are allowed to insert a row to hs_office.sepamandate. */ -create or replace function hs_office_sepamandate_insert_permission_check_tf() +create or replace function hs_office.sepamandate_insert_permission_check_tf() returns trigger language plpgsql as $$ declare @@ -164,23 +164,23 @@ declare begin -- check INSERT permission via indirect foreign key: NEW.debitorUuid superObjectUuid := (SELECT debitorRel.uuid - FROM hs_office_relation debitorRel - JOIN hs_office_debitor debitor ON debitor.debitorRelUuid = debitorRel.uuid + FROM hs_office.relation debitorRel + JOIN hs_office.debitor debitor ON debitor.debitorRelUuid = debitorRel.uuid WHERE debitor.uuid = NEW.debitorUuid ); - assert superObjectUuid is not null, 'object uuid fetched depending on hs_office_sepamandate.debitorUuid must not be null, also check fetchSql in RBAC DSL'; - if rbac.hasInsertPermission(superObjectUuid, 'hs_office_sepamandate') then + assert superObjectUuid is not null, 'object uuid fetched depending on hs_office.sepamandate.debitorUuid must not be null, also check fetchSql in RBAC DSL'; + if rbac.hasInsertPermission(superObjectUuid, 'hs_office.sepamandate') then return NEW; end if; - raise exception '[403] insert into hs_office_sepamandate values(%) not allowed for current subjects % (%)', + raise exception '[403] insert into hs_office.sepamandate values(%) not allowed for current subjects % (%)', NEW, base.currentSubjects(), rbac.currentSubjectOrAssumedRolesUuids(); end; $$; -create trigger hs_office_sepamandate_insert_permission_check_tg - before insert on hs_office_sepamandate +create trigger sepamandate_insert_permission_check_tg + before insert on hs_office.sepamandate for each row - execute procedure hs_office_sepamandate_insert_permission_check_tf(); + execute procedure hs_office.sepamandate_insert_permission_check_tf(); --// @@ -188,11 +188,11 @@ create trigger hs_office_sepamandate_insert_permission_check_tg --changeset RbacIdentityViewGenerator:hs-office-sepamandate-rbac-IDENTITY-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call rbac.generateRbacIdentityViewFromQuery('hs_office_sepamandate', +call rbac.generateRbacIdentityViewFromQuery('hs_office.sepamandate', $idName$ select sm.uuid as uuid, ba.iban || '-' || sm.validity as idName - from hs_office_sepamandate sm - join hs_office_bankaccount ba on ba.uuid = sm.bankAccountUuid + from hs_office.sepamandate sm + join hs_office.bankaccount ba on ba.uuid = sm.bankAccountUuid $idName$); --// @@ -200,7 +200,7 @@ call rbac.generateRbacIdentityViewFromQuery('hs_office_sepamandate', -- ============================================================================ --changeset RbacRestrictedViewGenerator:hs-office-sepamandate-rbac-RESTRICTED-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call rbac.generateRbacRestrictedView('hs_office_sepamandate', +call rbac.generateRbacRestrictedView('hs_office.sepamandate', $orderBy$ validity $orderBy$, diff --git a/src/main/resources/db/changelog/5-hs-office/507-sepamandate/5076-hs-office-sepamandate-migration.sql b/src/main/resources/db/changelog/5-hs-office/507-sepamandate/5076-hs-office-sepamandate-migration.sql index 01e2298b..2446eff9 100644 --- a/src/main/resources/db/changelog/5-hs-office/507-sepamandate/5076-hs-office-sepamandate-migration.sql +++ b/src/main/resources/db/changelog/5-hs-office/507-sepamandate/5076-hs-office-sepamandate-migration.sql @@ -7,9 +7,9 @@ --changeset michael.hoennig:hs-office-sepamandate-MIGRATION-mapping endDelimiter:--// -- ---------------------------------------------------------------------------- -CREATE TABLE hs_office_sepamandate_legacy_id +CREATE TABLE hs_office.sepamandate_legacy_id ( - uuid uuid NOT NULL REFERENCES hs_office_sepamandate(uuid), + uuid uuid NOT NULL REFERENCES hs_office.sepamandate(uuid), sepa_mandate_id integer NOT NULL ); --// @@ -19,10 +19,10 @@ CREATE TABLE hs_office_sepamandate_legacy_id --changeset michael.hoennig:hs-office-sepamandate-MIGRATION-sequence endDelimiter:--// -- ---------------------------------------------------------------------------- -CREATE SEQUENCE IF NOT EXISTS hs_office_sepamandate_legacy_id_seq +CREATE SEQUENCE IF NOT EXISTS hs_office.sepamandate_legacy_id_seq AS integer START 1000000000 - OWNED BY hs_office_sepamandate_legacy_id.sepa_mandate_id; + OWNED BY hs_office.sepamandate_legacy_id.sepa_mandate_id; --// @@ -30,9 +30,9 @@ CREATE SEQUENCE IF NOT EXISTS hs_office_sepamandate_legacy_id_seq --changeset michael.hoennig:hs-office-sepamandate-MIGRATION-default endDelimiter:--// -- ---------------------------------------------------------------------------- -ALTER TABLE hs_office_sepamandate_legacy_id +ALTER TABLE hs_office.sepamandate_legacy_id ALTER COLUMN sepa_mandate_id - SET DEFAULT nextVal('hs_office_sepamandate_legacy_id_seq'); + SET DEFAULT nextVal('hs_office.sepamandate_legacy_id_seq'); --/ @@ -42,8 +42,8 @@ ALTER TABLE hs_office_sepamandate_legacy_id -- ---------------------------------------------------------------------------- CALL base.defineContext('schema-migration'); -INSERT INTO hs_office_sepamandate_legacy_id(uuid, sepa_mandate_id) - SELECT uuid, nextVal('hs_office_sepamandate_legacy_id_seq') FROM hs_office_sepamandate; +INSERT INTO hs_office.sepamandate_legacy_id(uuid, sepa_mandate_id) + SELECT uuid, nextVal('hs_office.sepamandate_legacy_id_seq') FROM hs_office.sepamandate; --/ @@ -59,14 +59,14 @@ begin raise exception 'invalid usage of trigger'; end if; - INSERT INTO hs_office_sepamandate_legacy_id VALUES - (NEW.uuid, nextVal('hs_office_sepamandate_legacy_id_seq')); + INSERT INTO hs_office.sepamandate_legacy_id VALUES + (NEW.uuid, nextVal('hs_office.sepamandate_legacy_id_seq')); return NEW; end; $$; create trigger createSepaMandateLegacyIdMapping - after insert on hs_office_sepamandate + after insert on hs_office.sepamandate for each row execute procedure insertSepaMandateLegacyIdMapping(); --/ @@ -84,14 +84,14 @@ begin raise exception 'invalid usage of trigger'; end if; - DELETE FROM hs_office_sepamandate_legacy_id + DELETE FROM hs_office.sepamandate_legacy_id WHERE uuid = OLD.uuid; return OLD; end; $$; create trigger removeSepaMandateLegacyIdMapping - before delete on hs_office_sepamandate + before delete on hs_office.sepamandate for each row execute procedure deleteSepaMandateLegacyIdMapping(); --/ diff --git a/src/main/resources/db/changelog/5-hs-office/507-sepamandate/5078-hs-office-sepamandate-test-data.sql b/src/main/resources/db/changelog/5-hs-office/507-sepamandate/5078-hs-office-sepamandate-test-data.sql index c737be8f..51e33f6b 100644 --- a/src/main/resources/db/changelog/5-hs-office/507-sepamandate/5078-hs-office-sepamandate-test-data.sql +++ b/src/main/resources/db/changelog/5-hs-office/507-sepamandate/5078-hs-office-sepamandate-test-data.sql @@ -15,23 +15,23 @@ create or replace procedure createHsOfficeSepaMandateTestData( withReference varchar) language plpgsql as $$ declare - relatedDebitor hs_office_debitor; - relatedBankAccount hs_office_bankAccount; + relatedDebitor hs_office.debitor; + relatedBankAccount hs_office.bankAccount; begin select debitor.* into relatedDebitor - from hs_office_debitor debitor - join hs_office_relation debitorRel on debitorRel.uuid = debitor.debitorRelUuid - join hs_office_relation partnerRel on partnerRel.holderUuid = debitorRel.anchorUuid - join hs_office_partner partner on partner.partnerRelUuid = partnerRel.uuid + from hs_office.debitor debitor + join hs_office.relation debitorRel on debitorRel.uuid = debitor.debitorRelUuid + join hs_office.relation partnerRel on partnerRel.holderUuid = debitorRel.anchorUuid + join hs_office.partner partner on partner.partnerRelUuid = partnerRel.uuid where partner.partnerNumber = forPartnerNumber and debitor.debitorNumberSuffix = forDebitorSuffix; select b.* into relatedBankAccount - from hs_office_bankAccount b where b.iban = forIban; + from hs_office.bankAccount b where b.iban = forIban; raise notice 'creating test SEPA-mandate: %', forPartnerNumber::text || forDebitorSuffix::text; raise notice '- using debitor (%): %', relatedDebitor.uuid, relatedDebitor; raise notice '- using bankAccount (%): %', relatedBankAccount.uuid, relatedBankAccount; insert - into hs_office_sepamandate (uuid, debitoruuid, bankAccountuuid, reference, agreement, validity) + into hs_office.sepamandate (uuid, debitoruuid, bankAccountuuid, reference, agreement, validity) values (uuid_generate_v4(), relatedDebitor.uuid, relatedBankAccount.uuid, withReference, '20220930', daterange('20221001' , '20261231', '[]')); end; $$; --// diff --git a/src/main/resources/db/changelog/5-hs-office/510-membership/5100-hs-office-membership.sql b/src/main/resources/db/changelog/5-hs-office/510-membership/5100-hs-office-membership.sql index 7fe4223e..e0147e5a 100644 --- a/src/main/resources/db/changelog/5-hs-office/510-membership/5100-hs-office-membership.sql +++ b/src/main/resources/db/changelog/5-hs-office/510-membership/5100-hs-office-membership.sql @@ -17,11 +17,11 @@ CREATE TYPE HsOfficeMembershipStatus AS ENUM ( CREATE CAST (character varying as HsOfficeMembershipStatus) WITH INOUT AS IMPLICIT; -create table if not exists hs_office_membership +create table if not exists hs_office.membership ( uuid uuid unique references rbac.object (uuid) initially deferred, version int not null default 0, - partnerUuid uuid not null references hs_office_partner(uuid), + partnerUuid uuid not null references hs_office.partner(uuid), memberNumberSuffix char(2) not null check (memberNumberSuffix::text ~ '^[0-9][0-9]$'), validity daterange not null, status HsOfficeMembershipStatus not null default 'ACTIVE', @@ -36,5 +36,5 @@ create table if not exists hs_office_membership --changeset michael.hoennig:hs-office-membership-MAIN-TABLE-JOURNAL endDelimiter:--// -- ---------------------------------------------------------------------------- -call base.create_journal('hs_office_membership'); +call base.create_journal('hs_office.membership'); --// diff --git a/src/main/resources/db/changelog/5-hs-office/510-membership/5103-hs-office-membership-rbac.sql b/src/main/resources/db/changelog/5-hs-office/510-membership/5103-hs-office-membership-rbac.sql index b5239725..18d53198 100644 --- a/src/main/resources/db/changelog/5-hs-office/510-membership/5103-hs-office-membership-rbac.sql +++ b/src/main/resources/db/changelog/5-hs-office/510-membership/5103-hs-office-membership-rbac.sql @@ -5,14 +5,14 @@ -- ============================================================================ --changeset RbacObjectGenerator:hs-office-membership-rbac-OBJECT endDelimiter:--// -- ---------------------------------------------------------------------------- -call rbac.generateRelatedRbacObject('hs_office_membership'); +call rbac.generateRelatedRbacObject('hs_office.membership'); --// -- ============================================================================ --changeset RbacRoleDescriptorsGenerator:hs-office-membership-rbac-ROLE-DESCRIPTORS endDelimiter:--// -- ---------------------------------------------------------------------------- -call rbac.generateRbacRoleDescriptors('hsOfficeMembership', 'hs_office_membership'); +call rbac.generateRbacRoleDescriptors('hsOfficeMembership', 'hs_office.membership'); --// @@ -24,20 +24,20 @@ call rbac.generateRbacRoleDescriptors('hsOfficeMembership', 'hs_office_membershi Creates the roles, grants and permission for the AFTER INSERT TRIGGER. */ -create or replace procedure buildRbacSystemForHsOfficeMembership( - NEW hs_office_membership +create or replace procedure hs_office.membership_build_rbac_system( + NEW hs_office.membership ) language plpgsql as $$ declare - newPartnerRel hs_office_relation; + newPartnerRel hs_office.relation; begin call rbac.enterTriggerForObjectUuid(NEW.uuid); SELECT partnerRel.* - FROM hs_office_partner AS partner - JOIN hs_office_relation AS partnerRel ON partnerRel.uuid = partner.partnerRelUuid + FROM hs_office.partner AS partner + JOIN hs_office.relation AS partnerRel ON partnerRel.uuid = partner.partnerRelUuid WHERE partner.uuid = NEW.partnerUuid INTO newPartnerRel; assert newPartnerRel.uuid is not null, format('newPartnerRel must not be null for NEW.partnerUuid = %s', NEW.partnerUuid); @@ -69,22 +69,22 @@ begin end; $$; /* - AFTER INSERT TRIGGER to create the role+grant structure for a new hs_office_membership row. + AFTER INSERT TRIGGER to create the role+grant structure for a new hs_office.membership row. */ -create or replace function insertTriggerForHsOfficeMembership_tf() +create or replace function hs_office.membership_build_rbac_system_after_insert_tf() returns trigger language plpgsql strict as $$ begin - call buildRbacSystemForHsOfficeMembership(NEW); + call hs_office.membership_build_rbac_system(NEW); return NEW; end; $$; -create trigger insertTriggerForHsOfficeMembership_tg - after insert on hs_office_membership +create trigger build_rbac_system_after_insert_tg + after insert on hs_office.membership for each row -execute procedure insertTriggerForHsOfficeMembership_tf(); +execute procedure hs_office.membership_build_rbac_system_after_insert_tf(); --// @@ -95,45 +95,45 @@ execute procedure insertTriggerForHsOfficeMembership_tf(); -- granting INSERT permission to rbac.global ---------------------------- /* - Grants INSERT INTO hs_office_membership permissions to specified role of pre-existing rbac.global rows. + Grants INSERT INTO hs_office.membership permissions to specified role of pre-existing rbac.global rows. */ do language plpgsql $$ declare row rbac.global; begin - call base.defineContext('create INSERT INTO hs_office_membership permissions for pre-exising rbac.global rows'); + call base.defineContext('create INSERT INTO hs_office.membership permissions for pre-exising rbac.global rows'); FOR row IN SELECT * FROM rbac.global -- unconditional for all rows in that table LOOP call rbac.grantPermissionToRole( - rbac.createPermission(row.uuid, 'INSERT', 'hs_office_membership'), + rbac.createPermission(row.uuid, 'INSERT', 'hs_office.membership'), rbac.globalADMIN()); END LOOP; end; $$; /** - Grants hs_office_membership INSERT permission to specified role of new global rows. + Grants hs_office.membership INSERT permission to specified role of new global rows. */ -create or replace function new_hsof_membership_grants_insert_to_global_tf() +create or replace function hs_office.new_membership_grants_insert_to_global_tf() returns trigger language plpgsql strict as $$ begin -- unconditional for all rows in that table call rbac.grantPermissionToRole( - rbac.createPermission(NEW.uuid, 'INSERT', 'hs_office_membership'), + rbac.createPermission(NEW.uuid, 'INSERT', 'hs_office.membership'), rbac.globalADMIN()); -- end. return NEW; end; $$; -- z_... is to put it at the end of after insert triggers, to make sure the roles exist -create trigger z_new_hs_office_membership_grants_after_insert_tg +create trigger z_new_membership_grants_after_insert_tg after insert on rbac.global for each row -execute procedure new_hsof_membership_grants_insert_to_global_tf(); +execute procedure hs_office.new_membership_grants_insert_to_global_tf(); -- ============================================================================ @@ -141,27 +141,27 @@ execute procedure new_hsof_membership_grants_insert_to_global_tf(); -- ---------------------------------------------------------------------------- /** - Checks if the user respectively the assumed roles are allowed to insert a row to hs_office_membership. + Checks if the user respectively the assumed roles are allowed to insert a row to hs_office.membership. */ -create or replace function hs_office_membership_insert_permission_check_tf() +create or replace function hs_office.membership_insert_permission_check_tf() returns trigger language plpgsql as $$ declare superObjectUuid uuid; begin - -- check INSERT INSERT if rbac.global ADMIN + -- check INSERT permission if rbac.global ADMIN if rbac.isGlobalAdmin() then return NEW; end if; - raise exception '[403] insert into hs_office_membership values(%) not allowed for current subjects % (%)', + raise exception '[403] insert into hs_office.membership values(%) not allowed for current subjects % (%)', NEW, base.currentSubjects(), rbac.currentSubjectOrAssumedRolesUuids(); end; $$; -create trigger hs_office_membership_insert_permission_check_tg - before insert on hs_office_membership +create trigger membership_insert_permission_check_tg + before insert on hs_office.membership for each row - execute procedure hs_office_membership_insert_permission_check_tf(); + execute procedure hs_office.membership_insert_permission_check_tf(); --// @@ -169,12 +169,12 @@ create trigger hs_office_membership_insert_permission_check_tg --changeset RbacIdentityViewGenerator:hs-office-membership-rbac-IDENTITY-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call rbac.generateRbacIdentityViewFromQuery('hs_office_membership', +call rbac.generateRbacIdentityViewFromQuery('hs_office.membership', $idName$ SELECT m.uuid AS uuid, 'M-' || p.partnerNumber || m.memberNumberSuffix as idName - FROM hs_office_membership AS m - JOIN hs_office_partner AS p ON p.uuid = m.partnerUuid + FROM hs_office.membership AS m + JOIN hs_office.partner AS p ON p.uuid = m.partnerUuid $idName$); --// @@ -182,7 +182,7 @@ call rbac.generateRbacIdentityViewFromQuery('hs_office_membership', -- ============================================================================ --changeset RbacRestrictedViewGenerator:hs-office-membership-rbac-RESTRICTED-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call rbac.generateRbacRestrictedView('hs_office_membership', +call rbac.generateRbacRestrictedView('hs_office.membership', $orderBy$ validity $orderBy$, diff --git a/src/main/resources/db/changelog/5-hs-office/510-membership/5108-hs-office-membership-test-data.sql b/src/main/resources/db/changelog/5-hs-office/510-membership/5108-hs-office-membership-test-data.sql index bb25dc6f..8b904d6d 100644 --- a/src/main/resources/db/changelog/5-hs-office/510-membership/5108-hs-office-membership-test-data.sql +++ b/src/main/resources/db/changelog/5-hs-office/510-membership/5108-hs-office-membership-test-data.sql @@ -13,15 +13,15 @@ create or replace procedure createHsOfficeMembershipTestData( newMemberNumberSuffix char(2) ) language plpgsql as $$ declare - relatedPartner hs_office_partner; + relatedPartner hs_office.partner; begin - select partner.* from hs_office_partner partner + select partner.* from hs_office.partner partner where partner.partnerNumber = forPartnerNumber into relatedPartner; raise notice 'creating test Membership: M-% %', forPartnerNumber, newMemberNumberSuffix; raise notice '- using partner (%): %', relatedPartner.uuid, relatedPartner; insert - into hs_office_membership (uuid, partneruuid, memberNumberSuffix, validity, status) + into hs_office.membership (uuid, partneruuid, memberNumberSuffix, validity, status) values (uuid_generate_v4(), relatedPartner.uuid, newMemberNumberSuffix, daterange('20221001' , null, '[]'), 'ACTIVE'); end; $$; --// diff --git a/src/main/resources/db/changelog/5-hs-office/511-coopshares/5110-hs-office-coopshares.sql b/src/main/resources/db/changelog/5-hs-office/511-coopshares/5110-hs-office-coopshares.sql index 119b4a2a..7e15a874 100644 --- a/src/main/resources/db/changelog/5-hs-office/511-coopshares/5110-hs-office-coopshares.sql +++ b/src/main/resources/db/changelog/5-hs-office/511-coopshares/5110-hs-office-coopshares.sql @@ -8,16 +8,16 @@ CREATE TYPE HsOfficeCoopSharesTransactionType AS ENUM ('ADJUSTMENT', 'SUBSCRIPTI CREATE CAST (character varying as HsOfficeCoopSharesTransactionType) WITH INOUT AS IMPLICIT; -create table if not exists hs_office_coopsharestransaction +create table if not exists hs_office.coopsharestransaction ( uuid uuid unique references rbac.object (uuid) initially deferred, version int not null default 0, - membershipUuid uuid not null references hs_office_membership(uuid), + membershipUuid uuid not null references hs_office.membership(uuid), transactionType HsOfficeCoopSharesTransactionType not null, valueDate date not null, shareCount integer not null, reference varchar(48) not null, - adjustedShareTxUuid uuid unique REFERENCES hs_office_coopsharestransaction(uuid) DEFERRABLE INITIALLY DEFERRED, + adjustedShareTxUuid uuid unique REFERENCES hs_office.coopsharestransaction(uuid) DEFERRABLE INITIALLY DEFERRED, comment varchar(512) ); --// @@ -26,8 +26,8 @@ create table if not exists hs_office_coopsharestransaction --changeset michael.hoennig:hs-office-coopshares-BUSINESS-RULES endDelimiter:--// -- ---------------------------------------------------------------------------- -alter table hs_office_coopsharestransaction - add constraint hs_office_coopsharestransaction_reverse_entry_missing +alter table hs_office.coopsharestransaction + add constraint reverse_entry_missing check ( transactionType = 'ADJUSTMENT' and adjustedShareTxUuid is not null or transactionType <> 'ADJUSTMENT' and adjustedShareTxUuid is null); --// @@ -44,7 +44,7 @@ declare totalShareCount integer; begin select sum(cst.shareCount) - from hs_office_coopsharestransaction cst + from hs_office.coopsharestransaction cst where cst.membershipUuid = forMembershipUuid into currentShareCount; totalShareCount := currentShareCount + newShareCount; @@ -54,8 +54,8 @@ begin return true; end; $$; -alter table hs_office_coopsharestransaction - add constraint hs_office_coopshares_positive +alter table hs_office.coopsharestransaction + add constraint check_positive_total_shares_count check ( checkSharesByMembershipUuid(membershipUuid, shareCount) ); --// @@ -64,5 +64,5 @@ alter table hs_office_coopsharestransaction --changeset michael.hoennig:hs-office-coopshares-MAIN-TABLE-JOURNAL endDelimiter:--// -- ---------------------------------------------------------------------------- -call base.create_journal('hs_office_coopsharestransaction'); +call base.create_journal('hs_office.coopsharestransaction'); --// diff --git a/src/main/resources/db/changelog/5-hs-office/511-coopshares/5113-hs-office-coopshares-rbac.sql b/src/main/resources/db/changelog/5-hs-office/511-coopshares/5113-hs-office-coopshares-rbac.sql index b77458ee..66df3a08 100644 --- a/src/main/resources/db/changelog/5-hs-office/511-coopshares/5113-hs-office-coopshares-rbac.sql +++ b/src/main/resources/db/changelog/5-hs-office/511-coopshares/5113-hs-office-coopshares-rbac.sql @@ -5,14 +5,14 @@ -- ============================================================================ --changeset RbacObjectGenerator:hs-office-coopsharestransaction-rbac-OBJECT endDelimiter:--// -- ---------------------------------------------------------------------------- -call rbac.generateRelatedRbacObject('hs_office_coopsharestransaction'); +call rbac.generateRelatedRbacObject('hs_office.coopsharestransaction'); --// -- ============================================================================ --changeset RbacRoleDescriptorsGenerator:hs-office-coopsharestransaction-rbac-ROLE-DESCRIPTORS endDelimiter:--// -- ---------------------------------------------------------------------------- -call rbac.generateRbacRoleDescriptors('hsOfficeCoopSharesTransaction', 'hs_office_coopsharestransaction'); +call rbac.generateRbacRoleDescriptors('hsOfficeCoopSharesTransaction', 'hs_office.coopsharestransaction'); --// @@ -24,18 +24,18 @@ call rbac.generateRbacRoleDescriptors('hsOfficeCoopSharesTransaction', 'hs_offic Creates the roles, grants and permission for the AFTER INSERT TRIGGER. */ -create or replace procedure buildRbacSystemForHsOfficeCoopSharesTransaction( - NEW hs_office_coopsharestransaction +create or replace procedure hs_office.coopsharestransaction_build_rbac_system( + NEW hs_office.coopsharestransaction ) language plpgsql as $$ declare - newMembership hs_office_membership; + newMembership hs_office.membership; begin call rbac.enterTriggerForObjectUuid(NEW.uuid); - SELECT * FROM hs_office_membership WHERE uuid = NEW.membershipUuid INTO newMembership; + SELECT * FROM hs_office.membership WHERE uuid = NEW.membershipUuid INTO newMembership; assert newMembership.uuid is not null, format('newMembership must not be null for NEW.membershipUuid = %s', NEW.membershipUuid); call rbac.grantPermissionToRole(rbac.createPermission(NEW.uuid, 'SELECT'), hsOfficeMembershipAGENT(newMembership)); @@ -45,22 +45,22 @@ begin end; $$; /* - AFTER INSERT TRIGGER to create the role+grant structure for a new hs_office_coopsharestransaction row. + AFTER INSERT TRIGGER to create the role+grant structure for a new hs_office.coopsharestransaction row. */ -create or replace function insertTriggerForHsOfficeCoopSharesTransaction_tf() +create or replace function hs_office.coopsharestransaction_build_rbac_system_after_insert_tf() returns trigger language plpgsql strict as $$ begin - call buildRbacSystemForHsOfficeCoopSharesTransaction(NEW); + call hs_office.coopsharestransaction_build_rbac_system(NEW); return NEW; end; $$; -create trigger insertTriggerForHsOfficeCoopSharesTransaction_tg - after insert on hs_office_coopsharestransaction +create trigger build_rbac_system_after_insert_tg + after insert on hs_office.coopsharestransaction for each row -execute procedure insertTriggerForHsOfficeCoopSharesTransaction_tf(); +execute procedure hs_office.coopsharestransaction_build_rbac_system_after_insert_tf(); --// @@ -68,48 +68,48 @@ execute procedure insertTriggerForHsOfficeCoopSharesTransaction_tf(); --changeset InsertTriggerGenerator:hs-office-coopsharestransaction-rbac-GRANTING-INSERT-PERMISSION endDelimiter:--// -- ---------------------------------------------------------------------------- --- granting INSERT permission to hs_office_membership ---------------------------- +-- granting INSERT permission to hs_office.membership ---------------------------- /* - Grants INSERT INTO hs_office_coopsharestransaction permissions to specified role of pre-existing hs_office_membership rows. + Grants INSERT INTO hs_office.coopsharestransaction permissions to specified role of pre-existing hs_office.membership rows. */ do language plpgsql $$ declare - row hs_office_membership; + row hs_office.membership; begin - call base.defineContext('create INSERT INTO hs_office_coopsharestransaction permissions for pre-exising hs_office_membership rows'); + call base.defineContext('create INSERT INTO hs_office.coopsharestransaction permissions for pre-exising hs_office.membership rows'); - FOR row IN SELECT * FROM hs_office_membership + FOR row IN SELECT * FROM hs_office.membership -- unconditional for all rows in that table LOOP call rbac.grantPermissionToRole( - rbac.createPermission(row.uuid, 'INSERT', 'hs_office_coopsharestransaction'), + rbac.createPermission(row.uuid, 'INSERT', 'hs_office.coopsharestransaction'), hsOfficeMembershipADMIN(row)); END LOOP; end; $$; /** - Grants hs_office_coopsharestransaction INSERT permission to specified role of new hs_office_membership rows. + Grants hs_office.coopsharestransaction INSERT permission to specified role of new membership rows. */ -create or replace function new_hsof_coopsharetx_grants_insert_to_hsof_membership_tf() +create or replace function hs_office.new_coopsharetx_grants_insert_to_membership_tf() returns trigger language plpgsql strict as $$ begin -- unconditional for all rows in that table call rbac.grantPermissionToRole( - rbac.createPermission(NEW.uuid, 'INSERT', 'hs_office_coopsharestransaction'), + rbac.createPermission(NEW.uuid, 'INSERT', 'hs_office.coopsharestransaction'), hsOfficeMembershipADMIN(NEW)); -- end. return NEW; end; $$; -- z_... is to put it at the end of after insert triggers, to make sure the roles exist -create trigger z_new_hs_office_coopsharestransaction_grants_after_insert_tg - after insert on hs_office_membership +create trigger z_new_coopsharestransaction_grants_after_insert_tg + after insert on hs_office.membership for each row -execute procedure new_hsof_coopsharetx_grants_insert_to_hsof_membership_tf(); +execute procedure hs_office.new_coopsharetx_grants_insert_to_membership_tf(); -- ============================================================================ @@ -117,27 +117,27 @@ execute procedure new_hsof_coopsharetx_grants_insert_to_hsof_membership_tf(); -- ---------------------------------------------------------------------------- /** - Checks if the user respectively the assumed roles are allowed to insert a row to hs_office_coopsharestransaction. + Checks if the user respectively the assumed roles are allowed to insert a row to hs_office.coopsharestransaction. */ -create or replace function hs_office_coopsharestransaction_insert_permission_check_tf() +create or replace function hs_office.coopsharestransaction_insert_permission_check_tf() returns trigger language plpgsql as $$ declare superObjectUuid uuid; begin -- check INSERT permission via direct foreign key: NEW.membershipUuid - if rbac.hasInsertPermission(NEW.membershipUuid, 'hs_office_coopsharestransaction') then + if rbac.hasInsertPermission(NEW.membershipUuid, 'hs_office.coopsharestransaction') then return NEW; end if; - raise exception '[403] insert into hs_office_coopsharestransaction values(%) not allowed for current subjects % (%)', + raise exception '[403] insert into hs_office.coopsharestransaction values(%) not allowed for current subjects % (%)', NEW, base.currentSubjects(), rbac.currentSubjectOrAssumedRolesUuids(); end; $$; -create trigger hs_office_coopsharestransaction_insert_permission_check_tg - before insert on hs_office_coopsharestransaction +create trigger coopsharestransaction_insert_permission_check_tg + before insert on hs_office.coopsharestransaction for each row - execute procedure hs_office_coopsharestransaction_insert_permission_check_tf(); + execute procedure hs_office.coopsharestransaction_insert_permission_check_tf(); --// @@ -145,7 +145,7 @@ create trigger hs_office_coopsharestransaction_insert_permission_check_tg --changeset RbacIdentityViewGenerator:hs-office-coopsharestransaction-rbac-IDENTITY-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call rbac.generateRbacIdentityViewFromProjection('hs_office_coopsharestransaction', +call rbac.generateRbacIdentityViewFromProjection('hs_office.coopsharestransaction', $idName$ reference $idName$); @@ -155,7 +155,7 @@ call rbac.generateRbacIdentityViewFromProjection('hs_office_coopsharestransactio -- ============================================================================ --changeset RbacRestrictedViewGenerator:hs-office-coopsharestransaction-rbac-RESTRICTED-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call rbac.generateRbacRestrictedView('hs_office_coopsharestransaction', +call rbac.generateRbacRestrictedView('hs_office.coopsharestransaction', $orderBy$ reference $orderBy$, diff --git a/src/main/resources/db/changelog/5-hs-office/511-coopshares/5116-hs-office-coopshares-migration.sql b/src/main/resources/db/changelog/5-hs-office/511-coopshares/5116-hs-office-coopshares-migration.sql index bd690b3e..40912e0c 100644 --- a/src/main/resources/db/changelog/5-hs-office/511-coopshares/5116-hs-office-coopshares-migration.sql +++ b/src/main/resources/db/changelog/5-hs-office/511-coopshares/5116-hs-office-coopshares-migration.sql @@ -7,9 +7,9 @@ --changeset michael.hoennig:hs-office-coopshares-MIGRATION-mapping endDelimiter:--// -- ---------------------------------------------------------------------------- -CREATE TABLE hs_office_coopsharestransaction_legacy_id +CREATE TABLE hs_office.coopsharestransaction_legacy_id ( - uuid uuid NOT NULL REFERENCES hs_office_coopsharestransaction(uuid), + uuid uuid NOT NULL REFERENCES hs_office.coopsharestransaction(uuid), member_share_id integer NOT NULL ); --// @@ -19,10 +19,10 @@ CREATE TABLE hs_office_coopsharestransaction_legacy_id --changeset michael.hoennig:hs-office-coopshares-MIGRATION-sequence endDelimiter:--// -- ---------------------------------------------------------------------------- -CREATE SEQUENCE IF NOT EXISTS hs_office_coopsharestransaction_legacy_id_seq +CREATE SEQUENCE IF NOT EXISTS hs_office.coopsharestransaction_legacy_id_seq AS integer START 1000000000 - OWNED BY hs_office_coopsharestransaction_legacy_id.member_share_id; + OWNED BY hs_office.coopsharestransaction_legacy_id.member_share_id; --// @@ -30,9 +30,9 @@ CREATE SEQUENCE IF NOT EXISTS hs_office_coopsharestransaction_legacy_id_seq --changeset michael.hoennig:hs-office-coopshares-MIGRATION-default endDelimiter:--// -- ---------------------------------------------------------------------------- -ALTER TABLE hs_office_coopsharestransaction_legacy_id +ALTER TABLE hs_office.coopsharestransaction_legacy_id ALTER COLUMN member_share_id - SET DEFAULT nextVal('hs_office_coopsharestransaction_legacy_id_seq'); + SET DEFAULT nextVal('hs_office.coopsharestransaction_legacy_id_seq'); --/ @@ -41,8 +41,8 @@ ALTER TABLE hs_office_coopsharestransaction_legacy_id -- ---------------------------------------------------------------------------- CALL base.defineContext('schema-migration'); -INSERT INTO hs_office_coopsharestransaction_legacy_id(uuid, member_share_id) - SELECT uuid, nextVal('hs_office_coopsharestransaction_legacy_id_seq') FROM hs_office_coopsharestransaction; +INSERT INTO hs_office.coopsharestransaction_legacy_id(uuid, member_share_id) + SELECT uuid, nextVal('hs_office.coopsharestransaction_legacy_id_seq') FROM hs_office.coopsharestransaction; --/ @@ -58,14 +58,14 @@ begin raise exception 'invalid usage of trigger'; end if; - INSERT INTO hs_office_coopsharestransaction_legacy_id VALUES - (NEW.uuid, nextVal('hs_office_coopsharestransaction_legacy_id_seq')); + INSERT INTO hs_office.coopsharestransaction_legacy_id VALUES + (NEW.uuid, nextVal('hs_office.coopsharestransaction_legacy_id_seq')); return NEW; end; $$; create trigger createCoopSharesLegacyIdMapping - after insert on hs_office_coopsharestransaction + after insert on hs_office.coopsharestransaction for each row execute procedure insertCoopSharesLegacyIdMapping(); --/ @@ -83,14 +83,14 @@ begin raise exception 'invalid usage of trigger'; end if; - DELETE FROM hs_office_coopsharestransaction_legacy_id + DELETE FROM hs_office.coopsharestransaction_legacy_id WHERE uuid = OLD.uuid; return OLD; end; $$; create trigger removeCoopSharesLegacyIdMapping - before delete on hs_office_coopsharestransaction + before delete on hs_office.coopsharestransaction for each row execute procedure deleteCoopSharesLegacyIdMapping(); --/ diff --git a/src/main/resources/db/changelog/5-hs-office/511-coopshares/5118-hs-office-coopshares-test-data.sql b/src/main/resources/db/changelog/5-hs-office/511-coopshares/5118-hs-office-coopshares-test-data.sql index c894b00f..a4c634a7 100644 --- a/src/main/resources/db/changelog/5-hs-office/511-coopshares/5118-hs-office-coopshares-test-data.sql +++ b/src/main/resources/db/changelog/5-hs-office/511-coopshares/5118-hs-office-coopshares-test-data.sql @@ -14,12 +14,12 @@ create or replace procedure createHsOfficeCoopSharesTransactionTestData( ) language plpgsql as $$ declare - membership hs_office_membership; + membership hs_office.membership; subscriptionEntryUuid uuid; begin select m.uuid - from hs_office_membership m - join hs_office_partner p on p.uuid = m.partneruuid + from hs_office.membership m + join hs_office.partner p on p.uuid = m.partneruuid where p.partnerNumber = givenPartnerNumber and m.memberNumberSuffix = givenMemberNumberSuffix into membership; @@ -27,7 +27,7 @@ begin raise notice 'creating test coopSharesTransaction: %', givenPartnerNumber::text || givenMemberNumberSuffix; subscriptionEntryUuid := uuid_generate_v4(); insert - into hs_office_coopsharestransaction(uuid, membershipuuid, transactiontype, valuedate, sharecount, reference, comment, adjustedShareTxUuid) + into hs_office.coopsharestransaction(uuid, membershipuuid, transactiontype, valuedate, sharecount, reference, comment, adjustedShareTxUuid) values (uuid_generate_v4(), membership.uuid, 'SUBSCRIPTION', '2010-03-15', 4, 'ref '||givenPartnerNumber::text || givenMemberNumberSuffix||'-1', 'initial subscription', null), (uuid_generate_v4(), membership.uuid, 'CANCELLATION', '2021-09-01', -2, 'ref '||givenPartnerNumber::text || givenMemberNumberSuffix||'-2', 'cancelling some', null), diff --git a/src/main/resources/db/changelog/5-hs-office/512-coopassets/5120-hs-office-coopassets.sql b/src/main/resources/db/changelog/5-hs-office/512-coopassets/5120-hs-office-coopassets.sql index fa3ddf51..4804f4d7 100644 --- a/src/main/resources/db/changelog/5-hs-office/512-coopassets/5120-hs-office-coopassets.sql +++ b/src/main/resources/db/changelog/5-hs-office/512-coopassets/5120-hs-office-coopassets.sql @@ -15,16 +15,16 @@ CREATE TYPE HsOfficeCoopAssetsTransactionType AS ENUM ('ADJUSTMENT', CREATE CAST (character varying as HsOfficeCoopAssetsTransactionType) WITH INOUT AS IMPLICIT; -create table if not exists hs_office_coopassetstransaction +create table if not exists hs_office.coopassetstransaction ( uuid uuid unique references rbac.object (uuid) initially deferred, version int not null default 0, - membershipUuid uuid not null references hs_office_membership(uuid), + membershipUuid uuid not null references hs_office.membership(uuid), transactionType HsOfficeCoopAssetsTransactionType not null, valueDate date not null, assetValue money not null, reference varchar(48) not null, - adjustedAssetTxUuid uuid unique REFERENCES hs_office_coopassetstransaction(uuid) DEFERRABLE INITIALLY DEFERRED, + adjustedAssetTxUuid uuid unique REFERENCES hs_office.coopassetstransaction(uuid) DEFERRABLE INITIALLY DEFERRED, comment varchar(512) ); --// @@ -34,8 +34,8 @@ create table if not exists hs_office_coopassetstransaction --changeset michael.hoennig:hs-office-coopassets-BUSINESS-RULES endDelimiter:--// -- ---------------------------------------------------------------------------- -alter table hs_office_coopassetstransaction - add constraint hs_office_coopassetstransaction_reverse_entry_missing +alter table hs_office.coopassetstransaction + add constraint reverse_entry_missing check ( transactionType = 'ADJUSTMENT' and adjustedAssetTxUuid is not null or transactionType <> 'ADJUSTMENT' and adjustedAssetTxUuid is null); --// @@ -52,7 +52,7 @@ declare totalAssetValue money; begin select sum(cat.assetValue) - from hs_office_coopassetstransaction cat + from hs_office.coopassetstransaction cat where cat.membershipUuid = forMembershipUuid into currentAssetValue; totalAssetValue := currentAssetValue + newAssetValue; @@ -62,8 +62,8 @@ begin return true; end; $$; -alter table hs_office_coopassetstransaction - add constraint hs_office_coopassets_positive +alter table hs_office.coopassetstransaction + add constraint check_positive_total check ( checkAssetsByMembershipUuid(membershipUuid, assetValue) ); --// @@ -72,5 +72,5 @@ alter table hs_office_coopassetstransaction --changeset michael.hoennig:hs-office-coopassets-MAIN-TABLE-JOURNAL endDelimiter:--// -- ---------------------------------------------------------------------------- -call base.create_journal('hs_office_coopassetstransaction'); +call base.create_journal('hs_office.coopassetstransaction'); --// diff --git a/src/main/resources/db/changelog/5-hs-office/512-coopassets/5123-hs-office-coopassets-rbac.sql b/src/main/resources/db/changelog/5-hs-office/512-coopassets/5123-hs-office-coopassets-rbac.sql index 52b39ae3..d7dbc2b5 100644 --- a/src/main/resources/db/changelog/5-hs-office/512-coopassets/5123-hs-office-coopassets-rbac.sql +++ b/src/main/resources/db/changelog/5-hs-office/512-coopassets/5123-hs-office-coopassets-rbac.sql @@ -5,14 +5,14 @@ -- ============================================================================ --changeset RbacObjectGenerator:hs-office-coopassetstransaction-rbac-OBJECT endDelimiter:--// -- ---------------------------------------------------------------------------- -call rbac.generateRelatedRbacObject('hs_office_coopassetstransaction'); +call rbac.generateRelatedRbacObject('hs_office.coopassetstransaction'); --// -- ============================================================================ --changeset RbacRoleDescriptorsGenerator:hs-office-coopassetstransaction-rbac-ROLE-DESCRIPTORS endDelimiter:--// -- ---------------------------------------------------------------------------- -call rbac.generateRbacRoleDescriptors('hsOfficeCoopAssetsTransaction', 'hs_office_coopassetstransaction'); +call rbac.generateRbacRoleDescriptors('hsOfficeCoopAssetsTransaction', 'hs_office.coopassetstransaction'); --// @@ -24,18 +24,18 @@ call rbac.generateRbacRoleDescriptors('hsOfficeCoopAssetsTransaction', 'hs_offic Creates the roles, grants and permission for the AFTER INSERT TRIGGER. */ -create or replace procedure buildRbacSystemForHsOfficeCoopAssetsTransaction( - NEW hs_office_coopassetstransaction +create or replace procedure hs_office.coopassetstransaction_build_rbac_system( + NEW hs_office.coopassetstransaction ) language plpgsql as $$ declare - newMembership hs_office_membership; + newMembership hs_office.membership; begin call rbac.enterTriggerForObjectUuid(NEW.uuid); - SELECT * FROM hs_office_membership WHERE uuid = NEW.membershipUuid INTO newMembership; + SELECT * FROM hs_office.membership WHERE uuid = NEW.membershipUuid INTO newMembership; assert newMembership.uuid is not null, format('newMembership must not be null for NEW.membershipUuid = %s', NEW.membershipUuid); call rbac.grantPermissionToRole(rbac.createPermission(NEW.uuid, 'SELECT'), hsOfficeMembershipAGENT(newMembership)); @@ -45,22 +45,22 @@ begin end; $$; /* - AFTER INSERT TRIGGER to create the role+grant structure for a new hs_office_coopassetstransaction row. + AFTER INSERT TRIGGER to create the role+grant structure for a new hs_office.coopassetstransaction row. */ -create or replace function insertTriggerForHsOfficeCoopAssetsTransaction_tf() +create or replace function hs_office.coopassetstransaction_build_rbac_system_after_insert_tf() returns trigger language plpgsql strict as $$ begin - call buildRbacSystemForHsOfficeCoopAssetsTransaction(NEW); + call hs_office.coopassetstransaction_build_rbac_system(NEW); return NEW; end; $$; -create trigger insertTriggerForHsOfficeCoopAssetsTransaction_tg - after insert on hs_office_coopassetstransaction +create trigger build_rbac_system_after_insert_tg + after insert on hs_office.coopassetstransaction for each row -execute procedure insertTriggerForHsOfficeCoopAssetsTransaction_tf(); +execute procedure hs_office.coopassetstransaction_build_rbac_system_after_insert_tf(); --// @@ -68,48 +68,48 @@ execute procedure insertTriggerForHsOfficeCoopAssetsTransaction_tf(); --changeset InsertTriggerGenerator:hs-office-coopassetstransaction-rbac-GRANTING-INSERT-PERMISSION endDelimiter:--// -- ---------------------------------------------------------------------------- --- granting INSERT permission to hs_office_membership ---------------------------- +-- granting INSERT permission to hs_office.membership ---------------------------- /* - Grants INSERT INTO hs_office_coopassetstransaction permissions to specified role of pre-existing hs_office_membership rows. + Grants INSERT INTO hs_office.coopassetstransaction permissions to specified role of pre-existing hs_office.membership rows. */ do language plpgsql $$ declare - row hs_office_membership; + row hs_office.membership; begin - call base.defineContext('create INSERT INTO hs_office_coopassetstransaction permissions for pre-exising hs_office_membership rows'); + call base.defineContext('create INSERT INTO hs_office.coopassetstransaction permissions for pre-exising hs_office.membership rows'); - FOR row IN SELECT * FROM hs_office_membership + FOR row IN SELECT * FROM hs_office.membership -- unconditional for all rows in that table LOOP call rbac.grantPermissionToRole( - rbac.createPermission(row.uuid, 'INSERT', 'hs_office_coopassetstransaction'), + rbac.createPermission(row.uuid, 'INSERT', 'hs_office.coopassetstransaction'), hsOfficeMembershipADMIN(row)); END LOOP; end; $$; /** - Grants hs_office_coopassetstransaction INSERT permission to specified role of new hs_office_membership rows. + Grants hs_office.coopassetstransaction INSERT permission to specified role of new membership rows. */ -create or replace function new_hsof_coopassettx_grants_insert_to_hsof_membership_tf() +create or replace function hs_office.new_coopassettx_grants_insert_to_membership_tf() returns trigger language plpgsql strict as $$ begin -- unconditional for all rows in that table call rbac.grantPermissionToRole( - rbac.createPermission(NEW.uuid, 'INSERT', 'hs_office_coopassetstransaction'), + rbac.createPermission(NEW.uuid, 'INSERT', 'hs_office.coopassetstransaction'), hsOfficeMembershipADMIN(NEW)); -- end. return NEW; end; $$; -- z_... is to put it at the end of after insert triggers, to make sure the roles exist -create trigger z_new_hs_office_coopassetstransaction_grants_after_insert_tg - after insert on hs_office_membership +create trigger z_new_coopassetstransaction_grants_after_insert_tg + after insert on hs_office.membership for each row -execute procedure new_hsof_coopassettx_grants_insert_to_hsof_membership_tf(); +execute procedure hs_office.new_coopassettx_grants_insert_to_membership_tf(); -- ============================================================================ @@ -117,27 +117,27 @@ execute procedure new_hsof_coopassettx_grants_insert_to_hsof_membership_tf(); -- ---------------------------------------------------------------------------- /** - Checks if the user respectively the assumed roles are allowed to insert a row to hs_office_coopassetstransaction. + Checks if the user respectively the assumed roles are allowed to insert a row to hs_office.coopassetstransaction. */ -create or replace function hs_office_coopassetstransaction_insert_permission_check_tf() +create or replace function hs_office.coopassetstransaction_insert_permission_check_tf() returns trigger language plpgsql as $$ declare superObjectUuid uuid; begin -- check INSERT permission via direct foreign key: NEW.membershipUuid - if rbac.hasInsertPermission(NEW.membershipUuid, 'hs_office_coopassetstransaction') then + if rbac.hasInsertPermission(NEW.membershipUuid, 'hs_office.coopassetstransaction') then return NEW; end if; - raise exception '[403] insert into hs_office_coopassetstransaction values(%) not allowed for current subjects % (%)', + raise exception '[403] insert into hs_office.coopassetstransaction values(%) not allowed for current subjects % (%)', NEW, base.currentSubjects(), rbac.currentSubjectOrAssumedRolesUuids(); end; $$; -create trigger hs_office_coopassetstransaction_insert_permission_check_tg - before insert on hs_office_coopassetstransaction +create trigger coopassetstransaction_insert_permission_check_tg + before insert on hs_office.coopassetstransaction for each row - execute procedure hs_office_coopassetstransaction_insert_permission_check_tf(); + execute procedure hs_office.coopassetstransaction_insert_permission_check_tf(); --// @@ -145,7 +145,7 @@ create trigger hs_office_coopassetstransaction_insert_permission_check_tg --changeset RbacIdentityViewGenerator:hs-office-coopassetstransaction-rbac-IDENTITY-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call rbac.generateRbacIdentityViewFromProjection('hs_office_coopassetstransaction', +call rbac.generateRbacIdentityViewFromProjection('hs_office.coopassetstransaction', $idName$ reference $idName$); @@ -155,7 +155,7 @@ call rbac.generateRbacIdentityViewFromProjection('hs_office_coopassetstransactio -- ============================================================================ --changeset RbacRestrictedViewGenerator:hs-office-coopassetstransaction-rbac-RESTRICTED-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- -call rbac.generateRbacRestrictedView('hs_office_coopassetstransaction', +call rbac.generateRbacRestrictedView('hs_office.coopassetstransaction', $orderBy$ reference $orderBy$, diff --git a/src/main/resources/db/changelog/5-hs-office/512-coopassets/5126-hs-office-coopassets-migration.sql b/src/main/resources/db/changelog/5-hs-office/512-coopassets/5126-hs-office-coopassets-migration.sql index f506e855..3919b13c 100644 --- a/src/main/resources/db/changelog/5-hs-office/512-coopassets/5126-hs-office-coopassets-migration.sql +++ b/src/main/resources/db/changelog/5-hs-office/512-coopassets/5126-hs-office-coopassets-migration.sql @@ -7,9 +7,9 @@ --changeset michael.hoennig:hs-office-coopassets-MIGRATION-mapping endDelimiter:--// -- ---------------------------------------------------------------------------- -CREATE TABLE hs_office_coopassetstransaction_legacy_id +CREATE TABLE hs_office.coopassetstransaction_legacy_id ( - uuid uuid NOT NULL REFERENCES hs_office_coopassetstransaction(uuid), + uuid uuid NOT NULL REFERENCES hs_office.coopassetstransaction(uuid), member_asset_id integer NOT NULL ); --// @@ -19,10 +19,10 @@ CREATE TABLE hs_office_coopassetstransaction_legacy_id --changeset michael.hoennig:hs-office-coopassets-MIGRATION-sequence endDelimiter:--// -- ---------------------------------------------------------------------------- -CREATE SEQUENCE IF NOT EXISTS hs_office_coopassetstransaction_legacy_id_seq +CREATE SEQUENCE IF NOT EXISTS hs_office.coopassetstransaction_legacy_id_seq AS integer START 1000000000 - OWNED BY hs_office_coopassetstransaction_legacy_id.member_asset_id; + OWNED BY hs_office.coopassetstransaction_legacy_id.member_asset_id; --// @@ -30,9 +30,9 @@ CREATE SEQUENCE IF NOT EXISTS hs_office_coopassetstransaction_legacy_id_seq --changeset michael.hoennig:hs-office-coopassets-MIGRATION-default endDelimiter:--// -- ---------------------------------------------------------------------------- -ALTER TABLE hs_office_coopassetstransaction_legacy_id +ALTER TABLE hs_office.coopassetstransaction_legacy_id ALTER COLUMN member_asset_id - SET DEFAULT nextVal('hs_office_coopassetstransaction_legacy_id_seq'); + SET DEFAULT nextVal('hs_office.coopassetstransaction_legacy_id_seq'); --/ @@ -41,8 +41,8 @@ ALTER TABLE hs_office_coopassetstransaction_legacy_id -- ---------------------------------------------------------------------------- CALL base.defineContext('schema-migration'); -INSERT INTO hs_office_coopassetstransaction_legacy_id(uuid, member_asset_id) - SELECT uuid, nextVal('hs_office_coopassetstransaction_legacy_id_seq') FROM hs_office_coopassetstransaction; +INSERT INTO hs_office.coopassetstransaction_legacy_id(uuid, member_asset_id) + SELECT uuid, nextVal('hs_office.coopassetstransaction_legacy_id_seq') FROM hs_office.coopassetstransaction; --/ @@ -58,14 +58,14 @@ begin raise exception 'invalid usage of trigger'; end if; - INSERT INTO hs_office_coopassetstransaction_legacy_id VALUES - (NEW.uuid, nextVal('hs_office_coopassetstransaction_legacy_id_seq')); + INSERT INTO hs_office.coopassetstransaction_legacy_id VALUES + (NEW.uuid, nextVal('hs_office.coopassetstransaction_legacy_id_seq')); return NEW; end; $$; create trigger createCoopAssetsLegacyIdMapping - after insert on hs_office_coopassetstransaction + after insert on hs_office.coopassetstransaction for each row execute procedure insertCoopAssetsLegacyIdMapping(); --/ @@ -83,14 +83,14 @@ begin raise exception 'invalid usage of trigger'; end if; - DELETE FROM hs_office_coopassetstransaction_legacy_id + DELETE FROM hs_office.coopassetstransaction_legacy_id WHERE uuid = OLD.uuid; return OLD; end; $$; create trigger removeCoopAssetsLegacyIdMapping - before delete on hs_office_coopassetstransaction + before delete on hs_office.coopassetstransaction for each row execute procedure deleteCoopAssetsLegacyIdMapping(); --/ diff --git a/src/main/resources/db/changelog/5-hs-office/512-coopassets/5128-hs-office-coopassets-test-data.sql b/src/main/resources/db/changelog/5-hs-office/512-coopassets/5128-hs-office-coopassets-test-data.sql index b2d9c27d..21a4ef82 100644 --- a/src/main/resources/db/changelog/5-hs-office/512-coopassets/5128-hs-office-coopassets-test-data.sql +++ b/src/main/resources/db/changelog/5-hs-office/512-coopassets/5128-hs-office-coopassets-test-data.sql @@ -14,12 +14,12 @@ create or replace procedure createHsOfficeCoopAssetsTransactionTestData( ) language plpgsql as $$ declare - membership hs_office_membership; + membership hs_office.membership; lossEntryUuid uuid; begin select m.uuid - from hs_office_membership m - join hs_office_partner p on p.uuid = m.partneruuid + from hs_office.membership m + join hs_office.partner p on p.uuid = m.partneruuid where p.partnerNumber = givenPartnerNumber and m.memberNumberSuffix = givenMemberNumberSuffix into membership; @@ -27,7 +27,7 @@ begin raise notice 'creating test coopAssetsTransaction: %', givenPartnerNumber || givenMemberNumberSuffix; lossEntryUuid := uuid_generate_v4(); insert - into hs_office_coopassetstransaction(uuid, membershipuuid, transactiontype, valuedate, assetvalue, reference, comment, adjustedAssetTxUuid) + into hs_office.coopassetstransaction(uuid, membershipuuid, transactiontype, valuedate, assetvalue, reference, comment, adjustedAssetTxUuid) values (uuid_generate_v4(), membership.uuid, 'DEPOSIT', '2010-03-15', 320.00, 'ref '||givenPartnerNumber || givenMemberNumberSuffix||'-1', 'initial deposit', null), (uuid_generate_v4(), membership.uuid, 'DISBURSAL', '2021-09-01', -128.00, 'ref '||givenPartnerNumber || givenMemberNumberSuffix||'-2', 'partial disbursal', null), diff --git a/src/main/resources/db/changelog/6-hs-booking/610-booking-debitor/6100-hs-booking-debitor.sql b/src/main/resources/db/changelog/6-hs-booking/610-booking-debitor/6100-hs-booking-debitor.sql index a610023c..f3e0b612 100644 --- a/src/main/resources/db/changelog/6-hs-booking/610-booking-debitor/6100-hs-booking-debitor.sql +++ b/src/main/resources/db/changelog/6-hs-booking/610-booking-debitor/6100-hs-booking-debitor.sql @@ -9,9 +9,9 @@ create view hs_booking_debitor_xv as debitor.version, (partner.partnerNumber::varchar || debitor.debitorNumberSuffix)::numeric as debitorNumber, debitor.defaultPrefix - from hs_office_debitor debitor + from hs_office.debitor debitor -- RBAC for debitor is sufficient, for faster access we are bypassing RBAC for the join tables - join hs_office_relation debitorRel on debitor.debitorReluUid=debitorRel.uuid - join hs_office_relation partnerRel on partnerRel.holderUuid=debitorRel.anchorUuid - join hs_office_partner partner on partner.partnerReluUid=partnerRel.uuid; + join hs_office.relation debitorRel on debitor.debitorReluUid=debitorRel.uuid + join hs_office.relation partnerRel on partnerRel.holderUuid=debitorRel.anchorUuid + join hs_office.partner partner on partner.partnerReluUid=partnerRel.uuid; --// diff --git a/src/main/resources/db/changelog/6-hs-booking/620-booking-project/6200-hs-booking-project.sql b/src/main/resources/db/changelog/6-hs-booking/620-booking-project/6200-hs-booking-project.sql index a0250fc4..70724958 100644 --- a/src/main/resources/db/changelog/6-hs-booking/620-booking-project/6200-hs-booking-project.sql +++ b/src/main/resources/db/changelog/6-hs-booking/620-booking-project/6200-hs-booking-project.sql @@ -8,7 +8,7 @@ create table if not exists hs_booking_project ( uuid uuid unique references rbac.object (uuid), version int not null default 0, - debitorUuid uuid not null references hs_office_debitor(uuid), + debitorUuid uuid not null references hs_office.debitor(uuid), caption varchar(80) not null ); --// diff --git a/src/main/resources/db/changelog/6-hs-booking/620-booking-project/6203-hs-booking-project-rbac.sql b/src/main/resources/db/changelog/6-hs-booking/620-booking-project/6203-hs-booking-project-rbac.sql index 0f0098f7..053c0f86 100644 --- a/src/main/resources/db/changelog/6-hs-booking/620-booking-project/6203-hs-booking-project-rbac.sql +++ b/src/main/resources/db/changelog/6-hs-booking/620-booking-project/6203-hs-booking-project-rbac.sql @@ -3,45 +3,45 @@ -- ============================================================================ ---changeset michael.hoennig:hs-booking-project-rbac-OBJECT endDelimiter:--// +--changeset RbacObjectGenerator:hs-booking-project-rbac-OBJECT endDelimiter:--// -- ---------------------------------------------------------------------------- call rbac.generateRelatedRbacObject('hs_booking_project'); --// -- ============================================================================ ---changeset michael.hoennig:hs-booking-project-rbac-ROLE-DESCRIPTORS endDelimiter:--// +--changeset RbacRoleDescriptorsGenerator:hs-booking-project-rbac-ROLE-DESCRIPTORS endDelimiter:--// -- ---------------------------------------------------------------------------- call rbac.generateRbacRoleDescriptors('hsBookingProject', 'hs_booking_project'); --// -- ============================================================================ ---changeset michael.hoennig:hs-booking-project-rbac-insert-trigger endDelimiter:--// +--changeset RolesGrantsAndPermissionsGenerator:hs-booking-project-rbac-insert-trigger endDelimiter:--// -- ---------------------------------------------------------------------------- /* Creates the roles, grants and permission for the AFTER INSERT TRIGGER. */ -create or replace procedure buildRbacSystemForHsBookingProject( +create or replace procedure hs_booking_project_build_rbac_system( NEW hs_booking_project ) language plpgsql as $$ declare - newDebitor hs_office_debitor; - newDebitorRel hs_office_relation; + newDebitor hs_office.debitor; + newDebitorRel hs_office.relation; begin call rbac.enterTriggerForObjectUuid(NEW.uuid); - SELECT * FROM hs_office_debitor WHERE uuid = NEW.debitorUuid INTO newDebitor; + SELECT * FROM hs_office.debitor WHERE uuid = NEW.debitorUuid INTO newDebitor; assert newDebitor.uuid is not null, format('newDebitor must not be null for NEW.debitorUuid = %s', NEW.debitorUuid); SELECT debitorRel.* - FROM hs_office_relation debitorRel - JOIN hs_office_debitor debitor ON debitor.debitorRelUuid = debitorRel.uuid + FROM hs_office.relation debitorRel + JOIN hs_office.debitor debitor ON debitor.debitorRelUuid = debitorRel.uuid WHERE debitor.uuid = NEW.debitorUuid INTO newDebitorRel; assert newDebitorRel.uuid is not null, format('newDebitorRel must not be null for NEW.debitorUuid = %s', NEW.debitorUuid); @@ -79,38 +79,38 @@ end; $$; AFTER INSERT TRIGGER to create the role+grant structure for a new hs_booking_project row. */ -create or replace function insertTriggerForHsBookingProject_tf() +create or replace function hs_booking_project_build_rbac_system_after_insert_tf() returns trigger language plpgsql strict as $$ begin - call buildRbacSystemForHsBookingProject(NEW); + call hs_booking_project_build_rbac_system(NEW); return NEW; end; $$; -create trigger insertTriggerForHsBookingProject_tg +create trigger build_rbac_system_after_insert_tg after insert on hs_booking_project for each row -execute procedure insertTriggerForHsBookingProject_tf(); +execute procedure hs_booking_project_build_rbac_system_after_insert_tf(); --// -- ============================================================================ ---changeset michael.hoennig:hs-booking-project-rbac-GRANTING-INSERT-PERMISSION endDelimiter:--// +--changeset InsertTriggerGenerator:hs-booking-project-rbac-GRANTING-INSERT-PERMISSION endDelimiter:--// -- ---------------------------------------------------------------------------- --- granting INSERT permission to hs_office_relation ---------------------------- +-- granting INSERT permission to hs_office.relation ---------------------------- /* - Grants INSERT INTO hs_booking_project permissions to specified role of pre-existing hs_office_relation rows. + Grants INSERT INTO hs_booking_project permissions to specified role of pre-existing hs_office.relation rows. */ do language plpgsql $$ declare - row hs_office_relation; + row hs_office.relation; begin - call base.defineContext('create INSERT INTO hs_booking_project permissions for pre-exising hs_office_relation rows'); + call base.defineContext('create INSERT INTO hs_booking_project permissions for pre-exising hs_office.relation rows'); - FOR row IN SELECT * FROM hs_office_relation + FOR row IN SELECT * FROM hs_office.relation WHERE type = 'DEBITOR' LOOP call rbac.grantPermissionToRole( @@ -121,9 +121,9 @@ do language plpgsql $$ $$; /** - Grants hs_booking_project INSERT permission to specified role of new hs_office_relation rows. + Grants hs_booking_project INSERT permission to specified role of new relation rows. */ -create or replace function new_hs_booking_project_grants_insert_to_hs_office_relation_tf() +create or replace function new_hsbk_project_grants_insert_to_relation_tf() returns trigger language plpgsql strict as $$ @@ -137,14 +137,14 @@ begin end; $$; -- z_... is to put it at the end of after insert triggers, to make sure the roles exist -create trigger z_new_hs_booking_project_grants_insert_to_hs_office_relation_tg - after insert on hs_office_relation +create trigger z_new_hs_booking_project_grants_after_insert_tg + after insert on hs_office.relation for each row -execute procedure new_hs_booking_project_grants_insert_to_hs_office_relation_tf(); +execute procedure new_hsbk_project_grants_insert_to_relation_tf(); -- ============================================================================ ---changeset michael.hoennig:hs_booking_project-rbac-CHECKING-INSERT-PERMISSION endDelimiter:--// +--changeset InsertTriggerGenerator:hs-booking-project-rbac-CHECKING-INSERT-PERMISSION endDelimiter:--// -- ---------------------------------------------------------------------------- /** @@ -158,8 +158,8 @@ declare begin -- check INSERT permission via indirect foreign key: NEW.debitorUuid superObjectUuid := (SELECT debitorRel.uuid - FROM hs_office_relation debitorRel - JOIN hs_office_debitor debitor ON debitor.debitorRelUuid = debitorRel.uuid + FROM hs_office.relation debitorRel + JOIN hs_office.debitor debitor ON debitor.debitorRelUuid = debitorRel.uuid WHERE debitor.uuid = NEW.debitorUuid ); assert superObjectUuid is not null, 'object uuid fetched depending on hs_booking_project.debitorUuid must not be null, also check fetchSql in RBAC DSL'; @@ -179,20 +179,20 @@ create trigger hs_booking_project_insert_permission_check_tg -- ============================================================================ ---changeset michael.hoennig:hs-booking-project-rbac-IDENTITY-VIEW endDelimiter:--// +--changeset RbacIdentityViewGenerator:hs-booking-project-rbac-IDENTITY-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- call rbac.generateRbacIdentityViewFromQuery('hs_booking_project', $idName$ SELECT bookingProject.uuid as uuid, debitorIV.idName || '-' || base.cleanIdentifier(bookingProject.caption) as idName FROM hs_booking_project bookingProject - JOIN hs_office_debitor_iv debitorIV ON debitorIV.uuid = bookingProject.debitorUuid + JOIN hs_office.debitor_iv debitorIV ON debitorIV.uuid = bookingProject.debitorUuid $idName$); --// -- ============================================================================ ---changeset michael.hoennig:hs-booking-project-rbac-RESTRICTED-VIEW endDelimiter:--// +--changeset RbacRestrictedViewGenerator:hs-booking-project-rbac-RESTRICTED-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- call rbac.generateRbacRestrictedView('hs_booking_project', $orderBy$ diff --git a/src/main/resources/db/changelog/6-hs-booking/620-booking-project/6208-hs-booking-project-test-data.sql b/src/main/resources/db/changelog/6-hs-booking/620-booking-project/6208-hs-booking-project-test-data.sql index 7275ce2c..60871add 100644 --- a/src/main/resources/db/changelog/6-hs-booking/620-booking-project/6208-hs-booking-project-test-data.sql +++ b/src/main/resources/db/changelog/6-hs-booking/620-booking-project/6208-hs-booking-project-test-data.sql @@ -14,14 +14,14 @@ create or replace procedure createHsBookingProjectTransactionTestData( ) language plpgsql as $$ declare - relatedDebitor hs_office_debitor; + relatedDebitor hs_office.debitor; begin select debitor.* into relatedDebitor - from hs_office_debitor debitor - join hs_office_relation debitorRel on debitorRel.uuid = debitor.debitorRelUuid - join hs_office_relation partnerRel on partnerRel.holderUuid = debitorRel.anchorUuid - join hs_office_partner partner on partner.partnerRelUuid = partnerRel.uuid + from hs_office.debitor debitor + join hs_office.relation debitorRel on debitorRel.uuid = debitor.debitorRelUuid + join hs_office.relation partnerRel on partnerRel.holderUuid = debitorRel.anchorUuid + join hs_office.partner partner on partner.partnerRelUuid = partnerRel.uuid where partner.partnerNumber = givenPartnerNumber and debitor.debitorNumberSuffix = givenDebitorSuffix; raise notice 'creating test booking-project: %', givenDebitorSuffix::text; diff --git a/src/main/resources/db/changelog/6-hs-booking/630-booking-item/6303-hs-booking-item-rbac.sql b/src/main/resources/db/changelog/6-hs-booking/630-booking-item/6303-hs-booking-item-rbac.sql index dd0ea486..a27e0f8a 100644 --- a/src/main/resources/db/changelog/6-hs-booking/630-booking-item/6303-hs-booking-item-rbac.sql +++ b/src/main/resources/db/changelog/6-hs-booking/630-booking-item/6303-hs-booking-item-rbac.sql @@ -3,28 +3,28 @@ -- ============================================================================ ---changeset michael.hoennig:hs-booking-item-rbac-OBJECT endDelimiter:--// +--changeset RbacObjectGenerator:hs-booking-item-rbac-OBJECT endDelimiter:--// -- ---------------------------------------------------------------------------- call rbac.generateRelatedRbacObject('hs_booking_item'); --// -- ============================================================================ ---changeset michael.hoennig:hs-booking-item-rbac-ROLE-DESCRIPTORS endDelimiter:--// +--changeset RbacRoleDescriptorsGenerator:hs-booking-item-rbac-ROLE-DESCRIPTORS endDelimiter:--// -- ---------------------------------------------------------------------------- call rbac.generateRbacRoleDescriptors('hsBookingItem', 'hs_booking_item'); --// -- ============================================================================ ---changeset michael.hoennig:hs-booking-item-rbac-insert-trigger endDelimiter:--// +--changeset RolesGrantsAndPermissionsGenerator:hs-booking-item-rbac-insert-trigger endDelimiter:--// -- ---------------------------------------------------------------------------- /* Creates the roles, grants and permission for the AFTER INSERT TRIGGER. */ -create or replace procedure buildRbacSystemForHsBookingItem( +create or replace procedure hs_booking_item_build_rbac_system( NEW hs_booking_item ) language plpgsql as $$ @@ -78,34 +78,34 @@ end; $$; AFTER INSERT TRIGGER to create the role+grant structure for a new hs_booking_item row. */ -create or replace function insertTriggerForHsBookingItem_tf() +create or replace function hs_booking_item_build_rbac_system_after_insert_tf() returns trigger language plpgsql strict as $$ begin - call buildRbacSystemForHsBookingItem(NEW); + call hs_booking_item_build_rbac_system(NEW); return NEW; end; $$; -create trigger insertTriggerForHsBookingItem_tg +create trigger build_rbac_system_after_insert_tg after insert on hs_booking_item for each row -execute procedure insertTriggerForHsBookingItem_tf(); +execute procedure hs_booking_item_build_rbac_system_after_insert_tf(); --// -- ============================================================================ ---changeset michael.hoennig:hs-booking-item-rbac-GRANTING-INSERT-PERMISSION endDelimiter:--// +--changeset InsertTriggerGenerator:hs-booking-item-rbac-GRANTING-INSERT-PERMISSION endDelimiter:--// -- ---------------------------------------------------------------------------- --- granting INSERT permission to global ---------------------------- +-- granting INSERT permission to rbac.global ---------------------------- /* - Grants INSERT INTO hs_booking_item permissions to specified role of pre-existing global rows. + Grants INSERT INTO hs_booking_item permissions to specified role of pre-existing rbac.global rows. */ do language plpgsql $$ declare - row rbac.global%ROWTYPE; + row rbac.global; begin call base.defineContext('create INSERT INTO hs_booking_item permissions for pre-exising rbac.global rows'); @@ -114,15 +114,15 @@ do language plpgsql $$ LOOP call rbac.grantPermissionToRole( rbac.createPermission(row.uuid, 'INSERT', 'hs_booking_item'), - rbac.globalAdmin()); + rbac.globalADMIN()); END LOOP; end; $$; /** - Grants hs_booking_item INSERT permission to specified role of new rbac.global rows. + Grants hs_booking_item INSERT permission to specified role of new global rows. */ -create or replace function new_hs_booking_item_grants_insert_to_global_tf() +create or replace function new_hsbk_item_grants_insert_to_global_tf() returns trigger language plpgsql strict as $$ @@ -130,16 +130,16 @@ begin -- unconditional for all rows in that table call rbac.grantPermissionToRole( rbac.createPermission(NEW.uuid, 'INSERT', 'hs_booking_item'), - rbac.globalAdmin()); + rbac.globalADMIN()); -- end. return NEW; end; $$; -- z_... is to put it at the end of after insert triggers, to make sure the roles exist -create trigger z_new_hs_booking_item_grants_insert_to_global_tg +create trigger z_new_hs_booking_item_grants_after_insert_tg after insert on rbac.global for each row -execute procedure new_hs_booking_item_grants_insert_to_global_tf(); +execute procedure new_hsbk_item_grants_insert_to_global_tf(); -- granting INSERT permission to hs_booking_project ---------------------------- @@ -165,7 +165,7 @@ $$; /** Grants hs_booking_item INSERT permission to specified role of new hs_booking_project rows. */ -create or replace function new_hs_booking_item_grants_insert_to_hs_booking_project_tf() +create or replace function new_hsbk_item_grants_insert_to_hsbk_project_tf() returns trigger language plpgsql strict as $$ @@ -179,10 +179,10 @@ begin end; $$; -- z_... is to put it at the end of after insert triggers, to make sure the roles exist -create trigger z_new_hs_booking_item_grants_insert_to_hs_booking_project_tg +create trigger z_new_hs_booking_item_grants_after_insert_tg after insert on hs_booking_project for each row -execute procedure new_hs_booking_item_grants_insert_to_hs_booking_project_tf(); +execute procedure new_hsbk_item_grants_insert_to_hsbk_project_tf(); -- granting INSERT permission to hs_booking_item ---------------------------- @@ -192,7 +192,7 @@ execute procedure new_hs_booking_item_grants_insert_to_hs_booking_project_tf(); /** Grants hs_booking_item INSERT permission to specified role of new hs_booking_item rows. */ -create or replace function new_hs_booking_item_grants_insert_to_hs_booking_item_tf() +create or replace function new_hsbk_item_grants_insert_to_hsbk_item_tf() returns trigger language plpgsql strict as $$ @@ -206,14 +206,14 @@ begin end; $$; -- z_... is to put it at the end of after insert triggers, to make sure the roles exist -create trigger z_new_hs_booking_item_grants_insert_to_hs_booking_item_tg +create trigger z_new_hs_booking_item_grants_after_insert_tg after insert on hs_booking_item for each row -execute procedure new_hs_booking_item_grants_insert_to_hs_booking_item_tf(); +execute procedure new_hsbk_item_grants_insert_to_hsbk_item_tf(); -- ============================================================================ ---changeset michael.hoennig:hs_booking_item-rbac-CHECKING-INSERT-PERMISSION endDelimiter:--// +--changeset InsertTriggerGenerator:hs-booking-item-rbac-CHECKING-INSERT-PERMISSION endDelimiter:--// -- ---------------------------------------------------------------------------- /** @@ -225,7 +225,7 @@ create or replace function hs_booking_item_insert_permission_check_tf() declare superObjectUuid uuid; begin - -- check INSERT INSERT if rbac.Global ADMIN + -- check INSERT permission if rbac.global ADMIN if rbac.isGlobalAdmin() then return NEW; end if; @@ -250,7 +250,7 @@ create trigger hs_booking_item_insert_permission_check_tg -- ============================================================================ ---changeset michael.hoennig:hs-booking-item-rbac-IDENTITY-VIEW endDelimiter:--// +--changeset RbacIdentityViewGenerator:hs-booking-item-rbac-IDENTITY-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- call rbac.generateRbacIdentityViewFromProjection('hs_booking_item', @@ -261,7 +261,7 @@ call rbac.generateRbacIdentityViewFromProjection('hs_booking_item', -- ============================================================================ ---changeset michael.hoennig:hs-booking-item-rbac-RESTRICTED-VIEW endDelimiter:--// +--changeset RbacRestrictedViewGenerator:hs-booking-item-rbac-RESTRICTED-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- call rbac.generateRbacRestrictedView('hs_booking_item', $orderBy$ diff --git a/src/main/resources/db/changelog/7-hs-hosting/701-hosting-asset/7010-hs-hosting-asset.sql b/src/main/resources/db/changelog/7-hs-hosting/701-hosting-asset/7010-hs-hosting-asset.sql index 0bec8667..aef12936 100644 --- a/src/main/resources/db/changelog/7-hs-hosting/701-hosting-asset/7010-hs-hosting-asset.sql +++ b/src/main/resources/db/changelog/7-hs-hosting/701-hosting-asset/7010-hs-hosting-asset.sql @@ -39,7 +39,7 @@ create table if not exists hs_hosting_asset identifier varchar(80) not null, caption varchar(80), config jsonb not null, - alarmContactUuid uuid null references hs_office_contact(uuid) initially deferred, + alarmContactUuid uuid null references hs_office.contact(uuid) initially deferred, constraint chk_hs_hosting_asset_has_booking_item_or_parent_asset check (bookingItemUuid is not null or parentAssetUuid is not null or type in ('DOMAIN_SETUP', 'IPV4_NUMBER', 'IPV6_NUMBER')) diff --git a/src/main/resources/db/changelog/7-hs-hosting/701-hosting-asset/7013-hs-hosting-asset-rbac.sql b/src/main/resources/db/changelog/7-hs-hosting/701-hosting-asset/7013-hs-hosting-asset-rbac.sql index 3bfd9df8..7050afd3 100644 --- a/src/main/resources/db/changelog/7-hs-hosting/701-hosting-asset/7013-hs-hosting-asset-rbac.sql +++ b/src/main/resources/db/changelog/7-hs-hosting/701-hosting-asset/7013-hs-hosting-asset-rbac.sql @@ -3,28 +3,28 @@ -- ============================================================================ ---changeset michael.hoennig:hs-hosting-asset-rbac-OBJECT endDelimiter:--// +--changeset RbacObjectGenerator:hs-hosting-asset-rbac-OBJECT endDelimiter:--// -- ---------------------------------------------------------------------------- call rbac.generateRelatedRbacObject('hs_hosting_asset'); --// -- ============================================================================ ---changeset michael.hoennig:hs-hosting-asset-rbac-ROLE-DESCRIPTORS endDelimiter:--// +--changeset RbacRoleDescriptorsGenerator:hs-hosting-asset-rbac-ROLE-DESCRIPTORS endDelimiter:--// -- ---------------------------------------------------------------------------- call rbac.generateRbacRoleDescriptors('hsHostingAsset', 'hs_hosting_asset'); --// -- ============================================================================ ---changeset michael.hoennig:hs-hosting-asset-rbac-insert-trigger endDelimiter:--// +--changeset RolesGrantsAndPermissionsGenerator:hs-hosting-asset-rbac-insert-trigger endDelimiter:--// -- ---------------------------------------------------------------------------- /* Creates the roles, grants and permission for the AFTER INSERT TRIGGER. */ -create or replace procedure buildRbacSystemForHsHostingAsset( +create or replace procedure hs_hosting_asset_build_rbac_system( NEW hs_hosting_asset ) language plpgsql as $$ @@ -32,7 +32,7 @@ create or replace procedure buildRbacSystemForHsHostingAsset( declare newBookingItem hs_booking_item; newAssignedToAsset hs_hosting_asset; - newAlarmContact hs_office_contact; + newAlarmContact hs_office.contact; newParentAsset hs_hosting_asset; begin @@ -42,7 +42,7 @@ begin SELECT * FROM hs_hosting_asset WHERE uuid = NEW.assignedToAssetUuid INTO newAssignedToAsset; - SELECT * FROM hs_office_contact WHERE uuid = NEW.alarmContactUuid INTO newAlarmContact; + SELECT * FROM hs_office.contact WHERE uuid = NEW.alarmContactUuid INTO newAlarmContact; SELECT * FROM hs_hosting_asset WHERE uuid = NEW.parentAssetUuid INTO newParentAsset; @@ -50,9 +50,9 @@ begin hsHostingAssetOWNER(NEW), permissions => array['DELETE'], incomingSuperRoles => array[ - rbac.globalADMIN(rbac.unassumed()), hsBookingItemADMIN(newBookingItem), - hsHostingAssetADMIN(newParentAsset)], + hsHostingAssetADMIN(newParentAsset), + rbac.globalADMIN(rbac.unassumed())], subjectUuids => array[rbac.currentSubjectUuid()] ); @@ -96,31 +96,31 @@ end; $$; AFTER INSERT TRIGGER to create the role+grant structure for a new hs_hosting_asset row. */ -create or replace function insertTriggerForHsHostingAsset_tf() +create or replace function hs_hosting_asset_build_rbac_system_after_insert_tf() returns trigger language plpgsql strict as $$ begin - call buildRbacSystemForHsHostingAsset(NEW); + call hs_hosting_asset_build_rbac_system(NEW); return NEW; end; $$; -create trigger insertTriggerForHsHostingAsset_tg +create trigger build_rbac_system_after_insert_tg after insert on hs_hosting_asset for each row -execute procedure insertTriggerForHsHostingAsset_tf(); +execute procedure hs_hosting_asset_build_rbac_system_after_insert_tf(); --// -- ============================================================================ ---changeset michael.hoennig:hs-hosting-asset-rbac-update-trigger endDelimiter:--// +--changeset RolesGrantsAndPermissionsGenerator:hs-hosting-asset-rbac-update-trigger endDelimiter:--// -- ---------------------------------------------------------------------------- /* Called from the AFTER UPDATE TRIGGER to re-wire the grants. */ -create or replace procedure updateRbacRulesForHsHostingAsset( +create or replace procedure hs_hosting_asset_update_rbac_system( OLD hs_hosting_asset, NEW hs_hosting_asset ) @@ -130,32 +130,32 @@ begin if NEW.assignedToAssetUuid is distinct from OLD.assignedToAssetUuid or NEW.alarmContactUuid is distinct from OLD.alarmContactUuid then delete from rbac.grants g where g.grantedbytriggerof = OLD.uuid; - call buildRbacSystemForHsHostingAsset(NEW); + call hs_hosting_asset_build_rbac_system(NEW); end if; end; $$; /* - AFTER INSERT TRIGGER to re-wire the grant structure for a new hs_hosting_asset row. + AFTER UPDATE TRIGGER to re-wire the grant structure for a new hs_hosting_asset row. */ -create or replace function updateTriggerForHsHostingAsset_tf() +create or replace function hs_hosting_asset_update_rbac_system_after_update_tf() returns trigger language plpgsql strict as $$ begin - call updateRbacRulesForHsHostingAsset(OLD, NEW); + call hs_hosting_asset_update_rbac_system(OLD, NEW); return NEW; end; $$; -create trigger updateTriggerForHsHostingAsset_tg +create trigger update_rbac_system_after_update_tg after update on hs_hosting_asset for each row -execute procedure updateTriggerForHsHostingAsset_tf(); +execute procedure hs_hosting_asset_update_rbac_system_after_update_tf(); --// -- ============================================================================ ---changeset michael.hoennig:hs-hosting-asset-rbac-IDENTITY-VIEW endDelimiter:--// +--changeset RbacIdentityViewGenerator:hs-hosting-asset-rbac-IDENTITY-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- call rbac.generateRbacIdentityViewFromProjection('hs_hosting_asset', @@ -166,7 +166,7 @@ call rbac.generateRbacIdentityViewFromProjection('hs_hosting_asset', -- ============================================================================ ---changeset michael.hoennig:hs-hosting-asset-rbac-RESTRICTED-VIEW endDelimiter:--// +--changeset RbacRestrictedViewGenerator:hs-hosting-asset-rbac-RESTRICTED-VIEW endDelimiter:--// -- ---------------------------------------------------------------------------- call rbac.generateRbacRestrictedView('hs_hosting_asset', $orderBy$ diff --git a/src/main/resources/db/changelog/7-hs-hosting/701-hosting-asset/7018-hs-hosting-asset-test-data.sql b/src/main/resources/db/changelog/7-hs-hosting/701-hosting-asset/7018-hs-hosting-asset-test-data.sql index 711773ba..1a89bcc7 100644 --- a/src/main/resources/db/changelog/7-hs-hosting/701-hosting-asset/7018-hs-hosting-asset-test-data.sql +++ b/src/main/resources/db/changelog/7-hs-hosting/701-hosting-asset/7018-hs-hosting-asset-test-data.sql @@ -12,7 +12,7 @@ create or replace procedure createHsHostingAssetTestData(givenProjectCaption var language plpgsql as $$ declare relatedProject hs_booking_project; - relatedDebitor hs_office_debitor; + relatedDebitor hs_office.debitor; privateCloudBI hs_booking_item; managedServerBI hs_booking_item; cloudServerBI hs_booking_item; @@ -38,7 +38,7 @@ begin assert relatedProject.uuid is not null, 'relatedProject for "' || givenProjectCaption || '" must not be null'; select debitor.* into relatedDebitor - from hs_office_debitor debitor + from hs_office.debitor debitor where debitor.uuid = relatedProject.debitorUuid; assert relatedDebitor.uuid is not null, 'relatedDebitor for "' || givenProjectCaption || '" must not be null'; diff --git a/src/main/resources/db/changelog/db.changelog-master.yaml b/src/main/resources/db/changelog/db.changelog-master.yaml index a8029152..ced88d6c 100644 --- a/src/main/resources/db/changelog/db.changelog-master.yaml +++ b/src/main/resources/db/changelog/db.changelog-master.yaml @@ -69,6 +69,8 @@ databaseChangeLog: file: db/changelog/2-rbactest/203-rbactest-domain/2033-rbactest-domain-rbac.sql - include: file: db/changelog/2-rbactest/203-rbactest-domain/2038-rbactest-domain-test-data.sql + - include: + file: db/changelog/5-hs-office/500-hs-office-schema.sql - include: file: db/changelog/5-hs-office/501-contact/5010-hs-office-contact.sql - include: diff --git a/src/test/java/net/hostsharing/hsadminng/hs/booking/project/HsBookingProjectRepositoryIntegrationTest.java b/src/test/java/net/hostsharing/hsadminng/hs/booking/project/HsBookingProjectRepositoryIntegrationTest.java index f4ada1b2..beae21e0 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/booking/project/HsBookingProjectRepositoryIntegrationTest.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/booking/project/HsBookingProjectRepositoryIntegrationTest.java @@ -135,7 +135,7 @@ class HsBookingProjectRepositoryIntegrationTest extends ContextBasedTestWithClea context("superuser-alex@hostsharing.net"); final var initialRoleNames = distinctRoleNamesOf(rawRoleRepo.findAll()); final var initialGrantNames = distinctGrantDisplaysOf(rawGrantRepo.findAll()).stream() - .map(s -> s.replace("hs_office_", "")) + .map(s -> s.replace("hs_office.", "")) .toList(); // when @@ -157,7 +157,7 @@ class HsBookingProjectRepositoryIntegrationTest extends ContextBasedTestWithClea "hs_booking_project#D-1000111-somenewbookingproject:OWNER", "hs_booking_project#D-1000111-somenewbookingproject:TENANT")); assertThat(distinctGrantDisplaysOf(rawGrantRepo.findAll())) - .map(s -> s.replace("hs_office_", "")) + .map(s -> s.replace("hs_office.", "")) .containsExactlyInAnyOrder(fromFormatted( initialGrantNames, diff --git a/src/test/java/net/hostsharing/hsadminng/hs/migration/BaseOfficeDataImport.java b/src/test/java/net/hostsharing/hsadminng/hs/migration/BaseOfficeDataImport.java index c8f107f1..3bdd17b3 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/migration/BaseOfficeDataImport.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/migration/BaseOfficeDataImport.java @@ -112,7 +112,7 @@ public abstract class BaseOfficeDataImport extends CsvDataImport { @Order(1) void verifyInitialDatabase() { // SQL DELETE for thousands of records takes too long, so we make sure, we only start with initial or test data - final var contactCount = (Integer) em.createNativeQuery("select count(*) from hs_office_contact", Integer.class) + final var contactCount = (Integer) em.createNativeQuery("select count(*) from hs_office.contact", Integer.class) .getSingleResult(); assertThat(contactCount).isLessThan(20); } @@ -614,7 +614,7 @@ public abstract class BaseOfficeDataImport extends CsvDataImport { jpaAttempt.transacted(() -> { context(rbacSuperuser); contacts.forEach(this::persist); - updateLegacyIds(contacts, "hs_office_contact_legacy_id", "contact_id"); + updateLegacyIds(contacts, "hs_office.contact_legacy_id", "contact_id"); }).assertSuccessful(); jpaAttempt.transacted(() -> { @@ -640,7 +640,7 @@ public abstract class BaseOfficeDataImport extends CsvDataImport { partner.setPartnerRel(em.merge(partner.getPartnerRel())); em.persist(partner); }); - updateLegacyIds(partners, "hs_office_partner_legacy_id", "bp_id"); + updateLegacyIds(partners, "hs_office.partner_legacy_id", "bp_id"); }).assertSuccessful(); jpaAttempt.transacted(() -> { @@ -664,20 +664,20 @@ public abstract class BaseOfficeDataImport extends CsvDataImport { jpaAttempt.transacted(() -> { context(rbacSuperuser); sepaMandates.forEach(this::persist); - updateLegacyIds(sepaMandates, "hs_office_sepamandate_legacy_id", "sepa_mandate_id"); + updateLegacyIds(sepaMandates, "hs_office.sepamandate_legacy_id", "sepa_mandate_id"); }).assertSuccessful(); jpaAttempt.transacted(() -> { context(rbacSuperuser); coopShares.forEach(this::persist); - updateLegacyIds(coopShares, "hs_office_coopsharestransaction_legacy_id", "member_share_id"); + updateLegacyIds(coopShares, "hs_office.coopsharestransaction_legacy_id", "member_share_id"); }).assertSuccessful(); jpaAttempt.transacted(() -> { context(rbacSuperuser); coopAssets.forEach(this::persist); - updateLegacyIds(coopAssets, "hs_office_coopassetstransaction_legacy_id", "member_asset_id"); + updateLegacyIds(coopAssets, "hs_office.coopassetstransaction_legacy_id", "member_asset_id"); }).assertSuccessful(); } @@ -685,7 +685,7 @@ public abstract class BaseOfficeDataImport extends CsvDataImport { @Test @Order(9190) void verifyMembershipsActuallyPersisted() { - final var biCount = (Integer) em.createNativeQuery("select count(*) from hs_office_membership", Integer.class) + final var biCount = (Integer) em.createNativeQuery("select count(*) from hs_office.membership", Integer.class) .getSingleResult(); assertThat(biCount).isGreaterThan(isImportingControlledTestData() ? 5 : 300); } diff --git a/src/test/java/net/hostsharing/hsadminng/hs/migration/CsvDataImport.java b/src/test/java/net/hostsharing/hsadminng/hs/migration/CsvDataImport.java index 66cfc5e7..59f1d909 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/migration/CsvDataImport.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/migration/CsvDataImport.java @@ -254,34 +254,34 @@ public class CsvDataImport extends ContextBasedTest { em.createNativeQuery("delete from hs_booking_item_ex where true").executeUpdate(); em.createNativeQuery("delete from hs_booking_project where true").executeUpdate(); em.createNativeQuery("delete from hs_booking_project_ex where true").executeUpdate(); - em.createNativeQuery("delete from hs_office_coopassetstransaction where true").executeUpdate(); - em.createNativeQuery("delete from hs_office_coopassetstransaction_legacy_id where true").executeUpdate(); - em.createNativeQuery("delete from hs_office_coopsharestransaction where true").executeUpdate(); - em.createNativeQuery("delete from hs_office_coopsharestransaction_legacy_id where true").executeUpdate(); - em.createNativeQuery("delete from hs_office_membership where true").executeUpdate(); - em.createNativeQuery("delete from hs_office_sepamandate where true").executeUpdate(); - em.createNativeQuery("delete from hs_office_sepamandate_legacy_id where true").executeUpdate(); - em.createNativeQuery("delete from hs_office_debitor where true").executeUpdate(); - em.createNativeQuery("delete from hs_office_bankaccount where true").executeUpdate(); - em.createNativeQuery("delete from hs_office_partner where true").executeUpdate(); - em.createNativeQuery("delete from hs_office_partner_details where true").executeUpdate(); - em.createNativeQuery("delete from hs_office_relation where true").executeUpdate(); - em.createNativeQuery("delete from hs_office_contact where true").executeUpdate(); - em.createNativeQuery("delete from hs_office_person where true").executeUpdate(); + em.createNativeQuery("delete from hs_office.coopassetstransaction where true").executeUpdate(); + em.createNativeQuery("delete from hs_office.coopassetstransaction_legacy_id where true").executeUpdate(); + em.createNativeQuery("delete from hs_office.coopsharestransaction where true").executeUpdate(); + em.createNativeQuery("delete from hs_office.coopsharestransaction_legacy_id where true").executeUpdate(); + em.createNativeQuery("delete from hs_office.membership where true").executeUpdate(); + em.createNativeQuery("delete from hs_office.sepamandate where true").executeUpdate(); + em.createNativeQuery("delete from hs_office.sepamandate_legacy_id where true").executeUpdate(); + em.createNativeQuery("delete from hs_office.debitor where true").executeUpdate(); + em.createNativeQuery("delete from hs_office.bankaccount where true").executeUpdate(); + em.createNativeQuery("delete from hs_office.partner where true").executeUpdate(); + em.createNativeQuery("delete from hs_office.partner_details where true").executeUpdate(); + em.createNativeQuery("delete from hs_office.relation where true").executeUpdate(); + em.createNativeQuery("delete from hs_office.contact where true").executeUpdate(); + em.createNativeQuery("delete from hs_office.person where true").executeUpdate(); }).assertSuccessful(); } protected void resetHsOfficeSequences() { jpaAttempt.transacted(() -> { context(rbacSuperuser); - em.createNativeQuery("alter sequence hs_office_contact_legacy_id_seq restart with 1000000000;").executeUpdate(); - em.createNativeQuery("alter sequence hs_office_coopassetstransaction_legacy_id_seq restart with 1000000000;") + em.createNativeQuery("alter sequence hs_office.contact_legacy_id_seq restart with 1000000000;").executeUpdate(); + em.createNativeQuery("alter sequence hs_office.coopassetstransaction_legacy_id_seq restart with 1000000000;") .executeUpdate(); - em.createNativeQuery("alter sequence public.hs_office_coopsharestransaction_legacy_id_seq restart with 1000000000;") + em.createNativeQuery("alter sequence public.hs_office.coopsharestransaction_legacy_id_seq restart with 1000000000;") .executeUpdate(); - em.createNativeQuery("alter sequence public.hs_office_partner_legacy_id_seq restart with 1000000000;") + em.createNativeQuery("alter sequence public.hs_office.partner_legacy_id_seq restart with 1000000000;") .executeUpdate(); - em.createNativeQuery("alter sequence public.hs_office_sepamandate_legacy_id_seq restart with 1000000000;") + em.createNativeQuery("alter sequence public.hs_office.sepamandate_legacy_id_seq restart with 1000000000;") .executeUpdate(); }); } diff --git a/src/test/java/net/hostsharing/hsadminng/hs/office/bankaccount/HsOfficeBankAccountRepositoryIntegrationTest.java b/src/test/java/net/hostsharing/hsadminng/hs/office/bankaccount/HsOfficeBankAccountRepositoryIntegrationTest.java index df853a61..ed573418 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/office/bankaccount/HsOfficeBankAccountRepositoryIntegrationTest.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/office/bankaccount/HsOfficeBankAccountRepositoryIntegrationTest.java @@ -102,21 +102,21 @@ class HsOfficeBankAccountRepositoryIntegrationTest extends ContextBasedTestWithC final var roles = rawRoleRepo.findAll(); assertThat(distinctRoleNamesOf(roles)).containsExactlyInAnyOrder(Array.from( initialRoleNames, - "hs_office_bankaccount#DE25500105176934832579:OWNER", - "hs_office_bankaccount#DE25500105176934832579:ADMIN", - "hs_office_bankaccount#DE25500105176934832579:REFERRER" + "hs_office.bankaccount#DE25500105176934832579:OWNER", + "hs_office.bankaccount#DE25500105176934832579:ADMIN", + "hs_office.bankaccount#DE25500105176934832579:REFERRER" )); assertThat(distinctGrantDisplaysOf(rawGrantRepo.findAll())).containsExactlyInAnyOrder(Array.fromFormatted( initialGrantNames, - "{ grant perm:hs_office_bankaccount#DE25500105176934832579:DELETE to role:hs_office_bankaccount#DE25500105176934832579:OWNER by system and assume }", - "{ grant role:hs_office_bankaccount#DE25500105176934832579:OWNER to role:rbac.global#global:ADMIN by system and assume }", - "{ grant role:hs_office_bankaccount#DE25500105176934832579:OWNER to user:selfregistered-user-drew@hostsharing.org by hs_office_bankaccount#DE25500105176934832579:OWNER and assume }", + "{ grant perm:hs_office.bankaccount#DE25500105176934832579:DELETE to role:hs_office.bankaccount#DE25500105176934832579:OWNER by system and assume }", + "{ grant role:hs_office.bankaccount#DE25500105176934832579:OWNER to role:rbac.global#global:ADMIN by system and assume }", + "{ grant role:hs_office.bankaccount#DE25500105176934832579:OWNER to user:selfregistered-user-drew@hostsharing.org by hs_office.bankaccount#DE25500105176934832579:OWNER and assume }", - "{ grant role:hs_office_bankaccount#DE25500105176934832579:ADMIN to role:hs_office_bankaccount#DE25500105176934832579:OWNER by system and assume }", - "{ grant perm:hs_office_bankaccount#DE25500105176934832579:UPDATE to role:hs_office_bankaccount#DE25500105176934832579:ADMIN by system and assume }", + "{ grant role:hs_office.bankaccount#DE25500105176934832579:ADMIN to role:hs_office.bankaccount#DE25500105176934832579:OWNER by system and assume }", + "{ grant perm:hs_office.bankaccount#DE25500105176934832579:UPDATE to role:hs_office.bankaccount#DE25500105176934832579:ADMIN by system and assume }", - "{ grant perm:hs_office_bankaccount#DE25500105176934832579:SELECT to role:hs_office_bankaccount#DE25500105176934832579:REFERRER by system and assume }", - "{ grant role:hs_office_bankaccount#DE25500105176934832579:REFERRER to role:hs_office_bankaccount#DE25500105176934832579:ADMIN by system and assume }", + "{ grant perm:hs_office.bankaccount#DE25500105176934832579:SELECT to role:hs_office.bankaccount#DE25500105176934832579:REFERRER by system and assume }", + "{ grant role:hs_office.bankaccount#DE25500105176934832579:REFERRER to role:hs_office.bankaccount#DE25500105176934832579:ADMIN by system and assume }", null )); } @@ -273,7 +273,7 @@ class HsOfficeBankAccountRepositoryIntegrationTest extends ContextBasedTestWithC final var query = em.createNativeQuery(""" select currentTask, targetTable, targetOp, targetdelta->>'iban' from base.tx_journal_v - where targettable = 'hs_office_bankaccount'; + where targettable = 'hs_office.bankaccount'; """); // when @@ -281,9 +281,9 @@ class HsOfficeBankAccountRepositoryIntegrationTest extends ContextBasedTestWithC // then assertThat(customerLogEntries).map(Arrays::toString).contains( - "[creating bankaccount test-data, hs_office_bankaccount, INSERT, DE02120300000000202051]", - "[creating bankaccount test-data, hs_office_bankaccount, INSERT, DE02500105170137075030]", - "[creating bankaccount test-data, hs_office_bankaccount, INSERT, DE02100500000054540402]"); + "[creating bankaccount test-data, hs_office.bankaccount, INSERT, DE02120300000000202051]", + "[creating bankaccount test-data, hs_office.bankaccount, INSERT, DE02500105170137075030]", + "[creating bankaccount test-data, hs_office.bankaccount, INSERT, DE02100500000054540402]"); } private HsOfficeBankAccountEntity givenSomeTemporaryBankAccount(final String createdByUser) { diff --git a/src/test/java/net/hostsharing/hsadminng/hs/office/contact/HsOfficeContactRbacRepositoryIntegrationTest.java b/src/test/java/net/hostsharing/hsadminng/hs/office/contact/HsOfficeContactRbacRepositoryIntegrationTest.java index e7759f4b..b05b6da7 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/office/contact/HsOfficeContactRbacRepositoryIntegrationTest.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/office/contact/HsOfficeContactRbacRepositoryIntegrationTest.java @@ -103,20 +103,20 @@ class HsOfficeContactRbacRepositoryIntegrationTest extends ContextBasedTestWithC final var roles = rawRoleRepo.findAll(); assertThat(distinctRoleNamesOf(roles)).containsExactlyInAnyOrder(Array.from( initialRoleNames, - "hs_office_contact#anothernewcontact:OWNER", - "hs_office_contact#anothernewcontact:ADMIN", - "hs_office_contact#anothernewcontact:REFERRER" + "hs_office.contact#anothernewcontact:OWNER", + "hs_office.contact#anothernewcontact:ADMIN", + "hs_office.contact#anothernewcontact:REFERRER" )); assertThat(distinctGrantDisplaysOf(rawGrantRepo.findAll())).containsExactlyInAnyOrder(Array.fromFormatted( initialGrantNames, - "{ grant role:hs_office_contact#anothernewcontact:OWNER to role:rbac.global#global:ADMIN by system and assume }", - "{ grant perm:hs_office_contact#anothernewcontact:UPDATE to role:hs_office_contact#anothernewcontact:ADMIN by system and assume }", - "{ grant role:hs_office_contact#anothernewcontact:OWNER to user:selfregistered-user-drew@hostsharing.org by hs_office_contact#anothernewcontact:OWNER and assume }", - "{ grant perm:hs_office_contact#anothernewcontact:DELETE to role:hs_office_contact#anothernewcontact:OWNER by system and assume }", - "{ grant role:hs_office_contact#anothernewcontact:ADMIN to role:hs_office_contact#anothernewcontact:OWNER by system and assume }", + "{ grant role:hs_office.contact#anothernewcontact:OWNER to role:rbac.global#global:ADMIN by system and assume }", + "{ grant perm:hs_office.contact#anothernewcontact:UPDATE to role:hs_office.contact#anothernewcontact:ADMIN by system and assume }", + "{ grant role:hs_office.contact#anothernewcontact:OWNER to user:selfregistered-user-drew@hostsharing.org by hs_office.contact#anothernewcontact:OWNER and assume }", + "{ grant perm:hs_office.contact#anothernewcontact:DELETE to role:hs_office.contact#anothernewcontact:OWNER by system and assume }", + "{ grant role:hs_office.contact#anothernewcontact:ADMIN to role:hs_office.contact#anothernewcontact:OWNER by system and assume }", - "{ grant perm:hs_office_contact#anothernewcontact:SELECT to role:hs_office_contact#anothernewcontact:REFERRER by system and assume }", - "{ grant role:hs_office_contact#anothernewcontact:REFERRER to role:hs_office_contact#anothernewcontact:ADMIN by system and assume }" + "{ grant perm:hs_office.contact#anothernewcontact:SELECT to role:hs_office.contact#anothernewcontact:REFERRER by system and assume }", + "{ grant role:hs_office.contact#anothernewcontact:REFERRER to role:hs_office.contact#anothernewcontact:ADMIN by system and assume }" )); } @@ -258,17 +258,17 @@ class HsOfficeContactRbacRepositoryIntegrationTest extends ContextBasedTestWithC final var query = em.createNativeQuery(""" select currentTask, targetTable, targetOp, targetdelta->>'caption' from base.tx_journal_v - where targettable = 'hs_office_contact'; - """); + where targettable = 'hs_office.contact'; + """); // when @SuppressWarnings("unchecked") final List customerLogEntries = query.getResultList(); // then assertThat(customerLogEntries).map(Arrays::toString).contains( - "[creating contact test-data, hs_office_contact, INSERT, first contact]", - "[creating contact test-data, hs_office_contact, INSERT, second contact]", - "[creating contact test-data, hs_office_contact, INSERT, third contact]"); + "[creating contact test-data, hs_office.contact, INSERT, first contact]", + "[creating contact test-data, hs_office.contact, INSERT, second contact]", + "[creating contact test-data, hs_office.contact, INSERT, third contact]"); } private HsOfficeContactRbacEntity givenSomeTemporaryContact( diff --git a/src/test/java/net/hostsharing/hsadminng/hs/office/coopassets/HsOfficeCoopAssetsTransactionControllerAcceptanceTest.java b/src/test/java/net/hostsharing/hsadminng/hs/office/coopassets/HsOfficeCoopAssetsTransactionControllerAcceptanceTest.java index 9358e9ba..1ca91c75 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/office/coopassets/HsOfficeCoopAssetsTransactionControllerAcceptanceTest.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/office/coopassets/HsOfficeCoopAssetsTransactionControllerAcceptanceTest.java @@ -391,9 +391,9 @@ class HsOfficeCoopAssetsTransactionControllerAcceptanceTest extends ContextBased void cleanup() { jpaAttempt.transacted(() -> { context.define("superuser-alex@hostsharing.net", null); - // HsOfficeCoopAssetsTransactionEntity respectively hs_office_coopassetstransaction_rv + // HsOfficeCoopAssetsTransactionEntity respectively hs_office.coopassetstransaction_rv // cannot be deleted at all, but the underlying table record can be deleted. - em.createNativeQuery("delete from hs_office_coopassetstransaction where reference like 'temp %'") + em.createNativeQuery("delete from hs_office.coopassetstransaction where reference like 'temp %'") .executeUpdate(); }).assertSuccessful(); } diff --git a/src/test/java/net/hostsharing/hsadminng/hs/office/coopassets/HsOfficeCoopAssetsTransactionRepositoryIntegrationTest.java b/src/test/java/net/hostsharing/hsadminng/hs/office/coopassets/HsOfficeCoopAssetsTransactionRepositoryIntegrationTest.java index cf636cc6..b13ff2f5 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/office/coopassets/HsOfficeCoopAssetsTransactionRepositoryIntegrationTest.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/office/coopassets/HsOfficeCoopAssetsTransactionRepositoryIntegrationTest.java @@ -89,7 +89,7 @@ class HsOfficeCoopAssetsTransactionRepositoryIntegrationTest extends ContextBase context("superuser-alex@hostsharing.net"); final var initialRoleNames = distinctRoleNamesOf(rawRoleRepo.findAll()); final var initialGrantNames = distinctGrantDisplaysOf(rawGrantRepo.findAll()).stream() - .map(s -> s.replace("hs_office_", "")) + .map(s -> s.replace("hs_office.", "")) .toList(); // when @@ -109,7 +109,7 @@ class HsOfficeCoopAssetsTransactionRepositoryIntegrationTest extends ContextBase final var all = rawRoleRepo.findAll(); assertThat(distinctRoleNamesOf(all)).containsExactlyInAnyOrder(Array.from(initialRoleNames)); // no new roles created assertThat(distinctGrantDisplaysOf(rawGrantRepo.findAll())) - .map(s -> s.replace("hs_office_", "")) + .map(s -> s.replace("hs_office.", "")) .containsExactlyInAnyOrder(Array.fromFormatted( initialGrantNames, "{ grant perm:coopassetstransaction#temprefB:SELECT to role:membership#M-1000101:AGENT by system and assume }", @@ -198,7 +198,7 @@ class HsOfficeCoopAssetsTransactionRepositoryIntegrationTest extends ContextBase @Test public void partnerPersonAdmin_canViewRelatedCoopAssetsTransactions() { // given: - context("superuser-alex@hostsharing.net", "hs_office_person#FirstGmbH:ADMIN"); + context("superuser-alex@hostsharing.net", "hs_office.person#FirstGmbH:ADMIN"); // when: final var result = coopAssetsTransactionRepo.findCoopAssetsTransactionByOptionalMembershipUuidAndDateRange( @@ -222,7 +222,7 @@ class HsOfficeCoopAssetsTransactionRepositoryIntegrationTest extends ContextBase final var query = em.createNativeQuery(""" select currentTask, targetTable, targetOp, targetdelta->>'reference' from base.tx_journal_v - where targettable = 'hs_office_coopassetstransaction'; + where targettable = 'hs_office.coopassetstransaction'; """); // when @@ -230,18 +230,18 @@ class HsOfficeCoopAssetsTransactionRepositoryIntegrationTest extends ContextBase // then assertThat(customerLogEntries).map(Arrays::toString).contains( - "[creating coopAssetsTransaction test-data, hs_office_coopassetstransaction, INSERT, ref 1000101-1]", - "[creating coopAssetsTransaction test-data, hs_office_coopassetstransaction, INSERT, ref 1000101-2]", - "[creating coopAssetsTransaction test-data, hs_office_coopassetstransaction, INSERT, ref 1000101-3]", - "[creating coopAssetsTransaction test-data, hs_office_coopassetstransaction, INSERT, ref 1000101-3]", - "[creating coopAssetsTransaction test-data, hs_office_coopassetstransaction, INSERT, ref 1000202-1]", - "[creating coopAssetsTransaction test-data, hs_office_coopassetstransaction, INSERT, ref 1000202-2]", - "[creating coopAssetsTransaction test-data, hs_office_coopassetstransaction, INSERT, ref 1000202-3]", - "[creating coopAssetsTransaction test-data, hs_office_coopassetstransaction, INSERT, ref 1000202-3]", - "[creating coopAssetsTransaction test-data, hs_office_coopassetstransaction, INSERT, ref 1000303-1]", - "[creating coopAssetsTransaction test-data, hs_office_coopassetstransaction, INSERT, ref 1000303-2]", - "[creating coopAssetsTransaction test-data, hs_office_coopassetstransaction, INSERT, ref 1000303-3]", - "[creating coopAssetsTransaction test-data, hs_office_coopassetstransaction, INSERT, ref 1000303-3]"); + "[creating coopAssetsTransaction test-data, hs_office.coopassetstransaction, INSERT, ref 1000101-1]", + "[creating coopAssetsTransaction test-data, hs_office.coopassetstransaction, INSERT, ref 1000101-2]", + "[creating coopAssetsTransaction test-data, hs_office.coopassetstransaction, INSERT, ref 1000101-3]", + "[creating coopAssetsTransaction test-data, hs_office.coopassetstransaction, INSERT, ref 1000101-3]", + "[creating coopAssetsTransaction test-data, hs_office.coopassetstransaction, INSERT, ref 1000202-1]", + "[creating coopAssetsTransaction test-data, hs_office.coopassetstransaction, INSERT, ref 1000202-2]", + "[creating coopAssetsTransaction test-data, hs_office.coopassetstransaction, INSERT, ref 1000202-3]", + "[creating coopAssetsTransaction test-data, hs_office.coopassetstransaction, INSERT, ref 1000202-3]", + "[creating coopAssetsTransaction test-data, hs_office.coopassetstransaction, INSERT, ref 1000303-1]", + "[creating coopAssetsTransaction test-data, hs_office.coopassetstransaction, INSERT, ref 1000303-2]", + "[creating coopAssetsTransaction test-data, hs_office.coopassetstransaction, INSERT, ref 1000303-3]", + "[creating coopAssetsTransaction test-data, hs_office.coopassetstransaction, INSERT, ref 1000303-3]"); } @BeforeEach diff --git a/src/test/java/net/hostsharing/hsadminng/hs/office/coopshares/HsOfficeCoopSharesTransactionControllerAcceptanceTest.java b/src/test/java/net/hostsharing/hsadminng/hs/office/coopshares/HsOfficeCoopSharesTransactionControllerAcceptanceTest.java index 83fd3917..a379c415 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/office/coopshares/HsOfficeCoopSharesTransactionControllerAcceptanceTest.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/office/coopshares/HsOfficeCoopSharesTransactionControllerAcceptanceTest.java @@ -55,9 +55,9 @@ class HsOfficeCoopSharesTransactionControllerAcceptanceTest extends ContextBased void cleanup() { jpaAttempt.transacted(() -> { context.define("superuser-alex@hostsharing.net", null); - // HsOfficeCoopSharesTransactionEntity respectively hs_office_coopsharestransaction_rv + // HsOfficeCoopSharesTransactionEntity respectively hs_office.coopsharestransaction_rv // cannot be deleted at all, but the underlying table record can be deleted. - em.createNativeQuery("delete from hs_office_coopsharestransaction where reference like 'temp %'").executeUpdate(); + em.createNativeQuery("delete from hs_office.coopsharestransaction where reference like 'temp %'").executeUpdate(); }).assertSuccessful(); } diff --git a/src/test/java/net/hostsharing/hsadminng/hs/office/coopshares/HsOfficeCoopSharesTransactionRepositoryIntegrationTest.java b/src/test/java/net/hostsharing/hsadminng/hs/office/coopshares/HsOfficeCoopSharesTransactionRepositoryIntegrationTest.java index af627350..6ef36d57 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/office/coopshares/HsOfficeCoopSharesTransactionRepositoryIntegrationTest.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/office/coopshares/HsOfficeCoopSharesTransactionRepositoryIntegrationTest.java @@ -88,7 +88,7 @@ class HsOfficeCoopSharesTransactionRepositoryIntegrationTest extends ContextBase context("superuser-alex@hostsharing.net"); final var initialRoleNames = distinctRoleNamesOf(rawRoleRepo.findAll()); final var initialGrantNames = distinctGrantDisplaysOf(rawGrantRepo.findAll()).stream() - .map(s -> s.replace("hs_office_", "")) + .map(s -> s.replace("hs_office.", "")) .toList(); // when @@ -108,7 +108,7 @@ class HsOfficeCoopSharesTransactionRepositoryIntegrationTest extends ContextBase final var all = rawRoleRepo.findAll(); assertThat(distinctRoleNamesOf(all)).containsExactlyInAnyOrder(Array.from(initialRoleNames)); // no new roles created assertThat(distinctGrantDisplaysOf(rawGrantRepo.findAll())) - .map(s -> s.replace("hs_office_", "")) + .map(s -> s.replace("hs_office.", "")) .containsExactlyInAnyOrder(Array.fromFormatted( initialGrantNames, "{ grant perm:coopsharestransaction#temprefB:SELECT to role:membership#M-1000101:AGENT by system and assume }", @@ -197,7 +197,7 @@ class HsOfficeCoopSharesTransactionRepositoryIntegrationTest extends ContextBase @Test public void normalUser_canViewOnlyRelatedCoopSharesTransactions() { // given: - context("superuser-alex@hostsharing.net", "hs_office_membership#M-1000101:ADMIN"); + context("superuser-alex@hostsharing.net", "hs_office.membership#M-1000101:ADMIN"); // when: final var result = coopSharesTransactionRepo.findCoopSharesTransactionByOptionalMembershipUuidAndDateRange( @@ -221,7 +221,7 @@ class HsOfficeCoopSharesTransactionRepositoryIntegrationTest extends ContextBase final var query = em.createNativeQuery(""" select currentTask, targetTable, targetOp, targetdelta->>'reference' from base.tx_journal_v - where targettable = 'hs_office_coopsharestransaction'; + where targettable = 'hs_office.coopsharestransaction'; """); // when @@ -229,18 +229,18 @@ class HsOfficeCoopSharesTransactionRepositoryIntegrationTest extends ContextBase // then assertThat(customerLogEntries).map(Arrays::toString).contains( - "[creating coopSharesTransaction test-data, hs_office_coopsharestransaction, INSERT, ref 1000101-1]", - "[creating coopSharesTransaction test-data, hs_office_coopsharestransaction, INSERT, ref 1000101-2]", - "[creating coopSharesTransaction test-data, hs_office_coopsharestransaction, INSERT, ref 1000101-3]", - "[creating coopSharesTransaction test-data, hs_office_coopsharestransaction, INSERT, ref 1000101-4]", - "[creating coopSharesTransaction test-data, hs_office_coopsharestransaction, INSERT, ref 1000202-1]", - "[creating coopSharesTransaction test-data, hs_office_coopsharestransaction, INSERT, ref 1000202-2]", - "[creating coopSharesTransaction test-data, hs_office_coopsharestransaction, INSERT, ref 1000202-3]", - "[creating coopSharesTransaction test-data, hs_office_coopsharestransaction, INSERT, ref 1000202-4]", - "[creating coopSharesTransaction test-data, hs_office_coopsharestransaction, INSERT, ref 1000303-1]", - "[creating coopSharesTransaction test-data, hs_office_coopsharestransaction, INSERT, ref 1000303-2]", - "[creating coopSharesTransaction test-data, hs_office_coopsharestransaction, INSERT, ref 1000303-3]", - "[creating coopSharesTransaction test-data, hs_office_coopsharestransaction, INSERT, ref 1000303-4]"); + "[creating coopSharesTransaction test-data, hs_office.coopsharestransaction, INSERT, ref 1000101-1]", + "[creating coopSharesTransaction test-data, hs_office.coopsharestransaction, INSERT, ref 1000101-2]", + "[creating coopSharesTransaction test-data, hs_office.coopsharestransaction, INSERT, ref 1000101-3]", + "[creating coopSharesTransaction test-data, hs_office.coopsharestransaction, INSERT, ref 1000101-4]", + "[creating coopSharesTransaction test-data, hs_office.coopsharestransaction, INSERT, ref 1000202-1]", + "[creating coopSharesTransaction test-data, hs_office.coopsharestransaction, INSERT, ref 1000202-2]", + "[creating coopSharesTransaction test-data, hs_office.coopsharestransaction, INSERT, ref 1000202-3]", + "[creating coopSharesTransaction test-data, hs_office.coopsharestransaction, INSERT, ref 1000202-4]", + "[creating coopSharesTransaction test-data, hs_office.coopsharestransaction, INSERT, ref 1000303-1]", + "[creating coopSharesTransaction test-data, hs_office.coopsharestransaction, INSERT, ref 1000303-2]", + "[creating coopSharesTransaction test-data, hs_office.coopsharestransaction, INSERT, ref 1000303-3]", + "[creating coopSharesTransaction test-data, hs_office.coopsharestransaction, INSERT, ref 1000303-4]"); } @BeforeEach diff --git a/src/test/java/net/hostsharing/hsadminng/hs/office/debitor/HsOfficeDebitorControllerAcceptanceTest.java b/src/test/java/net/hostsharing/hsadminng/hs/office/debitor/HsOfficeDebitorControllerAcceptanceTest.java index 1f1a188a..98ba650c 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/office/debitor/HsOfficeDebitorControllerAcceptanceTest.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/office/debitor/HsOfficeDebitorControllerAcceptanceTest.java @@ -638,7 +638,7 @@ class HsOfficeDebitorControllerAcceptanceTest extends ContextBasedTestWithCleanu RestAssured // @formatter:off .given() .header("current-subject", "superuser-alex@hostsharing.net") - .header("assumed-roles", "hs_office_contact#fourthcontact:ADMIN") + .header("assumed-roles", "hs_office.contact#fourthcontact:ADMIN") .contentType(ContentType.JSON) .body(""" { @@ -651,7 +651,7 @@ class HsOfficeDebitorControllerAcceptanceTest extends ContextBasedTestWithCleanu .then().log().all().assertThat() .statusCode(403) .body("message", containsString("ERROR: [403] Subject")) - .body("message", containsString("is not allowed to update hs_office_debitor uuid ")); + .body("message", containsString("is not allowed to update hs_office.debitor uuid ")); } } diff --git a/src/test/java/net/hostsharing/hsadminng/hs/office/debitor/HsOfficeDebitorRepositoryIntegrationTest.java b/src/test/java/net/hostsharing/hsadminng/hs/office/debitor/HsOfficeDebitorRepositoryIntegrationTest.java index 97f30b8a..53807d89 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/office/debitor/HsOfficeDebitorRepositoryIntegrationTest.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/office/debitor/HsOfficeDebitorRepositoryIntegrationTest.java @@ -141,7 +141,7 @@ class HsOfficeDebitorRepositoryIntegrationTest extends ContextBasedTestWithClean // then result.assertExceptionWithRootCauseMessage(org.hibernate.exception.ConstraintViolationException.class, - "ERROR: new row for relation \"hs_office_debitor\" violates check constraint \"check_default_prefix\""); + "ERROR: new row for relation \"debitor\" violates check constraint \"check_default_prefix\""); } @Test @@ -151,7 +151,7 @@ class HsOfficeDebitorRepositoryIntegrationTest extends ContextBasedTestWithClean final var initialRoleNames = distinctRoleNamesOf(rawRoleRepo.findAll()); final var initialGrantNames = distinctGrantDisplaysOf(rawGrantRepo.findAll()).stream() // some search+replace to make the output fit into the screen width - .map(s -> s.replace("hs_office_", "")) + .map(s -> s.replace("hs_office.", "")) .toList(); // when @@ -176,12 +176,12 @@ class HsOfficeDebitorRepositoryIntegrationTest extends ContextBasedTestWithClean // then assertThat(distinctRoleNamesOf(rawRoleRepo.findAll())).containsExactlyInAnyOrder(Array.from( initialRoleNames, - "hs_office_relation#FirstGmbH-with-DEBITOR-FourtheG:OWNER", - "hs_office_relation#FirstGmbH-with-DEBITOR-FourtheG:ADMIN", - "hs_office_relation#FirstGmbH-with-DEBITOR-FourtheG:AGENT", - "hs_office_relation#FirstGmbH-with-DEBITOR-FourtheG:TENANT")); + "hs_office.relation#FirstGmbH-with-DEBITOR-FourtheG:OWNER", + "hs_office.relation#FirstGmbH-with-DEBITOR-FourtheG:ADMIN", + "hs_office.relation#FirstGmbH-with-DEBITOR-FourtheG:AGENT", + "hs_office.relation#FirstGmbH-with-DEBITOR-FourtheG:TENANT")); assertThat(distinctGrantDisplaysOf(rawGrantRepo.findAll())) - .map(s -> s.replace("hs_office_", "")) + .map(s -> s.replace("hs_office.", "")) .containsExactlyInAnyOrder(Array.fromFormatted( initialGrantNames, "{ grant perm:relation#FirstGmbH-with-DEBITOR-FourtheG:INSERT>sepamandate to role:relation#FirstGmbH-with-DEBITOR-FourtheG:ADMIN by system and assume }", @@ -247,9 +247,9 @@ class HsOfficeDebitorRepositoryIntegrationTest extends ContextBasedTestWithClean @ParameterizedTest @Disabled // TODO: reactivate once partner.person + partner.contact are removed @ValueSource(strings = { - "hs_office_partner#10001:FirstGmbH-firstcontact:ADMIN", - "hs_office_person#FirstGmbH:ADMIN", - "hs_office_contact#firstcontact:ADMIN", + "hs_office.partner#10001:FirstGmbH-firstcontact:ADMIN", + "hs_office.person#FirstGmbH:ADMIN", + "hs_office.contact#firstcontact:ADMIN", }) public void relatedPersonAdmin_canViewRelatedDebitors(final String assumedRole) { // given: @@ -321,7 +321,7 @@ class HsOfficeDebitorRepositoryIntegrationTest extends ContextBasedTestWithClean assertThatDebitorIsVisibleForUserWithRole( givenDebitor, - "hs_office_relation#FourtheG-with-DEBITOR-FourtheG:ADMIN", true); + "hs_office.relation#FourtheG-with-DEBITOR-FourtheG:ADMIN", true); final var givenNewPartnerPerson = one(personRepo.findPersonByOptionalNameLike("First")); final var givenNewBillingPerson = one(personRepo.findPersonByOptionalNameLike("Firby")); final var givenNewContact = one(contactrealRepo.findContactByOptionalCaptionLike("sixth contact")); @@ -354,26 +354,26 @@ class HsOfficeDebitorRepositoryIntegrationTest extends ContextBasedTestWithClean // ... partner role was reassigned: assertThatDebitorIsNotVisibleForUserWithRole( result.returnedValue(), - "hs_office_relation#FourtheG-with-DEBITOR-FourtheG:ADMIN"); + "hs_office.relation#FourtheG-with-DEBITOR-FourtheG:ADMIN"); assertThatDebitorIsVisibleForUserWithRole( result.returnedValue(), - "hs_office_relation#FirstGmbH-with-DEBITOR-FirbySusan:AGENT", true); + "hs_office.relation#FirstGmbH-with-DEBITOR-FirbySusan:AGENT", true); // ... contact role was reassigned: assertThatDebitorIsNotVisibleForUserWithRole( result.returnedValue(), - "hs_office_contact#fifthcontact:ADMIN"); + "hs_office.contact#fifthcontact:ADMIN"); assertThatDebitorIsVisibleForUserWithRole( result.returnedValue(), - "hs_office_contact#sixthcontact:ADMIN", false); + "hs_office.contact#sixthcontact:ADMIN", false); // ... bank-account role was reassigned: assertThatDebitorIsNotVisibleForUserWithRole( result.returnedValue(), - "hs_office_bankaccount#DE02200505501015871393:ADMIN"); + "hs_office.bankaccount#DE02200505501015871393:ADMIN"); assertThatDebitorIsVisibleForUserWithRole( result.returnedValue(), - "hs_office_bankaccount#DE02120300000000202051:ADMIN", true); + "hs_office.bankaccount#DE02120300000000202051:ADMIN", true); } @Test @@ -383,7 +383,7 @@ class HsOfficeDebitorRepositoryIntegrationTest extends ContextBasedTestWithClean final var givenDebitor = givenSomeTemporaryDebitor("Fourth", "fifth contact", null, "fig"); assertThatDebitorIsVisibleForUserWithRole( givenDebitor, - "hs_office_relation#FourtheG-with-DEBITOR-FourtheG:ADMIN", true); + "hs_office.relation#FourtheG-with-DEBITOR-FourtheG:ADMIN", true); assertThatDebitorActuallyInDatabase(givenDebitor, true); final var givenNewBankAccount = one(bankAccountRepo.findByOptionalHolderLike("first")); @@ -403,7 +403,7 @@ class HsOfficeDebitorRepositoryIntegrationTest extends ContextBasedTestWithClean // ... bank-account role was assigned: assertThatDebitorIsVisibleForUserWithRole( result.returnedValue(), - "hs_office_bankaccount#DE02120300000000202051:ADMIN", true); + "hs_office.bankaccount#DE02120300000000202051:ADMIN", true); } @Test @@ -413,7 +413,7 @@ class HsOfficeDebitorRepositoryIntegrationTest extends ContextBasedTestWithClean final var givenDebitor = givenSomeTemporaryDebitor("Fourth", "fifth contact", "Fourth", "fih"); assertThatDebitorIsVisibleForUserWithRole( givenDebitor, - "hs_office_relation#HostsharingeG-with-PARTNER-FourtheG:AGENT", true); + "hs_office.relation#HostsharingeG-with-PARTNER-FourtheG:AGENT", true); assertThatDebitorActuallyInDatabase(givenDebitor, true); // when @@ -432,7 +432,7 @@ class HsOfficeDebitorRepositoryIntegrationTest extends ContextBasedTestWithClean // ... bank-account role was removed from previous bank-account admin: assertThatDebitorIsNotVisibleForUserWithRole( result.returnedValue(), - "hs_office_bankaccount#DE02200505501015871393:ADMIN"); + "hs_office.bankaccount#DE02200505501015871393:ADMIN"); } @Test @@ -442,19 +442,19 @@ class HsOfficeDebitorRepositoryIntegrationTest extends ContextBasedTestWithClean final var givenDebitor = givenSomeTemporaryDebitor("Fourth", "eighth", "Fourth", "eig"); assertThatDebitorIsVisibleForUserWithRole( givenDebitor, - "hs_office_relation#HostsharingeG-with-PARTNER-FourtheG:AGENT", true); + "hs_office.relation#HostsharingeG-with-PARTNER-FourtheG:AGENT", true); assertThatDebitorActuallyInDatabase(givenDebitor, true); // when final var result = jpaAttempt.transacted(() -> { - context("superuser-alex@hostsharing.net", "hs_office_relation#HostsharingeG-with-PARTNER-FourtheG:AGENT"); + context("superuser-alex@hostsharing.net", "hs_office.relation#HostsharingeG-with-PARTNER-FourtheG:AGENT"); givenDebitor.setVatId("NEW-VAT-ID"); return toCleanup(debitorRepo.save(givenDebitor)); }); // then result.assertExceptionWithRootCauseMessage(JpaSystemException.class, - "[403] Subject ", " is not allowed to update hs_office_debitor uuid"); + "[403] Subject ", " is not allowed to update hs_office.debitor uuid"); } @Test @@ -463,11 +463,11 @@ class HsOfficeDebitorRepositoryIntegrationTest extends ContextBasedTestWithClean context("superuser-alex@hostsharing.net"); final var givenDebitor = givenSomeTemporaryDebitor("Fourth", "ninth", "Fourth", "nin"); assertThatDebitorActuallyInDatabase(givenDebitor, true); - assertThatDebitorIsVisibleForUserWithRole(givenDebitor, "hs_office_contact#ninthcontact:ADMIN", false); + assertThatDebitorIsVisibleForUserWithRole(givenDebitor, "hs_office.contact#ninthcontact:ADMIN", false); // when final var result = jpaAttempt.transacted(() -> { - context("superuser-alex@hostsharing.net", "hs_office_contact#ninthcontact:ADMIN"); + context("superuser-alex@hostsharing.net", "hs_office.contact#ninthcontact:ADMIN"); givenDebitor.setVatId("NEW-VAT-ID"); final HsOfficeDebitorEntity entity = debitorRepo.save(givenDebitor); return toCleanup(entity.load()); @@ -477,7 +477,7 @@ class HsOfficeDebitorRepositoryIntegrationTest extends ContextBasedTestWithClean result.assertExceptionWithRootCauseMessage( JpaSystemException.class, "ERROR: [403]", - "is not allowed to update hs_office_debitor uuid"); + "is not allowed to update hs_office.debitor uuid"); } private void assertThatDebitorActuallyInDatabase(final HsOfficeDebitorEntity saved, final boolean withPartner) { @@ -547,7 +547,7 @@ class HsOfficeDebitorRepositoryIntegrationTest extends ContextBasedTestWithClean // when final var result = jpaAttempt.transacted(() -> { - context("superuser-alex@hostsharing.net", "hs_office_relation#FourtheG-with-DEBITOR-FourtheG:ADMIN"); + context("superuser-alex@hostsharing.net", "hs_office.relation#FourtheG-with-DEBITOR-FourtheG:ADMIN"); assertThat(debitorRepo.findByUuid(givenDebitor.getUuid())).isPresent(); debitorRepo.deleteByUuid(givenDebitor.getUuid()); @@ -556,7 +556,7 @@ class HsOfficeDebitorRepositoryIntegrationTest extends ContextBasedTestWithClean // then result.assertExceptionWithRootCauseMessage( JpaSystemException.class, - "[403] Subject ", " not allowed to delete hs_office_debitor"); + "[403] Subject ", " not allowed to delete hs_office.debitor"); assertThat(jpaAttempt.transacted(() -> { context("superuser-alex@hostsharing.net"); return debitorRepo.findByUuid(givenDebitor.getUuid()); @@ -591,7 +591,7 @@ class HsOfficeDebitorRepositoryIntegrationTest extends ContextBasedTestWithClean final var query = em.createNativeQuery(""" select currentTask, targetTable, targetOp, targetdelta->>'defaultprefix' from base.tx_journal_v - where targettable = 'hs_office_debitor'; + where targettable = 'hs_office.debitor'; """); // when @@ -599,9 +599,9 @@ class HsOfficeDebitorRepositoryIntegrationTest extends ContextBasedTestWithClean // then assertThat(customerLogEntries).map(Arrays::toString).contains( - "[creating debitor test-data, hs_office_debitor, INSERT, fir]", - "[creating debitor test-data, hs_office_debitor, INSERT, sec]", - "[creating debitor test-data, hs_office_debitor, INSERT, thi]"); + "[creating debitor test-data, hs_office.debitor, INSERT, fir]", + "[creating debitor test-data, hs_office.debitor, INSERT, sec]", + "[creating debitor test-data, hs_office.debitor, INSERT, thi]"); } private HsOfficeDebitorEntity givenSomeTemporaryDebitor( diff --git a/src/test/java/net/hostsharing/hsadminng/hs/office/membership/HsOfficeMembershipControllerAcceptanceTest.java b/src/test/java/net/hostsharing/hsadminng/hs/office/membership/HsOfficeMembershipControllerAcceptanceTest.java index ee6b956c..55f2fbd7 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/office/membership/HsOfficeMembershipControllerAcceptanceTest.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/office/membership/HsOfficeMembershipControllerAcceptanceTest.java @@ -263,7 +263,7 @@ class HsOfficeMembershipControllerAcceptanceTest extends ContextBasedTestWithCle RestAssured // @formatter:off .given() .header("current-subject", "superuser-alex@hostsharing.net") - .header("assumed-roles", "hs_office_relation#HostsharingeG-with-PARTNER-ThirdOHG:AGENT") + .header("assumed-roles", "hs_office.relation#HostsharingeG-with-PARTNER-ThirdOHG:AGENT") .port(port) .when() .get("http://localhost/api/hs/office/memberships/" + givenMembershipUuid) @@ -331,7 +331,7 @@ class HsOfficeMembershipControllerAcceptanceTest extends ContextBasedTestWithCle void partnerRelAdmin_canPatchValidityOfRelatedMembership() { // given - final var givenPartnerAdmin = "hs_office_relation#HostsharingeG-with-PARTNER-FirstGmbH:ADMIN"; + final var givenPartnerAdmin = "hs_office.relation#HostsharingeG-with-PARTNER-FirstGmbH:ADMIN"; context.define("superuser-alex@hostsharing.net", givenPartnerAdmin); final var givenMembership = givenSomeTemporaryMembershipBessler("First"); @@ -392,7 +392,7 @@ class HsOfficeMembershipControllerAcceptanceTest extends ContextBasedTestWithCle RestAssured // @formatter:off .given() .header("current-subject", "superuser-alex@hostsharing.net") - .header("assumed-roles", "hs_office_relation#HostsharingeG-with-PARTNER-FirstGmbH:AGENT") + .header("assumed-roles", "hs_office.relation#HostsharingeG-with-PARTNER-FirstGmbH:AGENT") .port(port) .when() .delete("http://localhost/api/hs/office/memberships/" + givenMembership.getUuid()) diff --git a/src/test/java/net/hostsharing/hsadminng/hs/office/membership/HsOfficeMembershipRepositoryIntegrationTest.java b/src/test/java/net/hostsharing/hsadminng/hs/office/membership/HsOfficeMembershipRepositoryIntegrationTest.java index 5916abc0..8192c705 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/office/membership/HsOfficeMembershipRepositoryIntegrationTest.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/office/membership/HsOfficeMembershipRepositoryIntegrationTest.java @@ -91,7 +91,7 @@ class HsOfficeMembershipRepositoryIntegrationTest extends ContextBasedTestWithCl context("superuser-alex@hostsharing.net"); final var initialRoleNames = distinctRoleNamesOf(rawRoleRepo.findAll()); final var initialGrantNames = distinctGrantDisplaysOf(rawGrantRepo.findAll()).stream() - .map(s -> s.replace("hs_office_", "")) + .map(s -> s.replace("hs_office.", "")) .toList(); // when @@ -110,11 +110,11 @@ class HsOfficeMembershipRepositoryIntegrationTest extends ContextBasedTestWithCl final var all = rawRoleRepo.findAll(); assertThat(distinctRoleNamesOf(all)).containsExactlyInAnyOrder(Array.from( initialRoleNames, - "hs_office_membership#M-1000117:OWNER", - "hs_office_membership#M-1000117:ADMIN", - "hs_office_membership#M-1000117:AGENT")); + "hs_office.membership#M-1000117:OWNER", + "hs_office.membership#M-1000117:ADMIN", + "hs_office.membership#M-1000117:AGENT")); assertThat(distinctGrantDisplaysOf(rawGrantRepo.findAll())) - .map(s -> s.replace("hs_office_", "")) + .map(s -> s.replace("hs_office.", "")) .containsExactlyInAnyOrder(Array.fromFormatted( initialGrantNames, // insert @@ -230,13 +230,13 @@ class HsOfficeMembershipRepositoryIntegrationTest extends ContextBasedTestWithCl assertThatMembershipExistsAndIsAccessibleToCurrentContext(givenMembership); assertThatMembershipIsVisibleForRole( givenMembership, - "hs_office_membership#M-1000113:AGENT"); + "hs_office.membership#M-1000113:AGENT"); final var newValidityEnd = LocalDate.now(); // when final var result = jpaAttempt.transacted(() -> { // TODO: we should test with debitor- and partner-admin as well - context("superuser-alex@hostsharing.net", "hs_office_membership#M-1000113:AGENT"); + context("superuser-alex@hostsharing.net", "hs_office.membership#M-1000113:AGENT"); givenMembership.setValidity( Range.closedOpen(givenMembership.getValidity().lower(), newValidityEnd)); return membershipRepo.save(givenMembership); @@ -244,7 +244,7 @@ class HsOfficeMembershipRepositoryIntegrationTest extends ContextBasedTestWithCl // then result.assertExceptionWithRootCauseMessage(JpaSystemException.class, - "[403] Subject ", " is not allowed to update hs_office_membership uuid"); + "[403] Subject ", " is not allowed to update hs_office.membership uuid"); } private void assertThatMembershipExistsAndIsAccessibleToCurrentContext(final HsOfficeMembershipEntity saved) { @@ -294,7 +294,7 @@ class HsOfficeMembershipRepositoryIntegrationTest extends ContextBasedTestWithCl // when final var result = jpaAttempt.transacted(() -> { - context("superuser-alex@hostsharing.net", "hs_office_relation#HostsharingeG-with-PARTNER-FirstGmbH:AGENT"); + context("superuser-alex@hostsharing.net", "hs_office.relation#HostsharingeG-with-PARTNER-FirstGmbH:AGENT"); assertThat(membershipRepo.findByUuid(givenMembership.getUuid())).isPresent(); membershipRepo.deleteByUuid(givenMembership.getUuid()); @@ -303,7 +303,7 @@ class HsOfficeMembershipRepositoryIntegrationTest extends ContextBasedTestWithCl // then result.assertExceptionWithRootCauseMessage( JpaSystemException.class, - "[403] Subject ", " not allowed to delete hs_office_membership"); + "[403] Subject ", " not allowed to delete hs_office.membership"); assertThat(jpaAttempt.transacted(() -> { context("superuser-alex@hostsharing.net"); return membershipRepo.findByUuid(givenMembership.getUuid()); @@ -338,7 +338,7 @@ class HsOfficeMembershipRepositoryIntegrationTest extends ContextBasedTestWithCl final var query = em.createNativeQuery(""" select currentTask, targetTable, targetOp, targetdelta->>'membernumbersuffix' from base.tx_journal_v - where targettable = 'hs_office_membership'; + where targettable = 'hs_office.membership'; """); // when @@ -346,9 +346,9 @@ class HsOfficeMembershipRepositoryIntegrationTest extends ContextBasedTestWithCl // then assertThat(customerLogEntries).map(Arrays::toString).contains( - "[creating Membership test-data, hs_office_membership, INSERT, 01]", - "[creating Membership test-data, hs_office_membership, INSERT, 02]", - "[creating Membership test-data, hs_office_membership, INSERT, 03]"); + "[creating Membership test-data, hs_office.membership, INSERT, 01]", + "[creating Membership test-data, hs_office.membership, INSERT, 02]", + "[creating Membership test-data, hs_office.membership, INSERT, 03]"); } private HsOfficeMembershipEntity givenSomeTemporaryMembership(final String partnerTradeName, final String memberNumberSuffix) { diff --git a/src/test/java/net/hostsharing/hsadminng/hs/office/partner/HsOfficePartnerRepositoryIntegrationTest.java b/src/test/java/net/hostsharing/hsadminng/hs/office/partner/HsOfficePartnerRepositoryIntegrationTest.java index f0ad1527..90c79490 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/office/partner/HsOfficePartnerRepositoryIntegrationTest.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/office/partner/HsOfficePartnerRepositoryIntegrationTest.java @@ -103,7 +103,7 @@ class HsOfficePartnerRepositoryIntegrationTest extends ContextBasedTestWithClean final var initialGrantNames = distinctGrantDisplaysOf(rawGrantRepo.findAll()).stream() .map(s -> s.replace("ErbenBesslerMelBessler", "EBess")) .map(s -> s.replace("fourthcontact", "4th")) - .map(s -> s.replace("hs_office_", "")) + .map(s -> s.replace("hs_office.", "")) .toList(); // when @@ -131,14 +131,14 @@ class HsOfficePartnerRepositoryIntegrationTest extends ContextBasedTestWithClean // then assertThat(distinctRoleNamesOf(rawRoleRepo.findAll())).containsExactlyInAnyOrder(from( initialRoleNames, - "hs_office_relation#HostsharingeG-with-PARTNER-ErbenBesslerMelBessler:OWNER", - "hs_office_relation#HostsharingeG-with-PARTNER-ErbenBesslerMelBessler:ADMIN", - "hs_office_relation#HostsharingeG-with-PARTNER-ErbenBesslerMelBessler:AGENT", - "hs_office_relation#HostsharingeG-with-PARTNER-ErbenBesslerMelBessler:TENANT")); + "hs_office.relation#HostsharingeG-with-PARTNER-ErbenBesslerMelBessler:OWNER", + "hs_office.relation#HostsharingeG-with-PARTNER-ErbenBesslerMelBessler:ADMIN", + "hs_office.relation#HostsharingeG-with-PARTNER-ErbenBesslerMelBessler:AGENT", + "hs_office.relation#HostsharingeG-with-PARTNER-ErbenBesslerMelBessler:TENANT")); assertThat(distinctGrantDisplaysOf(rawGrantRepo.findAll())) .map(s -> s.replace("ErbenBesslerMelBessler", "EBess")) .map(s -> s.replace("fourthcontact", "4th")) - .map(s -> s.replace("hs_office_", "")) + .map(s -> s.replace("hs_office.", "")) .containsExactlyInAnyOrder(distinct(from( initialGrantNames, @@ -263,7 +263,7 @@ class HsOfficePartnerRepositoryIntegrationTest extends ContextBasedTestWithClean final var givenPartner = givenSomeTemporaryHostsharingPartner(20036, "Erben Bessler", "fifth contact"); assertThatPartnerIsVisibleForUserWithRole( givenPartner, - "hs_office_person#ErbenBesslerMelBessler:ADMIN"); + "hs_office.person#ErbenBesslerMelBessler:ADMIN"); assertThatPartnerActuallyInDatabase(givenPartner); // when @@ -281,10 +281,10 @@ class HsOfficePartnerRepositoryIntegrationTest extends ContextBasedTestWithClean "rbac.global#global:ADMIN"); assertThatPartnerIsVisibleForUserWithRole( givenPartner, - "hs_office_person#ThirdOHG:ADMIN"); + "hs_office.person#ThirdOHG:ADMIN"); assertThatPartnerIsNotVisibleForUserWithRole( givenPartner, - "hs_office_person#ErbenBesslerMelBessler:ADMIN"); + "hs_office.person#ErbenBesslerMelBessler:ADMIN"); } @Test @@ -294,13 +294,13 @@ class HsOfficePartnerRepositoryIntegrationTest extends ContextBasedTestWithClean final var givenPartner = givenSomeTemporaryHostsharingPartner(20037, "Erben Bessler", "ninth"); assertThatPartnerIsVisibleForUserWithRole( givenPartner, - "hs_office_person#ErbenBesslerMelBessler:ADMIN"); + "hs_office.person#ErbenBesslerMelBessler:ADMIN"); assertThatPartnerActuallyInDatabase(givenPartner); // when final var result = jpaAttempt.transacted(() -> { context("superuser-alex@hostsharing.net", - "hs_office_person#ErbenBesslerMelBessler:ADMIN"); + "hs_office.person#ErbenBesslerMelBessler:ADMIN"); givenPartner.getDetails().setBirthName("new birthname"); return partnerRepo.save(givenPartner); }); @@ -316,21 +316,21 @@ class HsOfficePartnerRepositoryIntegrationTest extends ContextBasedTestWithClean final var givenPartner = givenSomeTemporaryHostsharingPartner(20037, "Erben Bessler", "ninth"); assertThatPartnerIsVisibleForUserWithRole( givenPartner, - "hs_office_person#ErbenBesslerMelBessler:ADMIN"); + "hs_office.person#ErbenBesslerMelBessler:ADMIN"); assertThatPartnerActuallyInDatabase(givenPartner); // when final var result = jpaAttempt.transacted(() -> { context("superuser-alex@hostsharing.net", - "hs_office_relation#HostsharingeG-with-PARTNER-ErbenBesslerMelBessler:TENANT"); + "hs_office.relation#HostsharingeG-with-PARTNER-ErbenBesslerMelBessler:TENANT"); givenPartner.getDetails().setBirthName("new birthname"); return partnerRepo.save(givenPartner); }); // then result.assertExceptionWithRootCauseMessage(JpaSystemException.class, - "ERROR: [403] insert into hs_office_partner_details ", - " not allowed for current subjects {hs_office_relation#HostsharingeG-with-PARTNER-ErbenBesslerMelBessler:TENANT}"); + "ERROR: [403] insert into hs_office.partner_details ", + " not allowed for current subjects {hs_office.relation#HostsharingeG-with-PARTNER-ErbenBesslerMelBessler:TENANT}"); } private void assertThatPartnerActuallyInDatabase(final HsOfficePartnerEntity saved) { @@ -398,7 +398,7 @@ class HsOfficePartnerRepositoryIntegrationTest extends ContextBasedTestWithClean // then result.assertExceptionWithRootCauseMessage( JpaSystemException.class, - "[403] Subject ", " not allowed to delete hs_office_partner"); + "[403] Subject ", " not allowed to delete hs_office.partner"); assertThat(jpaAttempt.transacted(() -> { context("superuser-alex@hostsharing.net"); return partnerRepo.findByUuid(givenPartner.getUuid()); @@ -435,7 +435,7 @@ class HsOfficePartnerRepositoryIntegrationTest extends ContextBasedTestWithClean final var query = em.createNativeQuery(""" select currentTask, targetTable, targetOp, targetdelta->>'partnernumber' from base.tx_journal_v - where targettable = 'hs_office_partner'; + where targettable = 'hs_office.partner'; """); // when @@ -443,11 +443,11 @@ class HsOfficePartnerRepositoryIntegrationTest extends ContextBasedTestWithClean // then assertThat(customerLogEntries).map(Arrays::toString).contains( - "[creating partner test-data , hs_office_partner, INSERT, 10001]", - "[creating partner test-data , hs_office_partner, INSERT, 10002]", - "[creating partner test-data , hs_office_partner, INSERT, 10003]", - "[creating partner test-data , hs_office_partner, INSERT, 10004]", - "[creating partner test-data , hs_office_partner, INSERT, 10010]"); + "[creating partner test-data , hs_office.partner, INSERT, 10001]", + "[creating partner test-data , hs_office.partner, INSERT, 10002]", + "[creating partner test-data , hs_office.partner, INSERT, 10003]", + "[creating partner test-data , hs_office.partner, INSERT, 10004]", + "[creating partner test-data , hs_office.partner, INSERT, 10010]"); } private HsOfficePartnerEntity givenSomeTemporaryHostsharingPartner( diff --git a/src/test/java/net/hostsharing/hsadminng/hs/office/person/HsOfficePersonRepositoryIntegrationTest.java b/src/test/java/net/hostsharing/hsadminng/hs/office/person/HsOfficePersonRepositoryIntegrationTest.java index 43a9792f..595c732a 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/office/person/HsOfficePersonRepositoryIntegrationTest.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/office/person/HsOfficePersonRepositoryIntegrationTest.java @@ -102,23 +102,23 @@ class HsOfficePersonRepositoryIntegrationTest extends ContextBasedTestWithCleanu assertThat(distinctRoleNamesOf(rawRoleRepo.findAll())).containsExactlyInAnyOrder( Array.from( initialRoleNames, - "hs_office_person#anothernewperson:OWNER", - "hs_office_person#anothernewperson:ADMIN", - "hs_office_person#anothernewperson:REFERRER" + "hs_office.person#anothernewperson:OWNER", + "hs_office.person#anothernewperson:ADMIN", + "hs_office.person#anothernewperson:REFERRER" )); assertThat(distinctGrantDisplaysOf(rawGrantRepo.findAll())).containsExactlyInAnyOrder( Array.fromFormatted( initialGrantNames, - "{ grant perm:hs_office_person#anothernewperson:INSERT>hs_office_relation to role:hs_office_person#anothernewperson:ADMIN by system and assume }", + "{ grant perm:hs_office.person#anothernewperson:INSERT>hs_office.relation to role:hs_office.person#anothernewperson:ADMIN by system and assume }", - "{ grant role:hs_office_person#anothernewperson:OWNER to user:selfregistered-user-drew@hostsharing.org by hs_office_person#anothernewperson:OWNER and assume }", - "{ grant role:hs_office_person#anothernewperson:OWNER to role:rbac.global#global:ADMIN by system and assume }", - "{ grant perm:hs_office_person#anothernewperson:UPDATE to role:hs_office_person#anothernewperson:ADMIN by system and assume }", - "{ grant perm:hs_office_person#anothernewperson:DELETE to role:hs_office_person#anothernewperson:OWNER by system and assume }", - "{ grant role:hs_office_person#anothernewperson:ADMIN to role:hs_office_person#anothernewperson:OWNER by system and assume }", + "{ grant role:hs_office.person#anothernewperson:OWNER to user:selfregistered-user-drew@hostsharing.org by hs_office.person#anothernewperson:OWNER and assume }", + "{ grant role:hs_office.person#anothernewperson:OWNER to role:rbac.global#global:ADMIN by system and assume }", + "{ grant perm:hs_office.person#anothernewperson:UPDATE to role:hs_office.person#anothernewperson:ADMIN by system and assume }", + "{ grant perm:hs_office.person#anothernewperson:DELETE to role:hs_office.person#anothernewperson:OWNER by system and assume }", + "{ grant role:hs_office.person#anothernewperson:ADMIN to role:hs_office.person#anothernewperson:OWNER by system and assume }", - "{ grant perm:hs_office_person#anothernewperson:SELECT to role:hs_office_person#anothernewperson:REFERRER by system and assume }", - "{ grant role:hs_office_person#anothernewperson:REFERRER to role:hs_office_person#anothernewperson:ADMIN by system and assume }" + "{ grant perm:hs_office.person#anothernewperson:SELECT to role:hs_office.person#anothernewperson:REFERRER by system and assume }", + "{ grant role:hs_office.person#anothernewperson:REFERRER to role:hs_office.person#anothernewperson:ADMIN by system and assume }" )); } @@ -262,7 +262,7 @@ class HsOfficePersonRepositoryIntegrationTest extends ContextBasedTestWithCleanu final var query = em.createNativeQuery(""" select currentTask, targetTable, targetOp, targetdelta->>'tradename', targetdelta->>'lastname' from base.tx_journal_v - where targettable = 'hs_office_person'; + where targettable = 'hs_office.person'; """); // when @@ -270,10 +270,10 @@ class HsOfficePersonRepositoryIntegrationTest extends ContextBasedTestWithCleanu // then assertThat(customerLogEntries).map(Arrays::toString).contains( - "[creating person test-data, hs_office_person, INSERT, Hostsharing eG, null]", - "[creating person test-data, hs_office_person, INSERT, First GmbH, null]", - "[creating person test-data, hs_office_person, INSERT, Second e.K., null]", - "[creating person test-data, hs_office_person, INSERT, Third OHG, null]"); + "[creating person test-data, hs_office.person, INSERT, Hostsharing eG, null]", + "[creating person test-data, hs_office.person, INSERT, First GmbH, null]", + "[creating person test-data, hs_office.person, INSERT, Second e.K., null]", + "[creating person test-data, hs_office.person, INSERT, Third OHG, null]"); } private HsOfficePersonEntity givenSomeTemporaryPerson( diff --git a/src/test/java/net/hostsharing/hsadminng/hs/office/relation/HsOfficeRelationRepositoryIntegrationTest.java b/src/test/java/net/hostsharing/hsadminng/hs/office/relation/HsOfficeRelationRepositoryIntegrationTest.java index e285e8c3..aa5d54d8 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/office/relation/HsOfficeRelationRepositoryIntegrationTest.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/office/relation/HsOfficeRelationRepositoryIntegrationTest.java @@ -125,33 +125,33 @@ class HsOfficeRelationRepositoryIntegrationTest extends ContextBasedTestWithClea // then assertThat(distinctRoleNamesOf(rawRoleRepo.findAll())).containsExactlyInAnyOrder(Array.from( initialRoleNames, - "hs_office_relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:OWNER", - "hs_office_relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:ADMIN", - "hs_office_relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:AGENT", - "hs_office_relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:TENANT")); + "hs_office.relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:OWNER", + "hs_office.relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:ADMIN", + "hs_office.relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:AGENT", + "hs_office.relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:TENANT")); assertThat(distinctGrantDisplaysOf(rawGrantRepo.findAll())).containsExactlyInAnyOrder(Array.fromFormatted( initialGrantNames, - "{ grant perm:hs_office_relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:DELETE to role:hs_office_relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:OWNER by system and assume }", - "{ grant role:hs_office_relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:OWNER to role:rbac.global#global:ADMIN by system and assume }", - "{ grant role:hs_office_relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:OWNER to user:superuser-alex@hostsharing.net by hs_office_relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:OWNER and assume }", + "{ grant perm:hs_office.relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:DELETE to role:hs_office.relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:OWNER by system and assume }", + "{ grant role:hs_office.relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:OWNER to role:rbac.global#global:ADMIN by system and assume }", + "{ grant role:hs_office.relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:OWNER to user:superuser-alex@hostsharing.net by hs_office.relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:OWNER and assume }", - "{ grant perm:hs_office_relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:UPDATE to role:hs_office_relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:ADMIN by system and assume }", - "{ grant role:hs_office_relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:ADMIN to role:hs_office_relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:OWNER by system and assume }", - "{ grant role:hs_office_relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:OWNER to role:hs_office_person#BesslerBert:ADMIN by system and assume }", - "{ grant role:hs_office_person#ErbenBesslerMelBessler:OWNER to role:hs_office_relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:ADMIN by system and assume }", + "{ grant perm:hs_office.relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:UPDATE to role:hs_office.relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:ADMIN by system and assume }", + "{ grant role:hs_office.relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:ADMIN to role:hs_office.relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:OWNER by system and assume }", + "{ grant role:hs_office.relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:OWNER to role:hs_office.person#BesslerBert:ADMIN by system and assume }", + "{ grant role:hs_office.person#ErbenBesslerMelBessler:OWNER to role:hs_office.relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:ADMIN by system and assume }", - "{ grant role:hs_office_relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:AGENT to role:hs_office_person#ErbenBesslerMelBessler:ADMIN by system and assume }", - "{ grant role:hs_office_relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:AGENT to role:hs_office_relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:ADMIN by system and assume }", + "{ grant role:hs_office.relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:AGENT to role:hs_office.person#ErbenBesslerMelBessler:ADMIN by system and assume }", + "{ grant role:hs_office.relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:AGENT to role:hs_office.relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:ADMIN by system and assume }", - "{ grant perm:hs_office_relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:SELECT to role:hs_office_relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:TENANT by system and assume }", - "{ grant role:hs_office_relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:TENANT to role:hs_office_relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:AGENT by system and assume }", - "{ grant role:hs_office_person#BesslerBert:REFERRER to role:hs_office_relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:TENANT by system and assume }", - "{ grant role:hs_office_person#ErbenBesslerMelBessler:REFERRER to role:hs_office_relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:TENANT by system and assume }", - "{ grant role:hs_office_contact#fourthcontact:REFERRER to role:hs_office_relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:TENANT by system and assume }", + "{ grant perm:hs_office.relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:SELECT to role:hs_office.relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:TENANT by system and assume }", + "{ grant role:hs_office.relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:TENANT to role:hs_office.relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:AGENT by system and assume }", + "{ grant role:hs_office.person#BesslerBert:REFERRER to role:hs_office.relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:TENANT by system and assume }", + "{ grant role:hs_office.person#ErbenBesslerMelBessler:REFERRER to role:hs_office.relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:TENANT by system and assume }", + "{ grant role:hs_office.contact#fourthcontact:REFERRER to role:hs_office.relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:TENANT by system and assume }", // REPRESENTATIVE holder person -> (represented) anchor person - "{ grant role:hs_office_relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:TENANT to role:hs_office_contact#fourthcontact:ADMIN by system and assume }", + "{ grant role:hs_office.relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerBert:TENANT to role:hs_office.contact#fourthcontact:ADMIN by system and assume }", null) ); } @@ -217,7 +217,7 @@ class HsOfficeRelationRepositoryIntegrationTest extends ContextBasedTestWithClea assertThatRelationActuallyInDatabase(givenRelation); assertThatRelationIsVisibleForUserWithRole( givenRelation, - "hs_office_person#ErbenBesslerMelBessler:ADMIN"); + "hs_office.person#ErbenBesslerMelBessler:ADMIN"); context("superuser-alex@hostsharing.net"); final var givenContact = contactrealRepo.findContactByOptionalCaptionLike("sixth contact").stream().findFirst().orElseThrow(); @@ -236,11 +236,11 @@ class HsOfficeRelationRepositoryIntegrationTest extends ContextBasedTestWithClea "rbac.global#global:ADMIN"); assertThatRelationIsVisibleForUserWithRole( result.returnedValue(), - "hs_office_contact#sixthcontact:ADMIN"); + "hs_office.contact#sixthcontact:ADMIN"); assertThatRelationIsNotVisibleForUserWithRole( result.returnedValue(), - "hs_office_contact#fifthcontact:ADMIN"); + "hs_office.contact#fifthcontact:ADMIN"); relationRbacRepo.deleteByUuid(givenRelation.getUuid()); } @@ -253,19 +253,19 @@ class HsOfficeRelationRepositoryIntegrationTest extends ContextBasedTestWithClea "Anita", "eighth"); assertThatRelationIsVisibleForUserWithRole( givenRelation, - "hs_office_relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerAnita:AGENT"); + "hs_office.relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerAnita:AGENT"); assertThatRelationActuallyInDatabase(givenRelation); // when final var result = jpaAttempt.transacted(() -> { - context("superuser-alex@hostsharing.net", "hs_office_relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerAnita:AGENT"); + context("superuser-alex@hostsharing.net", "hs_office.relation#ErbenBesslerMelBessler-with-REPRESENTATIVE-BesslerAnita:AGENT"); givenRelation.setContact(null); return relationRbacRepo.save(givenRelation); }); // then result.assertExceptionWithRootCauseMessage(JpaSystemException.class, - "[403] Subject ", " is not allowed to update hs_office_relation uuid"); + "[403] Subject ", " is not allowed to update hs_office.relation uuid"); } @Test @@ -276,19 +276,19 @@ class HsOfficeRelationRepositoryIntegrationTest extends ContextBasedTestWithClea "Anita", "ninth"); assertThatRelationIsVisibleForUserWithRole( givenRelation, - "hs_office_contact#ninthcontact:ADMIN"); + "hs_office.contact#ninthcontact:ADMIN"); assertThatRelationActuallyInDatabase(givenRelation); // when final var result = jpaAttempt.transacted(() -> { - context("superuser-alex@hostsharing.net", "hs_office_contact#ninthcontact:ADMIN"); + context("superuser-alex@hostsharing.net", "hs_office.contact#ninthcontact:ADMIN"); givenRelation.setContact(null); // TODO return relationRbacRepo.save(givenRelation); }); // then result.assertExceptionWithRootCauseMessage(JpaSystemException.class, - "[403] Subject ", " is not allowed to update hs_office_relation uuid"); + "[403] Subject ", " is not allowed to update hs_office.relation uuid"); } private void assertThatRelationActuallyInDatabase(final HsOfficeRelation saved) { @@ -360,7 +360,7 @@ class HsOfficeRelationRepositoryIntegrationTest extends ContextBasedTestWithClea // then result.assertExceptionWithRootCauseMessage( JpaSystemException.class, - "[403] Subject ", " not allowed to delete hs_office_relation"); + "[403] Subject ", " not allowed to delete hs_office.relation"); assertThat(jpaAttempt.transacted(() -> { context("superuser-alex@hostsharing.net"); return relationRbacRepo.findByUuid(givenRelation.getUuid()); @@ -396,7 +396,7 @@ class HsOfficeRelationRepositoryIntegrationTest extends ContextBasedTestWithClea final var query = em.createNativeQuery(""" select currentTask, targetTable, targetOp, targetdelta->>'mark' from base.tx_journal_v - where targettable = 'hs_office_relation'; + where targettable = 'hs_office.relation'; """); // when @@ -404,7 +404,7 @@ class HsOfficeRelationRepositoryIntegrationTest extends ContextBasedTestWithClea // then assertThat(customerLogEntries).map(Arrays::toString).contains( - "[creating relation test-data, hs_office_relation, INSERT, members-announce]"); + "[creating relation test-data, hs_office.relation, INSERT, members-announce]"); } private HsOfficeRelationRbacEntity givenSomeTemporaryRelationBessler(final String holderPerson, final String contact) { diff --git a/src/test/java/net/hostsharing/hsadminng/hs/office/sepamandate/HsOfficeSepaMandateRepositoryIntegrationTest.java b/src/test/java/net/hostsharing/hsadminng/hs/office/sepamandate/HsOfficeSepaMandateRepositoryIntegrationTest.java index ff5ea172..8046fc68 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/office/sepamandate/HsOfficeSepaMandateRepositoryIntegrationTest.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/office/sepamandate/HsOfficeSepaMandateRepositoryIntegrationTest.java @@ -95,7 +95,7 @@ class HsOfficeSepaMandateRepositoryIntegrationTest extends ContextBasedTestWithC context("superuser-alex@hostsharing.net"); final var initialRoleNames = distinctRoleNamesOf(rawRoleRepo.findAll()); final var initialGrantNames = distinctGrantDisplaysOf(rawGrantRepo.findAll()).stream() - .map(s -> s.replace("hs_office_", "")) + .map(s -> s.replace("hs_office.", "")) .toList(); // when @@ -117,12 +117,12 @@ class HsOfficeSepaMandateRepositoryIntegrationTest extends ContextBasedTestWithC final var all = rawRoleRepo.findAll(); assertThat(distinctRoleNamesOf(all)).containsExactlyInAnyOrder(Array.from( initialRoleNames, - "hs_office_sepamandate#DE02600501010002034304-[2020-01-01,2023-01-01):ADMIN", - "hs_office_sepamandate#DE02600501010002034304-[2020-01-01,2023-01-01):AGENT", - "hs_office_sepamandate#DE02600501010002034304-[2020-01-01,2023-01-01):OWNER", - "hs_office_sepamandate#DE02600501010002034304-[2020-01-01,2023-01-01):REFERRER")); + "hs_office.sepamandate#DE02600501010002034304-[2020-01-01,2023-01-01):ADMIN", + "hs_office.sepamandate#DE02600501010002034304-[2020-01-01,2023-01-01):AGENT", + "hs_office.sepamandate#DE02600501010002034304-[2020-01-01,2023-01-01):OWNER", + "hs_office.sepamandate#DE02600501010002034304-[2020-01-01,2023-01-01):REFERRER")); assertThat(distinctGrantDisplaysOf(rawGrantRepo.findAll())) - .map(s -> s.replace("hs_office_", "")) + .map(s -> s.replace("hs_office.", "")) .containsExactlyInAnyOrder(fromFormatted( initialGrantNames, @@ -233,7 +233,7 @@ class HsOfficeSepaMandateRepositoryIntegrationTest extends ContextBasedTestWithC final var givenSepaMandate = givenSomeTemporarySepaMandate("DE02600501010002034304"); assertThatSepaMandateIsVisibleForUserWithRole( givenSepaMandate, - "hs_office_bankaccount#DE02600501010002034304:ADMIN"); + "hs_office.bankaccount#DE02600501010002034304:ADMIN"); // when final var result = jpaAttempt.transacted(() -> { @@ -262,13 +262,13 @@ class HsOfficeSepaMandateRepositoryIntegrationTest extends ContextBasedTestWithC final var givenSepaMandate = givenSomeTemporarySepaMandate("DE02300606010002474689"); assertThatSepaMandateIsVisibleForUserWithRole( givenSepaMandate, - "hs_office_bankaccount#DE02300606010002474689:ADMIN"); + "hs_office.bankaccount#DE02300606010002474689:ADMIN"); assertThatSepaMandateActuallyInDatabase(givenSepaMandate); final var newValidityEnd = LocalDate.now(); // when final var result = jpaAttempt.transacted(() -> { - context("superuser-alex@hostsharing.net", "hs_office_bankaccount#DE02300606010002474689:ADMIN"); + context("superuser-alex@hostsharing.net", "hs_office.bankaccount#DE02300606010002474689:ADMIN"); givenSepaMandate.setValidity(Range.closedOpen( givenSepaMandate.getValidity().lower(), newValidityEnd)); @@ -277,7 +277,7 @@ class HsOfficeSepaMandateRepositoryIntegrationTest extends ContextBasedTestWithC // then result.assertExceptionWithRootCauseMessage(JpaSystemException.class, - "[403] Subject ", " is not allowed to update hs_office_sepamandate uuid"); + "[403] Subject ", " is not allowed to update hs_office.sepamandate uuid"); } private void assertThatSepaMandateActuallyInDatabase(final HsOfficeSepaMandateEntity saved) { @@ -346,7 +346,7 @@ class HsOfficeSepaMandateRepositoryIntegrationTest extends ContextBasedTestWithC // then result.assertExceptionWithRootCauseMessage( JpaSystemException.class, - "[403] Subject ", " not allowed to delete hs_office_sepamandate"); + "[403] Subject ", " not allowed to delete hs_office.sepamandate"); assertThat(jpaAttempt.transacted(() -> { context("superuser-alex@hostsharing.net"); return sepaMandateRepo.findByUuid(givenSepaMandate.getUuid()); @@ -381,7 +381,7 @@ class HsOfficeSepaMandateRepositoryIntegrationTest extends ContextBasedTestWithC final var query = em.createNativeQuery(""" select currentTask, targetTable, targetOp, targetdelta->>'reference' from base.tx_journal_v - where targettable = 'hs_office_sepamandate'; + where targettable = 'hs_office.sepamandate'; """); // when @@ -389,9 +389,9 @@ class HsOfficeSepaMandateRepositoryIntegrationTest extends ContextBasedTestWithC // then assertThat(customerLogEntries).map(Arrays::toString).contains( - "[creating SEPA-mandate test-data, hs_office_sepamandate, INSERT, ref-10001-11]", - "[creating SEPA-mandate test-data, hs_office_sepamandate, INSERT, ref-10002-12]", - "[creating SEPA-mandate test-data, hs_office_sepamandate, INSERT, ref-10003-13]"); + "[creating SEPA-mandate test-data, hs_office.sepamandate, INSERT, ref-10001-11]", + "[creating SEPA-mandate test-data, hs_office.sepamandate, INSERT, ref-10002-12]", + "[creating SEPA-mandate test-data, hs_office.sepamandate, INSERT, ref-10003-13]"); } private HsOfficeSepaMandateEntity givenSomeTemporarySepaMandate(final String iban) { diff --git a/src/test/java/net/hostsharing/hsadminng/rbac/grant/RbacGrantsDiagramServiceIntegrationTest.java b/src/test/java/net/hostsharing/hsadminng/rbac/grant/RbacGrantsDiagramServiceIntegrationTest.java index 2f6dc3a9..f3ebb87f 100644 --- a/src/test/java/net/hostsharing/hsadminng/rbac/grant/RbacGrantsDiagramServiceIntegrationTest.java +++ b/src/test/java/net/hostsharing/hsadminng/rbac/grant/RbacGrantsDiagramServiceIntegrationTest.java @@ -90,12 +90,12 @@ class RbacGrantsDiagramServiceIntegrationTest extends ContextBasedTestWithCleanu @Test @Disabled // enable to generate from a real database void print() throws IOException { - //context("superuser-alex@hostsharing.net", "hs_office_person#FirbySusan:ADMIN"); + //context("superuser-alex@hostsharing.net", "hs_office.person#FirbySusan:ADMIN"); context("superuser-alex@hostsharing.net"); //final var graph = grantsMermaidService.allGrantsTocurrentSubject(EnumSet.of(Include.NON_TEST_ENTITIES, Include.PERMISSIONS)); - final var targetObject = (UUID) em.createNativeQuery("SELECT uuid FROM hs_office_coopassetstransaction WHERE reference='ref 1000101-1'").getSingleResult(); + final var targetObject = (UUID) em.createNativeQuery("SELECT uuid FROM hs_office.coopassetstransaction WHERE reference='ref 1000101-1'").getSingleResult(); final var graph = grantsMermaidService.allGrantsFrom(targetObject, "view", EnumSet.of(Include.USERS)); RbacGrantsDiagramService.writeToFile(join(";", context.fetchAssumedRoles()), graph, "doc/all-grants.md");