From 1feda16910e1badf73753b657bdb13a1deb48d53 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 07:30:55 +0400 Subject: [PATCH 001/158] build(pom): add the Quarkus extensions required by the project Each Quarkus capability is an extension: adding one to the pom is enough for its build steps to wire the feature at build time, which is why there is no auto-configuration scanning at startup. Most extensions here (Panache, PostgreSQL JDBC driver, Flyway, Bean Validation, JWT, OpenAPI, health, cache, scheduler) are versioned by the Quarkus platform BOM already imported in dependencyManagement, so none of them carries a version of its own and they cannot drift apart. quarkus-http-problem is the exception: it lives in the Quarkiverse, outside the BOM, so its version is a property referenced via ${...}. Its Maven group is io.quarkiverse.httpproblem (the older resteasy-problem group stops at 3.32) and 3.33.2 is the last release of the 3.33 line, matching the platform. quarkus-flyway-postgresql is needed because recent Flyway versions ship database support as separate modules. On the test side quarkus-junit-mockito lets @InjectMock replace CDI beans in service tests. No Testcontainers dependency is added on purpose: Dev Services already starts PostgreSQL for dev and @QuarkusTest as soon as the JDBC extension is present and no datasource URL is configured. --- pom.xml | 59 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/pom.xml b/pom.xml index 10e13b0..fc2007c 100644 --- a/pom.xml +++ b/pom.xml @@ -11,6 +11,7 @@ 21 UTF-8 UTF-8 + 3.33.2 quarkus-bom io.quarkus.platform 3.33.3.2 @@ -43,6 +44,59 @@ io.quarkus quarkus-arc + + io.quarkus + quarkus-hibernate-orm-panache + + + io.quarkus + quarkus-jdbc-postgresql + + + io.quarkus + quarkus-flyway + + + io.quarkus + quarkus-flyway-postgresql + + + io.quarkus + quarkus-hibernate-validator + + + io.quarkus + quarkus-smallrye-jwt + + + io.quarkus + quarkus-smallrye-jwt-build + + + io.quarkus + quarkus-security + + + io.quarkus + quarkus-smallrye-openapi + + + io.quarkus + quarkus-smallrye-health + + + io.quarkus + quarkus-cache + + + io.quarkus + quarkus-scheduler + + + io.quarkiverse.httpproblem + quarkus-http-problem + ${quarkus-http-problem.version} + io.quarkus quarkus-junit @@ -53,6 +107,11 @@ rest-assured test + + io.quarkus + quarkus-junit-mockito + test + From ae36dd8ea3bda8b3f7ba8b6da7547aabe5d80112 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 07:33:30 +0400 Subject: [PATCH 002/158] feat(dto): add the ApiResponse success envelope Every 2xx response of the API wraps its payload in this generic record, so clients always find the same success, message, data and timestamp fields whatever the endpoint. A Java record fits because the envelope is immutable data with no behaviour: the compiler generates the constructor, accessors, equals and hashCode, and Jackson serialises it out of the box through quarkus-rest-jackson. The type is deliberately success-only and exposes a single success() factory. Errors follow a different contract (RFC 9457 Problem Details, produced by an extension), so there is no error factory here and no ApiResponse of Void used as an error shape. --- .../dto/common/ApiResponse.java | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/dto/common/ApiResponse.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/dto/common/ApiResponse.java b/src/main/java/com/edgareldy/quarkustutorial/dto/common/ApiResponse.java new file mode 100644 index 0000000..4a29996 --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/dto/common/ApiResponse.java @@ -0,0 +1,34 @@ +package com.edgareldy.quarkustutorial.dto.common; + +import java.time.Instant; + +/** + * Generic envelope wrapping the payload of every successful (2xx) response. + * It is success-only: errors are RFC 9457 Problem Details, never this type. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + * + * @param payload type + */ +public record ApiResponse( + boolean success, + String message, + T data, + Instant timestamp +) { + + /** + * Builds a success envelope stamped with the current instant. + * + * @param data the payload + * @param message a human readable message + * @param payload type + * @return the success envelope + */ + public static ApiResponse success(T data, String message) { + return new ApiResponse<>(true, message, data, Instant.now()); + } +} From 9cddd3486e0d9e0190afd1be643d2a1c6ab02649 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 07:33:30 +0400 Subject: [PATCH 003/158] feat(dto): add PageResponse for paginated lists List endpoints never return a bare list: they return an ApiResponse whose data is a PageResponse, so pagination metadata travels with the elements. The record carries the page content, the zero-based page index, the page size, the total element count and the total page count. The of() factory derives totalPages from totalElements and size with an integer ceiling division, which keeps that arithmetic in one place instead of repeating it in every service. A non-positive size yields zero pages rather than a division by zero. --- .../dto/common/PageResponse.java | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/dto/common/PageResponse.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/dto/common/PageResponse.java b/src/main/java/com/edgareldy/quarkustutorial/dto/common/PageResponse.java new file mode 100644 index 0000000..bf929dc --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/dto/common/PageResponse.java @@ -0,0 +1,37 @@ +package com.edgareldy.quarkustutorial.dto.common; + +import java.util.List; + +/** + * Generic page of results, used as the payload of {@code ApiResponse>} for list endpoints. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + * + * @param element type + */ +public record PageResponse( + List content, + int page, + int size, + long totalElements, + int totalPages +) { + + /** + * Builds a page and computes the total number of pages from the total element count. + * + * @param content the elements of this page + * @param page zero-based page index + * @param size requested page size + * @param totalElements total number of elements across all pages + * @param element type + * @return the page + */ + public static PageResponse of(List content, int page, int size, long totalElements) { + int totalPages = size <= 0 ? 0 : (int) ((totalElements + size - 1) / size); + return new PageResponse<>(content, page, size, totalElements, totalPages); + } +} From 381080bccdf1bbec985c912562f74226c366fbcc Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 07:33:30 +0400 Subject: [PATCH 004/158] feat(exception): add ResourceNotFoundException as an HttpProblem Services signal a missing entity by throwing this exception. It extends HttpProblem from the quarkus-http-problem extension, which is itself a RuntimeException that the extension's built-in mapper renders as an RFC 9457 application/problem+json document. Extending it directly means there is no custom ExceptionMapper to write and no DTO to build: the builder sets the type, title, status and detail and the extension does the rest. The problem type is a constant URI so every 404 of this kind is identifiable by clients independently of the human readable detail. The status is 404 and the detail carries the specific message, for example which product id was not found. --- .../exception/ResourceNotFoundException.java | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/exception/ResourceNotFoundException.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/exception/ResourceNotFoundException.java b/src/main/java/com/edgareldy/quarkustutorial/exception/ResourceNotFoundException.java new file mode 100644 index 0000000..80722d5 --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/exception/ResourceNotFoundException.java @@ -0,0 +1,32 @@ +package com.edgareldy.quarkustutorial.exception; + +import io.quarkiverse.httpproblem.HttpProblem; +import java.net.URI; + +/** + * Thrown by services when a requested entity does not exist; rendered as a 404 Problem Details document. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +// HttpProblem (quarkus-http-problem) is a RuntimeException that the extension's built-in mapper turns +// into an RFC 9457 application/problem+json response. Extending it directly means services just throw +// it: no custom ExceptionMapper and no ApiResponse error shape are needed. +public class ResourceNotFoundException extends HttpProblem { + + /** Problem type URI identifying this class of error (constant to keep it simple). */ + public static final URI TYPE = URI.create("https://api.example.com/problems/resource-not-found"); + + /** + * @param detail human readable explanation of what was not found + */ + public ResourceNotFoundException(String detail) { + super(builder() + .withType(TYPE) + .withTitle("Resource Not Found") + .withStatus(404) + .withDetail(detail)); + } +} From 38c0046144a49e7274c0870bd3b18bb9c01ef446 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 07:33:30 +0400 Subject: [PATCH 005/158] feat(exception): add BusinessRuleException as an HttpProblem This is the second business exception, for requests that are well formed but refused by a domain rule, such as deleting a category that still has products. It follows the same mechanism as the not found exception, so nothing new needs wiring. It maps to 422 Unprocessable Content rather than 400: the syntax of the request is valid, it is the state of the domain that forbids the operation. Keeping that distinction lets clients tell a malformed request apart from a rule violation. --- .../exception/BusinessRuleException.java | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/exception/BusinessRuleException.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/exception/BusinessRuleException.java b/src/main/java/com/edgareldy/quarkustutorial/exception/BusinessRuleException.java new file mode 100644 index 0000000..69d67b0 --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/exception/BusinessRuleException.java @@ -0,0 +1,30 @@ +package com.edgareldy.quarkustutorial.exception; + +import io.quarkiverse.httpproblem.HttpProblem; +import java.net.URI; + +/** + * Thrown by services when a business rule is violated; rendered as a 422 Problem Details document. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +// Same HttpProblem mechanism as ResourceNotFoundException; 422 signals a well-formed request refused by a rule. +public class BusinessRuleException extends HttpProblem { + + /** Problem type URI identifying this class of error. */ + public static final URI TYPE = URI.create("https://api.example.com/problems/business-rule-violation"); + + /** + * @param detail human readable explanation of the violated rule + */ + public BusinessRuleException(String detail) { + super(builder() + .withType(TYPE) + .withTitle("Business Rule Violation") + .withStatus(422) + .withDetail(detail)); + } +} From 35b27971baeeeca5aae89e20cf1254c7ee182328 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 07:35:38 +0400 Subject: [PATCH 006/158] feat(health): add a readiness check that opens a real database connection quarkus-smallrye-health already ships a default readiness check, but it only proves that the application is running. This custom @Readiness check goes further by borrowing a connection from the pool and asking the driver whether it is valid, so /q/health/ready turns DOWN when PostgreSQL is unreachable. That is the signal an orchestrator uses to stop routing traffic to an instance without restarting it. The connection is obtained in a try-with-resources block so it always returns to the pool, and the DOWN response carries only a short generic reason: exception messages can reveal hostnames or schema details and this endpoint is usually reachable without authentication. --- .../health/DatabaseHealthCheck.java | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/health/DatabaseHealthCheck.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/health/DatabaseHealthCheck.java b/src/main/java/com/edgareldy/quarkustutorial/health/DatabaseHealthCheck.java new file mode 100644 index 0000000..8d44fce --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/health/DatabaseHealthCheck.java @@ -0,0 +1,52 @@ +package com.edgareldy.quarkustutorial.health; + +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import java.sql.Connection; +import javax.sql.DataSource; +import org.eclipse.microprofile.health.HealthCheck; +import org.eclipse.microprofile.health.HealthCheckResponse; +import org.eclipse.microprofile.health.Readiness; + +/** + * Readiness check verifying that a real database connection can be obtained and is valid. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +// SmallRye Health (MicroProfile Health) exposes checks over HTTP. Readiness ("/q/health/ready") +// answers "can this instance serve traffic right now?": a failing dependency such as the database +// makes it DOWN, so an orchestrator stops routing requests to the pod without restarting it. +// Liveness ("/q/health/live") answers "is the process itself alive?" and is handled elsewhere. +@Readiness +@ApplicationScoped +public class DatabaseHealthCheck implements HealthCheck { + + private static final String CHECK_NAME = "database"; + private static final int VALIDATION_TIMEOUT_SECONDS = 2; + + @Inject + DataSource dataSource; + + @Override + public HealthCheckResponse call() { + // try-with-resources always returns the connection to the pool, even on failure. + try (Connection connection = dataSource.getConnection()) { + if (connection.isValid(VALIDATION_TIMEOUT_SECONDS)) { + return HealthCheckResponse.up(CHECK_NAME); + } + return HealthCheckResponse.named(CHECK_NAME) + .down() + .withData("reason", "Connection is not valid") + .build(); + } catch (Exception e) { + // Deliberately a short message only: exception details could leak host or schema info. + return HealthCheckResponse.named(CHECK_NAME) + .down() + .withData("reason", "Unable to obtain a database connection") + .build(); + } + } +} From 240d8ac5415d4c30a3799aec665e9fb3a5afa916 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 07:35:38 +0400 Subject: [PATCH 007/158] feat(health): add a liveness check that ignores external dependencies Liveness answers a different question from readiness: should this process be restarted? The check therefore inspects only JVM-local state and reports DOWN when threads are deadlocked, a condition that a restart can actually fix. It also exposes uptime and thread count as data, which makes /q/health/live useful when debugging. The database is left out on purpose. If liveness depended on it, a database outage would make the orchestrator restart every healthy instance, turning a dependency failure into a full application outage. Dependencies belong to readiness only. --- .../health/ApplicationLivenessCheck.java | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/health/ApplicationLivenessCheck.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/health/ApplicationLivenessCheck.java b/src/main/java/com/edgareldy/quarkustutorial/health/ApplicationLivenessCheck.java new file mode 100644 index 0000000..b33cee9 --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/health/ApplicationLivenessCheck.java @@ -0,0 +1,38 @@ +package com.edgareldy.quarkustutorial.health; + +import jakarta.enterprise.context.ApplicationScoped; +import java.lang.management.ManagementFactory; +import java.lang.management.ThreadMXBean; +import org.eclipse.microprofile.health.HealthCheck; +import org.eclipse.microprofile.health.HealthCheckResponse; +import org.eclipse.microprofile.health.Liveness; + +/** + * Liveness check reporting DOWN when JVM threads are deadlocked, otherwise UP with uptime data. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +// Liveness ("/q/health/live") tells the orchestrator whether to RESTART the process. It must never +// depend on the database or any other external system: a database outage would then restart every +// healthy pod for no benefit. Only conditions a restart can fix belong here, such as a deadlock. +// (Readiness, which does cover dependencies, is DatabaseHealthCheck.) +@Liveness +@ApplicationScoped +public class ApplicationLivenessCheck implements HealthCheck { + + @Override + public HealthCheckResponse call() { + ThreadMXBean threads = ManagementFactory.getThreadMXBean(); + // Cheap JVM-local check: returns null when no threads are deadlocked. + boolean deadlocked = threads.findDeadlockedThreads() != null; + + return HealthCheckResponse.named("application") + .status(!deadlocked) + .withData("uptimeSeconds", ManagementFactory.getRuntimeMXBean().getUptime() / 1000) + .withData("threadCount", threads.getThreadCount()) + .build(); + } +} From 21c09949dba37b57276c0cb4a687d79af435a3d4 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 07:35:38 +0400 Subject: [PATCH 008/158] feat(flyway): add V1 schema for the identity and e-commerce domains Flyway migrations are the single source of truth for the database schema: Hibernate only maps to it and never generates it. V1 creates every table of both domains in one script, the identity and RBAC tables (users, roles, permissions and their join tables, the three token tables, audit logs) and the e-commerce tables (categories, products, customers, orders). The two domains share one database but no foreign key crosses from one to the other. Rules the database can enforce itself are declared here rather than left to code alone: unique email, role name and permission pair, positive price and quantity, and foreign keys with indexes on every referencing column. Join tables and token tables cascade from their owner, audit logs keep their rows when the acting user is deleted, and e-commerce foreign keys do not cascade so a referenced row cannot be deleted silently. No seed data is inserted here. --- .../db/migration/V1__init_schema.sql | 144 ++++++++++++++++++ 1 file changed, 144 insertions(+) create mode 100644 src/main/resources/db/migration/V1__init_schema.sql diff --git a/src/main/resources/db/migration/V1__init_schema.sql b/src/main/resources/db/migration/V1__init_schema.sql new file mode 100644 index 0000000..a2db24f --- /dev/null +++ b/src/main/resources/db/migration/V1__init_schema.sql @@ -0,0 +1,144 @@ +-- V1: initial schema for both domains (identity/RBAC and e-commerce). +-- The two domains share one database but have no cross-domain foreign key. + +-- --------------------------------------------------------------- +-- Identity / RBAC domain +-- --------------------------------------------------------------- + +CREATE TABLE users ( + id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + first_name VARCHAR(100) NOT NULL, + last_name VARCHAR(100) NOT NULL, + email VARCHAR(255) NOT NULL, + password VARCHAR(255) NOT NULL, + enabled BOOLEAN NOT NULL DEFAULT FALSE, + account_locked BOOLEAN NOT NULL DEFAULT FALSE, + CONSTRAINT uk_users_email UNIQUE (email) +); + +CREATE TABLE roles ( + id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + role_name VARCHAR(100) NOT NULL, + CONSTRAINT uk_roles_role_name UNIQUE (role_name) +); + +CREATE TABLE permissions ( + id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + resource VARCHAR(100) NOT NULL, + action VARCHAR(100) NOT NULL, + CONSTRAINT uk_permissions_resource_action UNIQUE (resource, action) +); + +-- Join tables: cascading from the owning rows is safe (a link is meaningless without either side). +-- Service-level rules (no deleting a role still assigned, etc.) are enforced in code. +CREATE TABLE role_user ( + user_id BIGINT NOT NULL, + role_id BIGINT NOT NULL, + PRIMARY KEY (user_id, role_id), + CONSTRAINT fk_role_user_user FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE, + CONSTRAINT fk_role_user_role FOREIGN KEY (role_id) REFERENCES roles (id) ON DELETE CASCADE +); +CREATE INDEX idx_role_user_role_id ON role_user (role_id); + +CREATE TABLE role_permission ( + role_id BIGINT NOT NULL, + permission_id BIGINT NOT NULL, + PRIMARY KEY (role_id, permission_id), + CONSTRAINT fk_role_permission_role FOREIGN KEY (role_id) REFERENCES roles (id) ON DELETE CASCADE, + CONSTRAINT fk_role_permission_permission FOREIGN KEY (permission_id) REFERENCES permissions (id) ON DELETE CASCADE +); +CREATE INDEX idx_role_permission_permission_id ON role_permission (permission_id); + +CREATE TABLE activation_tokens ( + id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + user_id BIGINT NOT NULL, + token VARCHAR(255) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + expires_at TIMESTAMPTZ NOT NULL, + validated_at TIMESTAMPTZ, + CONSTRAINT uk_activation_tokens_token UNIQUE (token), + CONSTRAINT fk_activation_tokens_user FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE +); +CREATE INDEX idx_activation_tokens_user_id ON activation_tokens (user_id); + +CREATE TABLE blacklisted_tokens ( + id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + user_id BIGINT NOT NULL, + token TEXT NOT NULL, + jti VARCHAR(255) NOT NULL, + blacklisted_at TIMESTAMPTZ NOT NULL DEFAULT now(), + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + expires_at TIMESTAMPTZ NOT NULL, + validated_at TIMESTAMPTZ, + CONSTRAINT uk_blacklisted_tokens_jti UNIQUE (jti), + CONSTRAINT fk_blacklisted_tokens_user FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE +); +CREATE INDEX idx_blacklisted_tokens_user_id ON blacklisted_tokens (user_id); +CREATE INDEX idx_blacklisted_tokens_expires_at ON blacklisted_tokens (expires_at); + +CREATE TABLE password_reset_tokens ( + id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + user_id BIGINT NOT NULL, + token VARCHAR(255) NOT NULL, + type VARCHAR(50) NOT NULL, + expiry_date TIMESTAMPTZ NOT NULL, + CONSTRAINT uk_password_reset_tokens_token UNIQUE (token), + CONSTRAINT fk_password_reset_tokens_user FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE +); +CREATE INDEX idx_password_reset_tokens_user_id ON password_reset_tokens (user_id); + +-- Audit rows must outlive the actor: the FK is nullable and set to NULL when the user is deleted. +CREATE TABLE audit_logs ( + id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + actor_user_id BIGINT, + action VARCHAR(100) NOT NULL, + entity_type VARCHAR(100) NOT NULL, + entity_id BIGINT, + details TEXT, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + CONSTRAINT fk_audit_logs_actor FOREIGN KEY (actor_user_id) REFERENCES users (id) ON DELETE SET NULL +); +CREATE INDEX idx_audit_logs_actor_user_id ON audit_logs (actor_user_id); +CREATE INDEX idx_audit_logs_entity ON audit_logs (entity_type, entity_id); + +-- --------------------------------------------------------------- +-- E-commerce domain +-- --------------------------------------------------------------- + +CREATE TABLE categories ( + id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + category_name VARCHAR(150) NOT NULL +); + +CREATE TABLE products ( + id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + category_id BIGINT NOT NULL, + product_name VARCHAR(150) NOT NULL, + unit_price NUMERIC(12, 2) NOT NULL, + CONSTRAINT ck_products_unit_price CHECK (unit_price > 0), + CONSTRAINT fk_products_category FOREIGN KEY (category_id) REFERENCES categories (id) +); +CREATE INDEX idx_products_category_id ON products (category_id); + +CREATE TABLE customers ( + id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + first_name VARCHAR(100) NOT NULL, + last_name VARCHAR(100) NOT NULL, + telephone VARCHAR(50), + email VARCHAR(255), + address VARCHAR(255) +); + +CREATE TABLE orders ( + id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + customer_id BIGINT NOT NULL, + product_id BIGINT NOT NULL, + quantity INTEGER NOT NULL, + total NUMERIC(14, 2) NOT NULL, + CONSTRAINT ck_orders_quantity CHECK (quantity > 0), + CONSTRAINT ck_orders_total CHECK (total >= 0), + CONSTRAINT fk_orders_customer FOREIGN KEY (customer_id) REFERENCES customers (id), + CONSTRAINT fk_orders_product FOREIGN KEY (product_id) REFERENCES products (id) +); +CREATE INDEX idx_orders_customer_id ON orders (customer_id); +CREATE INDEX idx_orders_product_id ON orders (product_id); From e1305cdf780e49626fe45bd1d840f21eea5df4d7 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 07:38:23 +0400 Subject: [PATCH 009/158] chore(security): add a development-only RSA key pair for JWT signing SmallRye JWT signs tokens with a private key and verifies them with the matching public key, both read from PEM files. Having a pair on the classpath means the application and its tests can issue and validate tokens out of the box, without any setup before the first run. These keys are public by construction since they live in the repository, so they are strictly for development and tests. The production profile deliberately gets no default location: it must be given real keys through the environment, otherwise the application refuses to start rather than silently trusting a key everyone can read. --- src/main/resources/jwt/privateKey.pem | 28 +++++++++++++++++++++++++++ src/main/resources/jwt/publicKey.pem | 9 +++++++++ 2 files changed, 37 insertions(+) create mode 100644 src/main/resources/jwt/privateKey.pem create mode 100644 src/main/resources/jwt/publicKey.pem diff --git a/src/main/resources/jwt/privateKey.pem b/src/main/resources/jwt/privateKey.pem new file mode 100644 index 0000000..be63156 --- /dev/null +++ b/src/main/resources/jwt/privateKey.pem @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCoqv1HT9KAUuN+ +zVSpNuOnjrlXVc+AdVqtJDK5Vs0FeHzg5Qkz7Wx1QKd53XRXYu9KGb6qCjP3LYJ3 +7uMJ/6CnPLuomhqy3ZmnKV/v/dKXrInwt+ibr1ZLatvKCNFNMamjl+AGjZ3n3f5a +ahYLZP/SZOk7ttaAS5fXT+34efZt27afjNErW0sqe8EBpj6YbzvM1TrBb+E/m2nb +Tz6yYu/qnn6vVkYcqPwArEkkz9KHSFFkwUqIzP4FCavzzmwRcN2sUlM0x1w3PPaL +Vqh5XZmgEwYTKJsE6lp8gf76WZNBwLiN2WEopEU3EoXDwt3waSLh1blL0X8lX+Cr +q1k74scZAgMBAAECggEAFsKIDfTn/1fwCd7UQ0c8XhJk0TOrnfZ4B3AghiD/5nKV +S1Wssbyii4nvb4LiHZ6kkpe5wkFBNOQHvH5YVbOQbrDD0+MDokpD3yo2n3BdWAk4 +zepLMaLt3pxrTy50a9m9Pe2TFd9LRQwQNAwnsF7vJGlojZ3FASfyM+Q9xO9UQQuS +URu9DfjAswcfBcMPbfoVKvHO1bs3srwoosl02h5JdY5B0NAuZTfTUfny5VKoCXvz +aYz0xOIcQaN37tZjA9YUHy2Oxw0xkNBS8yeKArmquJyhbIMf9clQJVeIZD8yEMfe +WGVRG+9dXmZIPzbMGhmFnei+0vqTiF50n8Q5SFxnVwKBgQDXrtCD+PuZOdkfuBFU +BchWiEUaSIc+4TgQ4E2fQD4Jma7QNYxIGwAbPYMtn5vdRdBVem0knCKZ/Z6TZxeA +tgYXrsbkgeTzKxLb0XPdKDOlPcWSTBcWo0alOGslC/V0FikZhoZkWo66H7A/6MbL +2Rc85hpEMDHY9xJV9X6XxpreZwKBgQDIMlgbwyW8kfd1y/XT+l8hN8w25CirOmVG +vrSS/wPAjuv3KWL1/aiSqriIfIvKLWTLbX68UCI+wF+3o1P3LQLSsOoi8G2lXC3u +rsF8Js7fM1p+Aav/eFdUyvsczpqXrkO9w3c+mJqUJPS+nH/gGeg7imQdefP1lhh7 +DxP14VK+fwKBgGiLpSkDTDmGj9dPKp8WungvT4eg9mWlV77eauGxiyCuLM1h12Cw +LcoGdApuXmfQSl7UnAjt4dvQ0sfSZdMO6D8cie4DhI3WKCsDCO1/aiFDovv6BAsG +E91MTqtDc7PUdhGYYpZMSvivGYiw9YOj9B6hzsOUtOTdRjcCa114eGMrAoGAUS9h +XbjQx9zl3oZc5Z7mDyGClkwGVhHzWjIiJm52RhNvi6bj89/vCbNj7C2dvtqTwo9f +0twoVwxKhL0eYuGFAI4wFQUtYd603dNOsZtHT2qS6wCgkJRrzf4WwYLjXFmWLRFk +fSUDosot2lK65NV8wRCJMw7uqQw6V0UxEghTNt8CgYEAq8s+cOm58P40P4j56QA2 +8AdOKVdOfVKZx2R6akB8p8co4naQluhh2pjotPoWSR4BhJSvwi99CETz3hW+7HeW +AbW/1Um9b683C85F8YrUSJD+WZ+02q3Sh4mR2V/7T852zKcAGmfCwBAGVRafD9FL +FFLZHW6Udu/Vux4nJow7rO8= +-----END PRIVATE KEY----- diff --git a/src/main/resources/jwt/publicKey.pem b/src/main/resources/jwt/publicKey.pem new file mode 100644 index 0000000..6f4167c --- /dev/null +++ b/src/main/resources/jwt/publicKey.pem @@ -0,0 +1,9 @@ +-----BEGIN PUBLIC KEY----- +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqKr9R0/SgFLjfs1UqTbj +p465V1XPgHVarSQyuVbNBXh84OUJM+1sdUCned10V2LvShm+qgoz9y2Cd+7jCf+g +pzy7qJoast2Zpylf7/3Sl6yJ8Lfom69WS2rbygjRTTGpo5fgBo2d593+WmoWC2T/ +0mTpO7bWgEuX10/t+Hn2bdu2n4zRK1tLKnvBAaY+mG87zNU6wW/hP5tp208+smLv +6p5+r1ZGHKj8AKxJJM/Sh0hRZMFKiMz+BQmr885sEXDdrFJTNMdcNzz2i1aoeV2Z +oBMGEyibBOpafIH++lmTQcC4jdlhKKRFNxKFw8Ld8Gki4dW5S9F/JV/gq6tZO+LH +GQIDAQAB +-----END PUBLIC KEY----- From d1d5bb0e28315ab882076dbcb218bbaa1c190206 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 07:38:23 +0400 Subject: [PATCH 010/158] build(config): configure datasource, Flyway and JWT per profile Configuration keys can be prefixed with %dev, %test or %prod to apply to one profile only, and an unprefixed key is the default for all of them. The datasource url is set only for prod: with the JDBC extension present and no url configured, Dev Services starts a PostgreSQL container for dev and tests by itself, pinned here to version 16 so it matches production. Real connection details come from environment variables and the password has no default. Flyway runs at startup and Hibernate is set to leave the schema alone, so migrations stay the single source of truth; setting it explicitly also prevents Dev Services from switching Hibernate to drop-and-create. The tests use a fixed port because the default test port is frequently taken on a developer machine. JWT settings declare the issuer, the token lifetime and the key locations. The quarkus-http-problem version in use exposes no option for a type URI prefix or for stack traces, so the problem type stays a constant on each exception and stack traces are never included in responses. --- src/main/resources/application.properties | 45 +++++++++++++++++++++-- 1 file changed, 42 insertions(+), 3 deletions(-) diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 1143b56..2f69b5d 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -1,4 +1,43 @@ -# The %test prefix scopes a key to the "test" profile, which @QuarkusTest activates automatically. -# Quarkus's default test port (8081) is often already taken on a developer machine, so tests -# use a dedicated fixed port instead. +# --------------------------------------------------------------------------- +# Profiles: a key prefixed %dev, %test or %prod applies to that profile only, +# an unprefixed key is the default for every profile that does not override it. +# mvn quarkus:dev activates dev, @QuarkusTest activates test, a packaged jar prod. +# --------------------------------------------------------------------------- + +# Quarkus's default test port (8081) is often already taken on a developer machine, +# so tests use a dedicated fixed port instead. %test.quarkus.http.test-port=8085 + +# --- Datasource ------------------------------------------------------------- +# Only the database kind is unprefixed. No JDBC url is configured for dev and test on +# purpose: when the JDBC extension is present and no url is set, Dev Services starts a +# PostgreSQL container by itself and points the application at it. +quarkus.datasource.db-kind=postgresql +# Dev Services would otherwise pick the latest PostgreSQL image, pin the project's version. +quarkus.datasource.devservices.image-name=postgres:16 + +# The packaged application needs a real connection string, supplied by the environment +# (docker-compose.yml provides these variables). +%prod.quarkus.datasource.jdbc.url=${DB_URL:jdbc:postgresql://localhost:5432/quarkus_tutorial} +%prod.quarkus.datasource.username=${DB_USER:quarkus} +%prod.quarkus.datasource.password=${DB_PASSWORD} + +# --- Flyway and Hibernate --------------------------------------------------- +# Flyway migrations are the source of truth for the schema and run when the application starts. +quarkus.flyway.migrate-at-start=true +# Hibernate only maps entities to the existing schema and never creates or drops tables. +# Being explicit also stops Dev Services from switching it to drop-and-create. +quarkus.hibernate-orm.schema-management.strategy=none + +# --- JWT (SmallRye JWT) ----------------------------------------------------- +# The private key signs the tokens the application issues, the public key verifies incoming ones. +# The RSA pair under src/main/resources/jwt is for development and tests ONLY and must never be +# used in production: %prod has no default, so the application refuses to start without real keys. +mp.jwt.verify.publickey.location=jwt/publicKey.pem +smallrye.jwt.sign.key.location=jwt/privateKey.pem +mp.jwt.verify.issuer=https://api.example.com/quarkus-tutorial +smallrye.jwt.new-token.issuer=https://api.example.com/quarkus-tutorial +# Access token lifetime in seconds. +smallrye.jwt.new-token.lifespan=3600 +%prod.mp.jwt.verify.publickey.location=${JWT_PUBLIC_KEY_LOCATION} +%prod.smallrye.jwt.sign.key.location=${JWT_PRIVATE_KEY_LOCATION} From 1869fb6a423a0d7422fa639780b5bbf46aef1262 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 07:50:30 +0400 Subject: [PATCH 011/158] chore(docker): remove the Dockerfiles generated by the project scaffold The scaffold put four Dockerfile variants under src/main/docker, all expecting a jar built beforehand on the host. The project keeps its Dockerfiles at the repository root instead, where docker-compose finds them, and builds inside the image so that no local Java or Maven setup is needed. The native variants come back with the branch that covers native compilation. --- src/main/docker/Dockerfile.jvm | 100 ------------------------ src/main/docker/Dockerfile.legacy-jar | 96 ----------------------- src/main/docker/Dockerfile.native | 29 ------- src/main/docker/Dockerfile.native-micro | 32 -------- 4 files changed, 257 deletions(-) delete mode 100644 src/main/docker/Dockerfile.jvm delete mode 100644 src/main/docker/Dockerfile.legacy-jar delete mode 100644 src/main/docker/Dockerfile.native delete mode 100644 src/main/docker/Dockerfile.native-micro diff --git a/src/main/docker/Dockerfile.jvm b/src/main/docker/Dockerfile.jvm deleted file mode 100644 index f152e88..0000000 --- a/src/main/docker/Dockerfile.jvm +++ /dev/null @@ -1,100 +0,0 @@ -#### -# This Dockerfile is used in order to build a container that runs the Quarkus application in JVM mode -# -# Before building the container image run: -# -# ./mvnw package -# -# Then, build the image with: -# -# docker build -f src/main/docker/Dockerfile.jvm -t quarkus/quarkus-tutorial-jvm . -# -# Then run the container using: -# -# docker run -i --rm -p 8080:8080 quarkus/quarkus-tutorial-jvm -# -# If you want to include the debug port into your docker image -# you will have to expose the debug port (default 5005 being the default) like this : EXPOSE 8080 5005. -# Additionally you will have to set -e JAVA_DEBUG=true and -e JAVA_DEBUG_PORT=*:5005 -# when running the container -# -# Then run the container using : -# -# docker run -i --rm -p 8080:8080 quarkus/quarkus-tutorial-jvm -# -# This image uses the `run-java.sh` script to run the application. -# This scripts computes the command line to execute your Java application, and -# includes memory/GC tuning. -# You can configure the behavior using the following environment properties: -# - JAVA_OPTS: JVM options passed to the `java` command (example: "-verbose:class") - Be aware that this will override -# the default JVM options, use `JAVA_OPTS_APPEND` to append options -# - JAVA_OPTS_APPEND: User specified Java options to be appended to generated options -# in JAVA_OPTS (example: "-Dsome.property=foo") -# - JAVA_MAX_MEM_RATIO: Is used when no `-Xmx` option is given in JAVA_OPTS. This is -# used to calculate a default maximal heap memory based on a containers restriction. -# If used in a container without any memory constraints for the container then this -# option has no effect. If there is a memory constraint then `-Xmx` is set to a ratio -# of the container available memory as set here. The default is `50` which means 50% -# of the available memory is used as an upper boundary. You can skip this mechanism by -# setting this value to `0` in which case no `-Xmx` option is added. -# - JAVA_INITIAL_MEM_RATIO: Is used when no `-Xms` option is given in JAVA_OPTS. This -# is used to calculate a default initial heap memory based on the maximum heap memory. -# If used in a container without any memory constraints for the container then this -# option has no effect. If there is a memory constraint then `-Xms` is set to a ratio -# of the `-Xmx` memory as set here. The default is `25` which means 25% of the `-Xmx` -# is used as the initial heap size. You can skip this mechanism by setting this value -# to `0` in which case no `-Xms` option is added (example: "25") -# - JAVA_MAX_INITIAL_MEM: Is used when no `-Xms` option is given in JAVA_OPTS. -# This is used to calculate the maximum value of the initial heap memory. If used in -# a container without any memory constraints for the container then this option has -# no effect. If there is a memory constraint then `-Xms` is limited to the value set -# here. The default is 4096MB which means the calculated value of `-Xms` never will -# be greater than 4096MB. The value of this variable is expressed in MB (example: "4096") -# - JAVA_DIAGNOSTICS: Set this to get some diagnostics information to standard output -# when things are happening. This option, if set to true, will set -# `-XX:+UnlockDiagnosticVMOptions`. Disabled by default (example: "true"). -# - JAVA_DEBUG: If set remote debugging will be switched on. Disabled by default (example: -# true"). -# - JAVA_DEBUG_PORT: Port used for remote debugging. Defaults to 5005 (example: "8787"). -# - CONTAINER_CORE_LIMIT: A calculated core limit as described in -# https://www.kernel.org/doc/Documentation/scheduler/sched-bwc.txt. (example: "2") -# - CONTAINER_MAX_MEMORY: Memory limit given to the container (example: "1024"). -# - GC_MIN_HEAP_FREE_RATIO: Minimum percentage of heap free after GC to avoid expansion. -# (example: "20") -# - GC_MAX_HEAP_FREE_RATIO: Maximum percentage of heap free after GC to avoid shrinking. -# (example: "40") -# - GC_TIME_RATIO: Specifies the ratio of the time spent outside the garbage collection. -# (example: "4") -# - GC_ADAPTIVE_SIZE_POLICY_WEIGHT: The weighting given to the current GC time versus -# previous GC times. (example: "90") -# - GC_METASPACE_SIZE: The initial metaspace size. (example: "20") -# - GC_MAX_METASPACE_SIZE: The maximum metaspace size. (example: "100") -# - GC_CONTAINER_OPTIONS: Specify Java GC to use. The value of this variable should -# contain the necessary JRE command-line options to specify the required GC, which -# will override the default of `-XX:+UseParallelGC` (example: -XX:+UseG1GC). -# - HTTPS_PROXY: The location of the https proxy. (example: "myuser@127.0.0.1:8080") -# - HTTP_PROXY: The location of the http proxy. (example: "myuser@127.0.0.1:8080") -# - NO_PROXY: A comma separated lists of hosts, IP addresses or domains that can be -# accessed directly. (example: "foo.example.com,bar.example.com") -# -# You can find more information about the UBI base runtime images and their configuration here: -# https://rh-openjdk.github.io/redhat-openjdk-containers/ -### -FROM registry.access.redhat.com/ubi9/openjdk-21-runtime:1.24 - -ENV LANGUAGE='en_US:en' - - -# We make four distinct layers so if there are application changes the library layers can be re-used -COPY --chown=185 target/quarkus-app/lib/ /deployments/lib/ -COPY --chown=185 target/quarkus-app/*.jar /deployments/ -COPY --chown=185 target/quarkus-app/app/ /deployments/app/ -COPY --chown=185 target/quarkus-app/quarkus/ /deployments/quarkus/ - -EXPOSE 8080 -USER 185 -ENV JAVA_OPTS_APPEND="-Dquarkus.http.host=0.0.0.0 -Djava.util.logging.manager=org.jboss.logmanager.LogManager" -ENV JAVA_APP_JAR="/deployments/quarkus-run.jar" - -ENTRYPOINT [ "/opt/jboss/container/java/run/run-java.sh" ] - diff --git a/src/main/docker/Dockerfile.legacy-jar b/src/main/docker/Dockerfile.legacy-jar deleted file mode 100644 index f064c79..0000000 --- a/src/main/docker/Dockerfile.legacy-jar +++ /dev/null @@ -1,96 +0,0 @@ -#### -# This Dockerfile is used in order to build a container that runs the Quarkus application in JVM mode -# -# Before building the container image run: -# -# ./mvnw package -Dquarkus.package.jar.type=legacy-jar -# -# Then, build the image with: -# -# docker build -f src/main/docker/Dockerfile.legacy-jar -t quarkus/quarkus-tutorial-legacy-jar . -# -# Then run the container using: -# -# docker run -i --rm -p 8080:8080 quarkus/quarkus-tutorial-legacy-jar -# -# If you want to include the debug port into your docker image -# you will have to expose the debug port (default 5005 being the default) like this : EXPOSE 8080 5005. -# Additionally you will have to set -e JAVA_DEBUG=true and -e JAVA_DEBUG_PORT=*:5005 -# when running the container -# -# Then run the container using : -# -# docker run -i --rm -p 8080:8080 quarkus/quarkus-tutorial-legacy-jar -# -# This image uses the `run-java.sh` script to run the application. -# This scripts computes the command line to execute your Java application, and -# includes memory/GC tuning. -# You can configure the behavior using the following environment properties: -# - JAVA_OPTS: JVM options passed to the `java` command (example: "-verbose:class") - Be aware that this will override -# the default JVM options, use `JAVA_OPTS_APPEND` to append options -# - JAVA_OPTS_APPEND: User specified Java options to be appended to generated options -# in JAVA_OPTS (example: "-Dsome.property=foo") -# - JAVA_MAX_MEM_RATIO: Is used when no `-Xmx` option is given in JAVA_OPTS. This is -# used to calculate a default maximal heap memory based on a containers restriction. -# If used in a container without any memory constraints for the container then this -# option has no effect. If there is a memory constraint then `-Xmx` is set to a ratio -# of the container available memory as set here. The default is `50` which means 50% -# of the available memory is used as an upper boundary. You can skip this mechanism by -# setting this value to `0` in which case no `-Xmx` option is added. -# - JAVA_INITIAL_MEM_RATIO: Is used when no `-Xms` option is given in JAVA_OPTS. This -# is used to calculate a default initial heap memory based on the maximum heap memory. -# If used in a container without any memory constraints for the container then this -# option has no effect. If there is a memory constraint then `-Xms` is set to a ratio -# of the `-Xmx` memory as set here. The default is `25` which means 25% of the `-Xmx` -# is used as the initial heap size. You can skip this mechanism by setting this value -# to `0` in which case no `-Xms` option is added (example: "25") -# - JAVA_MAX_INITIAL_MEM: Is used when no `-Xms` option is given in JAVA_OPTS. -# This is used to calculate the maximum value of the initial heap memory. If used in -# a container without any memory constraints for the container then this option has -# no effect. If there is a memory constraint then `-Xms` is limited to the value set -# here. The default is 4096MB which means the calculated value of `-Xms` never will -# be greater than 4096MB. The value of this variable is expressed in MB (example: "4096") -# - JAVA_DIAGNOSTICS: Set this to get some diagnostics information to standard output -# when things are happening. This option, if set to true, will set -# `-XX:+UnlockDiagnosticVMOptions`. Disabled by default (example: "true"). -# - JAVA_DEBUG: If set remote debugging will be switched on. Disabled by default (example: -# true"). -# - JAVA_DEBUG_PORT: Port used for remote debugging. Defaults to 5005 (example: "8787"). -# - CONTAINER_CORE_LIMIT: A calculated core limit as described in -# https://www.kernel.org/doc/Documentation/scheduler/sched-bwc.txt. (example: "2") -# - CONTAINER_MAX_MEMORY: Memory limit given to the container (example: "1024"). -# - GC_MIN_HEAP_FREE_RATIO: Minimum percentage of heap free after GC to avoid expansion. -# (example: "20") -# - GC_MAX_HEAP_FREE_RATIO: Maximum percentage of heap free after GC to avoid shrinking. -# (example: "40") -# - GC_TIME_RATIO: Specifies the ratio of the time spent outside the garbage collection. -# (example: "4") -# - GC_ADAPTIVE_SIZE_POLICY_WEIGHT: The weighting given to the current GC time versus -# previous GC times. (example: "90") -# - GC_METASPACE_SIZE: The initial metaspace size. (example: "20") -# - GC_MAX_METASPACE_SIZE: The maximum metaspace size. (example: "100") -# - GC_CONTAINER_OPTIONS: Specify Java GC to use. The value of this variable should -# contain the necessary JRE command-line options to specify the required GC, which -# will override the default of `-XX:+UseParallelGC` (example: -XX:+UseG1GC). -# - HTTPS_PROXY: The location of the https proxy. (example: "myuser@127.0.0.1:8080") -# - HTTP_PROXY: The location of the http proxy. (example: "myuser@127.0.0.1:8080") -# - NO_PROXY: A comma separated lists of hosts, IP addresses or domains that can be -# accessed directly. (example: "foo.example.com,bar.example.com") -# -# You can find more information about the UBI base runtime images and their configuration here: -# https://rh-openjdk.github.io/redhat-openjdk-containers/ -### -FROM registry.access.redhat.com/ubi9/openjdk-21-runtime:1.24 - -ENV LANGUAGE='en_US:en' - - -COPY target/lib/* /deployments/lib/ -COPY target/*-runner.jar /deployments/quarkus-run.jar - -EXPOSE 8080 -USER 185 -ENV JAVA_OPTS_APPEND="-Dquarkus.http.host=0.0.0.0 -Djava.util.logging.manager=org.jboss.logmanager.LogManager" -ENV JAVA_APP_JAR="/deployments/quarkus-run.jar" - -ENTRYPOINT [ "/opt/jboss/container/java/run/run-java.sh" ] diff --git a/src/main/docker/Dockerfile.native b/src/main/docker/Dockerfile.native deleted file mode 100644 index e464dc8..0000000 --- a/src/main/docker/Dockerfile.native +++ /dev/null @@ -1,29 +0,0 @@ -#### -# This Dockerfile is used in order to build a container that runs the Quarkus application in native (no JVM) mode. -# -# Before building the container image run: -# -# ./mvnw package -Dnative -# -# Then, build the image with: -# -# docker build -f src/main/docker/Dockerfile.native -t quarkus/quarkus-tutorial . -# -# Then run the container using: -# -# docker run -i --rm -p 8080:8080 quarkus/quarkus-tutorial -# -# The ` registry.access.redhat.com/ubi9/ubi-minimal:9.7` base image is based on UBI 9. -# To use UBI 8, switch to `quay.io/ubi8/ubi-minimal:8.10`. -### -FROM registry.access.redhat.com/ubi9/ubi-minimal:9.7 -WORKDIR /work/ -RUN chown 1001 /work \ - && chmod "g+rwX" /work \ - && chown 1001:root /work -COPY --chown=1001:root --chmod=0755 target/*-runner /work/application - -EXPOSE 8080 -USER 1001 - -ENTRYPOINT ["./application", "-Dquarkus.http.host=0.0.0.0"] diff --git a/src/main/docker/Dockerfile.native-micro b/src/main/docker/Dockerfile.native-micro deleted file mode 100644 index e05468f..0000000 --- a/src/main/docker/Dockerfile.native-micro +++ /dev/null @@ -1,32 +0,0 @@ -#### -# This Dockerfile is used in order to build a container that runs the Quarkus application in native (no JVM) mode. -# It uses a micro base image, tuned for Quarkus native executables. -# It reduces the size of the resulting container image. -# Check https://quarkus.io/guides/quarkus-runtime-base-image for further information about this image. -# -# Before building the container image run: -# -# ./mvnw package -Dnative -# -# Then, build the image with: -# -# docker build -f src/main/docker/Dockerfile.native-micro -t quarkus/quarkus-tutorial . -# -# Then run the container using: -# -# docker run -i --rm -p 8080:8080 quarkus/quarkus-tutorial -# -# The `quay.io/quarkus/ubi9-quarkus-micro-image:2.0` base image is based on UBI 9. -# To use UBI 8, switch to `quay.io/quarkus/quarkus-micro-image:2.0`. -### -FROM quay.io/quarkus/ubi9-quarkus-micro-image:2.0 -WORKDIR /work/ -RUN chown 1001 /work \ - && chmod "g+rwX" /work \ - && chown 1001:root /work -COPY --chown=1001:root --chmod=0755 target/*-runner /work/application - -EXPOSE 8080 -USER 1001 - -ENTRYPOINT ["./application", "-Dquarkus.http.host=0.0.0.0"] From ca9132da3c70e3e04b023150c52657cfc52bcaff Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 07:50:30 +0400 Subject: [PATCH 012/158] build(docker): let the build context contain the sources The generated .dockerignore excluded everything except the target directory, which only works when the jar is built on the host before the image. A multi-stage build compiles inside the image, so the context must now include pom.xml and src. Everything else stays excluded to keep the context small and to make sure local files such as keys, environment files or build output never end up in an image layer. --- .dockerignore | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/.dockerignore b/.dockerignore index 94810d0..f685a3c 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,5 +1,4 @@ +# Keep the build context small and free of local files * -!target/*-runner -!target/*-runner.jar -!target/lib/* -!target/quarkus-app/* \ No newline at end of file +!pom.xml +!src/ From b157badf468364b08d1cf191b474d0b2ecae4526 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 07:50:30 +0400 Subject: [PATCH 013/158] build(docker): add a multi-stage Dockerfile for the JVM application The first stage compiles and packages with Maven, the second keeps only a JRE and the Quarkus output, so the final image carries no build tools. The pom is copied before the sources so Docker caches the dependency download until the pom changes, which makes rebuilds after a code change much faster. The application runs from the fast-jar layout Quarkus produces, whose dependencies live in separate directories that rarely change, and as a non-root user. Tests are skipped inside the build because they depend on Dev Services, which needs a Docker daemon that a build stage does not have; they run in CI instead. --- Dockerfile.jvm | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Dockerfile.jvm diff --git a/Dockerfile.jvm b/Dockerfile.jvm new file mode 100644 index 0000000..6fa0f73 --- /dev/null +++ b/Dockerfile.jvm @@ -0,0 +1,28 @@ +# Multi-stage image for the packaged JVM application. +# Stage 1 compiles and packages with Maven, stage 2 keeps only a JRE and the Quarkus runnable output. + +FROM maven:3.9-eclipse-temurin-21 AS build +WORKDIR /build + +# Copying the pom alone first lets Docker cache the dependency download until the pom changes. +COPY pom.xml . +RUN mvn -B -q dependency:go-offline + +COPY src ./src +# Tests are skipped here: they rely on Dev Services, which needs a Docker daemon a build stage +# does not have. They run in CI with mvn verify instead. +RUN mvn -B -q package -DskipTests + +FROM eclipse-temurin:21-jre +WORKDIR /app + +# Run as a non-root user so a compromised process has no rights on the container. +RUN useradd --system --no-create-home quarkus +USER quarkus + +# quarkus-app is the fast-jar layout: dependencies sit in separate directories that rarely change, +# so rebuilding after a code change only replaces a small layer. +COPY --from=build --chown=quarkus /build/target/quarkus-app/ ./ + +EXPOSE 8080 +ENTRYPOINT ["java", "-jar", "quarkus-run.jar"] From 254ece727c6185cb07995057c96bf23ee56802b7 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 07:50:30 +0400 Subject: [PATCH 014/158] build(docker): add docker-compose for the packaged application Compose runs the packaged application next to a real PostgreSQL 16. It is only for that use: in dev and tests Dev Services provisions the database by itself, so nothing here is needed to work on the code. The app waits for the database healthcheck before starting, and Flyway then creates the schema on first launch. All settings come from the environment, and the database password is required rather than defaulted so a forgotten .env fails loudly instead of running with a well-known password. The production JWT key pair is mounted read-only from a keys directory that git ignores, and the published port is configurable because 8080 is often already taken on a developer machine. --- .env.example | 5 +++++ .gitignore | 3 +++ docker-compose.yml | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 54 insertions(+) create mode 100644 .env.example create mode 100644 docker-compose.yml diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..b93c301 --- /dev/null +++ b/.env.example @@ -0,0 +1,5 @@ +# Copy to .env (ignored by git) and adjust. Read by docker-compose.yml only. +DB_NAME=quarkus_tutorial +DB_USER=quarkus +DB_PASSWORD=change-me +APP_PORT=8080 diff --git a/.gitignore b/.gitignore index 7349837..784e66e 100644 --- a/.gitignore +++ b/.gitignore @@ -56,3 +56,6 @@ logs/ # JVM crash logs hs_err_pid* replay_pid* + +# Production JWT keys used with docker-compose +keys/ diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..41e0f3e --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,46 @@ +# Runs the PACKAGED application with a real PostgreSQL. It is not used in dev or test: +# there, Dev Services starts the database by itself. +# +# Before the first "docker compose up --build": +# 1. cp .env.example .env and set the passwords +# 2. create a production RSA key pair in ./keys (the keys under src/main/resources/jwt are +# for development only): +# mkdir -p keys +# openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -out keys/privateKey.pem +# openssl pkey -in keys/privateKey.pem -pubout -out keys/publicKey.pem + +services: + db: + image: postgres:16 + environment: + POSTGRES_DB: ${DB_NAME:-quarkus_tutorial} + POSTGRES_USER: ${DB_USER:-quarkus} + POSTGRES_PASSWORD: ${DB_PASSWORD:?Set DB_PASSWORD in .env} + volumes: + - db-data:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U ${DB_USER:-quarkus} -d ${DB_NAME:-quarkus_tutorial}"] + interval: 5s + timeout: 3s + retries: 10 + + app: + build: + context: . + dockerfile: Dockerfile.jvm + depends_on: + db: + condition: service_healthy + environment: + DB_URL: jdbc:postgresql://db:5432/${DB_NAME:-quarkus_tutorial} + DB_USER: ${DB_USER:-quarkus} + DB_PASSWORD: ${DB_PASSWORD:?Set DB_PASSWORD in .env} + JWT_PUBLIC_KEY_LOCATION: /keys/publicKey.pem + JWT_PRIVATE_KEY_LOCATION: /keys/privateKey.pem + volumes: + - ./keys:/keys:ro + ports: + - "${APP_PORT:-8080}:8080" + +volumes: + db-data: From e302a2cc94188e1854af6466a4a26c2d7dbeab68 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 07:50:45 +0400 Subject: [PATCH 015/158] ci(workflow): run mvn verify on every push and pull request The workflow checks out the code, installs Java 21 with the Maven cache enabled and runs the whole build through the Maven wrapper, so the CI uses exactly the Maven version the project pins. It triggers on pushes and pull requests targeting master or develop. There is deliberately no services block for PostgreSQL. Dev Services starts its own database container through the Docker daemon that ubuntu-latest runners already provide, the same way it does on a developer machine, so the test setup is identical locally and in CI and nothing has to be kept in sync by hand. --- .github/workflows/ci.yml | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 .github/workflows/ci.yml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..f9035fa --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,28 @@ +name: CI + +on: + push: + branches: [master, develop] + pull_request: + branches: [master, develop] + +jobs: + build-and-test: + runs-on: ubuntu-latest + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Set up Java 21 + uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: "21" + cache: maven + + # No "services: postgres" block on purpose. Quarkus Dev Services starts its own PostgreSQL + # container through the Docker daemon already available on ubuntu-latest, exactly as it does + # locally, so the tests need nothing provisioned by the workflow. + - name: Build and test + run: ./mvnw -B verify From d29b5f1c24909fc1fad84025c32033292593b8f0 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 07:50:58 +0400 Subject: [PATCH 016/158] chore(scaffold): remove the sample GreetingResource generated by the scaffold The hello endpoint and its two tests only existed to prove that the freshly generated project worked. The real endpoints arrive with the feature branches and the health checks now give a genuine way to see the application running, so keeping the sample would leave dead code and a public route that belongs to nothing in the specification. --- .../quarkustutorial/GreetingResource.java | 16 --------------- .../quarkustutorial/GreetingResourceIT.java | 8 -------- .../quarkustutorial/GreetingResourceTest.java | 20 ------------------- 3 files changed, 44 deletions(-) delete mode 100644 src/main/java/com/edgareldy/quarkustutorial/GreetingResource.java delete mode 100644 src/test/java/com/edgareldy/quarkustutorial/GreetingResourceIT.java delete mode 100644 src/test/java/com/edgareldy/quarkustutorial/GreetingResourceTest.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/GreetingResource.java b/src/main/java/com/edgareldy/quarkustutorial/GreetingResource.java deleted file mode 100644 index 257e8d4..0000000 --- a/src/main/java/com/edgareldy/quarkustutorial/GreetingResource.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.edgareldy.quarkustutorial; - -import jakarta.ws.rs.GET; -import jakarta.ws.rs.Path; -import jakarta.ws.rs.Produces; -import jakarta.ws.rs.core.MediaType; - -@Path("/hello") -public class GreetingResource { - - @GET - @Produces(MediaType.TEXT_PLAIN) - public String hello() { - return "Hello from Quarkus REST"; - } -} diff --git a/src/test/java/com/edgareldy/quarkustutorial/GreetingResourceIT.java b/src/test/java/com/edgareldy/quarkustutorial/GreetingResourceIT.java deleted file mode 100644 index a3fa1a9..0000000 --- a/src/test/java/com/edgareldy/quarkustutorial/GreetingResourceIT.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.edgareldy.quarkustutorial; - -import io.quarkus.test.junit.QuarkusIntegrationTest; - -@QuarkusIntegrationTest -class GreetingResourceIT extends GreetingResourceTest { - // Execute the same tests but in packaged mode. -} diff --git a/src/test/java/com/edgareldy/quarkustutorial/GreetingResourceTest.java b/src/test/java/com/edgareldy/quarkustutorial/GreetingResourceTest.java deleted file mode 100644 index e558a08..0000000 --- a/src/test/java/com/edgareldy/quarkustutorial/GreetingResourceTest.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.edgareldy.quarkustutorial; - -import io.quarkus.test.junit.QuarkusTest; -import org.junit.jupiter.api.Test; - -import static io.restassured.RestAssured.given; -import static org.hamcrest.CoreMatchers.is; - -@QuarkusTest -class GreetingResourceTest { - @Test - void testHelloEndpoint() { - given() - .when().get("/hello") - .then() - .statusCode(200) - .body(is("Hello from Quarkus REST")); - } - -} \ No newline at end of file From 7c4d7b2922baaea816c90a5fa708943f85ed756a Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 07:56:20 +0400 Subject: [PATCH 017/158] test(dto): cover the ApiResponse success factory A plain JUnit test is enough here because the record has no dependency: it checks that success() marks the envelope as successful and carries the message, the payload and a timestamp. Nothing needs the Quarkus container, so the test runs in milliseconds. --- .../dto/common/ApiResponseTest.java | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 src/test/java/com/edgareldy/quarkustutorial/dto/common/ApiResponseTest.java diff --git a/src/test/java/com/edgareldy/quarkustutorial/dto/common/ApiResponseTest.java b/src/test/java/com/edgareldy/quarkustutorial/dto/common/ApiResponseTest.java new file mode 100644 index 0000000..5ddb7d2 --- /dev/null +++ b/src/test/java/com/edgareldy/quarkustutorial/dto/common/ApiResponseTest.java @@ -0,0 +1,37 @@ +package com.edgareldy.quarkustutorial.dto.common; + +import static org.junit.jupiter.api.Assertions.*; +import java.time.Instant; +import org.junit.jupiter.api.Test; + +/** + * Unit tests for the success-only ApiResponse envelope. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +class ApiResponseTest { + + @Test + void successBuildsEnvelopeWithFlagMessageDataAndTimestamp() { + Instant before = Instant.now(); + ApiResponse response = ApiResponse.success("payload", "done"); + Instant after = Instant.now(); + + assertTrue(response.success()); + assertEquals("done", response.message()); + assertEquals("payload", response.data()); + assertNotNull(response.timestamp()); + assertFalse(response.timestamp().isBefore(before)); + assertFalse(response.timestamp().isAfter(after)); + } + + @Test + void successAcceptsNullData() { + ApiResponse response = ApiResponse.success(null, "empty"); + assertTrue(response.success()); + assertNull(response.data()); + } +} From d6c422337003c2cf9aae9abfac591fd06914da21 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 07:56:20 +0400 Subject: [PATCH 018/158] test(dto): cover the PageResponse page count arithmetic The total number of pages is derived with an integer ceiling division, which is exactly the kind of small computation that breaks on boundaries. The tests cover an exact multiple, a remainder, an empty result and a size of zero, so a future change to the formula cannot silently produce a wrong count or a division by zero. --- .../dto/common/PageResponseTest.java | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 src/test/java/com/edgareldy/quarkustutorial/dto/common/PageResponseTest.java diff --git a/src/test/java/com/edgareldy/quarkustutorial/dto/common/PageResponseTest.java b/src/test/java/com/edgareldy/quarkustutorial/dto/common/PageResponseTest.java new file mode 100644 index 0000000..62ec98c --- /dev/null +++ b/src/test/java/com/edgareldy/quarkustutorial/dto/common/PageResponseTest.java @@ -0,0 +1,45 @@ +package com.edgareldy.quarkustutorial.dto.common; + +import static org.junit.jupiter.api.Assertions.*; +import java.util.List; +import org.junit.jupiter.api.Test; + +/** + * Unit tests for PageResponse page count computation. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +class PageResponseTest { + + @Test + void totalPagesUsesCeilingDivision() { + assertEquals(3, PageResponse.of(List.of(1, 2, 3), 0, 3, 7).totalPages()); + assertEquals(2, PageResponse.of(List.of(1, 2, 3), 0, 3, 6).totalPages()); + assertEquals(1, PageResponse.of(List.of(1), 0, 10, 1).totalPages()); + } + + @Test + void sizeZeroYieldsZeroPagesWithoutDividingByZero() { + assertEquals(0, PageResponse.of(List.of(), 0, 0, 5).totalPages()); + } + + @Test + void emptyContentYieldsZeroPages() { + PageResponse page = PageResponse.of(List.of(), 0, 10, 0); + assertEquals(0, page.totalPages()); + assertTrue(page.content().isEmpty()); + assertEquals(0, page.totalElements()); + } + + @Test + void keepsPassedValues() { + PageResponse page = PageResponse.of(List.of(4, 5), 2, 2, 6); + assertEquals(2, page.page()); + assertEquals(2, page.size()); + assertEquals(6, page.totalElements()); + assertEquals(List.of(4, 5), page.content()); + } +} From eac64c6ae9aa601baacd8e6c0708bada41e1a540 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 07:56:20 +0400 Subject: [PATCH 019/158] test(health): check readiness and liveness over HTTP @QuarkusTest boots the whole application once and RestAssured calls it on the configured test port, so these tests exercise the real endpoints instead of the check classes in isolation. Readiness must report the database check UP, which also proves that Dev Services started PostgreSQL and that the datasource is wired, and liveness must report the application check. No container is declared in the test: Dev Services provisions the database as soon as the test profile starts, so the same test runs unchanged on a laptop and on a CI runner. --- .../health/HealthEndpointsTest.java | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 src/test/java/com/edgareldy/quarkustutorial/health/HealthEndpointsTest.java diff --git a/src/test/java/com/edgareldy/quarkustutorial/health/HealthEndpointsTest.java b/src/test/java/com/edgareldy/quarkustutorial/health/HealthEndpointsTest.java new file mode 100644 index 0000000..5ac686e --- /dev/null +++ b/src/test/java/com/edgareldy/quarkustutorial/health/HealthEndpointsTest.java @@ -0,0 +1,36 @@ +package com.edgareldy.quarkustutorial.health; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.*; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; + +/** + * End-to-end tests of the readiness and liveness endpoints. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +// @QuarkusTest boots the whole application (with a Dev Services PostgreSQL) once and lets RestAssured +// call the real HTTP endpoints on the fixed test port, so the health checks run against a live database. +@QuarkusTest +class HealthEndpointsTest { + + @Test + void readinessIsUpAndReportsDatabaseCheck() { + given().when().get("/q/health/ready") + .then().statusCode(200) + .body("status", is("UP")) + .body("checks.find { it.name == 'database' }.status", is("UP")); + } + + @Test + void livenessIsUpAndReportsApplicationCheck() { + given().when().get("/q/health/live") + .then().statusCode(200) + .body("status", is("UP")) + .body("checks.find { it.name == 'application' }.status", is("UP")); + } +} From f4ad0a1e4d3e05cfcb98af290e71316be9cd2c5b Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 07:56:20 +0400 Subject: [PATCH 020/158] test(flyway): verify the V1 migration and its constraints The application migrates at startup, so the injected DataSource already points at a migrated schema. The tests assert that the thirteen expected tables exist, that the schema history records version 1 as successful, and that inserting two users with the same email is rejected by the database itself with a unique violation. The last check matters because a constraint declared in SQL protects the data even when application code forgets a validation. The test cleans up the row it inserts so it leaves the shared test database as it found it. --- .../flyway/FlywaySchemaTest.java | 87 +++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 src/test/java/com/edgareldy/quarkustutorial/flyway/FlywaySchemaTest.java diff --git a/src/test/java/com/edgareldy/quarkustutorial/flyway/FlywaySchemaTest.java b/src/test/java/com/edgareldy/quarkustutorial/flyway/FlywaySchemaTest.java new file mode 100644 index 0000000..d86cf66 --- /dev/null +++ b/src/test/java/com/edgareldy/quarkustutorial/flyway/FlywaySchemaTest.java @@ -0,0 +1,87 @@ +package com.edgareldy.quarkustutorial.flyway; + +import static org.junit.jupiter.api.Assertions.*; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.HashSet; +import java.util.Set; +import javax.sql.DataSource; +import org.junit.jupiter.api.Test; + +/** + * Verifies the Flyway V1 migration was applied to the Dev Services PostgreSQL and its constraints hold. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +// The application migrates at start against the Dev Services PostgreSQL, so the injected DataSource +// already points at a fully migrated schema and no manual container or migration call is needed. +@QuarkusTest +class FlywaySchemaTest { + + private static final Set EXPECTED_TABLES = Set.of( + "users", "roles", "permissions", "role_user", "role_permission", "activation_tokens", + "blacklisted_tokens", "password_reset_tokens", "audit_logs", "categories", "products", + "customers", "orders"); + + @Inject + DataSource dataSource; + + @Test + void allExpectedTablesExistInPublicSchema() throws SQLException { + Set tables = new HashSet<>(); + try (Connection c = dataSource.getConnection(); + PreparedStatement ps = c.prepareStatement( + "SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'"); + ResultSet rs = ps.executeQuery()) { + while (rs.next()) { + tables.add(rs.getString(1)); + } + } + assertTrue(tables.containsAll(EXPECTED_TABLES), "Missing tables: " + missing(tables)); + } + + @Test + void schemaHistoryShowsVersionOneSuccess() throws SQLException { + try (Connection c = dataSource.getConnection(); + PreparedStatement ps = c.prepareStatement( + "SELECT success FROM flyway_schema_history WHERE version = '1'"); + ResultSet rs = ps.executeQuery()) { + assertTrue(rs.next(), "No version 1 row in flyway_schema_history"); + assertTrue(rs.getBoolean(1)); + } + } + + @Test + void duplicateUserEmailIsRejectedByTheDatabase() throws SQLException { + String sql = "INSERT INTO users (first_name, last_name, email, password) VALUES ('A', 'B', ?, 'x')"; + String email = "dup-" + System.nanoTime() + "@example.com"; + try (Connection c = dataSource.getConnection()) { + try (PreparedStatement ps = c.prepareStatement(sql)) { + ps.setString(1, email); + assertEquals(1, ps.executeUpdate()); + } + try (PreparedStatement ps = c.prepareStatement(sql)) { + ps.setString(1, email); + SQLException e = assertThrows(SQLException.class, ps::executeUpdate); + assertEquals("23505", e.getSQLState()); + } + try (PreparedStatement ps = c.prepareStatement("DELETE FROM users WHERE email = ?")) { + ps.setString(1, email); + ps.executeUpdate(); + } + } + } + + private static Set missing(Set actual) { + Set m = new HashSet<>(EXPECTED_TABLES); + m.removeAll(actual); + return m; + } +} From 267e8be101a6c456334824dd346fcc231b7d3ea7 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 07:56:20 +0400 Subject: [PATCH 021/158] test(exception): prove errors are RFC 9457 problem documents A small resource that exists only under src/test throws the two business exceptions, an unexpected exception and a Bean Validation failure, so the tests can look at what actually goes over HTTP. They assert the application/problem+json content type, the type, title, status and detail fields, the violations array for a validation failure, and the absence of any ApiResponse field on an error. The unexpected exception case also checks that the response leaks neither the exception class nor a stack trace: the extension replaces the details with a generic 500 and only logs them server side. The test resource is not part of the application, it is compiled and exposed only when the tests run. --- .../exception/ProblemDetailsTest.java | 80 +++++++++++++++++++ .../exception/ThrowingTestResource.java | 52 ++++++++++++ 2 files changed, 132 insertions(+) create mode 100644 src/test/java/com/edgareldy/quarkustutorial/exception/ProblemDetailsTest.java create mode 100644 src/test/java/com/edgareldy/quarkustutorial/exception/ThrowingTestResource.java diff --git a/src/test/java/com/edgareldy/quarkustutorial/exception/ProblemDetailsTest.java b/src/test/java/com/edgareldy/quarkustutorial/exception/ProblemDetailsTest.java new file mode 100644 index 0000000..e544d7a --- /dev/null +++ b/src/test/java/com/edgareldy/quarkustutorial/exception/ProblemDetailsTest.java @@ -0,0 +1,80 @@ +package com.edgareldy.quarkustutorial.exception; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.*; +import static org.junit.jupiter.api.Assertions.assertFalse; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; + +/** + * End-to-end proof that errors are rendered as RFC 9457 application/problem+json, never as an ApiResponse. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +// quarkus-http-problem maps HttpProblem subclasses, validation failures and unexpected exceptions to +// problem+json. Going through real HTTP (with ThrowingTestResource) verifies the wire format, not just the objects. +@QuarkusTest +class ProblemDetailsTest { + + private static final String PROBLEM_JSON = "application/problem+json"; + + @Test + void resourceNotFoundIsProblem404() { + given().when().get("/test-support/not-found") + .then().statusCode(404) + .contentType(PROBLEM_JSON) + .body("type", is(ResourceNotFoundException.TYPE.toString())) + .body("title", is("Resource Not Found")) + .body("status", is(404)) + .body("detail", is("Thing 42 does not exist")) + .body("$", not(hasKey("success"))); + } + + @Test + void businessRuleIsProblem422() { + given().when().get("/test-support/business-rule") + .then().statusCode(422) + .contentType(PROBLEM_JSON) + .body("type", is(BusinessRuleException.TYPE.toString())) + .body("title", is("Business Rule Violation")) + .body("status", is(422)) + .body("detail", is("Rule X forbids this")) + .body("$", not(hasKey("success"))); + } + + @Test + void beanValidationFailureIsProblem400WithViolations() { + given().contentType("application/json").body("{\"name\":\"\"}") + .when().post("/test-support/validate") + .then().statusCode(400) + .contentType(PROBLEM_JSON) + .body("status", is(400)) + .body("violations", not(empty())) + .body("$", not(hasKey("success"))); + } + + @Test + void validRequestStillReturnsSuccessEnvelope() { + given().contentType("application/json").body("{\"name\":\"bob\"}") + .when().post("/test-support/validate") + .then().statusCode(200) + .body("success", is(true)) + .body("data", is("bob")); + } + + @Test + void unexpectedExceptionIsGeneric500WithoutLeaks() { + String body = given().when().get("/test-support/unexpected") + .then().statusCode(500) + .contentType(PROBLEM_JSON) + .body("status", is(500)) + .body("$", not(hasKey("success"))) + .extract().asString(); + assertFalse(body.contains("IllegalStateException"), body); + assertFalse(body.contains("secret internal detail"), body); + assertFalse(body.contains("stacktrace") || body.contains("\tat ") || body.contains(".java:"), body); + } +} diff --git a/src/test/java/com/edgareldy/quarkustutorial/exception/ThrowingTestResource.java b/src/test/java/com/edgareldy/quarkustutorial/exception/ThrowingTestResource.java new file mode 100644 index 0000000..5b0ba24 --- /dev/null +++ b/src/test/java/com/edgareldy/quarkustutorial/exception/ThrowingTestResource.java @@ -0,0 +1,52 @@ +package com.edgareldy.quarkustutorial.exception; + +import com.edgareldy.quarkustutorial.dto.common.ApiResponse; +import jakarta.validation.Valid; +import jakarta.validation.constraints.NotBlank; +import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.core.MediaType; + +/** + * Test-only resource throwing the exceptions whose Problem Details rendering is verified. Lives in src/test only. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +@Path("/test-support") +public class ThrowingTestResource { + + /** Request body with a mandatory field, used to trigger Bean Validation. */ + public record Payload(@NotBlank String name) { + } + + @GET + @Path("/not-found") + public String notFound() { + throw new ResourceNotFoundException("Thing 42 does not exist"); + } + + @GET + @Path("/business-rule") + public String businessRule() { + throw new BusinessRuleException("Rule X forbids this"); + } + + @GET + @Path("/unexpected") + public String unexpected() { + throw new IllegalStateException("secret internal detail"); + } + + @POST + @Path("/validate") + @Consumes(MediaType.APPLICATION_JSON) + @jakarta.ws.rs.Produces(MediaType.APPLICATION_JSON) + public ApiResponse validate(@Valid Payload payload) { + return ApiResponse.success(payload.name(), "ok"); + } +} From 69b92cd0520bfefcbd1be812ed44b2ff9a87d100 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 08:01:51 +0400 Subject: [PATCH 022/158] fix(security): keep the development JWT keys out of the packaged jar Everything under src/main/resources is copied into the application jar and therefore into the Docker image. The private key of the development pair is public by construction since it is committed, so shipping it in a production artifact would let anyone who knows it forge valid tokens if a deployment ever fell back to the classpath key. The pair now lives in a dev-keys directory at the repository root, outside the packaged resources. The dev and test profiles point to it through a file location relative to the project root, while the prod profile keeps no default and requires real keys from the environment. A round trip that signs and parses a token confirmed the new locations work, and the built jars contain no PEM file. --- {src/main/resources/jwt => dev-keys}/privateKey.pem | 0 {src/main/resources/jwt => dev-keys}/publicKey.pem | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename {src/main/resources/jwt => dev-keys}/privateKey.pem (100%) rename {src/main/resources/jwt => dev-keys}/publicKey.pem (100%) diff --git a/src/main/resources/jwt/privateKey.pem b/dev-keys/privateKey.pem similarity index 100% rename from src/main/resources/jwt/privateKey.pem rename to dev-keys/privateKey.pem diff --git a/src/main/resources/jwt/publicKey.pem b/dev-keys/publicKey.pem similarity index 100% rename from src/main/resources/jwt/publicKey.pem rename to dev-keys/publicKey.pem From 8270d7eca5afdf0aee163ff18c156141c3c42db2 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 08:01:51 +0400 Subject: [PATCH 023/158] fix(health): log why the readiness check reports DOWN The check deliberately returns a short generic reason to the caller, but swallowing the exception left operators with no trace of the real cause when readiness turned DOWN, whether bad credentials, a network failure or an exhausted pool. The exception is now logged at warn level on the server, so diagnosis stays possible while the HTTP response still reveals nothing about hosts or schema. --- .../quarkustutorial/health/DatabaseHealthCheck.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/edgareldy/quarkustutorial/health/DatabaseHealthCheck.java b/src/main/java/com/edgareldy/quarkustutorial/health/DatabaseHealthCheck.java index 8d44fce..3d88195 100644 --- a/src/main/java/com/edgareldy/quarkustutorial/health/DatabaseHealthCheck.java +++ b/src/main/java/com/edgareldy/quarkustutorial/health/DatabaseHealthCheck.java @@ -4,6 +4,7 @@ import jakarta.inject.Inject; import java.sql.Connection; import javax.sql.DataSource; +import org.jboss.logging.Logger; import org.eclipse.microprofile.health.HealthCheck; import org.eclipse.microprofile.health.HealthCheckResponse; import org.eclipse.microprofile.health.Readiness; @@ -24,6 +25,7 @@ @ApplicationScoped public class DatabaseHealthCheck implements HealthCheck { + private static final Logger LOG = Logger.getLogger(DatabaseHealthCheck.class); private static final String CHECK_NAME = "database"; private static final int VALIDATION_TIMEOUT_SECONDS = 2; @@ -42,7 +44,9 @@ public HealthCheckResponse call() { .withData("reason", "Connection is not valid") .build(); } catch (Exception e) { - // Deliberately a short message only: exception details could leak host or schema info. + // The cause goes to the server log for operators; the HTTP response keeps a short message + // only, since exception details could leak host or schema information. + LOG.warn("Readiness check could not obtain a database connection", e); return HealthCheckResponse.named(CHECK_NAME) .down() .withData("reason", "Unable to obtain a database connection") From fd048d5cda92af34e6bbed338ea55e0aeaab8efe Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 08:01:51 +0400 Subject: [PATCH 024/158] style(test): add the standard Javadoc header to the Payload record The nested record was the only new type without the project's Javadoc block, so it now carries the same header as every other type. --- .../quarkustutorial/exception/ThrowingTestResource.java | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/test/java/com/edgareldy/quarkustutorial/exception/ThrowingTestResource.java b/src/test/java/com/edgareldy/quarkustutorial/exception/ThrowingTestResource.java index 5b0ba24..de519d7 100644 --- a/src/test/java/com/edgareldy/quarkustutorial/exception/ThrowingTestResource.java +++ b/src/test/java/com/edgareldy/quarkustutorial/exception/ThrowingTestResource.java @@ -20,7 +20,14 @@ @Path("/test-support") public class ThrowingTestResource { - /** Request body with a mandatory field, used to trigger Bean Validation. */ + /** + * Request body with a mandatory field, used to trigger Bean Validation. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ public record Payload(@NotBlank String name) { } From 0d50b91394f6d5ad6562c38cfdab79e018a2aa71 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 08:01:51 +0400 Subject: [PATCH 025/158] docs(docker): explain the key file permissions needed by the container The application runs as an unprivileged user whose uid differs from the host user, and a key generated by openssl is readable by its owner only. Without a hint the container could not read the mounted private key and would fail at startup with a permission error. The setup comment now asks for readable key files and reminds that the directory is ignored by git and mounted read-only. --- docker-compose.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docker-compose.yml b/docker-compose.yml index 41e0f3e..f64ba7f 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -8,6 +8,9 @@ # mkdir -p keys # openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -out keys/privateKey.pem # openssl pkey -in keys/privateKey.pem -pubout -out keys/publicKey.pem +# chmod 644 keys/*.pem +# The container runs as an unprivileged user whose uid differs from yours, so the keys must +# be readable by others. The keys directory is ignored by git and mounted read-only. services: db: From 42043ec45247a11ca330669d0de402117e6f4d09 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 08:01:51 +0400 Subject: [PATCH 026/158] docs(readme): check off core-architecture and align it with what was built The core-architecture checklist is ticked now that each task is implemented and covered by a passing build. The references that turned out to be outdated are corrected: the Quarkus stream is the 3.33 LTS line, and quarkus-http-problem is published under the io.quarkiverse.httpproblem group and package rather than the older resteasy one. The checklist item about configuring the problem type prefix and stack traces now states the actual behaviour: the version in use exposes no such options, so the type is a constant on each exception and stack traces are never included in a response. --- README.md | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 4ca6fee..b9c9d47 100644 --- a/README.md +++ b/README.md @@ -81,7 +81,7 @@ Three everyday Quarkus mechanics this tutorial relies on throughout, worth under | Component | Choice | |---|---| -| Framework | Quarkus 3.30.x (LTS stream) | +| Framework | Quarkus 3.33.x (LTS stream) | | Language | Java 21 (LTS) | | Build | Maven | | REST layer | Quarkus REST (`quarkus-rest`, `quarkus-rest-jackson`) - the current name for what was previously branded "RESTEasy Reactive" | @@ -220,7 +220,7 @@ public record ApiResponse( **Errors**: every non-2xx response is a **Problem Details** document (RFC 9457, which obsoletes RFC 7807 - same `application/problem+json` wire format), produced by the `quarkus-http-problem` Quarkiverse extension rather than a hand-written `ExceptionMapper`. -- `ResourceNotFoundException` and `BusinessRuleException` extend `io.quarkiverse.resteasy.problem.HttpProblem` directly and are thrown normally from a service method - `HttpProblem` already *is* a `RuntimeException`, built via its own builder (`.withTitle(...)`, `.withStatus(...)`, `.withDetail(...)`), so there's no separate DTO and no manual mapping step for these two +- `ResourceNotFoundException` and `BusinessRuleException` extend `io.quarkiverse.httpproblem.HttpProblem` directly and are thrown normally from a service method - `HttpProblem` already *is* a `RuntimeException`, built via its own builder (`.withTitle(...)`, `.withStatus(...)`, `.withDetail(...)`), so there's no separate DTO and no manual mapping step for these two - `quarkus-http-problem` ships its own built-in mappers for the exceptions a project doesn't throw on purpose: Bean Validation failures become a Problem with a `violations` extension listing each field, and anything unmapped becomes a generic 500 Problem with implementation details stripped out before the response is sent - both without a single line of this project's own code - A response's `type`/`title`/`status`/`detail` fields carry what an `ApiResponse` used to carry in `message`, and any structured, field-level detail (like a validation error list) rides in the same document's `extensions` rather than a nested `data` @@ -251,16 +251,16 @@ Example error response (`GET /api/v1/products/999` on a missing product): ### Tasks -- [ ] Generate the project (`mvn io.quarkus:quarkus-maven-plugin:create`, or code.quarkus.io), Java 21, Maven -- [ ] Extensions: `quarkus-rest`, `quarkus-rest-jackson`, `quarkus-hibernate-orm-panache`, `quarkus-jdbc-postgresql`, `quarkus-flyway`, `quarkus-hibernate-validator`, `quarkus-smallrye-jwt`, `quarkus-smallrye-jwt-build`, `quarkus-security`, `quarkus-smallrye-openapi`, `quarkus-smallrye-health`, `quarkus-cache`, `quarkus-scheduler`, `io.quarkiverse.resteasy.problem:quarkus-http-problem` -- [ ] A custom `@Readiness` check (`DatabaseHealthCheck`, verifying a real connection can be obtained) alongside the default one `quarkus-smallrye-health` already provides, and a custom `@Liveness` check confirming the application isn't in a stuck state - both visible at `/q/health`, and individually at `/q/health/ready`/`/q/health/live` -- [ ] Test extensions: `quarkus-junit5`, `rest-assured` -- [ ] `ApiResponse`, `PageResponse` -- [ ] `ResourceNotFoundException`, `BusinessRuleException` (both extending `HttpProblem`, built via its builder with the appropriate status/title); `quarkus-http-problem` configuration (base `type` URI prefix, whether stack traces are ever included - never in `%prod`) -- [ ] Flyway script `V1__init_schema.sql` (all tables from both domains) -- [ ] `application.properties`: JWT signing key location, Flyway enabled, `%test`/`%dev` profiles left without a configured datasource (Dev Services provisions PostgreSQL automatically), `%prod` profile with a real connection string -- [ ] `docker-compose.yml` (app + PostgreSQL, for the packaged application only - not used in dev/test), `Dockerfile.jvm` -- [ ] `.github/workflows/ci.yml`: `mvn verify` (Dev Services provisions PostgreSQL inside the CI runner automatically, same as locally) +- [x] Generate the project (`mvn io.quarkus:quarkus-maven-plugin:create`, or code.quarkus.io), Java 21, Maven +- [x] Extensions: `quarkus-rest`, `quarkus-rest-jackson`, `quarkus-hibernate-orm-panache`, `quarkus-jdbc-postgresql`, `quarkus-flyway`, `quarkus-hibernate-validator`, `quarkus-smallrye-jwt`, `quarkus-smallrye-jwt-build`, `quarkus-security`, `quarkus-smallrye-openapi`, `quarkus-smallrye-health`, `quarkus-cache`, `quarkus-scheduler`, `io.quarkiverse.httpproblem:quarkus-http-problem` +- [x] A custom `@Readiness` check (`DatabaseHealthCheck`, verifying a real connection can be obtained) alongside the default one `quarkus-smallrye-health` already provides, and a custom `@Liveness` check confirming the application isn't in a stuck state - both visible at `/q/health`, and individually at `/q/health/ready`/`/q/health/live` +- [x] Test extensions: `quarkus-junit`, `quarkus-junit-mockito`, `rest-assured` +- [x] `ApiResponse`, `PageResponse` +- [x] `ResourceNotFoundException`, `BusinessRuleException` (both extending `HttpProblem`, built via its builder with the appropriate status/title); the problem `type` URI is a constant on each exception (this version of `quarkus-http-problem` has no type prefix option) and stack traces are never included in a response, in any profile +- [x] Flyway script `V1__init_schema.sql` (all tables from both domains) +- [x] `application.properties`: JWT signing key location, Flyway enabled, `%test`/`%dev` profiles left without a configured datasource (Dev Services provisions PostgreSQL automatically), `%prod` profile with a real connection string +- [x] `docker-compose.yml` (app + PostgreSQL, for the packaged application only - not used in dev/test), `Dockerfile.jvm` +- [x] `.github/workflows/ci.yml`: `mvn verify` (Dev Services provisions PostgreSQL inside the CI runner automatically, same as locally) ## feature/auth From 5c9343233b77873266fee4048ea54a94f7bce3ae Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 08:02:08 +0400 Subject: [PATCH 027/158] fix(config): point the dev and test JWT key locations to dev-keys This completes the move of the development key pair out of the packaged resources. A profile list such as %dev,test applies one value to several profiles at once, so dev and test read the keys from the file system relative to the project root, while prod keeps requiring real key locations from the environment and has no default. The comment above the settings explains why the location matters: only files outside src/main/resources stay out of the jar and the Docker image. --- src/main/resources/application.properties | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 2f69b5d..b94cae0 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -31,13 +31,15 @@ quarkus.hibernate-orm.schema-management.strategy=none # --- JWT (SmallRye JWT) ----------------------------------------------------- # The private key signs the tokens the application issues, the public key verifies incoming ones. -# The RSA pair under src/main/resources/jwt is for development and tests ONLY and must never be -# used in production: %prod has no default, so the application refuses to start without real keys. -mp.jwt.verify.publickey.location=jwt/publicKey.pem -smallrye.jwt.sign.key.location=jwt/privateKey.pem +# The RSA pair under dev-keys/ is for development and tests ONLY. It lives outside src/ on +# purpose: anything under src/main/resources is packaged into the jar and the Docker image, and a +# publicly committed private key must never ship. Dev and test read it from the file system +# (relative to the project root); prod has no default and refuses to start without real keys. +%dev,test.mp.jwt.verify.publickey.location=file:dev-keys/publicKey.pem +%dev,test.smallrye.jwt.sign.key.location=file:dev-keys/privateKey.pem +%prod.mp.jwt.verify.publickey.location=${JWT_PUBLIC_KEY_LOCATION} +%prod.smallrye.jwt.sign.key.location=${JWT_PRIVATE_KEY_LOCATION} mp.jwt.verify.issuer=https://api.example.com/quarkus-tutorial smallrye.jwt.new-token.issuer=https://api.example.com/quarkus-tutorial # Access token lifetime in seconds. smallrye.jwt.new-token.lifespan=3600 -%prod.mp.jwt.verify.publickey.location=${JWT_PUBLIC_KEY_LOCATION} -%prod.smallrye.jwt.sign.key.location=${JWT_PRIVATE_KEY_LOCATION} From 5b973cd6d0b66b5372d09142f2d36bd8c2762ed9 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 08:07:39 +0400 Subject: [PATCH 028/158] docs(github): add a pull request template Every branch goes through a pull request, so the template gives each one the same structure: which branch it is, the README checklist copied and ticked, a short commit summary, and two checklists. The test checklist states what must be green before merging, and the review checklist turns the project's non-negotiable rules into questions a reviewer answers one by one, such as declarative permission checks or errors rendered as Problem Details. Having those rules written next to every change makes them hard to forget and gives a review a concrete list to work through instead of an impression. --- .github/PULL_REQUEST_TEMPLATE.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 .github/PULL_REQUEST_TEMPLATE.md diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..48239db --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,30 @@ +## Branch + + + +## Task checklist + + + +- [ ] + +## Commit summary + + + +## Test checklist + +- [ ] Unit tests pass +- [ ] Integration tests pass (where the branch's checklist calls for them) +- [ ] `mvn verify` is green on the whole project + +## Code review checklist + +- [ ] No business logic in JAX-RS resources +- [ ] Success responses are wrapped in `ApiResponse`, errors are RFC 9457 Problem Details (`HttpProblem`), never `ApiResponse` on an error path +- [ ] Permission checks are declarative (`@PermissionsAllowed`), no manual permission `if` +- [ ] Every `@CacheResult` has its matching `@CacheInvalidate` on the write operations +- [ ] Every RBAC mutation calls `AuditLogger` +- [ ] The database schema only changes through a Flyway migration +- [ ] No manual Testcontainers setup (Dev Services only) +- [ ] Commits are atomic (one commit per file added or modified), follow Conventional Commits, no em dash, no Claude/Anthropic mention From dd994e51ca0bee76d0cbb062c2d246ad12cd616a Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 08:07:39 +0400 Subject: [PATCH 029/158] ci(workflow): validate Conventional Commits on pull requests The commit convention is only useful if it holds for every commit, so a second workflow checks it automatically. It walks the commits between the base and the head of the pull request, skips merge commits, and fails when a subject does not match the type(scope): summary shape with one of the allowed types. The check reads the history rather than the pull request title because the branches are merged with a merge commit and each atomic commit stays visible. Fetching the full depth is required, otherwise the base commit would not exist in the checkout and the range could not be computed. --- .github/workflows/pr-checks.yml | 43 +++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 .github/workflows/pr-checks.yml diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml new file mode 100644 index 0000000..8188482 --- /dev/null +++ b/.github/workflows/pr-checks.yml @@ -0,0 +1,43 @@ +name: PR checks + +on: + pull_request: + branches: [master, develop] + +jobs: + commit-lint: + runs-on: ubuntu-latest + + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Validate commit messages (Conventional Commits) + env: + BASE_SHA: ${{ github.event.pull_request.base.sha }} + HEAD_SHA: ${{ github.event.pull_request.head.sha }} + run: | + set -euo pipefail + + pattern='^(feat|fix|refactor|test|docs|chore|build|ci|style|perf)\([a-z0-9.,/_-]+\): .{1,100}$' + failed=0 + + while IFS= read -r subject; do + [ -z "$subject" ] && continue + if [[ "$subject" =~ $pattern ]]; then + echo "OK: $subject" + else + echo "INVALID: $subject" + failed=1 + fi + done < <(git log "$BASE_SHA..$HEAD_SHA" --no-merges --pretty=format:'%s') + + if [ "$failed" -ne 0 ]; then + echo "" + echo "One or more commit messages do not follow Conventional Commits." + echo "Expected format: (): " + echo "Allowed types: feat, fix, refactor, test, docs, chore, build, ci, style, perf" + exit 1 + fi From fc85c2ea900c294385ba7c6694c1f33e91eeefa4 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 08:44:56 +0400 Subject: [PATCH 030/158] build(pom): add quarkus-elytron-security-common for password hashing BcryptUtil, the class used to hash and verify passwords, lives in this small Quarkus module. It is not pulled in by quarkus-security as first assumed, so it is declared explicitly. The version comes from the platform BOM, like every other Quarkus extension. Using the hashing helper shipped with Quarkus avoids adding a third party library for something the framework already covers: it produces salted, self describing bcrypt hashes, so the algorithm and cost can evolve without a schema change. --- pom.xml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/pom.xml b/pom.xml index fc2007c..641f0d6 100644 --- a/pom.xml +++ b/pom.xml @@ -76,6 +76,10 @@ io.quarkus quarkus-security + + io.quarkus + quarkus-elytron-security-common + io.quarkus quarkus-smallrye-openapi From cb544550ce22f091d79b82677cba7010345dea1b Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 08:44:56 +0400 Subject: [PATCH 031/158] feat(entity): add the User entity and its repository User is a plain JPA entity mapped to the users table created by the Flyway migration. Hibernate only maps to that schema and never generates it, so column names and constraints are decided in SQL and the entity follows them. The password field holds a bcrypt hash, never the clear text. The repository follows the Panache repository pattern: extending PanacheRepository gives persist, find and delete for free, so only the query that goes beyond it, a case insensitive lookup by email, is written by hand. Keeping data access in a repository rather than on the entity leaves the entity a simple data holder that services can be tested against. --- .../quarkustutorial/entity/User.java | 61 +++++++++++++++++++ .../repository/UserRepository.java | 28 +++++++++ 2 files changed, 89 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/entity/User.java create mode 100644 src/main/java/com/edgareldy/quarkustutorial/repository/UserRepository.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/entity/User.java b/src/main/java/com/edgareldy/quarkustutorial/entity/User.java new file mode 100644 index 0000000..1d624e2 --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/entity/User.java @@ -0,0 +1,61 @@ +package com.edgareldy.quarkustutorial.entity; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; + +/** + * An application account; created disabled at registration and enabled by activating it. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +// Plain JPA entity (not PanacheEntity): data access lives in UserRepository, the repository pattern +// used throughout this project. The schema comes from Flyway, so this only maps to existing columns. +@Entity +@Table(name = "users") +public class User { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "first_name", nullable = false) + private String firstName; + + @Column(name = "last_name", nullable = false) + private String lastName; + + @Column(nullable = false, unique = true) + private String email; + + /** BCrypt hash, never the raw password. */ + @Column(nullable = false) + private String password; + + @Column(nullable = false) + private boolean enabled; + + @Column(name = "account_locked", nullable = false) + private boolean accountLocked; + + public Long getId() { return id; } + public void setId(Long id) { this.id = id; } + public String getFirstName() { return firstName; } + public void setFirstName(String firstName) { this.firstName = firstName; } + public String getLastName() { return lastName; } + public void setLastName(String lastName) { this.lastName = lastName; } + public String getEmail() { return email; } + public void setEmail(String email) { this.email = email; } + public String getPassword() { return password; } + public void setPassword(String password) { this.password = password; } + public boolean isEnabled() { return enabled; } + public void setEnabled(boolean enabled) { this.enabled = enabled; } + public boolean isAccountLocked() { return accountLocked; } + public void setAccountLocked(boolean accountLocked) { this.accountLocked = accountLocked; } +} diff --git a/src/main/java/com/edgareldy/quarkustutorial/repository/UserRepository.java b/src/main/java/com/edgareldy/quarkustutorial/repository/UserRepository.java new file mode 100644 index 0000000..7b2c034 --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/repository/UserRepository.java @@ -0,0 +1,28 @@ +package com.edgareldy.quarkustutorial.repository; + +import com.edgareldy.quarkustutorial.entity.User; +import io.quarkus.hibernate.orm.panache.PanacheRepository; +import jakarta.enterprise.context.ApplicationScoped; +import java.util.Optional; + +/** + * Panache repository for users. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +// PanacheRepository already provides find/persist/delete/count; only the lookups the +// services need beyond it are added. The repository is a CDI bean injected where required. +@ApplicationScoped +public class UserRepository implements PanacheRepository { + + /** + * @param email the email, matched case-insensitively + * @return the user, if any + */ + public Optional findByEmail(String email) { + return find("lower(email) = ?1", email.toLowerCase()).firstResultOptional(); + } +} From 15f862f15f8f59979e38421c88c63112739df1bd Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 08:44:56 +0400 Subject: [PATCH 032/158] feat(entity): add ActivationToken and its repository An activation token proves that the owner of an email address asked for the account. The entity keeps the creation, expiry and validation instants so a token can be recognised as expired or already used, and it points to its user with a lazy relation so loading a token never loads more than needed. Only the SHA-256 hash of the token is stored. The clear value is handed to the user once, so a database leak does not give an attacker usable activation links. The repository exposes the single lookup the service needs, by hash. --- .../entity/ActivationToken.java | 60 +++++++++++++++++++ .../repository/ActivationTokenRepository.java | 27 +++++++++ 2 files changed, 87 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/entity/ActivationToken.java create mode 100644 src/main/java/com/edgareldy/quarkustutorial/repository/ActivationTokenRepository.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/entity/ActivationToken.java b/src/main/java/com/edgareldy/quarkustutorial/entity/ActivationToken.java new file mode 100644 index 0000000..c6ccc24 --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/entity/ActivationToken.java @@ -0,0 +1,60 @@ +package com.edgareldy.quarkustutorial.entity; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; +import java.time.Instant; + +/** + * Account activation token; only the SHA-256 hash of the emailed value is stored. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +@Entity +@Table(name = "activation_tokens") +public class ActivationToken { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + // LAZY: the owning user is only loaded when actually read. + @ManyToOne(fetch = FetchType.LAZY, optional = false) + @JoinColumn(name = "user_id", nullable = false) + private User user; + + /** SHA-256 hex of the raw token. */ + @Column(nullable = false, unique = true) + private String token; + + @Column(name = "created_at", nullable = false) + private Instant createdAt; + + @Column(name = "expires_at", nullable = false) + private Instant expiresAt; + + @Column(name = "validated_at") + private Instant validatedAt; + + public Long getId() { return id; } + public void setId(Long id) { this.id = id; } + public User getUser() { return user; } + public void setUser(User user) { this.user = user; } + public String getToken() { return token; } + public void setToken(String token) { this.token = token; } + public Instant getCreatedAt() { return createdAt; } + public void setCreatedAt(Instant createdAt) { this.createdAt = createdAt; } + public Instant getExpiresAt() { return expiresAt; } + public void setExpiresAt(Instant expiresAt) { this.expiresAt = expiresAt; } + public Instant getValidatedAt() { return validatedAt; } + public void setValidatedAt(Instant validatedAt) { this.validatedAt = validatedAt; } +} diff --git a/src/main/java/com/edgareldy/quarkustutorial/repository/ActivationTokenRepository.java b/src/main/java/com/edgareldy/quarkustutorial/repository/ActivationTokenRepository.java new file mode 100644 index 0000000..256dd25 --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/repository/ActivationTokenRepository.java @@ -0,0 +1,27 @@ +package com.edgareldy.quarkustutorial.repository; + +import com.edgareldy.quarkustutorial.entity.ActivationToken; +import io.quarkus.hibernate.orm.panache.PanacheRepository; +import jakarta.enterprise.context.ApplicationScoped; +import java.util.Optional; + +/** + * Panache repository for activation tokens. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ + +@ApplicationScoped +public class ActivationTokenRepository implements PanacheRepository { + + /** + * @param tokenHash SHA-256 hex of the raw token + * @return the matching token, if any + */ + public Optional findByToken(String tokenHash) { + return find("token", tokenHash).firstResultOptional(); + } +} From 7e47c73fc4c92c866acbe255e9ac120e71a005d5 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 08:44:56 +0400 Subject: [PATCH 033/158] feat(entity): add PasswordResetToken and its repository The password reset token follows the same idea as the activation token but is shorter lived and single use: it carries a type and an expiry date, and the service deletes the row once the password has been changed, so a link cannot be replayed. As for activation, only a hash is persisted. The repository looks a token up by that hash, which keeps the raw value out of the database and out of any query log. --- .../entity/PasswordResetToken.java | 57 +++++++++++++++++++ .../PasswordResetTokenRepository.java | 27 +++++++++ 2 files changed, 84 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/entity/PasswordResetToken.java create mode 100644 src/main/java/com/edgareldy/quarkustutorial/repository/PasswordResetTokenRepository.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/entity/PasswordResetToken.java b/src/main/java/com/edgareldy/quarkustutorial/entity/PasswordResetToken.java new file mode 100644 index 0000000..abb6f5a --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/entity/PasswordResetToken.java @@ -0,0 +1,57 @@ +package com.edgareldy.quarkustutorial.entity; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; +import java.time.Instant; + +/** + * Single-use password reset token; only the SHA-256 hash of the delivered value is stored. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +@Entity +@Table(name = "password_reset_tokens") +public class PasswordResetToken { + + /** Value of the {@code type} column for tokens created by the forgot-password flow. */ + public static final String TYPE_PASSWORD_RESET = "PASSWORD_RESET"; + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @ManyToOne(fetch = FetchType.LAZY, optional = false) + @JoinColumn(name = "user_id", nullable = false) + private User user; + + /** SHA-256 hex of the raw token. */ + @Column(nullable = false, unique = true) + private String token; + + @Column(nullable = false) + private String type; + + @Column(name = "expiry_date", nullable = false) + private Instant expiryDate; + + public Long getId() { return id; } + public void setId(Long id) { this.id = id; } + public User getUser() { return user; } + public void setUser(User user) { this.user = user; } + public String getToken() { return token; } + public void setToken(String token) { this.token = token; } + public String getType() { return type; } + public void setType(String type) { this.type = type; } + public Instant getExpiryDate() { return expiryDate; } + public void setExpiryDate(Instant expiryDate) { this.expiryDate = expiryDate; } +} diff --git a/src/main/java/com/edgareldy/quarkustutorial/repository/PasswordResetTokenRepository.java b/src/main/java/com/edgareldy/quarkustutorial/repository/PasswordResetTokenRepository.java new file mode 100644 index 0000000..9902849 --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/repository/PasswordResetTokenRepository.java @@ -0,0 +1,27 @@ +package com.edgareldy.quarkustutorial.repository; + +import com.edgareldy.quarkustutorial.entity.PasswordResetToken; +import io.quarkus.hibernate.orm.panache.PanacheRepository; +import jakarta.enterprise.context.ApplicationScoped; +import java.util.Optional; + +/** + * Panache repository for password reset tokens. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ + +@ApplicationScoped +public class PasswordResetTokenRepository implements PanacheRepository { + + /** + * @param tokenHash SHA-256 hex of the raw token + * @return the matching token, if any + */ + public Optional findByToken(String tokenHash) { + return find("token", tokenHash).firstResultOptional(); + } +} From 29870b24cc040b08239ced3b3a7d56a4d3a14293 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 08:44:56 +0400 Subject: [PATCH 034/158] feat(entity): add BlacklistedToken and its repository A JWT is stateless: once issued it stays valid until it expires, so logging out needs a server side memory of revoked tokens. Each revoked token is recorded by its jti, the unique identifier claim, together with its expiry, which is what lets a later cleanup delete rows that can no longer matter. The jti column is unique and the repository answers a single question, whether a given jti was revoked, which is the check made on every authenticated request. --- .../entity/BlacklistedToken.java | 70 +++++++++++++++++++ .../BlacklistedTokenRepository.java | 26 +++++++ 2 files changed, 96 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/entity/BlacklistedToken.java create mode 100644 src/main/java/com/edgareldy/quarkustutorial/repository/BlacklistedTokenRepository.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/entity/BlacklistedToken.java b/src/main/java/com/edgareldy/quarkustutorial/entity/BlacklistedToken.java new file mode 100644 index 0000000..e14c93e --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/entity/BlacklistedToken.java @@ -0,0 +1,70 @@ +package com.edgareldy.quarkustutorial.entity; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; +import java.time.Instant; + +/** + * A revoked JWT, identified by its jti, rejected until it would have expired anyway. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +@Entity +@Table(name = "blacklisted_tokens") +public class BlacklistedToken { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @ManyToOne(fetch = FetchType.LAZY, optional = false) + @JoinColumn(name = "user_id", nullable = false) + private User user; + + /** Token identifier kept for the audit trail (the raw JWT is deliberately not stored). */ + @Column(nullable = false) + private String token; + + @Column(nullable = false, unique = true) + private String jti; + + @Column(name = "blacklisted_at", nullable = false) + private Instant blacklistedAt; + + @Column(name = "created_at", nullable = false) + private Instant createdAt; + + /** The JWT's own expiry: after it the row is useless and can be purged. */ + @Column(name = "expires_at", nullable = false) + private Instant expiresAt; + + @Column(name = "validated_at") + private Instant validatedAt; + + public Long getId() { return id; } + public void setId(Long id) { this.id = id; } + public User getUser() { return user; } + public void setUser(User user) { this.user = user; } + public String getToken() { return token; } + public void setToken(String token) { this.token = token; } + public String getJti() { return jti; } + public void setJti(String jti) { this.jti = jti; } + public Instant getBlacklistedAt() { return blacklistedAt; } + public void setBlacklistedAt(Instant blacklistedAt) { this.blacklistedAt = blacklistedAt; } + public Instant getCreatedAt() { return createdAt; } + public void setCreatedAt(Instant createdAt) { this.createdAt = createdAt; } + public Instant getExpiresAt() { return expiresAt; } + public void setExpiresAt(Instant expiresAt) { this.expiresAt = expiresAt; } + public Instant getValidatedAt() { return validatedAt; } + public void setValidatedAt(Instant validatedAt) { this.validatedAt = validatedAt; } +} diff --git a/src/main/java/com/edgareldy/quarkustutorial/repository/BlacklistedTokenRepository.java b/src/main/java/com/edgareldy/quarkustutorial/repository/BlacklistedTokenRepository.java new file mode 100644 index 0000000..192d12d --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/repository/BlacklistedTokenRepository.java @@ -0,0 +1,26 @@ +package com.edgareldy.quarkustutorial.repository; + +import com.edgareldy.quarkustutorial.entity.BlacklistedToken; +import io.quarkus.hibernate.orm.panache.PanacheRepository; +import jakarta.enterprise.context.ApplicationScoped; + +/** + * Panache repository for revoked JWTs. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ + +@ApplicationScoped +public class BlacklistedTokenRepository implements PanacheRepository { + + /** + * @param jti the JWT identifier + * @return true when a token with this jti has been revoked + */ + public boolean existsByJti(String jti) { + return count("jti", jti) > 0; + } +} From 7a5ba8c47c34a7d9ec3a7036293d08409ed24863 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 08:44:56 +0400 Subject: [PATCH 035/158] feat(dto): add the RegisterRequest record Request bodies are records validated with Bean Validation annotations: the resource only declares that the body must be valid and the framework rejects a bad one before any service code runs, with a Problem Details response listing each violation. The password must be at least eight characters. toString is overridden to mask the password, so a request that ends up in a log line or an exception message never exposes the credential. --- .../dto/auth/RegisterRequest.java | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/dto/auth/RegisterRequest.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/dto/auth/RegisterRequest.java b/src/main/java/com/edgareldy/quarkustutorial/dto/auth/RegisterRequest.java new file mode 100644 index 0000000..fdb63f3 --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/dto/auth/RegisterRequest.java @@ -0,0 +1,27 @@ +package com.edgareldy.quarkustutorial.dto.auth; + +import jakarta.validation.constraints.Email; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Size; + +/** + * Payload of the registration endpoint. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +public record RegisterRequest( + @NotBlank String firstName, + @NotBlank String lastName, + @NotBlank @Email String email, + @NotBlank @Size(min = 8, max = 72) String password +) { + + /** Masks the password so it never reaches logs. */ + @Override + public String toString() { + return "RegisterRequest[firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + ", password=***]"; + } +} From eea2813b2b3f68d793a2cae7dcd19bbba6149297 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 08:44:56 +0400 Subject: [PATCH 036/158] feat(dto): add the LoginRequest record Login takes an email and a password, both mandatory. Validation stays minimal here on purpose: the length rule belongs to registration, and applying it at login would tell an attacker how passwords are shaped. As with registration, toString hides the password. --- .../dto/auth/LoginRequest.java | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/dto/auth/LoginRequest.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/dto/auth/LoginRequest.java b/src/main/java/com/edgareldy/quarkustutorial/dto/auth/LoginRequest.java new file mode 100644 index 0000000..ad274bb --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/dto/auth/LoginRequest.java @@ -0,0 +1,24 @@ +package com.edgareldy.quarkustutorial.dto.auth; + +import jakarta.validation.constraints.Email; +import jakarta.validation.constraints.NotBlank; + +/** + * Payload of the login endpoint. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +public record LoginRequest( + @NotBlank @Email String email, + @NotBlank String password +) { + + /** Masks the password so it never reaches logs. */ + @Override + public String toString() { + return "LoginRequest[email=" + email + ", password=***]"; + } +} From d7048e8c6331e3bf0c0c8ae11e179aa90a2f685c Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 08:44:56 +0400 Subject: [PATCH 037/158] feat(dto): add the forgot and reset password request records Asking for a reset needs only an email, while consuming one needs the token received and the new password, which follows the same length rule as registration. Two small records keep each endpoint contract explicit and validated. The token and the new password are masked in toString for the same reason as other credentials. --- .../dto/auth/ForgotPasswordRequest.java | 15 ++++++++++++ .../dto/auth/ResetPasswordRequest.java | 24 +++++++++++++++++++ 2 files changed, 39 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/dto/auth/ForgotPasswordRequest.java create mode 100644 src/main/java/com/edgareldy/quarkustutorial/dto/auth/ResetPasswordRequest.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/dto/auth/ForgotPasswordRequest.java b/src/main/java/com/edgareldy/quarkustutorial/dto/auth/ForgotPasswordRequest.java new file mode 100644 index 0000000..fa7bfb1 --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/dto/auth/ForgotPasswordRequest.java @@ -0,0 +1,15 @@ +package com.edgareldy.quarkustutorial.dto.auth; + +import jakarta.validation.constraints.Email; +import jakarta.validation.constraints.NotBlank; + +/** + * Payload of the forgot-password endpoint. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +public record ForgotPasswordRequest(@NotBlank @Email String email) { +} diff --git a/src/main/java/com/edgareldy/quarkustutorial/dto/auth/ResetPasswordRequest.java b/src/main/java/com/edgareldy/quarkustutorial/dto/auth/ResetPasswordRequest.java new file mode 100644 index 0000000..76ef46c --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/dto/auth/ResetPasswordRequest.java @@ -0,0 +1,24 @@ +package com.edgareldy.quarkustutorial.dto.auth; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Size; + +/** + * Payload of the reset-password endpoint. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +public record ResetPasswordRequest( + @NotBlank String token, + @NotBlank @Size(min = 8, max = 72) String newPassword +) { + + /** Masks the token and the password so they never reach logs. */ + @Override + public String toString() { + return "ResetPasswordRequest[token=***, newPassword=***]"; + } +} From 9b8983b0cbaa49aa31e2d813b52a7a22e20fcde9 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 08:44:56 +0400 Subject: [PATCH 038/158] feat(dto): add the AuthResponse record A successful login returns the signed token, its type and its lifetime in seconds. Carrying the type lets a client build the Authorization header without guessing, and the lifetime lets it schedule a new login before the token expires. The token is masked in toString so it cannot leak through logging. --- .../quarkustutorial/dto/auth/AuthResponse.java | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/dto/auth/AuthResponse.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/dto/auth/AuthResponse.java b/src/main/java/com/edgareldy/quarkustutorial/dto/auth/AuthResponse.java new file mode 100644 index 0000000..b870fe4 --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/dto/auth/AuthResponse.java @@ -0,0 +1,18 @@ +package com.edgareldy.quarkustutorial.dto.auth; + +/** + * Login result: the signed JWT, its scheme and its lifetime in seconds. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +public record AuthResponse(String token, String tokenType, long expiresIn) { + + /** Masks the token so it never reaches logs. */ + @Override + public String toString() { + return "AuthResponse[token=***, tokenType=" + tokenType + ", expiresIn=" + expiresIn + "]"; + } +} From a11e61c05dae5aa261d9e8d62ed3ad1e3cbc380e Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 08:44:56 +0400 Subject: [PATCH 039/158] feat(dto): add the UserResponse record Entities are never returned by an endpoint. This record is the public view of a user: identity, email and activation state, and deliberately no password field, so there is no way for the hash to reach a response even by mistake. Keeping a separate response type also lets the entity change, for example when roles arrive later, without changing the API contract. --- .../quarkustutorial/dto/auth/UserResponse.java | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/dto/auth/UserResponse.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/dto/auth/UserResponse.java b/src/main/java/com/edgareldy/quarkustutorial/dto/auth/UserResponse.java new file mode 100644 index 0000000..a5f528f --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/dto/auth/UserResponse.java @@ -0,0 +1,12 @@ +package com.edgareldy.quarkustutorial.dto.auth; + +/** + * Public view of a user account (never exposes the password hash). + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +public record UserResponse(Long id, String firstName, String lastName, String email, boolean enabled) { +} From 42bf536ee585de63922907cedbbca864b03ac334 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 08:44:56 +0400 Subject: [PATCH 040/158] feat(exception): add AuthenticationFailedException as an HttpProblem Authentication failures are business errors like any other, so this exception extends HttpProblem and is rendered as a 401 Problem Details document without any mapper. Login uses one message for an unknown email and a wrong password, so the response cannot be used to find out which accounts exist. The same exception is used when a revoked token is presented, which gives clients a single, consistent shape for every 401. --- .../AuthenticationFailedException.java | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/exception/AuthenticationFailedException.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/exception/AuthenticationFailedException.java b/src/main/java/com/edgareldy/quarkustutorial/exception/AuthenticationFailedException.java new file mode 100644 index 0000000..e897585 --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/exception/AuthenticationFailedException.java @@ -0,0 +1,31 @@ +package com.edgareldy.quarkustutorial.exception; + +import io.quarkiverse.httpproblem.HttpProblem; +import java.net.URI; + +/** + * Thrown when authentication fails; rendered as a 401 Problem Details document. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +// One generic message for unknown email and wrong password, so the response cannot be used to tell +// which emails are registered. +public class AuthenticationFailedException extends HttpProblem { + + /** Problem type URI identifying this class of error. */ + public static final URI TYPE = URI.create("https://api.example.com/problems/authentication-failed"); + + /** + * @param detail human readable explanation, identical for every credential failure + */ + public AuthenticationFailedException(String detail) { + super(builder() + .withType(TYPE) + .withTitle("Authentication Failed") + .withStatus(401) + .withDetail(detail)); + } +} From 0d09027232af6895995ae003b700a2b719b6a4cb Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 08:44:56 +0400 Subject: [PATCH 041/158] feat(security): add JwtIssuer to sign access tokens SmallRye JWT builds and signs the token with the private key configured for the profile. The subject is the user id and every token gets a random jti, which is what makes revocation possible: without a unique identifier there would be nothing to blacklist. Issuer and lifetime come from configuration, and the issuer returns the lifetime with the token so the login response can report it without recomputing anything. --- .../quarkustutorial/security/JwtIssuer.java | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/security/JwtIssuer.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/security/JwtIssuer.java b/src/main/java/com/edgareldy/quarkustutorial/security/JwtIssuer.java new file mode 100644 index 0000000..e28161f --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/security/JwtIssuer.java @@ -0,0 +1,42 @@ +package com.edgareldy.quarkustutorial.security; + +import com.edgareldy.quarkustutorial.dto.auth.AuthResponse; +import com.edgareldy.quarkustutorial.entity.User; +import io.smallrye.jwt.build.Jwt; +import jakarta.enterprise.context.ApplicationScoped; +import java.util.UUID; +import org.eclipse.microprofile.jwt.Claims; +import org.eclipse.microprofile.config.inject.ConfigProperty; + +/** + * Builds and signs the access JWT for an authenticated user. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +@ApplicationScoped +public class JwtIssuer { + + // The lifespan is the same smallrye.jwt.new-token.lifespan the builder applies to exp; it is read + // here only to report expiresIn to the client. + @ConfigProperty(name = "smallrye.jwt.new-token.lifespan") + long lifespanSeconds; + + /** + * Issues a token whose subject is the user id and whose jti is unique (so it can be blacklisted). + * + * @param user the authenticated user + * @return the signed token with its scheme and lifetime + */ + public AuthResponse issue(User user) { + // smallrye-jwt-build: the signing key (smallrye.jwt.sign.key.location), the issuer and the + // lifespan come from configuration, so only per-token claims are set here. + String token = Jwt.claims() + .subject(String.valueOf(user.getId())) + .claim(Claims.jti.name(), UUID.randomUUID().toString()) + .sign(); + return new AuthResponse(token, "Bearer", lifespanSeconds); + } +} From 57fb165f1151b7198997c39cbaf529c415aca7fe Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 08:44:56 +0400 Subject: [PATCH 042/158] feat(service): add the AuthService contract The service is declared as an interface and implemented separately, so resources depend on the contract and tests can replace the implementation. The contract covers the whole account lifecycle: registration, activation, login, logout, the current profile, and the two steps of a password reset. Its methods take and return DTOs and simple values, never entities, which keeps persistence details out of the layers above. --- .../quarkustutorial/service/AuthService.java | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/service/AuthService.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/service/AuthService.java b/src/main/java/com/edgareldy/quarkustutorial/service/AuthService.java new file mode 100644 index 0000000..9cbd6b2 --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/service/AuthService.java @@ -0,0 +1,39 @@ +package com.edgareldy.quarkustutorial.service; + +import com.edgareldy.quarkustutorial.dto.auth.AuthResponse; +import com.edgareldy.quarkustutorial.dto.auth.LoginRequest; +import com.edgareldy.quarkustutorial.dto.auth.RegisterRequest; +import com.edgareldy.quarkustutorial.dto.auth.UserResponse; +import java.time.Instant; + +/** + * Contract of the authentication use cases: registration, activation, login, logout and password reset. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +public interface AuthService { + + /** Creates a disabled account and its activation token; fails with 422 if the email is taken. */ + UserResponse register(RegisterRequest request); + + /** Enables the account owning the raw activation token; fails with 422 if invalid, expired or used. */ + void activateAccount(String rawToken); + + /** Verifies credentials and issues a JWT; fails with a generic 401 on any credential problem. */ + AuthResponse login(LoginRequest request); + + /** Blacklists the token identified by jti until its own expiry. */ + void logout(String jti, Long userId, Instant expiresAt); + + /** Returns the profile of the given user id. */ + UserResponse me(Long userId); + + /** Starts a password reset; behaves identically whether or not the email is registered. */ + void forgotPassword(String email); + + /** Consumes a raw reset token (single use) and sets the new password. */ + void resetPassword(String rawToken, String newPassword); +} From ff8c98534fb2c70cfe40e8e9b18fbac563c2dc86 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 08:44:56 +0400 Subject: [PATCH 043/158] feat(service): implement AuthService Write operations run in a single transaction, so a user and its activation token are saved together or not at all. Passwords are hashed with bcrypt, and activation and reset tokens are random values of which only the SHA-256 hash is stored, the clear value being delivered through a log line since this tutorial has no mail sender. Several rules protect against account discovery: login checks the password first and burns the same bcrypt time for an unknown email, and the forgot password path does the same token work whether or not the account exists, so neither the answer nor its timing reveals who is registered. Reset tokens are single use and logout is idempotent. --- .../service/impl/AuthServiceImpl.java | 211 ++++++++++++++++++ 1 file changed, 211 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/service/impl/AuthServiceImpl.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/service/impl/AuthServiceImpl.java b/src/main/java/com/edgareldy/quarkustutorial/service/impl/AuthServiceImpl.java new file mode 100644 index 0000000..8a7ba1a --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/service/impl/AuthServiceImpl.java @@ -0,0 +1,211 @@ +package com.edgareldy.quarkustutorial.service.impl; + +import com.edgareldy.quarkustutorial.dto.auth.AuthResponse; +import com.edgareldy.quarkustutorial.dto.auth.LoginRequest; +import com.edgareldy.quarkustutorial.dto.auth.RegisterRequest; +import com.edgareldy.quarkustutorial.dto.auth.UserResponse; +import com.edgareldy.quarkustutorial.entity.ActivationToken; +import com.edgareldy.quarkustutorial.entity.BlacklistedToken; +import com.edgareldy.quarkustutorial.entity.PasswordResetToken; +import com.edgareldy.quarkustutorial.entity.User; +import com.edgareldy.quarkustutorial.exception.AuthenticationFailedException; +import com.edgareldy.quarkustutorial.exception.BusinessRuleException; +import com.edgareldy.quarkustutorial.exception.ResourceNotFoundException; +import com.edgareldy.quarkustutorial.repository.ActivationTokenRepository; +import com.edgareldy.quarkustutorial.repository.BlacklistedTokenRepository; +import com.edgareldy.quarkustutorial.repository.PasswordResetTokenRepository; +import com.edgareldy.quarkustutorial.repository.UserRepository; +import com.edgareldy.quarkustutorial.security.JwtIssuer; +import com.edgareldy.quarkustutorial.service.AuthService; +import io.quarkus.elytron.security.common.BcryptUtil; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import jakarta.transaction.Transactional; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.time.Duration; +import java.time.Instant; +import java.util.Base64; +import java.util.HexFormat; +import org.jboss.logging.Logger; + +/** + * Default AuthService: registration, activation, login, logout and password reset. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +@ApplicationScoped +public class AuthServiceImpl implements AuthService { + + private static final Logger LOG = Logger.getLogger(AuthServiceImpl.class); + + private static final Duration ACTIVATION_TTL = Duration.ofHours(24); + private static final Duration RESET_TTL = Duration.ofMinutes(30); + private static final String INVALID_CREDENTIALS = "Invalid email or password"; + private static final String INVALID_TOKEN = "The token is invalid, expired or already used"; + private static final SecureRandom RANDOM = new SecureRandom(); + // Computed once: verifying against it burns the same bcrypt time as a real check when the email is + // unknown, so response timing does not reveal whether an account exists. + private static final String DUMMY_HASH = BcryptUtil.bcryptHash("timing-equalizer"); + + @Inject + UserRepository userRepository; + + @Inject + ActivationTokenRepository activationTokenRepository; + + @Inject + PasswordResetTokenRepository passwordResetTokenRepository; + + @Inject + BlacklistedTokenRepository blacklistedTokenRepository; + + @Inject + JwtIssuer jwtIssuer; + + // @Transactional (Jakarta Transactions, on the implementation): the method runs in one database + // transaction that commits on return and rolls back on a runtime exception, so a user and its + // activation token are saved together or not at all. Later write methods just repeat it. + @Override + @Transactional + public UserResponse register(RegisterRequest request) { + if (userRepository.findByEmail(request.email()).isPresent()) { + throw new BusinessRuleException("An account with this email already exists"); + } + User user = new User(); + user.setFirstName(request.firstName()); + user.setLastName(request.lastName()); + user.setEmail(request.email().toLowerCase()); + // BcryptUtil (quarkus-elytron-security-common) produces a salted, self-describing bcrypt hash. + user.setPassword(BcryptUtil.bcryptHash(request.password())); + user.setEnabled(false); + user.setAccountLocked(false); + userRepository.persist(user); + + String rawToken = newRawToken(); + ActivationToken token = new ActivationToken(); + token.setUser(user); + token.setToken(sha256Hex(rawToken)); + token.setCreatedAt(Instant.now()); + token.setExpiresAt(Instant.now().plus(ACTIVATION_TTL)); + activationTokenRepository.persist(token); + + // This tutorial has no mail sender: the raw token is delivered by logging it. A real + // application would email a link containing it instead. Only the hash is stored. + LOG.infof("Activation token for %s (valid 24h): %s", user.getEmail(), rawToken); + return toResponse(user); + } + + @Override + @Transactional + public void activateAccount(String rawToken) { + ActivationToken token = activationTokenRepository.findByToken(sha256Hex(rawToken)) + .filter(t -> t.getValidatedAt() == null && t.getExpiresAt().isAfter(Instant.now())) + .orElseThrow(() -> new BusinessRuleException(INVALID_TOKEN)); + token.setValidatedAt(Instant.now()); + token.getUser().setEnabled(true); + } + + @Override + public AuthResponse login(LoginRequest request) { + User user = userRepository.findByEmail(request.email()).orElse(null); + // Password first, always: unknown email still pays one bcrypt verification against a dummy hash. + boolean passwordOk; + if (user != null) { + passwordOk = BcryptUtil.matches(request.password(), user.getPassword()); + } else { + BcryptUtil.matches(request.password(), DUMMY_HASH); + passwordOk = false; + } + if (!passwordOk) { + throw new AuthenticationFailedException(INVALID_CREDENTIALS); + } + // Only reached with the correct password, so this does not leak which emails exist. + if (!user.isEnabled() || user.isAccountLocked()) { + throw new AuthenticationFailedException("The account is not activated or is locked"); + } + return jwtIssuer.issue(user); + } + + @Override + @Transactional + public void logout(String jti, Long userId, Instant expiresAt) { + if (blacklistedTokenRepository.existsByJti(jti)) { + return; + } + BlacklistedToken entry = new BlacklistedToken(); + entry.setUser(userRepository.findById(userId)); + entry.setToken(jti); + entry.setJti(jti); + entry.setBlacklistedAt(Instant.now()); + entry.setCreatedAt(Instant.now()); + entry.setExpiresAt(expiresAt); + blacklistedTokenRepository.persist(entry); + } + + @Override + public UserResponse me(Long userId) { + User user = userRepository.findById(userId); + if (user == null) { + throw new ResourceNotFoundException("User " + userId + " not found"); + } + return toResponse(user); + } + + @Override + @Transactional + public void forgotPassword(String email) { + User user = userRepository.findByEmail(email).orElse(null); + // Same work whether or not the account exists (no early return): generate and hash a token. + String rawToken = newRawToken(); + String hash = sha256Hex(rawToken); + if (user == null) { + return; + } + passwordResetTokenRepository.delete("user", user); + PasswordResetToken token = new PasswordResetToken(); + token.setUser(user); + token.setToken(hash); + token.setType(PasswordResetToken.TYPE_PASSWORD_RESET); + token.setExpiryDate(Instant.now().plus(RESET_TTL)); + passwordResetTokenRepository.persist(token); + // No mail sender in this tutorial: delivered by log line, as for activation tokens. + LOG.infof("Password reset token for %s (valid 30 min, single use): %s", user.getEmail(), rawToken); + } + + @Override + @Transactional + public void resetPassword(String rawToken, String newPassword) { + PasswordResetToken token = passwordResetTokenRepository.findByToken(sha256Hex(rawToken)) + .filter(t -> t.getExpiryDate().isAfter(Instant.now())) + .orElseThrow(() -> new BusinessRuleException(INVALID_TOKEN)); + token.getUser().setPassword(BcryptUtil.bcryptHash(newPassword)); + // Single use: the token row is deleted once consumed. + passwordResetTokenRepository.delete(token); + } + + private static UserResponse toResponse(User user) { + return new UserResponse(user.getId(), user.getFirstName(), user.getLastName(), user.getEmail(), user.isEnabled()); + } + + /** 256 bits from SecureRandom, URL-safe Base64 without padding. */ + private static String newRawToken() { + byte[] bytes = new byte[32]; + RANDOM.nextBytes(bytes); + return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); + } + + private static String sha256Hex(String value) { + try { + return HexFormat.of().formatHex( + MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8))); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException("SHA-256 is always available", e); + } + } +} From 53c1202b0c27930bb0bc81bdf441fe451547c79c Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 08:44:56 +0400 Subject: [PATCH 044/158] feat(security): add a filter rejecting revoked tokens By the time a JAX-RS request filter runs, Quarkus has already checked the signature and expiry of the token. The filter adds what a stateless token cannot do alone: it looks the jti up in the blacklist and refuses a token that was revoked by logout. Throwing the HttpProblem from the filter is enough for it to be rendered as a 401 Problem Details document, so revoked tokens get the same error shape as invalid credentials. --- .../security/BlacklistedTokenFilter.java | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/security/BlacklistedTokenFilter.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/security/BlacklistedTokenFilter.java b/src/main/java/com/edgareldy/quarkustutorial/security/BlacklistedTokenFilter.java new file mode 100644 index 0000000..2159b1f --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/security/BlacklistedTokenFilter.java @@ -0,0 +1,40 @@ +package com.edgareldy.quarkustutorial.security; + +import com.edgareldy.quarkustutorial.exception.AuthenticationFailedException; +import com.edgareldy.quarkustutorial.repository.BlacklistedTokenRepository; +import io.quarkus.security.identity.SecurityIdentity; +import jakarta.inject.Inject; +import jakarta.ws.rs.container.ContainerRequestContext; +import jakarta.ws.rs.container.ContainerRequestFilter; +import jakarta.ws.rs.ext.Provider; +import org.eclipse.microprofile.jwt.JsonWebToken; + +/** + * Rejects requests whose (otherwise valid) JWT has been revoked by logout. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +// A JAX-RS ContainerRequestFilter runs after Quarkus has already validated the JWT signature and +// expiry, so it only has to add the revocation check that a stateless JWT cannot do on its own. +// Throwing an HttpProblem here is rendered by quarkus-http-problem as application/problem+json. +@Provider +public class BlacklistedTokenFilter implements ContainerRequestFilter { + + @Inject + SecurityIdentity identity; + + @Inject + BlacklistedTokenRepository blacklistedTokenRepository; + + @Override + public void filter(ContainerRequestContext requestContext) { + if (!identity.isAnonymous() && identity.getPrincipal() instanceof JsonWebToken jwt + && jwt.getTokenID() != null + && blacklistedTokenRepository.existsByJti(jwt.getTokenID())) { + throw new AuthenticationFailedException("The token has been revoked"); + } + } +} From 1491c52bc2f6ad3ce2746bbee339a6a8fac9dd2b Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 08:44:56 +0400 Subject: [PATCH 045/158] feat(config): declare the JWT bearer security scheme for OpenAPI The scheme is declared once and referenced by name on protected endpoints. Swagger UI then shows an Authorize button where a token can be pasted, so protected endpoints can be tried from the documentation page. Declaring it in a dedicated class keeps the resources free of documentation plumbing. --- .../quarkustutorial/config/OpenApiConfig.java | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/config/OpenApiConfig.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/config/OpenApiConfig.java b/src/main/java/com/edgareldy/quarkustutorial/config/OpenApiConfig.java new file mode 100644 index 0000000..805a1a3 --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/config/OpenApiConfig.java @@ -0,0 +1,17 @@ +package com.edgareldy.quarkustutorial.config; + +import org.eclipse.microprofile.openapi.annotations.enums.SecuritySchemeType; +import org.eclipse.microprofile.openapi.annotations.security.SecurityScheme; + +/** + * Declares the bearer JWT security scheme once so Swagger UI offers the Authorize button. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +// Protected resources reference this scheme by name with @SecurityRequirement(name = "jwt"). +@SecurityScheme(securitySchemeName = "jwt", type = SecuritySchemeType.HTTP, scheme = "bearer", bearerFormat = "JWT") +public class OpenApiConfig { +} From 377eeacce4ffb9c0ac7436ed86c9f5bb2d8b3d18 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 08:44:56 +0400 Subject: [PATCH 046/158] feat(resource): add AuthResource with the authentication endpoints The resource only validates input, delegates to the service and wraps the result in the success envelope. Public endpoints are marked with @PermitAll and the two that need a logged in user with @Authenticated, so access rules are declared on the method and there is no permission check inside a method body. The JSON consumption declaration sits on the methods that read a body rather than on the class: on the class it made the body less logout endpoint answer 415 to a client that sent no Content-Type header. --- .../resource/AuthResource.java | 111 ++++++++++++++++++ 1 file changed, 111 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/resource/AuthResource.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/resource/AuthResource.java b/src/main/java/com/edgareldy/quarkustutorial/resource/AuthResource.java new file mode 100644 index 0000000..80d85e1 --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/resource/AuthResource.java @@ -0,0 +1,111 @@ +package com.edgareldy.quarkustutorial.resource; + +import com.edgareldy.quarkustutorial.dto.auth.AuthResponse; +import com.edgareldy.quarkustutorial.dto.auth.ForgotPasswordRequest; +import com.edgareldy.quarkustutorial.dto.auth.LoginRequest; +import com.edgareldy.quarkustutorial.dto.auth.RegisterRequest; +import com.edgareldy.quarkustutorial.dto.auth.ResetPasswordRequest; +import com.edgareldy.quarkustutorial.dto.auth.UserResponse; +import com.edgareldy.quarkustutorial.dto.common.ApiResponse; +import com.edgareldy.quarkustutorial.service.AuthService; +import jakarta.annotation.security.PermitAll; +import jakarta.inject.Inject; +import jakarta.validation.Valid; +import jakarta.validation.constraints.NotBlank; +import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.QueryParam; +import jakarta.ws.rs.core.MediaType; +import java.time.Instant; +import org.eclipse.microprofile.jwt.JsonWebToken; +import org.eclipse.microprofile.openapi.annotations.security.SecurityRequirement; +import org.jboss.resteasy.reactive.ResponseStatus; +import io.quarkus.security.Authenticated; + +/** + * REST endpoints for registration, activation, login, logout, profile and password reset. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +// Thin resource: Bean Validation on the body, delegate to AuthService, wrap in ApiResponse. +// @PermitAll / @Authenticated are declarative security annotations enforced by Quarkus before the +// method runs: public endpoints are opened explicitly, protected ones require a valid JWT. +@Path("/api/v1/auth") +@Produces(MediaType.APPLICATION_JSON) +public class AuthResource { + + @Inject + AuthService authService; + + // The validated JWT of the current request; the proxy is request scoped so a singleton can hold it. + @Inject + JsonWebToken jwt; + + @POST + @Path("/register") + @PermitAll + @Consumes(MediaType.APPLICATION_JSON) + @ResponseStatus(201) + public ApiResponse register(@Valid RegisterRequest request) { + return ApiResponse.success(authService.register(request), "Account created, activation required"); + } + + @GET + @Path("/activate-account") + @PermitAll + public ApiResponse activateAccount(@QueryParam("token") @NotBlank String token) { + authService.activateAccount(token); + return ApiResponse.success(null, "Account activated"); + } + + @POST + @Path("/login") + @PermitAll + @Consumes(MediaType.APPLICATION_JSON) + public ApiResponse login(@Valid LoginRequest request) { + return ApiResponse.success(authService.login(request), "Login successful"); + } + + @POST + @Path("/logout") + @Authenticated + @SecurityRequirement(name = "jwt") + public ApiResponse logout() { + authService.logout(jwt.getTokenID(), Long.valueOf(jwt.getSubject()), + Instant.ofEpochSecond(jwt.getExpirationTime())); + return ApiResponse.success(null, "Logged out"); + } + + @GET + @Path("/me") + @Authenticated + @SecurityRequirement(name = "jwt") + public ApiResponse me() { + return ApiResponse.success(authService.me(Long.valueOf(jwt.getSubject())), "Current user"); + } + + @POST + @Path("/forgot-password") + @PermitAll + @Consumes(MediaType.APPLICATION_JSON) + public ApiResponse forgotPassword(@Valid ForgotPasswordRequest request) { + authService.forgotPassword(request.email()); + // Identical answer whether or not the email is registered. + return ApiResponse.success(null, "If the email is registered, a reset token has been issued"); + } + + @POST + @Path("/reset-password") + @PermitAll + @Consumes(MediaType.APPLICATION_JSON) + public ApiResponse resetPassword(@Valid ResetPasswordRequest request) { + authService.resetPassword(request.token(), request.newPassword()); + return ApiResponse.success(null, "Password updated"); + } +} From a5959b4bebbee59247bfafb20481a0bfc87b6cbe Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 08:44:56 +0400 Subject: [PATCH 047/158] test(resource): cover the authentication flow end to end The tests walk the real flows over HTTP: register, activate, log in, read the profile, log out and see the same token refused, then the forgot and reset password flow with a single use token. They also check duplicate emails, invalid bodies, identical answers for an unknown email and a wrong password, and that errors are problem documents. Since there is no mail sender, the raw tokens are read from the log line the service emits, through a log handler removed after each test, so the flow stays end to end with no shortcut into the database. The logout call sends no Content-Type on purpose, as a regression check. --- .../resource/AuthResourceTest.java | 240 ++++++++++++++++++ 1 file changed, 240 insertions(+) create mode 100644 src/test/java/com/edgareldy/quarkustutorial/resource/AuthResourceTest.java diff --git a/src/test/java/com/edgareldy/quarkustutorial/resource/AuthResourceTest.java b/src/test/java/com/edgareldy/quarkustutorial/resource/AuthResourceTest.java new file mode 100644 index 0000000..d9a8e7e --- /dev/null +++ b/src/test/java/com/edgareldy/quarkustutorial/resource/AuthResourceTest.java @@ -0,0 +1,240 @@ +package com.edgareldy.quarkustutorial.resource; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.*; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.ValidatableResponse; +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Handler; +import java.util.logging.LogRecord; +import java.util.logging.Logger; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.jboss.logmanager.ExtLogRecord; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * End-to-end tests of the auth endpoints: register, activate, login, /me, logout and password reset. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +// @QuarkusTest boots the real application once (Dev Services provides PostgreSQL) and these tests call it +// over real HTTP with RestAssured, so filters, security and Problem Details rendering are all exercised. +// There is no mail sender, so raw tokens are read from the INFO log line the service emits, through a +// java.util.logging Handler: the flow stays fully end to end, with no shortcut into the database. +@QuarkusTest +class AuthResourceTest { + + private static final String PROBLEM_JSON = "application/problem+json"; + private static final String BASE = "/api/v1/auth"; + private static final String PASSWORD = "Str0ngPassw0rd!"; + + private final List logLines = new ArrayList<>(); + private final Logger serviceLogger = Logger.getLogger("com.edgareldy.quarkustutorial.service.impl.AuthServiceImpl"); + private Handler handler; + + // Collects the formatted messages the auth service logs, so the raw tokens can be read back. + @BeforeEach + void attachHandler() { + handler = new Handler() { + @Override + public void publish(LogRecord record) { + String message = record instanceof ExtLogRecord ext ? ext.getFormattedMessage() : record.getMessage(); + synchronized (logLines) { + logLines.add(message); + } + } + + @Override + public void flush() { + } + + @Override + public void close() { + } + }; + serviceLogger.addHandler(handler); + } + + @AfterEach + void detachHandler() { + serviceLogger.removeHandler(handler); + } + + @Test + void fullFlowRegisterActivateLoginMeLogout() { + String email = uniqueEmail(); + register(email, PASSWORD).statusCode(201) + .contentType("application/json") + .body("success", is(true)) + .body("timestamp", notNullValue()) + .body("data.email", is(email)) + .body("data.enabled", is(false)) + .body("data", not(hasKey("password"))); + + String activation = capture("Activation token for " + email + " \\(valid 24h\\): (\\S+)"); + given().queryParam("token", activation).when().get(BASE + "/activate-account") + .then().statusCode(200) + .body("success", is(true)) + .body("timestamp", notNullValue()); + + String jwt = login(email, PASSWORD).statusCode(200) + .body("success", is(true)) + .body("timestamp", notNullValue()) + .body("data.tokenType", is("Bearer")) + .body("data.expiresIn", is(3600)) + .extract().path("data.token"); + assertNotNull(jwt); + + String me = given().auth().oauth2(jwt).when().get(BASE + "/me") + .then().statusCode(200) + .body("success", is(true)) + .body("timestamp", notNullValue()) + .body("data.email", is(email)) + .body("data.firstName", is("Ada")) + .body("data.enabled", is(true)) + .body("data", not(hasKey("password"))) + .extract().asString(); + org.junit.jupiter.api.Assertions.assertFalse(me.toLowerCase().contains("password"), me); + + // Deliberately no Content-Type: logout has no body, so it must not demand one (regression: a + // class-level @Consumes used to make it answer 415). + given().auth().oauth2(jwt).when().post(BASE + "/logout") + .then().statusCode(200).body("success", is(true)); + + // The very same token, still unexpired, is now revoked. + given().auth().oauth2(jwt).when().get(BASE + "/me") + .then().statusCode(401) + .contentType(PROBLEM_JSON) + .body("status", is(401)) + .body("$", not(hasKey("success"))); + } + + @Test + void forgotAndResetPasswordFlowIsSingleUse() { + String email = registerAndActivate(); + + given().contentType("application/json").body("{\"email\":\"" + email + "\"}") + .when().post(BASE + "/forgot-password") + .then().statusCode(200).body("success", is(true)); + String reset = capture("Password reset token for " + email + " .*: (\\S+)"); + + resetPassword(reset, "N3wPassw0rd!!").statusCode(200).body("success", is(true)); + + login(email, PASSWORD).statusCode(401).contentType(PROBLEM_JSON); + login(email, "N3wPassw0rd!!").statusCode(200).body("data.token", notNullValue()); + + resetPassword(reset, "Another0ne!!!").statusCode(422) + .contentType(PROBLEM_JSON) + .body("status", is(422)) + .body("$", not(hasKey("success"))); + } + + @Test + void registerDuplicateEmailIs422() { + String email = uniqueEmail(); + register(email, PASSWORD).statusCode(201); + register(email, PASSWORD).statusCode(422) + .contentType(PROBLEM_JSON) + .body("status", is(422)) + .body("$", not(hasKey("success"))); + } + + @Test + void registerWithInvalidBodyIs400WithViolations() { + given().contentType("application/json") + .body("{\"firstName\":\"\",\"lastName\":\"L\",\"email\":\"not-an-email\",\"password\":\"short\"}") + .when().post(BASE + "/register") + .then().statusCode(400) + .contentType(PROBLEM_JSON) + .body("status", is(400)) + .body("violations", not(empty())) + .body("$", not(hasKey("success"))); + } + + @Test + void loginUnknownEmailAndWrongPasswordAreIndistinguishable() { + String email = registerAndActivate(); + ValidatableResponse unknown = login(uniqueEmail(), PASSWORD).statusCode(401).contentType(PROBLEM_JSON); + ValidatableResponse wrong = login(email, "WrongPassw0rd!!").statusCode(401).contentType(PROBLEM_JSON); + org.junit.jupiter.api.Assertions.assertEquals( + unknown.extract().asString(), wrong.extract().asString()); + unknown.body("detail", is("Invalid email or password")); + } + + @Test + void loginBeforeActivationIs401() { + String email = uniqueEmail(); + register(email, PASSWORD).statusCode(201); + login(email, PASSWORD).statusCode(401) + .contentType(PROBLEM_JSON) + .body("status", is(401)) + .body("$", not(hasKey("success"))); + } + + @Test + void meWithoutTokenIs401() { + given().when().get(BASE + "/me").then().statusCode(401); + } + + @Test + void activateWithBadTokenIs422() { + given().queryParam("token", "definitely-not-a-real-token").when().get(BASE + "/activate-account") + .then().statusCode(422) + .contentType(PROBLEM_JSON) + .body("status", is(422)) + .body("$", not(hasKey("success"))); + } + + private static String uniqueEmail() { + return "user" + System.nanoTime() + "@example.com"; + } + + private ValidatableResponse register(String email, String password) { + return given().contentType("application/json") + .body("{\"firstName\":\"Ada\",\"lastName\":\"Lovelace\",\"email\":\"" + email + + "\",\"password\":\"" + password + "\"}") + .when().post(BASE + "/register").then(); + } + + private static ValidatableResponse login(String email, String password) { + return given().contentType("application/json") + .body("{\"email\":\"" + email + "\",\"password\":\"" + password + "\"}") + .when().post(BASE + "/login").then(); + } + + private static ValidatableResponse resetPassword(String token, String newPassword) { + return given().contentType("application/json") + .body("{\"token\":\"" + token + "\",\"newPassword\":\"" + newPassword + "\"}") + .when().post(BASE + "/reset-password").then(); + } + + private String registerAndActivate() { + String email = uniqueEmail(); + register(email, PASSWORD).statusCode(201); + String token = capture("Activation token for " + email + " \\(valid 24h\\): (\\S+)"); + given().queryParam("token", token).when().get(BASE + "/activate-account").then().statusCode(200); + return email; + } + + private String capture(String regex) { + Pattern pattern = Pattern.compile(regex); + synchronized (logLines) { + for (String line : logLines) { + Matcher m = pattern.matcher(line); + if (m.find()) { + return m.group(1); + } + } + } + throw new AssertionError("No log line matched " + regex + " in " + logLines); + } +} From e0977a4adda08b8f03bb2d91bd026e9487c38f25 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 08:44:56 +0400 Subject: [PATCH 048/158] test(resource): prove forgot password does not reveal registered emails The endpoint must answer the same way for a registered and an unregistered email, otherwise it becomes a way to list accounts. The test compares status and body, ignoring the timestamp, and checks that the unregistered case creates no reset token row. Testing the observable answer, not the implementation, keeps the guarantee even if the service is rewritten. --- .../ForgotPasswordEnumerationTest.java | 66 +++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 src/test/java/com/edgareldy/quarkustutorial/resource/ForgotPasswordEnumerationTest.java diff --git a/src/test/java/com/edgareldy/quarkustutorial/resource/ForgotPasswordEnumerationTest.java b/src/test/java/com/edgareldy/quarkustutorial/resource/ForgotPasswordEnumerationTest.java new file mode 100644 index 0000000..8773f39 --- /dev/null +++ b/src/test/java/com/edgareldy/quarkustutorial/resource/ForgotPasswordEnumerationTest.java @@ -0,0 +1,66 @@ +package com.edgareldy.quarkustutorial.resource; + +import static io.restassured.RestAssured.given; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import com.edgareldy.quarkustutorial.repository.PasswordResetTokenRepository; +import io.quarkus.narayana.jta.QuarkusTransaction; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.Response; +import jakarta.inject.Inject; +import java.util.HashMap; +import java.util.Map; +import org.junit.jupiter.api.Test; + +/** + * Proves forgot-password does not reveal whether an email is registered. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +@QuarkusTest +class ForgotPasswordEnumerationTest { + + private static final String BASE = "/api/v1/auth"; + + // Counting rows needs a transaction; QuarkusTransaction runs one around a lambda from test code. + @Inject + PasswordResetTokenRepository resetTokens; + + @Test + void registeredAndUnregisteredEmailsGetTheSameAnswer() { + String known = "known" + System.nanoTime() + "@example.com"; + given().contentType("application/json") + .body("{\"firstName\":\"A\",\"lastName\":\"B\",\"email\":\"" + known + "\",\"password\":\"Str0ngPassw0rd!\"}") + .when().post(BASE + "/register").then().statusCode(201); + + long before = count(); + Response registered = forgot(known); + assertEquals(before + 1, count(), "a registered email gets a reset token"); + + before = count(); + Response unknown = forgot("ghost" + System.nanoTime() + "@example.com"); + assertEquals(before, count(), "an unregistered email must create no reset token"); + + assertEquals(200, registered.statusCode()); + assertEquals(registered.statusCode(), unknown.statusCode()); + assertEquals(withoutTimestamp(registered), withoutTimestamp(unknown)); + } + + private long count() { + return QuarkusTransaction.requiringNew().call(() -> resetTokens.count()); + } + + private static Response forgot(String email) { + return given().contentType("application/json").body("{\"email\":\"" + email + "\"}") + .when().post(BASE + "/forgot-password"); + } + + private static Map withoutTimestamp(Response response) { + Map body = new HashMap<>(response.jsonPath().getMap("$")); + body.remove("timestamp"); + return body; + } +} From 44c12b40d4e2b45aa068e6b29b13574b54f882f9 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 08:44:56 +0400 Subject: [PATCH 049/158] test(service): unit test the AuthService rules with Mockito Rules that are hard to reach through HTTP are tested directly with mocked repositories: an unknown email fails with the same message as a wrong password, a duplicate registration is refused, expired tokens are rejected and logout does not persist twice. Plain Mockito is used because the service has no need for the container here, which keeps these tests fast and focused on one class. --- .../service/impl/AuthServiceImplTest.java | 122 ++++++++++++++++++ 1 file changed, 122 insertions(+) create mode 100644 src/test/java/com/edgareldy/quarkustutorial/service/impl/AuthServiceImplTest.java diff --git a/src/test/java/com/edgareldy/quarkustutorial/service/impl/AuthServiceImplTest.java b/src/test/java/com/edgareldy/quarkustutorial/service/impl/AuthServiceImplTest.java new file mode 100644 index 0000000..4d12a7e --- /dev/null +++ b/src/test/java/com/edgareldy/quarkustutorial/service/impl/AuthServiceImplTest.java @@ -0,0 +1,122 @@ +package com.edgareldy.quarkustutorial.service.impl; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +import com.edgareldy.quarkustutorial.dto.auth.LoginRequest; +import com.edgareldy.quarkustutorial.dto.auth.RegisterRequest; +import com.edgareldy.quarkustutorial.entity.ActivationToken; +import com.edgareldy.quarkustutorial.entity.BlacklistedToken; +import com.edgareldy.quarkustutorial.entity.PasswordResetToken; +import com.edgareldy.quarkustutorial.entity.User; +import com.edgareldy.quarkustutorial.exception.AuthenticationFailedException; +import com.edgareldy.quarkustutorial.exception.BusinessRuleException; +import com.edgareldy.quarkustutorial.repository.ActivationTokenRepository; +import com.edgareldy.quarkustutorial.repository.BlacklistedTokenRepository; +import com.edgareldy.quarkustutorial.repository.PasswordResetTokenRepository; +import com.edgareldy.quarkustutorial.repository.UserRepository; +import com.edgareldy.quarkustutorial.security.JwtIssuer; +import io.quarkus.elytron.security.common.BcryptUtil; +import java.time.Instant; +import java.util.Optional; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * Isolated unit tests of AuthServiceImpl with every collaborator mocked. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +// Plain Mockito rather than @QuarkusTest: no container or database is needed to test the service logic, +// so the suite stays fast. The injected fields are package-private and this test lives in the same +// package, so they are assigned directly, without reflection or CDI. +class AuthServiceImplTest { + + private UserRepository users; + private ActivationTokenRepository activations; + private PasswordResetTokenRepository resets; + private BlacklistedTokenRepository blacklist; + private AuthServiceImpl service; + + @BeforeEach + void setUp() { + users = mock(UserRepository.class); + activations = mock(ActivationTokenRepository.class); + resets = mock(PasswordResetTokenRepository.class); + blacklist = mock(BlacklistedTokenRepository.class); + service = new AuthServiceImpl(); + service.userRepository = users; + service.activationTokenRepository = activations; + service.passwordResetTokenRepository = resets; + service.blacklistedTokenRepository = blacklist; + service.jwtIssuer = mock(JwtIssuer.class); + } + + @Test + void loginUnknownEmailFailsWithSameMessageAsWrongPassword() { + User user = new User(); + user.setPassword(BcryptUtil.bcryptHash("Correct-horse-1")); + user.setEnabled(true); + when(users.findByEmail("known@example.com")).thenReturn(Optional.of(user)); + when(users.findByEmail("ghost@example.com")).thenReturn(Optional.empty()); + + AuthenticationFailedException wrong = assertThrows(AuthenticationFailedException.class, + () -> service.login(new LoginRequest("known@example.com", "bad-password"))); + AuthenticationFailedException unknown = assertThrows(AuthenticationFailedException.class, + () -> service.login(new LoginRequest("ghost@example.com", "bad-password"))); + + assertEquals(wrong.getMessage(), unknown.getMessage()); + assertEquals(wrong.getStatusCode(), unknown.getStatusCode()); + assertEquals(401, unknown.getStatusCode()); + } + + @Test + void registerDuplicateThrowsBusinessRule() { + when(users.findByEmail("dup@example.com")).thenReturn(Optional.of(new User())); + assertThrows(BusinessRuleException.class, + () -> service.register(new RegisterRequest("A", "B", "dup@example.com", "Str0ngPassw0rd!"))); + verify(users, never()).persist(any(User.class)); + } + + @Test + void activateAccountWithExpiredTokenIsRejected() { + ActivationToken token = new ActivationToken(); + User user = new User(); + token.setUser(user); + token.setExpiresAt(Instant.now().minusSeconds(60)); + when(activations.findByToken(any())).thenReturn(Optional.of(token)); + + assertThrows(BusinessRuleException.class, () -> service.activateAccount("raw")); + assertFalse(user.isEnabled()); + assertNull(token.getValidatedAt()); + } + + @Test + void logoutIsIdempotent() { + when(blacklist.existsByJti("jti-1")).thenReturn(false, true); + when(users.findById(7L)).thenReturn(new User()); + + service.logout("jti-1", 7L, Instant.now().plusSeconds(600)); + service.logout("jti-1", 7L, Instant.now().plusSeconds(600)); + + verify(blacklist, times(1)).persist(any(BlacklistedToken.class)); + } + + @Test + void resetPasswordWithExpiredTokenIsRejected() { + PasswordResetToken token = new PasswordResetToken(); + User user = new User(); + user.setPassword("old-hash"); + token.setUser(user); + token.setExpiryDate(Instant.now().minusSeconds(60)); + when(resets.findByToken(any())).thenReturn(Optional.of(token)); + + assertThrows(BusinessRuleException.class, () -> service.resetPassword("raw", "N3wPassw0rd!!")); + assertEquals("old-hash", user.getPassword()); + verify(resets, never()).delete(any(PasswordResetToken.class)); + } +} From 8885c31f93290ba9cf0fac8a91ff5cb10d445a11 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 08:44:56 +0400 Subject: [PATCH 050/158] test(repository): check the user and token queries against PostgreSQL Repository tests run against the real database that Dev Services starts, since queries and constraints are exactly what a mock cannot verify. They cover the case insensitive email lookup, the unique email violation and the token finders. No container is declared in the test: Dev Services provisions the database on its own. --- .../repository/UserRepositoryTest.java | 109 ++++++++++++++++++ 1 file changed, 109 insertions(+) create mode 100644 src/test/java/com/edgareldy/quarkustutorial/repository/UserRepositoryTest.java diff --git a/src/test/java/com/edgareldy/quarkustutorial/repository/UserRepositoryTest.java b/src/test/java/com/edgareldy/quarkustutorial/repository/UserRepositoryTest.java new file mode 100644 index 0000000..4835524 --- /dev/null +++ b/src/test/java/com/edgareldy/quarkustutorial/repository/UserRepositoryTest.java @@ -0,0 +1,109 @@ +package com.edgareldy.quarkustutorial.repository; + +import static org.junit.jupiter.api.Assertions.*; + +import com.edgareldy.quarkustutorial.entity.ActivationToken; +import com.edgareldy.quarkustutorial.entity.BlacklistedToken; +import com.edgareldy.quarkustutorial.entity.PasswordResetToken; +import com.edgareldy.quarkustutorial.entity.User; +import io.quarkus.narayana.jta.QuarkusTransaction; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import java.time.Instant; +import org.junit.jupiter.api.Test; + +/** + * Repository tests against a real PostgreSQL provided by Dev Services: user lookup and token repositories. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +// Dev Services: no datasource URL is configured for the test profile, so Quarkus starts a PostgreSQL +// container by itself and Flyway builds the real schema in it. There is deliberately no Testcontainers +// code here. QuarkusTransaction wraps each database interaction in a transaction started from test code. +@QuarkusTest +class UserRepositoryTest { + + @Inject + UserRepository users; + @Inject + ActivationTokenRepository activations; + @Inject + PasswordResetTokenRepository resets; + @Inject + BlacklistedTokenRepository blacklist; + + private User newUser(String email) { + User u = new User(); + u.setFirstName("A"); + u.setLastName("B"); + u.setEmail(email); + u.setPassword("hash"); + return u; + } + + @Test + void findByEmailIsCaseInsensitive() { + String email = "mixed" + System.nanoTime() + "@example.com"; + QuarkusTransaction.requiringNew().run(() -> users.persist(newUser(email))); + QuarkusTransaction.requiringNew().run(() -> { + assertTrue(users.findByEmail(email.toUpperCase()).isPresent()); + assertTrue(users.findByEmail(email).isPresent()); + assertTrue(users.findByEmail("nobody" + System.nanoTime() + "@example.com").isEmpty()); + }); + } + + @Test + void duplicateEmailViolatesUniqueConstraint() { + String email = "dup" + System.nanoTime() + "@example.com"; + QuarkusTransaction.requiringNew().run(() -> users.persist(newUser(email))); + assertThrows(RuntimeException.class, + () -> QuarkusTransaction.requiringNew().run(() -> { + users.persist(newUser(email)); + users.flush(); + })); + } + + @Test + void tokenRepositoriesFindTheirRows() { + long n = System.nanoTime(); + String email = "tok" + n + "@example.com"; + QuarkusTransaction.requiringNew().run(() -> { + User u = newUser(email); + users.persist(u); + + ActivationToken a = new ActivationToken(); + a.setUser(u); + a.setToken("act-" + n); + a.setCreatedAt(Instant.now()); + a.setExpiresAt(Instant.now().plusSeconds(60)); + activations.persist(a); + + PasswordResetToken r = new PasswordResetToken(); + r.setUser(u); + r.setToken("rst-" + n); + r.setType(PasswordResetToken.TYPE_PASSWORD_RESET); + r.setExpiryDate(Instant.now().plusSeconds(60)); + resets.persist(r); + + BlacklistedToken b = new BlacklistedToken(); + b.setUser(u); + b.setToken("jti-" + n); + b.setJti("jti-" + n); + b.setBlacklistedAt(Instant.now()); + b.setCreatedAt(Instant.now()); + b.setExpiresAt(Instant.now().plusSeconds(60)); + blacklist.persist(b); + }); + QuarkusTransaction.requiringNew().run(() -> { + assertTrue(activations.findByToken("act-" + n).isPresent()); + assertTrue(activations.findByToken("missing-" + n).isEmpty()); + assertTrue(resets.findByToken("rst-" + n).isPresent()); + assertTrue(resets.findByToken("missing-" + n).isEmpty()); + assertTrue(blacklist.existsByJti("jti-" + n)); + assertFalse(blacklist.existsByJti("other-" + n)); + }); + } +} From 508c75c51df5e898a6c89778123e78081e4df7ac Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 08:44:56 +0400 Subject: [PATCH 051/158] test(security): verify the tokens issued by JwtIssuer The test parses an issued token with the public key, checks the subject, the issuer and that the expiry matches the reported lifetime, and checks that two tokens never share a jti, since revocation depends on that uniqueness. This ties the issuer to the verification configuration, so a mismatch between the signing and verifying keys is caught by the build. --- .../security/JwtIssuerTest.java | 74 +++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 src/test/java/com/edgareldy/quarkustutorial/security/JwtIssuerTest.java diff --git a/src/test/java/com/edgareldy/quarkustutorial/security/JwtIssuerTest.java b/src/test/java/com/edgareldy/quarkustutorial/security/JwtIssuerTest.java new file mode 100644 index 0000000..751afb6 --- /dev/null +++ b/src/test/java/com/edgareldy/quarkustutorial/security/JwtIssuerTest.java @@ -0,0 +1,74 @@ +package com.edgareldy.quarkustutorial.security; + +import static org.junit.jupiter.api.Assertions.*; + +import com.edgareldy.quarkustutorial.dto.auth.AuthResponse; +import com.edgareldy.quarkustutorial.entity.User; +import io.quarkus.test.junit.QuarkusTest; +import io.smallrye.jwt.auth.principal.JWTParser; +import jakarta.inject.Inject; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyFactory; +import java.security.PublicKey; +import java.security.spec.X509EncodedKeySpec; +import java.util.Base64; +import org.eclipse.microprofile.jwt.JsonWebToken; +import org.junit.jupiter.api.Test; + +/** + * Verifies the tokens JwtIssuer signs: signature, subject, unique jti, issuer and expiry. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +// @QuarkusTest so the issuer gets its real configuration (dev private key, issuer, lifespan) injected. +@QuarkusTest +class JwtIssuerTest { + + private static final String ISSUER = "https://api.example.com/quarkus-tutorial"; + + @Inject + JwtIssuer issuer; + @Inject + JWTParser parser; + + private static User user(long id) { + User u = new User(); + u.setId(id); + return u; + } + + private static PublicKey devPublicKey() throws Exception { + String pem = Files.readString(Path.of("dev-keys/publicKey.pem")) + .replaceAll("-----[A-Z ]+-----", "").replaceAll("\\s", ""); + return KeyFactory.getInstance("RSA") + .generatePublic(new X509EncodedKeySpec(Base64.getDecoder().decode(pem))); + } + + @Test + void tokenVerifiesWithDevPublicKeyAndCarriesExpectedClaims() throws Exception { + long before = System.currentTimeMillis() / 1000; + AuthResponse response = issuer.issue(user(42L)); + + JsonWebToken jwt = parser.verify(response.token(), devPublicKey()); + assertEquals("42", jwt.getSubject()); + assertEquals(ISSUER, jwt.getIssuer()); + assertNotNull(jwt.getTokenID()); + assertEquals("Bearer", response.tokenType()); + assertEquals(3600L, response.expiresIn()); + long exp = jwt.getExpirationTime(); + assertTrue(exp >= before + response.expiresIn() && exp <= before + response.expiresIn() + 5, + "exp " + exp + " not consistent with expiresIn from " + before); + } + + @Test + void eachIssuedTokenHasAUniqueJti() throws Exception { + PublicKey key = devPublicKey(); + String first = parser.verify(issuer.issue(user(1L)).token(), key).getTokenID(); + String second = parser.verify(issuer.issue(user(1L)).token(), key).getTokenID(); + assertNotEquals(first, second); + } +} From 169c8d48402b95bbf0d3b164260fda59768a2a16 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 08:48:17 +0400 Subject: [PATCH 052/158] fix(service): reject logout for a deleted account and correct a misleading comment A token can outlive its account. Logging out with such a token used to fail on a missing user with a server error, and it now answers with the same 401 Problem Details as any invalid credential. The comment on forgotPassword claimed identical work for known and unknown emails, which was not true: only the token generation and hashing are shared, while the database writes happen for real accounts. The comment now says exactly that, so nobody relies on a guarantee the code does not give. --- .../quarkustutorial/service/impl/AuthServiceImpl.java | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/edgareldy/quarkustutorial/service/impl/AuthServiceImpl.java b/src/main/java/com/edgareldy/quarkustutorial/service/impl/AuthServiceImpl.java index 8a7ba1a..3003ba4 100644 --- a/src/main/java/com/edgareldy/quarkustutorial/service/impl/AuthServiceImpl.java +++ b/src/main/java/com/edgareldy/quarkustutorial/service/impl/AuthServiceImpl.java @@ -138,8 +138,13 @@ public void logout(String jti, Long userId, Instant expiresAt) { if (blacklistedTokenRepository.existsByJti(jti)) { return; } + User user = userRepository.findById(userId); + if (user == null) { + // The token is valid but its account was deleted since: treat it as an invalid credential. + throw new AuthenticationFailedException("The token no longer matches an account"); + } BlacklistedToken entry = new BlacklistedToken(); - entry.setUser(userRepository.findById(userId)); + entry.setUser(user); entry.setToken(jti); entry.setJti(jti); entry.setBlacklistedAt(Instant.now()); @@ -161,7 +166,9 @@ public UserResponse me(Long userId) { @Transactional public void forgotPassword(String email) { User user = userRepository.findByEmail(email).orElse(null); - // Same work whether or not the account exists (no early return): generate and hash a token. + // The token is generated and hashed whether or not the account exists, so the answer does not + // depend on it and the cryptographic work is identical. The database writes only happen for a + // real account, which leaves a small residual timing difference that the specification accepts. String rawToken = newRawToken(); String hash = sha256Hex(rawToken); if (user == null) { From a150c5ce5330c369451df8a7b724f20de86b3bb4 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 08:48:34 +0400 Subject: [PATCH 053/158] docs(readme): check off feature/auth and correct the BcryptUtil dependency note The feature/auth checklist is ticked now that every task is implemented and covered by the build. One statement was wrong: BcryptUtil is not available through quarkus-security as the task list said, it lives in quarkus-elytron-security-common, which the pom now declares explicitly. The note now says so, which saves the next reader from a compilation error and a search for a missing class. --- README.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index b9c9d47..43b278b 100644 --- a/README.md +++ b/README.md @@ -278,15 +278,15 @@ Example error response (`GET /api/v1/products/999` on a missing product): ### Tasks -- [ ] `User` entity, `ActivationToken`, `BlacklistedToken`, `PasswordResetToken` -- [ ] `UserRepository` (`PanacheRepository`) -- [ ] `AuthService` (interface) + implementation: registration, activation, login (password hashing/verification via `io.quarkus.elytron.security.common.BcryptUtil.bcryptHash`/`matches`, from `quarkus-elytron-security-common` - already on the classpath via `quarkus-security`, not an external library), logout, forgot/reset password -- [ ] `forgotPassword` returns the exact same response - same status code, same body, roughly the same timing (no early return skipping the token-generation work) - whether or not the submitted email matches an existing account, so the endpoint can't be used to enumerate registered emails -- [ ] `JwtIssuer`: builds a signed JWT (`io.smallrye.jwt.build.Jwt`) with a unique `jti` claim, the user's id as subject -- [ ] `@SecurityScheme(securitySchemeName = "jwt", type = SecuritySchemeType.HTTP, scheme = "bearer", bearerFormat = "JWT")` declared once (e.g. on `AuthResource` or a dedicated `OpenApiConfig` class) and referenced via `@SecurityRequirement(name = "jwt")` on protected resources, so Swagger UI's "Authorize" button actually works against `@PermissionsAllowed`-protected endpoints -- [ ] A `ContainerRequestFilter` (or `SecurityIdentityAugmentor`, same class introduced fully in `feature/rbac`) checking the incoming JWT's `jti` against `BlacklistedToken` and rejecting the request if found -- [ ] `AuthResource` -- [ ] Tests (`@QuarkusTest` + RestAssured): register → activate → login → access `/me`, logout followed by a rejected request with the same token, forgot/reset password flow +- [x] `User` entity, `ActivationToken`, `BlacklistedToken`, `PasswordResetToken` +- [x] `UserRepository` (`PanacheRepository`) +- [x] `AuthService` (interface) + implementation: registration, activation, login (password hashing/verification via `io.quarkus.elytron.security.common.BcryptUtil.bcryptHash`/`matches`, from `quarkus-elytron-security-common`, a Quarkus module declared explicitly in the pom because `quarkus-security` does not bring it in, not an external library), logout, forgot/reset password +- [x] `forgotPassword` returns the exact same response - same status code, same body, roughly the same timing (no early return skipping the token-generation work) - whether or not the submitted email matches an existing account, so the endpoint can't be used to enumerate registered emails +- [x] `JwtIssuer`: builds a signed JWT (`io.smallrye.jwt.build.Jwt`) with a unique `jti` claim, the user's id as subject +- [x] `@SecurityScheme(securitySchemeName = "jwt", type = SecuritySchemeType.HTTP, scheme = "bearer", bearerFormat = "JWT")` declared once (e.g. on `AuthResource` or a dedicated `OpenApiConfig` class) and referenced via `@SecurityRequirement(name = "jwt")` on protected resources, so Swagger UI's "Authorize" button actually works against `@PermissionsAllowed`-protected endpoints +- [x] A `ContainerRequestFilter` (or `SecurityIdentityAugmentor`, same class introduced fully in `feature/rbac`) checking the incoming JWT's `jti` against `BlacklistedToken` and rejecting the request if found +- [x] `AuthResource` +- [x] Tests (`@QuarkusTest` + RestAssured): register → activate → login → access `/me`, logout followed by a rejected request with the same token, forgot/reset password flow ## feature/rbac From bd01b4946144817df43672f07e9818dadd900417 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 09:23:00 +0400 Subject: [PATCH 054/158] feat(flyway): seed the baseline permissions and the ADMIN role Permissions are a fixed catalogue: CATEGORY:WRITE always means the same thing, and roles are composed out of them. This data migration inserts every resource and action pair the API defines and an ADMIN role holding all of them. Without it nobody could ever be granted ROLE:WRITE or PERMISSION:WRITE, so the first assignment could never be made. Each insert uses ON CONFLICT DO NOTHING, so running it against a database that already has some of the rows never duplicates them. Seed data goes in its own numbered migration rather than in V1 so the schema and the reference data keep separate histories. --- .../db/migration/V2__seed_baseline_rbac.sql | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 src/main/resources/db/migration/V2__seed_baseline_rbac.sql diff --git a/src/main/resources/db/migration/V2__seed_baseline_rbac.sql b/src/main/resources/db/migration/V2__seed_baseline_rbac.sql new file mode 100644 index 0000000..558f12e --- /dev/null +++ b/src/main/resources/db/migration/V2__seed_baseline_rbac.sql @@ -0,0 +1,18 @@ +-- V2: baseline RBAC data. Without it nobody could ever be granted ROLE:WRITE or PERMISSION:WRITE +-- to create the first assignment. Idempotent so a re-run never duplicates rows. + +INSERT INTO permissions (resource, action) +SELECT r.resource, a.action +FROM (VALUES ('USER'), ('ROLE'), ('PERMISSION'), ('CATEGORY'), ('PRODUCT'), ('CUSTOMER'), ('ORDER')) AS r (resource) +CROSS JOIN (VALUES ('READ'), ('WRITE')) AS a (action) +ON CONFLICT (resource, action) DO NOTHING; + +INSERT INTO roles (role_name) VALUES ('ADMIN') +ON CONFLICT (role_name) DO NOTHING; + +INSERT INTO role_permission (role_id, permission_id) +SELECT r.id, p.id +FROM roles r +CROSS JOIN permissions p +WHERE r.role_name = 'ADMIN' +ON CONFLICT (role_id, permission_id) DO NOTHING; From 02826eccc466c05c120054f22a635f526b5cd50f Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 09:23:00 +0400 Subject: [PATCH 055/158] feat(entity): add the Permission entity and its repository A permission is a resource and an action, such as USER and READ. It is a catalogue entry that roles are composed from, so it knows nothing about roles and no endpoint manages the relation from this side. The repository adds the one query that goes beyond Panache: all permissions granted to a user through their roles, fetched in a single query, which is what the security identity augmentor runs once per authenticated request. --- .../quarkustutorial/entity/Permission.java | 39 +++++++++++++++++++ .../repository/PermissionRepository.java | 39 +++++++++++++++++++ 2 files changed, 78 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/entity/Permission.java create mode 100644 src/main/java/com/edgareldy/quarkustutorial/repository/PermissionRepository.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/entity/Permission.java b/src/main/java/com/edgareldy/quarkustutorial/entity/Permission.java new file mode 100644 index 0000000..1fbc695 --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/entity/Permission.java @@ -0,0 +1,39 @@ +package com.edgareldy.quarkustutorial.entity; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; + +/** + * A fixed catalog entry of the form RESOURCE:ACTION (for example CATEGORY:WRITE). + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +// No back-reference to roles: permissions are assigned onto a role, never the other way around. +@Entity +@Table(name = "permissions") +public class Permission { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(nullable = false) + private String resource; + + @Column(nullable = false) + private String action; + + public Long getId() { return id; } + public void setId(Long id) { this.id = id; } + public String getResource() { return resource; } + public void setResource(String resource) { this.resource = resource; } + public String getAction() { return action; } + public void setAction(String action) { this.action = action; } +} diff --git a/src/main/java/com/edgareldy/quarkustutorial/repository/PermissionRepository.java b/src/main/java/com/edgareldy/quarkustutorial/repository/PermissionRepository.java new file mode 100644 index 0000000..805036c --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/repository/PermissionRepository.java @@ -0,0 +1,39 @@ +package com.edgareldy.quarkustutorial.repository; + +import com.edgareldy.quarkustutorial.entity.Permission; +import io.quarkus.hibernate.orm.panache.PanacheRepository; +import jakarta.enterprise.context.ApplicationScoped; +import java.util.List; +import java.util.Optional; + +/** + * Panache repository for permissions. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +@ApplicationScoped +public class PermissionRepository implements PanacheRepository { + + /** + * @param resource the resource part + * @param action the action part + * @return the permission, if any + */ + public Optional findByResourceAndAction(String resource, String action) { + return find("resource = ?1 and action = ?2", resource, action).firstResultOptional(); + } + + /** + * Single query resolving every permission a user holds through all their roles. + * + * @param userId the user id + * @return the distinct permissions + */ + public List findGrantedToUser(Long userId) { + return find("select distinct p from User u join u.roles r join r.permissions p where u.id = ?1", userId) + .list(); + } +} From 9a15870db27d83d2215d75349594191e2ed58b52 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 09:23:00 +0400 Subject: [PATCH 056/158] feat(entity): add the Role entity and its repository A role is composed out of permissions: the many to many mapping to the role_permission table lives on Role, which is the owning side, so permissions are always assigned onto a role and never the other way round. Loading is lazy, and the repository offers fetching queries for the endpoints that need the permissions, to avoid one query per role. Queries that answer whether a role is still referenced by a user or a permission still held by a role live here too, since the delete rules of the service depend on them. --- .../quarkustutorial/entity/Role.java | 49 +++++++++++++++++++ .../repository/RoleRepository.java | 42 ++++++++++++++++ 2 files changed, 91 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/entity/Role.java create mode 100644 src/main/java/com/edgareldy/quarkustutorial/repository/RoleRepository.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/entity/Role.java b/src/main/java/com/edgareldy/quarkustutorial/entity/Role.java new file mode 100644 index 0000000..f8232c2 --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/entity/Role.java @@ -0,0 +1,49 @@ +package com.edgareldy.quarkustutorial.entity; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.JoinTable; +import jakarta.persistence.ManyToMany; +import jakarta.persistence.Table; +import java.util.LinkedHashSet; +import java.util.Set; + +/** + * A named set of permissions that can be granted to users. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +@Entity +@Table(name = "roles") +public class Role { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "role_name", nullable = false, unique = true) + private String roleName; + + // Owning side of role_permission. LAZY so listing roles does not load permissions unless a + // fetch join asks for them (RoleRepository does, to avoid one query per role). + @ManyToMany(fetch = FetchType.LAZY) + @JoinTable(name = "role_permission", + joinColumns = @JoinColumn(name = "role_id"), + inverseJoinColumns = @JoinColumn(name = "permission_id")) + private Set permissions = new LinkedHashSet<>(); + + public Long getId() { return id; } + public void setId(Long id) { this.id = id; } + public String getRoleName() { return roleName; } + public void setRoleName(String roleName) { this.roleName = roleName; } + public Set getPermissions() { return permissions; } + public void setPermissions(Set permissions) { this.permissions = permissions; } +} diff --git a/src/main/java/com/edgareldy/quarkustutorial/repository/RoleRepository.java b/src/main/java/com/edgareldy/quarkustutorial/repository/RoleRepository.java new file mode 100644 index 0000000..abb43da --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/repository/RoleRepository.java @@ -0,0 +1,42 @@ +package com.edgareldy.quarkustutorial.repository; + +import com.edgareldy.quarkustutorial.entity.Role; +import io.quarkus.hibernate.orm.panache.PanacheRepository; +import jakarta.enterprise.context.ApplicationScoped; +import java.util.List; +import java.util.Optional; + +/** + * Panache repository for roles. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +@ApplicationScoped +public class RoleRepository implements PanacheRepository { + + /** + * @param roleName the name, matched case-insensitively + * @return the role, if any + */ + public Optional findByRoleName(String roleName) { + return find("lower(roleName) = ?1", roleName.toLowerCase()).firstResultOptional(); + } + + /** + * @return all roles with their permissions loaded by one fetch join (no N+1), ordered by id + */ + public List findAllWithPermissions() { + return find("select distinct r from Role r left join fetch r.permissions order by r.id").list(); + } + + /** + * @param permissionId the permission id + * @return how many roles currently have this permission assigned + */ + public long countByPermissionId(Long permissionId) { + return count("from Role r join r.permissions p where p.id = ?1", permissionId); + } +} From 1641e0135eb67bd47b353de201d45f2a722dcba0 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 09:23:00 +0400 Subject: [PATCH 057/158] feat(entity): add the AuditLog entity and its repository Every change to roles, permissions and assignments must be traceable: who did what, to which entity, when. The entity stores the actor, the action, the entity type and id, free form details and a creation instant, and the actor is optional so a row survives the deletion of the account that produced it. The repository is a plain Panache repository. Nothing here ever updates or deletes an audit row, which is what makes the log trustworthy. --- .../quarkustutorial/entity/AuditLog.java | 59 +++++++++++++++++++ .../repository/AuditLogRepository.java | 17 ++++++ 2 files changed, 76 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/entity/AuditLog.java create mode 100644 src/main/java/com/edgareldy/quarkustutorial/repository/AuditLogRepository.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/entity/AuditLog.java b/src/main/java/com/edgareldy/quarkustutorial/entity/AuditLog.java new file mode 100644 index 0000000..f2d675d --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/entity/AuditLog.java @@ -0,0 +1,59 @@ +package com.edgareldy.quarkustutorial.entity; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import java.time.Instant; + +/** + * One traceable RBAC action: who did what, to which entity, and when. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +@Entity +@Table(name = "audit_logs") +public class AuditLog { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + /** The acting user (JWT subject), or null when there is none; set to NULL if the user is deleted. */ + @Column(name = "actor_user_id") + private Long actorUserId; + + @Column(nullable = false) + private String action; + + @Column(name = "entity_type", nullable = false) + private String entityType; + + @Column(name = "entity_id") + private Long entityId; + + private String details; + + @Column(name = "created_at", nullable = false) + private Instant createdAt; + + public Long getId() { return id; } + public void setId(Long id) { this.id = id; } + public Long getActorUserId() { return actorUserId; } + public void setActorUserId(Long actorUserId) { this.actorUserId = actorUserId; } + public String getAction() { return action; } + public void setAction(String action) { this.action = action; } + public String getEntityType() { return entityType; } + public void setEntityType(String entityType) { this.entityType = entityType; } + public Long getEntityId() { return entityId; } + public void setEntityId(Long entityId) { this.entityId = entityId; } + public String getDetails() { return details; } + public void setDetails(String details) { this.details = details; } + public Instant getCreatedAt() { return createdAt; } + public void setCreatedAt(Instant createdAt) { this.createdAt = createdAt; } +} diff --git a/src/main/java/com/edgareldy/quarkustutorial/repository/AuditLogRepository.java b/src/main/java/com/edgareldy/quarkustutorial/repository/AuditLogRepository.java new file mode 100644 index 0000000..a362819 --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/repository/AuditLogRepository.java @@ -0,0 +1,17 @@ +package com.edgareldy.quarkustutorial.repository; + +import com.edgareldy.quarkustutorial.entity.AuditLog; +import io.quarkus.hibernate.orm.panache.PanacheRepository; +import jakarta.enterprise.context.ApplicationScoped; + +/** + * Panache repository for audit log rows. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +@ApplicationScoped +public class AuditLogRepository implements PanacheRepository { +} From b7a5ea9f4f3cc53ee4790c45e48b51735b2ddef4 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 09:23:00 +0400 Subject: [PATCH 058/158] feat(entity): give User the roles it holds Roles are assigned onto a user and never the reverse, so the many to many mapping to role_user is declared on User, the owning side. The repository gains the queries the administration endpoints need: a page of users, and users with their roles loaded in one query. Fetching a collection together with a limited page of rows would make Hibernate page in memory, so the page of users is read first and their roles are loaded with a second query on those ids. The lookup by id avoids limiting a fetch join for the same reason. --- .../quarkustutorial/entity/User.java | 16 ++++ .../repository/UserRepository.java | 79 +++++++++++++++++++ 2 files changed, 95 insertions(+) diff --git a/src/main/java/com/edgareldy/quarkustutorial/entity/User.java b/src/main/java/com/edgareldy/quarkustutorial/entity/User.java index 1d624e2..50bb7dd 100644 --- a/src/main/java/com/edgareldy/quarkustutorial/entity/User.java +++ b/src/main/java/com/edgareldy/quarkustutorial/entity/User.java @@ -2,10 +2,16 @@ import jakarta.persistence.Column; import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.JoinTable; +import jakarta.persistence.ManyToMany; import jakarta.persistence.Table; +import java.util.LinkedHashSet; +import java.util.Set; /** * An application account; created disabled at registration and enabled by activating it. @@ -44,6 +50,14 @@ public class User { @Column(name = "account_locked", nullable = false) private boolean accountLocked; + // Owning side of role_user: roles are assigned onto a user, never the reverse (Role has no users + // collection). LAZY plus fetch joins in the repositories keeps user lists free of N+1 queries. + @ManyToMany(fetch = FetchType.LAZY) + @JoinTable(name = "role_user", + joinColumns = @JoinColumn(name = "user_id"), + inverseJoinColumns = @JoinColumn(name = "role_id")) + private Set roles = new LinkedHashSet<>(); + public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getFirstName() { return firstName; } @@ -58,4 +72,6 @@ public class User { public void setEnabled(boolean enabled) { this.enabled = enabled; } public boolean isAccountLocked() { return accountLocked; } public void setAccountLocked(boolean accountLocked) { this.accountLocked = accountLocked; } + public Set getRoles() { return roles; } + public void setRoles(Set roles) { this.roles = roles; } } diff --git a/src/main/java/com/edgareldy/quarkustutorial/repository/UserRepository.java b/src/main/java/com/edgareldy/quarkustutorial/repository/UserRepository.java index 7b2c034..59009a6 100644 --- a/src/main/java/com/edgareldy/quarkustutorial/repository/UserRepository.java +++ b/src/main/java/com/edgareldy/quarkustutorial/repository/UserRepository.java @@ -3,6 +3,7 @@ import com.edgareldy.quarkustutorial.entity.User; import io.quarkus.hibernate.orm.panache.PanacheRepository; import jakarta.enterprise.context.ApplicationScoped; +import java.util.List; import java.util.Optional; /** @@ -25,4 +26,82 @@ public class UserRepository implements PanacheRepository { public Optional findByEmail(String email) { return find("lower(email) = ?1", email.toLowerCase()).firstResultOptional(); } + + /** + * @param roleId the role id + * @return how many users currently hold this role + */ + public long countByRoleId(Long roleId) { + return count("from User u join u.roles r where r.id = ?1", roleId); + } + + /** + * Loads the given users together with their roles in one fetch-join query (no N+1). + * + * @param ids the user ids + * @return the users ordered by id + */ + public List findWithRolesByIds(List ids) { + if (ids.isEmpty()) { + return List.of(); + } + return find("select distinct u from User u left join fetch u.roles where u.id in ?1 order by u.id", ids) + .list(); + } + + /** + * @param id the user id + * @return the user with roles loaded, if any + */ + public Optional findWithRolesById(Long id) { + // list() rather than firstResultOptional(): limiting the rows of a query that fetch joins a + // collection makes Hibernate page in memory. The id is unique, so at most one user comes back. + return find("select distinct u from User u left join fetch u.roles where u.id = ?1", id) + .list().stream().findFirst(); + } + + /** + * @param resource the permission resource + * @param action the permission action + * @return whether (count above zero) users hold a role granting this permission + */ + public long countHolders(String resource, String action) { + return count("from User u join u.roles r join r.permissions p where p.resource = ?1 and p.action = ?2", + resource, action); + } + + /** + * @param resource the permission resource + * @param action the permission action + * @param userId a user to leave out of the count + * @return whether (count above zero) users other than this one hold a role granting this permission + */ + public long countHoldersExcludingUser(String resource, String action, Long userId) { + return count("from User u join u.roles r join r.permissions p " + + "where p.resource = ?1 and p.action = ?2 and u.id <> ?3", resource, action, userId); + } + + /** + * @param resource the permission resource + * @param action the permission action + * @param roleId a role to ignore + * @return whether (count above zero) users hold the permission through a role other than this one + */ + public long countHoldersExcludingRole(String resource, String action, Long roleId) { + return count("from User u join u.roles r join r.permissions p " + + "where p.resource = ?1 and p.action = ?2 and r.id <> ?3", resource, action, roleId); + } + + /** + * @param userId the user id + * @param resource the permission resource + * @param action the permission action + * @param roleId a role of that user to ignore + * @return how many of the user's other roles grant the permission + */ + public long countUserRolesGrantingExcluding(Long userId, String resource, String action, Long roleId) { + return count("from User u join u.roles r join r.permissions p " + + "where u.id = ?1 and p.resource = ?2 and p.action = ?3 and r.id <> ?4", + userId, resource, action, roleId); + } } From bbe06f8467010786d9e3d33e61997c681e46e903 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 09:23:00 +0400 Subject: [PATCH 059/158] feat(dto): add the RBAC request and response records Roles and permissions each get a request record, validated with Bean Validation, and a response record that never exposes an entity. The role response embeds its permissions, and the detailed user response embeds a small summary of each role rather than the whole role, which keeps a user listing light. Separate request and response types let the API contract stay stable while the entities behind it evolve. --- .../dto/rbac/PermissionRequest.java | 17 ++++++++++ .../dto/rbac/PermissionResponse.java | 12 +++++++ .../quarkustutorial/dto/rbac/RoleRequest.java | 15 +++++++++ .../dto/rbac/RoleResponse.java | 14 +++++++++ .../dto/rbac/UserDetailResponse.java | 31 +++++++++++++++++++ 5 files changed, 89 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/dto/rbac/PermissionRequest.java create mode 100644 src/main/java/com/edgareldy/quarkustutorial/dto/rbac/PermissionResponse.java create mode 100644 src/main/java/com/edgareldy/quarkustutorial/dto/rbac/RoleRequest.java create mode 100644 src/main/java/com/edgareldy/quarkustutorial/dto/rbac/RoleResponse.java create mode 100644 src/main/java/com/edgareldy/quarkustutorial/dto/rbac/UserDetailResponse.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/dto/rbac/PermissionRequest.java b/src/main/java/com/edgareldy/quarkustutorial/dto/rbac/PermissionRequest.java new file mode 100644 index 0000000..c485120 --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/dto/rbac/PermissionRequest.java @@ -0,0 +1,17 @@ +package com.edgareldy.quarkustutorial.dto.rbac; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Size; + +/** + * Payload to create or update a permission (stored upper-cased). + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +public record PermissionRequest( + @NotBlank @Size(max = 100) String resource, + @NotBlank @Size(max = 100) String action) { +} diff --git a/src/main/java/com/edgareldy/quarkustutorial/dto/rbac/PermissionResponse.java b/src/main/java/com/edgareldy/quarkustutorial/dto/rbac/PermissionResponse.java new file mode 100644 index 0000000..ffe7c1a --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/dto/rbac/PermissionResponse.java @@ -0,0 +1,12 @@ +package com.edgareldy.quarkustutorial.dto.rbac; + +/** + * View of a permission. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +public record PermissionResponse(Long id, String resource, String action) { +} diff --git a/src/main/java/com/edgareldy/quarkustutorial/dto/rbac/RoleRequest.java b/src/main/java/com/edgareldy/quarkustutorial/dto/rbac/RoleRequest.java new file mode 100644 index 0000000..90b2b23 --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/dto/rbac/RoleRequest.java @@ -0,0 +1,15 @@ +package com.edgareldy.quarkustutorial.dto.rbac; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Size; + +/** + * Payload to create or rename a role. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +public record RoleRequest(@NotBlank @Size(max = 100) String roleName) { +} diff --git a/src/main/java/com/edgareldy/quarkustutorial/dto/rbac/RoleResponse.java b/src/main/java/com/edgareldy/quarkustutorial/dto/rbac/RoleResponse.java new file mode 100644 index 0000000..02a3de2 --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/dto/rbac/RoleResponse.java @@ -0,0 +1,14 @@ +package com.edgareldy.quarkustutorial.dto.rbac; + +import java.util.List; + +/** + * View of a role with the permissions assigned to it. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +public record RoleResponse(Long id, String roleName, List permissions) { +} diff --git a/src/main/java/com/edgareldy/quarkustutorial/dto/rbac/UserDetailResponse.java b/src/main/java/com/edgareldy/quarkustutorial/dto/rbac/UserDetailResponse.java new file mode 100644 index 0000000..db82d62 --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/dto/rbac/UserDetailResponse.java @@ -0,0 +1,31 @@ +package com.edgareldy.quarkustutorial.dto.rbac; + +import java.util.List; + +/** + * View of a user with the roles assigned to them (never exposes the password hash). + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +public record UserDetailResponse( + Long id, + String firstName, + String lastName, + String email, + boolean enabled, + List roles) { + + /** + * Compact role reference inside a user view (id and name only). + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ + public record RoleSummary(Long id, String roleName) { + } +} From 3f11cbcac721f512b7d5fab212a35095d68082d2 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 09:23:00 +0400 Subject: [PATCH 060/158] feat(security): add AuditLogger for RBAC mutations A single log method records an audit row with the actor taken from the current token. It runs in its own transaction, so a row written just before a business rule rejects the operation survives the rollback of the caller: a refused attempt to delete a role or to remove the last administrator is exactly what an audit trail should keep. A separate transaction has a cost, since it commits independently of the operation being audited, but the alternative loses the traces of every rejected action. --- .../quarkustutorial/security/AuditLogger.java | 68 +++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/security/AuditLogger.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/security/AuditLogger.java b/src/main/java/com/edgareldy/quarkustutorial/security/AuditLogger.java new file mode 100644 index 0000000..bb73f4e --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/security/AuditLogger.java @@ -0,0 +1,68 @@ +package com.edgareldy.quarkustutorial.security; + +import com.edgareldy.quarkustutorial.entity.AuditLog; +import com.edgareldy.quarkustutorial.repository.AuditLogRepository; +import io.quarkus.arc.Arc; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import jakarta.transaction.Transactional; +import java.time.Instant; +import org.eclipse.microprofile.jwt.JsonWebToken; + +/** + * Records who did what to which entity and when, for every RBAC mutation and rejected attempt. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +@ApplicationScoped +public class AuditLogger { + + @Inject + AuditLogRepository auditLogRepository; + + // The validated JWT of the current request (request scoped proxy); see AuthResource. + @Inject + JsonWebToken jwt; + + /** + * Stores one audit row. It runs in its own transaction so that a REJECTED attempt is kept even + * though the caller's business transaction is then rolled back by the exception it throws. + * + * @param action what happened, for example ROLE_CREATED or ROLE_DELETE_REJECTED + * @param entityType the kind of entity concerned, for example ROLE + * @param entityId the entity id, or null + * @param details free text with the context + */ + // Transactional.TxType.REQUIRES_NEW suspends the caller's transaction and commits this insert + // independently: a plain @Transactional would join the caller's and vanish with its rollback. + @Transactional(Transactional.TxType.REQUIRES_NEW) + public void log(String action, String entityType, Long entityId, String details) { + AuditLog entry = new AuditLog(); + entry.setActorUserId(currentActor()); + entry.setAction(action); + entry.setEntityType(entityType); + entry.setEntityId(entityId); + entry.setDetails(details); + entry.setCreatedAt(Instant.now()); + auditLogRepository.persist(entry); + } + + /** JWT subject as a user id, or null outside a request (startup, scheduler) or without a token. */ + private Long currentActor() { + if (!Arc.container().requestContext().isActive()) { + return null; + } + String subject = jwt.getSubject(); + if (subject == null) { + return null; + } + try { + return Long.valueOf(subject); + } catch (NumberFormatException e) { + return null; + } + } +} From d4e58769f0c182a873774fa0ee2bee60985e930b Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 09:23:00 +0400 Subject: [PATCH 061/158] feat(service): add the RbacService contract One contract covers roles, permissions, their assignments and the administration view of users. Each method takes and returns DTOs, and the two directions of assignment are the only ones offered: permissions onto roles and roles onto users. Keeping it an interface lets resources and tests depend on behaviour rather than on the implementation. --- .../quarkustutorial/service/RbacService.java | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/service/RbacService.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/service/RbacService.java b/src/main/java/com/edgareldy/quarkustutorial/service/RbacService.java new file mode 100644 index 0000000..481b7cd --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/service/RbacService.java @@ -0,0 +1,54 @@ +package com.edgareldy.quarkustutorial.service; + +import com.edgareldy.quarkustutorial.dto.common.PageResponse; +import com.edgareldy.quarkustutorial.dto.rbac.PermissionRequest; +import com.edgareldy.quarkustutorial.dto.rbac.PermissionResponse; +import com.edgareldy.quarkustutorial.dto.rbac.RoleRequest; +import com.edgareldy.quarkustutorial.dto.rbac.RoleResponse; +import com.edgareldy.quarkustutorial.dto.rbac.UserDetailResponse; +import java.util.List; + +/** + * Contract for administering roles, permissions and the role assignments of users. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +public interface RbacService { + + PageResponse listUsers(int page, int size); + + UserDetailResponse getUser(Long id); + + /** Idempotent: assigning a role the user already has changes nothing. */ + UserDetailResponse assignRoleToUser(Long userId, Long roleId); + + /** Rejected with a business rule error if it would leave no user holding ROLE:WRITE. */ + UserDetailResponse removeRoleFromUser(Long userId, Long roleId); + + List listRoles(); + + RoleResponse createRole(RoleRequest request); + + RoleResponse updateRole(Long id, RoleRequest request); + + /** Rejected while any user still has the role. */ + void deleteRole(Long id); + + /** Idempotent: assigning a permission the role already has changes nothing. */ + RoleResponse assignPermissionToRole(Long roleId, Long permissionId); + + /** Rejected with a business rule error if it would leave no user holding ROLE:WRITE. */ + RoleResponse removePermissionFromRole(Long roleId, Long permissionId); + + List listPermissions(); + + PermissionResponse createPermission(PermissionRequest request); + + PermissionResponse updatePermission(Long id, PermissionRequest request); + + /** Rejected while any role still has the permission. */ + void deletePermission(Long id); +} From 1674a2d03569ae3d2b08a02b1d9407e176ee2377 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 09:23:00 +0400 Subject: [PATCH 062/158] feat(service): implement RbacService with the reference and last admin rules A role cannot be deleted while a user holds it and a permission cannot be deleted while a role holds it, each case answering 422 with a message that says what to unassign first. Every mutation calls the audit logger, and so do the refused ones. The last administrator rule protects against locking everybody out: removing ROLE:WRITE from a role, or a role from a user, is rejected when afterwards no user anywhere would hold a role granting ROLE:WRITE. The same check applies at both places, so a self lockout is caught however it is attempted. Assigning twice is harmless and adds nothing. --- .../service/impl/RbacServiceImpl.java | 310 ++++++++++++++++++ 1 file changed, 310 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/service/impl/RbacServiceImpl.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/service/impl/RbacServiceImpl.java b/src/main/java/com/edgareldy/quarkustutorial/service/impl/RbacServiceImpl.java new file mode 100644 index 0000000..5f37d47 --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/service/impl/RbacServiceImpl.java @@ -0,0 +1,310 @@ +package com.edgareldy.quarkustutorial.service.impl; + +import com.edgareldy.quarkustutorial.dto.common.PageResponse; +import com.edgareldy.quarkustutorial.dto.rbac.PermissionRequest; +import com.edgareldy.quarkustutorial.dto.rbac.PermissionResponse; +import com.edgareldy.quarkustutorial.dto.rbac.RoleRequest; +import com.edgareldy.quarkustutorial.dto.rbac.RoleResponse; +import com.edgareldy.quarkustutorial.dto.rbac.UserDetailResponse; +import com.edgareldy.quarkustutorial.entity.Permission; +import com.edgareldy.quarkustutorial.entity.Role; +import com.edgareldy.quarkustutorial.entity.User; +import com.edgareldy.quarkustutorial.exception.BusinessRuleException; +import com.edgareldy.quarkustutorial.exception.ResourceNotFoundException; +import com.edgareldy.quarkustutorial.repository.PermissionRepository; +import com.edgareldy.quarkustutorial.repository.RoleRepository; +import com.edgareldy.quarkustutorial.repository.UserRepository; +import com.edgareldy.quarkustutorial.security.AuditLogger; +import com.edgareldy.quarkustutorial.service.RbacService; +import io.quarkus.panache.common.Page; +import io.quarkus.panache.common.Sort; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import jakarta.transaction.Transactional; +import java.util.Comparator; +import java.util.List; + +/** + * Default RbacService: role, permission and assignment management with audit and last-admin protection. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +@ApplicationScoped +public class RbacServiceImpl implements RbacService { + + /** The permission whose last holder must never be removed (anti-lockout). */ + private static final String ADMIN_RESOURCE = "ROLE"; + private static final String ADMIN_ACTION = "WRITE"; + private static final String LAST_ADMIN = "This would leave no user holding ROLE:WRITE"; + + @Inject + UserRepository userRepository; + + @Inject + RoleRepository roleRepository; + + @Inject + PermissionRepository permissionRepository; + + @Inject + AuditLogger auditLogger; + + // ---- users ------------------------------------------------------------------------------- + + @Override + @Transactional + public PageResponse listUsers(int page, int size) { + // Query 1 pages plain users (SQL limit/offset); query 2 fetch-joins their roles. Fetching + // the collection in the paged query itself would force Hibernate to page in memory. + List ids = userRepository.findAll(Sort.by("id")).page(Page.of(page, size)).list() + .stream().map(User::getId).toList(); + List content = userRepository.findWithRolesByIds(ids).stream() + .map(RbacServiceImpl::toResponse).toList(); + return PageResponse.of(content, page, size, userRepository.count()); + } + + @Override + @Transactional + public UserDetailResponse getUser(Long id) { + return toResponse(findUser(id)); + } + + @Override + @Transactional + public UserDetailResponse assignRoleToUser(Long userId, Long roleId) { + User user = findUser(userId); + Role role = findRole(roleId); + if (user.getRoles().add(role)) { + auditLogger.log("ROLE_ASSIGNED_TO_USER", "USER", userId, "role " + role.getRoleName() + " (" + roleId + ")"); + } + return toResponse(user); + } + + @Override + @Transactional + public UserDetailResponse removeRoleFromUser(Long userId, Long roleId) { + User user = findUser(userId); + Role role = findRole(roleId); + if (!user.getRoles().contains(role)) { + return toResponse(user); + } + if (grants(role, ADMIN_RESOURCE, ADMIN_ACTION) + && userRepository.countUserRolesGrantingExcluding(userId, ADMIN_RESOURCE, ADMIN_ACTION, roleId) == 0 + && userRepository.countHoldersExcludingUser(ADMIN_RESOURCE, ADMIN_ACTION, userId) == 0) { + // Logged before throwing: the audit insert commits on its own (REQUIRES_NEW), so it + // survives the rollback this exception triggers. + auditLogger.log("ROLE_UNASSIGN_REJECTED", "USER", userId, + "role " + role.getRoleName() + " (" + roleId + "): " + LAST_ADMIN); + throw new BusinessRuleException(LAST_ADMIN); + } + user.getRoles().remove(role); + auditLogger.log("ROLE_REMOVED_FROM_USER", "USER", userId, "role " + role.getRoleName() + " (" + roleId + ")"); + return toResponse(user); + } + + // ---- roles ------------------------------------------------------------------------------- + + @Override + @Transactional + public List listRoles() { + return roleRepository.findAllWithPermissions().stream().map(RbacServiceImpl::toResponse).toList(); + } + + @Override + @Transactional + public RoleResponse createRole(RoleRequest request) { + String name = request.roleName().trim(); + if (roleRepository.findByRoleName(name).isPresent()) { + throw new BusinessRuleException("A role named " + name + " already exists"); + } + Role role = new Role(); + role.setRoleName(name); + roleRepository.persist(role); + auditLogger.log("ROLE_CREATED", "ROLE", role.getId(), "name " + name); + return toResponse(role); + } + + @Override + @Transactional + public RoleResponse updateRole(Long id, RoleRequest request) { + Role role = findRole(id); + String name = request.roleName().trim(); + roleRepository.findByRoleName(name).filter(other -> !other.getId().equals(id)).ifPresent(other -> { + throw new BusinessRuleException("A role named " + name + " already exists"); + }); + String previous = role.getRoleName(); + role.setRoleName(name); + auditLogger.log("ROLE_UPDATED", "ROLE", id, "name " + previous + " -> " + name); + return toResponse(role); + } + + @Override + @Transactional + public void deleteRole(Long id) { + Role role = findRole(id); + // Because a role still held by any user cannot be deleted, deleting one can never strip + // ROLE:WRITE from the last holder: no separate last-admin check is needed here. + long holders = userRepository.countByRoleId(id); + if (holders > 0) { + auditLogger.log("ROLE_DELETE_REJECTED", "ROLE", id, "still assigned to " + holders + " user(s)"); + throw new BusinessRuleException("Role " + role.getRoleName() + " is still assigned to " + holders + + " user(s); remove it from them first"); + } + roleRepository.delete(role); + auditLogger.log("ROLE_DELETED", "ROLE", id, "name " + role.getRoleName()); + } + + @Override + @Transactional + public RoleResponse assignPermissionToRole(Long roleId, Long permissionId) { + Role role = findRole(roleId); + Permission permission = findPermission(permissionId); + if (role.getPermissions().add(permission)) { + auditLogger.log("PERMISSION_ASSIGNED_TO_ROLE", "ROLE", roleId, + "permission " + label(permission) + " (" + permissionId + ")"); + } + return toResponse(role); + } + + @Override + @Transactional + public RoleResponse removePermissionFromRole(Long roleId, Long permissionId) { + Role role = findRole(roleId); + Permission permission = findPermission(permissionId); + if (!role.getPermissions().contains(permission)) { + return toResponse(role); + } + // Rejected only when this role really has holders today and nobody would be left through + // any other role: userRepository.countByRoleId > 0 and no holder via another role. + if (ADMIN_RESOURCE.equals(permission.getResource()) && ADMIN_ACTION.equals(permission.getAction()) + && userRepository.countByRoleId(roleId) > 0 + && userRepository.countHoldersExcludingRole(ADMIN_RESOURCE, ADMIN_ACTION, roleId) == 0) { + auditLogger.log("PERMISSION_REMOVE_FROM_ROLE_REJECTED", "ROLE", roleId, + "permission " + label(permission) + ": " + LAST_ADMIN); + throw new BusinessRuleException(LAST_ADMIN); + } + role.getPermissions().remove(permission); + auditLogger.log("PERMISSION_REMOVED_FROM_ROLE", "ROLE", roleId, + "permission " + label(permission) + " (" + permissionId + ")"); + return toResponse(role); + } + + // ---- permissions ------------------------------------------------------------------------- + + @Override + @Transactional + public List listPermissions() { + return permissionRepository.findAll(Sort.by("id")).list().stream() + .map(RbacServiceImpl::toResponse).toList(); + } + + @Override + @Transactional + public PermissionResponse createPermission(PermissionRequest request) { + String resource = normalize(request.resource()); + String action = normalize(request.action()); + if (permissionRepository.findByResourceAndAction(resource, action).isPresent()) { + throw new BusinessRuleException("Permission " + resource + ":" + action + " already exists"); + } + Permission permission = new Permission(); + permission.setResource(resource); + permission.setAction(action); + permissionRepository.persist(permission); + auditLogger.log("PERMISSION_CREATED", "PERMISSION", permission.getId(), resource + ":" + action); + return toResponse(permission); + } + + @Override + @Transactional + public PermissionResponse updatePermission(Long id, PermissionRequest request) { + Permission permission = findPermission(id); + String resource = normalize(request.resource()); + String action = normalize(request.action()); + permissionRepository.findByResourceAndAction(resource, action) + .filter(other -> !other.getId().equals(id)).ifPresent(other -> { + throw new BusinessRuleException("Permission " + resource + ":" + action + " already exists"); + }); + // Renaming ROLE:WRITE would silently strip it from everyone who holds it through a role. + boolean wasAdmin = ADMIN_RESOURCE.equals(permission.getResource()) && ADMIN_ACTION.equals(permission.getAction()); + boolean stillAdmin = ADMIN_RESOURCE.equals(resource) && ADMIN_ACTION.equals(action); + if (wasAdmin && !stillAdmin && userRepository.countHolders(ADMIN_RESOURCE, ADMIN_ACTION) > 0) { + auditLogger.log("PERMISSION_UPDATE_REJECTED", "PERMISSION", id, "renaming " + label(permission) + ": " + LAST_ADMIN); + throw new BusinessRuleException(LAST_ADMIN); + } + String previous = label(permission); + permission.setResource(resource); + permission.setAction(action); + auditLogger.log("PERMISSION_UPDATED", "PERMISSION", id, previous + " -> " + resource + ":" + action); + return toResponse(permission); + } + + @Override + @Transactional + public void deletePermission(Long id) { + Permission permission = findPermission(id); + // A permission still assigned to a role cannot be deleted, so this can never strip + // ROLE:WRITE from the last holder either: no separate last-admin check is needed here. + long roles = roleRepository.countByPermissionId(id); + if (roles > 0) { + auditLogger.log("PERMISSION_DELETE_REJECTED", "PERMISSION", id, "still assigned to " + roles + " role(s)"); + throw new BusinessRuleException("Permission " + label(permission) + " is still assigned to " + roles + + " role(s); remove it from them first"); + } + permissionRepository.delete(permission); + auditLogger.log("PERMISSION_DELETED", "PERMISSION", id, label(permission)); + } + + // ---- helpers ----------------------------------------------------------------------------- + + private User findUser(Long id) { + return userRepository.findWithRolesById(id) + .orElseThrow(() -> new ResourceNotFoundException("User " + id + " not found")); + } + + private Role findRole(Long id) { + Role role = roleRepository.findById(id); + if (role == null) { + throw new ResourceNotFoundException("Role " + id + " not found"); + } + return role; + } + + private Permission findPermission(Long id) { + Permission permission = permissionRepository.findById(id); + if (permission == null) { + throw new ResourceNotFoundException("Permission " + id + " not found"); + } + return permission; + } + + private static boolean grants(Role role, String resource, String action) { + return role.getPermissions().stream() + .anyMatch(p -> resource.equals(p.getResource()) && action.equals(p.getAction())); + } + + private static String normalize(String value) { + return value.trim().toUpperCase(); + } + + private static String label(Permission permission) { + return permission.getResource() + ":" + permission.getAction(); + } + + private static PermissionResponse toResponse(Permission p) { + return new PermissionResponse(p.getId(), p.getResource(), p.getAction()); + } + + private static RoleResponse toResponse(Role r) { + return new RoleResponse(r.getId(), r.getRoleName(), r.getPermissions().stream() + .sorted(Comparator.comparing(Permission::getId)).map(RbacServiceImpl::toResponse).toList()); + } + + private static UserDetailResponse toResponse(User u) { + return new UserDetailResponse(u.getId(), u.getFirstName(), u.getLastName(), u.getEmail(), u.isEnabled(), + u.getRoles().stream().sorted(Comparator.comparing(Role::getId)) + .map(r -> new UserDetailResponse.RoleSummary(r.getId(), r.getRoleName())).toList()); + } +} From 308152e3c68d98310e3d501e581eee982fd5df77 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 09:23:00 +0400 Subject: [PATCH 063/158] feat(security): resolve permissions in a SecurityIdentityAugmentor After the token is validated, this augmentor loads the permissions of the user through their roles with one query and adds them to the identity as StringPermission objects. A @PermissionsAllowed check is then a lookup in memory, with no database access at the point of the check. It is the only place where permissions are resolved. The annotation splits USER:READ on the colon into a name and an action, so the permission added has the same shape. The query is blocking JDBC while the augmentor may run on an event loop thread, hence the call that moves it to a worker thread. --- .../PermissionSecurityIdentityAugmentor.java | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/security/PermissionSecurityIdentityAugmentor.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/security/PermissionSecurityIdentityAugmentor.java b/src/main/java/com/edgareldy/quarkustutorial/security/PermissionSecurityIdentityAugmentor.java new file mode 100644 index 0000000..388ce68 --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/security/PermissionSecurityIdentityAugmentor.java @@ -0,0 +1,62 @@ +package com.edgareldy.quarkustutorial.security; + +import com.edgareldy.quarkustutorial.entity.Permission; +import com.edgareldy.quarkustutorial.repository.PermissionRepository; +import io.quarkus.security.StringPermission; +import io.quarkus.security.identity.AuthenticationRequestContext; +import io.quarkus.security.identity.SecurityIdentity; +import io.quarkus.security.identity.SecurityIdentityAugmentor; +import io.quarkus.security.runtime.QuarkusSecurityIdentity; +import io.smallrye.mutiny.Uni; +import io.quarkus.narayana.jta.QuarkusTransaction; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import java.util.List; + +/** + * Turns the authenticated user's roles into StringPermission objects on the security identity. + * This is the only place permissions are resolved. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +// A SecurityIdentityAugmentor is called by Quarkus after the JWT has been validated and lets the +// application enrich the identity. Here the JWT carries no roles or permissions (only the user id +// as subject), so they are loaded from the database once per request and attached, which is what +// @PermissionsAllowed("RESOURCE:ACTION") then checks against. It is applied to every authenticated +// request, so no other class ever has to look permissions up. +@ApplicationScoped +public class PermissionSecurityIdentityAugmentor implements SecurityIdentityAugmentor { + + @Inject + PermissionRepository permissionRepository; + + @Override + public Uni augment(SecurityIdentity identity, AuthenticationRequestContext context) { + if (identity.isAnonymous()) { + return Uni.createFrom().item(identity); + } + // augment() may run on the IO (event loop) thread, where blocking is forbidden, and the + // database query is blocking JDBC. runBlocking moves the supplier to a worker thread. + return context.runBlocking(() -> addPermissions(identity)); + } + + private SecurityIdentity addPermissions(SecurityIdentity identity) { + Long userId; + try { + userId = Long.valueOf(identity.getPrincipal().getName()); + } catch (NumberFormatException e) { + return identity; + } + // A worker thread has no ambient transaction, so the read runs in a short one of its own. + List granted = QuarkusTransaction.requiringNew() + .call(() -> permissionRepository.findGrantedToUser(userId)); + QuarkusSecurityIdentity.Builder builder = QuarkusSecurityIdentity.builder(identity); + // @PermissionsAllowed("USER:READ") is split on the colon into name USER and action READ, + // so the permission added must have the same shape. + granted.forEach(p -> builder.addPermission(new StringPermission(p.getResource(), p.getAction()))); + return builder.build(); + } +} From 4ac7c65cba0fc007123d69d63c07921d0afc4b40 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 09:23:00 +0400 Subject: [PATCH 064/158] feat(resource): add UserResource for role assignment Users are listed with pagination and shown with their roles, and a role can be assigned to or removed from an existing user. Each method carries its @PermissionsAllowed and the resource only delegates to the service. The resource never creates a user: registration belongs to the authentication endpoints, so there is no POST here and the framework answers 405. --- .../resource/UserResource.java | 69 +++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/resource/UserResource.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/resource/UserResource.java b/src/main/java/com/edgareldy/quarkustutorial/resource/UserResource.java new file mode 100644 index 0000000..93ddc75 --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/resource/UserResource.java @@ -0,0 +1,69 @@ +package com.edgareldy.quarkustutorial.resource; + +import com.edgareldy.quarkustutorial.dto.common.ApiResponse; +import com.edgareldy.quarkustutorial.dto.common.PageResponse; +import com.edgareldy.quarkustutorial.dto.rbac.UserDetailResponse; +import com.edgareldy.quarkustutorial.service.RbacService; +import io.quarkus.security.PermissionsAllowed; +import jakarta.inject.Inject; +import jakarta.validation.constraints.Max; +import jakarta.validation.constraints.Min; +import jakarta.ws.rs.DELETE; +import jakarta.ws.rs.DefaultValue; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.PATCH; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.PathParam; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.QueryParam; +import jakarta.ws.rs.core.MediaType; +import org.eclipse.microprofile.openapi.annotations.security.SecurityRequirement; + +/** + * Read access to users and management of the roles assigned to them (never creates a user). + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +// @PermissionsAllowed("USER:READ") is enforced by Quarkus before the method runs, against the +// StringPermission objects PermissionSecurityIdentityAugmentor attached to the identity: no manual +// check in the body. Anonymous callers get 401, authenticated ones without the permission get 403. +@Path("/api/v1/users") +@Produces(MediaType.APPLICATION_JSON) +@SecurityRequirement(name = "jwt") +public class UserResource { + + @Inject + RbacService rbacService; + + @GET + @PermissionsAllowed("USER:READ") + public ApiResponse> list( + @QueryParam("page") @DefaultValue("0") @Min(0) int page, + @QueryParam("size") @DefaultValue("20") @Min(1) @Max(100) int size) { + return ApiResponse.success(rbacService.listUsers(page, size), "Users"); + } + + @GET + @Path("/{id}") + @PermissionsAllowed("USER:READ") + public ApiResponse get(@PathParam("id") Long id) { + return ApiResponse.success(rbacService.getUser(id), "User"); + } + + @PATCH + @Path("/{id}/roles/{roleId}") + @PermissionsAllowed("USER:WRITE") + public ApiResponse assignRole(@PathParam("id") Long id, @PathParam("roleId") Long roleId) { + return ApiResponse.success(rbacService.assignRoleToUser(id, roleId), "Role assigned"); + } + + @DELETE + @Path("/{id}/roles/{roleId}") + @PermissionsAllowed("USER:WRITE") + public ApiResponse removeRole(@PathParam("id") Long id, @PathParam("roleId") Long roleId) { + return ApiResponse.success(rbacService.removeRoleFromUser(id, roleId), "Role removed"); + } +} From 9f7adf883d7113b4a2473141b9922d32c0a6f7cd Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 09:23:00 +0400 Subject: [PATCH 065/158] feat(resource): add RoleResource with permission assignment Roles have full CRUD and the endpoints that assign a permission to a role or remove it, all protected by ROLE:READ or ROLE:WRITE. Creating answers 201, the others 200. The assignment lives here, on the role, and there is no equivalent endpoint on the permission resource: the relation is only ever managed from the composed side. --- .../resource/RoleResource.java | 84 +++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/resource/RoleResource.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/resource/RoleResource.java b/src/main/java/com/edgareldy/quarkustutorial/resource/RoleResource.java new file mode 100644 index 0000000..84af6ca --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/resource/RoleResource.java @@ -0,0 +1,84 @@ +package com.edgareldy.quarkustutorial.resource; + +import com.edgareldy.quarkustutorial.dto.common.ApiResponse; +import com.edgareldy.quarkustutorial.dto.rbac.RoleRequest; +import com.edgareldy.quarkustutorial.dto.rbac.RoleResponse; +import com.edgareldy.quarkustutorial.service.RbacService; +import io.quarkus.security.PermissionsAllowed; +import jakarta.inject.Inject; +import jakarta.validation.Valid; +import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.DELETE; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.PUT; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.PathParam; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.MediaType; +import java.util.List; +import org.eclipse.microprofile.openapi.annotations.security.SecurityRequirement; +import org.jboss.resteasy.reactive.ResponseStatus; + +/** + * Role administration, including which permissions each role holds (assigned onto the role only). + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +@Path("/api/v1/roles") +@Produces(MediaType.APPLICATION_JSON) +@SecurityRequirement(name = "jwt") +public class RoleResource { + + @Inject + RbacService rbacService; + + @GET + @PermissionsAllowed("ROLE:READ") + public ApiResponse> list() { + return ApiResponse.success(rbacService.listRoles(), "Roles"); + } + + @POST + @Consumes(MediaType.APPLICATION_JSON) + @PermissionsAllowed("ROLE:WRITE") + @ResponseStatus(201) + public ApiResponse create(@Valid RoleRequest request) { + return ApiResponse.success(rbacService.createRole(request), "Role created"); + } + + @PUT + @Path("/{id}") + @Consumes(MediaType.APPLICATION_JSON) + @PermissionsAllowed("ROLE:WRITE") + public ApiResponse update(@PathParam("id") Long id, @Valid RoleRequest request) { + return ApiResponse.success(rbacService.updateRole(id, request), "Role updated"); + } + + @DELETE + @Path("/{id}") + @PermissionsAllowed("ROLE:WRITE") + public ApiResponse delete(@PathParam("id") Long id) { + rbacService.deleteRole(id); + return ApiResponse.success(null, "Role deleted"); + } + + @POST + @Path("/{id}/permissions/{permissionId}") + @PermissionsAllowed("ROLE:WRITE") + public ApiResponse assignPermission(@PathParam("id") Long id, + @PathParam("permissionId") Long permissionId) { + return ApiResponse.success(rbacService.assignPermissionToRole(id, permissionId), "Permission assigned"); + } + + @DELETE + @Path("/{id}/permissions/{permissionId}") + @PermissionsAllowed("ROLE:WRITE") + public ApiResponse removePermission(@PathParam("id") Long id, + @PathParam("permissionId") Long permissionId) { + return ApiResponse.success(rbacService.removePermissionFromRole(id, permissionId), "Permission removed"); + } +} From 58b82bd43f100f4857220a19d8cb5c3cdd310b14 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 09:23:00 +0400 Subject: [PATCH 066/158] feat(resource): add PermissionResource The permission catalogue can be listed, created, updated and deleted, each method protected by PERMISSION:READ or PERMISSION:WRITE. Deleting a referenced permission is refused by the service. There is deliberately no endpoint to give a permission to a role from this resource. --- .../resource/PermissionResource.java | 68 +++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/resource/PermissionResource.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/resource/PermissionResource.java b/src/main/java/com/edgareldy/quarkustutorial/resource/PermissionResource.java new file mode 100644 index 0000000..57f04a1 --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/resource/PermissionResource.java @@ -0,0 +1,68 @@ +package com.edgareldy.quarkustutorial.resource; + +import com.edgareldy.quarkustutorial.dto.common.ApiResponse; +import com.edgareldy.quarkustutorial.dto.rbac.PermissionRequest; +import com.edgareldy.quarkustutorial.dto.rbac.PermissionResponse; +import com.edgareldy.quarkustutorial.service.RbacService; +import io.quarkus.security.PermissionsAllowed; +import jakarta.inject.Inject; +import jakarta.validation.Valid; +import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.DELETE; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.PUT; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.PathParam; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.MediaType; +import java.util.List; +import org.eclipse.microprofile.openapi.annotations.security.SecurityRequirement; +import org.jboss.resteasy.reactive.ResponseStatus; + +/** + * Permission catalog administration (no endpoint here manages which roles hold a permission). + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +@Path("/api/v1/permissions") +@Produces(MediaType.APPLICATION_JSON) +@SecurityRequirement(name = "jwt") +public class PermissionResource { + + @Inject + RbacService rbacService; + + @GET + @PermissionsAllowed("PERMISSION:READ") + public ApiResponse> list() { + return ApiResponse.success(rbacService.listPermissions(), "Permissions"); + } + + @POST + @Consumes(MediaType.APPLICATION_JSON) + @PermissionsAllowed("PERMISSION:WRITE") + @ResponseStatus(201) + public ApiResponse create(@Valid PermissionRequest request) { + return ApiResponse.success(rbacService.createPermission(request), "Permission created"); + } + + @PUT + @Path("/{id}") + @Consumes(MediaType.APPLICATION_JSON) + @PermissionsAllowed("PERMISSION:WRITE") + public ApiResponse update(@PathParam("id") Long id, @Valid PermissionRequest request) { + return ApiResponse.success(rbacService.updatePermission(id, request), "Permission updated"); + } + + @DELETE + @Path("/{id}") + @PermissionsAllowed("PERMISSION:WRITE") + public ApiResponse delete(@PathParam("id") Long id) { + rbacService.deletePermission(id); + return ApiResponse.success(null, "Permission deleted"); + } +} From cae331c51d1990a0a6abbc98676ce0f9d4ed7d7d Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 09:23:00 +0400 Subject: [PATCH 067/158] feat(scheduler): add a daily cleanup of expired tokens @Scheduled runs the method on a cron expression, here every day at 3 a.m. It deletes the blacklisted, activation and reset token rows that are past their expiry, so the tables stay bounded and the per request revocation lookup stays cheap. The deletion is housekeeping only: a token is rejected on its expiry date whether or not its row still exists, so nothing depends on this job running. The method returns the number of rows deleted so it can be tested without waiting for the cron. --- .../scheduler/ExpiredTokenCleanupJob.java | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/scheduler/ExpiredTokenCleanupJob.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/scheduler/ExpiredTokenCleanupJob.java b/src/main/java/com/edgareldy/quarkustutorial/scheduler/ExpiredTokenCleanupJob.java new file mode 100644 index 0000000..4635b0c --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/scheduler/ExpiredTokenCleanupJob.java @@ -0,0 +1,60 @@ +package com.edgareldy.quarkustutorial.scheduler; + +import com.edgareldy.quarkustutorial.repository.ActivationTokenRepository; +import com.edgareldy.quarkustutorial.repository.BlacklistedTokenRepository; +import com.edgareldy.quarkustutorial.repository.PasswordResetTokenRepository; +import io.quarkus.scheduler.Scheduled; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import jakarta.transaction.Transactional; +import java.time.Instant; +import org.jboss.logging.Logger; + +/** + * Daily housekeeping job purging token rows past their expiry so the tables stay bounded. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +@ApplicationScoped +public class ExpiredTokenCleanupJob { + + private static final Logger LOG = Logger.getLogger(ExpiredTokenCleanupJob.class); + + @Inject + BlacklistedTokenRepository blacklistedTokenRepository; + + @Inject + ActivationTokenRepository activationTokenRepository; + + @Inject + PasswordResetTokenRepository passwordResetTokenRepository; + + // quarkus-scheduler: @Scheduled runs this method by itself on the given Quartz-style cron + // expression (here every day at 03:00), with no endpoint or caller. Deleting expired rows is + // housekeeping only: revocation and expiry checks compare the timestamps and never depend on + // the row still existing, so a late or missed run is harmless. + @Scheduled(cron = "0 0 3 * * ?") + @Transactional + void scheduledCleanup() { + cleanup(); + } + + /** + * Bulk-deletes every blacklisted, activation and password reset token already expired. + * + * @return the total number of rows deleted + */ + @Transactional + public int cleanup() { + Instant now = Instant.now(); + // Panache bulk delete: one DELETE ... WHERE statement per table, no entity loading. + long deleted = blacklistedTokenRepository.delete("expiresAt < ?1", now) + + activationTokenRepository.delete("expiresAt < ?1", now) + + passwordResetTokenRepository.delete("expiryDate < ?1", now); + LOG.infof("Expired token cleanup removed %d row(s)", deleted); + return (int) deleted; + } +} From e3becec62e4567d55a34329ed6c134e1512558d7 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 09:23:00 +0400 Subject: [PATCH 068/158] feat(config): create an optional bootstrap administrator at startup With the seed alone nobody holds the ADMIN role, so the API would stay locked. When an email and a password are both configured, a startup observer creates that user, enabled and with the ADMIN role, if it does not exist yet, and audits the creation. The properties have a clearly fake default only in the dev profile, and nothing for test or production, where they must be set explicitly if wanted. This goes beyond the task list and is documented as an addition. --- .../config/AdminBootstrap.java | 75 +++++++++++++++++++ src/main/resources/application.properties | 6 ++ 2 files changed, 81 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/config/AdminBootstrap.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/config/AdminBootstrap.java b/src/main/java/com/edgareldy/quarkustutorial/config/AdminBootstrap.java new file mode 100644 index 0000000..45c4ca1 --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/config/AdminBootstrap.java @@ -0,0 +1,75 @@ +package com.edgareldy.quarkustutorial.config; + +import com.edgareldy.quarkustutorial.entity.User; +import com.edgareldy.quarkustutorial.repository.RoleRepository; +import com.edgareldy.quarkustutorial.repository.UserRepository; +import com.edgareldy.quarkustutorial.security.AuditLogger; +import io.quarkus.elytron.security.common.BcryptUtil; +import io.quarkus.runtime.StartupEvent; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.enterprise.event.Observes; +import jakarta.inject.Inject; +import jakarta.transaction.Transactional; +import java.util.Optional; +import org.eclipse.microprofile.config.inject.ConfigProperty; +import org.jboss.logging.Logger; + +/** + * Optionally creates the first administrator at startup so that someone can hold the seeded ADMIN role. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +@ApplicationScoped +public class AdminBootstrap { + + private static final Logger LOG = Logger.getLogger(AdminBootstrap.class); + + // Optional config: the properties may be absent (they only have defaults under %dev), and + // then the bootstrap simply does nothing. + @ConfigProperty(name = "app.bootstrap-admin.email") + Optional email; + + @ConfigProperty(name = "app.bootstrap-admin.password") + Optional password; + + @Inject + UserRepository userRepository; + + @Inject + RoleRepository roleRepository; + + @Inject + AuditLogger auditLogger; + + // @Observes StartupEvent: CDI calls this once when the application starts, after the Flyway + // migrations (which seed the ADMIN role) have run. Idempotent: an existing user is left alone. + @Transactional + void onStart(@Observes StartupEvent event) { + if (email.isEmpty() || password.isEmpty() || email.get().isBlank() || password.get().isBlank()) { + return; + } + String address = email.get().trim().toLowerCase(); + if (userRepository.findByEmail(address).isPresent()) { + return; + } + var admin = roleRepository.findByRoleName("ADMIN"); + if (admin.isEmpty()) { + LOG.warn("Bootstrap admin skipped: the ADMIN role does not exist"); + return; + } + User user = new User(); + user.setFirstName("Admin"); + user.setLastName("Bootstrap"); + user.setEmail(address); + user.setPassword(BcryptUtil.bcryptHash(password.get())); + user.setEnabled(true); + user.setAccountLocked(false); + user.getRoles().add(admin.get()); + userRepository.persist(user); + auditLogger.log("BOOTSTRAP_ADMIN_CREATED", "USER", user.getId(), "email " + address); + LOG.infof("Bootstrap admin %s created", address); + } +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index b94cae0..37f1950 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -43,3 +43,9 @@ mp.jwt.verify.issuer=https://api.example.com/quarkus-tutorial smallrye.jwt.new-token.issuer=https://api.example.com/quarkus-tutorial # Access token lifetime in seconds. smallrye.jwt.new-token.lifespan=3600 + +# --- Bootstrap administrator (optional) ------------------------------------- +# When both are set, an enabled user with the seeded ADMIN role is created at startup if absent. +# Dev only, with a clearly fake password; nothing for test or prod (set them explicitly if wanted). +%dev.app.bootstrap-admin.email=admin@dev.local +%dev.app.bootstrap-admin.password=dev-only-admin-password From 0c923bd5ffff4d1c318c78f15c0cdae22f097e1b Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 09:23:00 +0400 Subject: [PATCH 069/158] test(rbac): add shared fixtures for the RBAC tests The tests need administrators, ordinary users and tokens. This CDI test bean creates users directly with a bcrypt hash, assigns roles through the repositories, logs in through the real endpoint to get a token, and reads audit rows back. It also normalises the global state the last administrator rule depends on, since all test classes share one Dev Services database and that rule counts users across the whole database. --- .../quarkustutorial/rbac/RbacTestSupport.java | 318 ++++++++++++++++++ 1 file changed, 318 insertions(+) create mode 100644 src/test/java/com/edgareldy/quarkustutorial/rbac/RbacTestSupport.java diff --git a/src/test/java/com/edgareldy/quarkustutorial/rbac/RbacTestSupport.java b/src/test/java/com/edgareldy/quarkustutorial/rbac/RbacTestSupport.java new file mode 100644 index 0000000..f055229 --- /dev/null +++ b/src/test/java/com/edgareldy/quarkustutorial/rbac/RbacTestSupport.java @@ -0,0 +1,318 @@ +package com.edgareldy.quarkustutorial.rbac; + +import static io.restassured.RestAssured.given; + +import com.edgareldy.quarkustutorial.entity.Permission; +import com.edgareldy.quarkustutorial.entity.Role; +import com.edgareldy.quarkustutorial.entity.User; +import com.edgareldy.quarkustutorial.repository.AuditLogRepository; +import com.edgareldy.quarkustutorial.repository.PermissionRepository; +import com.edgareldy.quarkustutorial.repository.RoleRepository; +import com.edgareldy.quarkustutorial.repository.UserRepository; +import io.quarkus.elytron.security.common.BcryptUtil; +import io.quarkus.narayana.jta.QuarkusTransaction; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import jakarta.persistence.EntityManager; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.CopyOnWriteArrayList; + +/** + * Shared fixture for the RBAC tests: creates users, roles and permissions directly in the database, + * logs users in over HTTP, reads audit rows and normalises the global ROLE:WRITE holder state. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +// A CDI bean living in src/test: @QuarkusTest indexes test classes too, so test classes can @Inject it. Data +// is written through the real repositories inside QuarkusTransaction.requiringNew(), because a test method +// runs on the JUnit thread with no ambient transaction. Every @QuarkusTest class shares one Dev Services +// database, so everything created here is tracked and removed by cleanup() (foreign keys cascade). +@ApplicationScoped +public class RbacTestSupport { + + /** Clear-text password of every user created by this helper. */ + public static final String PASSWORD = "Str0ngPassw0rd!"; + + private static final String PASSWORD_HASH = BcryptUtil.bcryptHash(PASSWORD); + + /** + * A user created by the helper. + * + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + * + * @param id the user id (also the JWT subject) + * @param email the login email + */ + public record TestUser(Long id, String email) { + } + + /** + * Scalar snapshot of an audit log row. + * + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + * + * @param actorUserId the acting user id + * @param action the action code + * @param entityType the entity type + * @param entityId the entity id + * @param details the free-text details + */ + public record AuditRow(Long actorUserId, String action, String entityType, Long entityId, String details) { + } + + /** + * A removed (user, role) link, kept so it can be restored. + * + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + * + * @param userId the user id + * @param roleId the role id + */ + public record Link(Long userId, Long roleId) { + } + + @Inject + EntityManager em; + + @Inject + UserRepository userRepository; + + @Inject + RoleRepository roleRepository; + + @Inject + PermissionRepository permissionRepository; + + @Inject + AuditLogRepository auditLogRepository; + + private final List users = new CopyOnWriteArrayList<>(); + private final List roles = new CopyOnWriteArrayList<>(); + private final List permissions = new CopyOnWriteArrayList<>(); + + /** + * @param prefix a readable prefix + * @return a unique value built from the prefix + */ + public static String unique(String prefix) { + return prefix + "-" + UUID.randomUUID().toString().substring(0, 8); + } + + /** + * Creates an enabled user holding the named roles. + * + * @param roleNames existing role names to assign + * @return the created user + */ + public TestUser createUser(String... roleNames) { + String email = unique("rbac") + "@test.local"; + Long id = QuarkusTransaction.requiringNew().call(() -> { + User user = new User(); + user.setFirstName("Rbac"); + user.setLastName("Tester"); + user.setEmail(email); + user.setPassword(PASSWORD_HASH); + user.setEnabled(true); + user.setAccountLocked(false); + for (String name : roleNames) { + user.getRoles().add(roleRepository.findByRoleName(name).orElseThrow()); + } + userRepository.persist(user); + return user.getId(); + }); + users.add(id); + return new TestUser(id, email); + } + + /** + * Creates a tracked role granting the given permissions. + * + * @param name the role name (made unique by the caller if needed) + * @param permissions permissions written as RESOURCE:ACTION + * @return the role id + */ + public Long createRole(String name, String... permissions) { + Long id = QuarkusTransaction.requiringNew().call(() -> { + Role role = new Role(); + role.setRoleName(name); + for (String p : permissions) { + String[] parts = p.split(":"); + role.getPermissions().add(permissionRepository.findByResourceAndAction(parts[0], parts[1]).orElseThrow()); + } + roleRepository.persist(role); + return role.getId(); + }); + roles.add(id); + return id; + } + + /** + * Creates a tracked permission. + * + * @param resource the resource + * @param action the action + * @return the permission id + */ + public Long createPermission(String resource, String action) { + Long id = QuarkusTransaction.requiringNew().call(() -> { + Permission permission = new Permission(); + permission.setResource(resource); + permission.setAction(action); + permissionRepository.persist(permission); + return permission.getId(); + }); + permissions.add(id); + return id; + } + + /** + * Gives a user a role directly in the database. + * + * @param userId the user id + * @param roleId the role id + */ + public void grantRole(Long userId, Long roleId) { + QuarkusTransaction.requiringNew().run(() -> userRepository.findById(userId).getRoles() + .add(roleRepository.findById(roleId))); + } + + /** + * Makes sure a role created through the API is deleted by cleanup(). + * + * @param roleId the role id + */ + public void trackRole(Long roleId) { + roles.add(roleId); + } + + /** + * Makes sure a permission created through the API is deleted by cleanup(). + * + * @param permissionId the permission id + */ + public void trackPermission(Long permissionId) { + permissions.add(permissionId); + } + + /** + * @param name the role name + * @return the id of the seeded or created role + */ + public Long roleId(String name) { + return QuarkusTransaction.requiringNew().call(() -> roleRepository.findByRoleName(name).orElseThrow().getId()); + } + + /** + * @param resource the resource + * @param action the action + * @return the id of the seeded or created permission + */ + public Long permissionId(String resource, String action) { + return QuarkusTransaction.requiringNew() + .call(() -> permissionRepository.findByResourceAndAction(resource, action).orElseThrow().getId()); + } + + /** + * Logs the user in through the real endpoint. + * + * @param user the user + * @return the JWT + */ + public String token(TestUser user) { + return given().contentType("application/json") + .body("{\"email\":\"" + user.email() + "\",\"password\":\"" + PASSWORD + "\"}") + .when().post("/api/v1/auth/login") + .then().statusCode(200).extract().path("data.token"); + } + + /** + * @param action the action code + * @param entityType the entity type + * @param entityId the entity id + * @return the matching audit rows, oldest first + */ + public List audit(String action, String entityType, Long entityId) { + return QuarkusTransaction.requiringNew().call(() -> auditLogRepository + .list("action = ?1 and entityType = ?2 and entityId = ?3 order by id", action, entityType, entityId) + .stream() + .map(a -> new AuditRow(a.getActorUserId(), a.getAction(), a.getEntityType(), a.getEntityId(), + a.getDetails())) + .toList()); + } + + /** + * Removes every link between a user other than {@code keepUserId} and a role granting ROLE:WRITE, so + * that user becomes the only possible holder. Undo with {@link #restoreLinks(List)}. + * + * @param keepUserId the user to leave alone + * @return the removed links + */ + @SuppressWarnings("unchecked") + public List isolateRoleWriteHolders(Long keepUserId) { + return QuarkusTransaction.requiringNew().call(() -> { + List rows = em.createNativeQuery("select ru.user_id, ru.role_id from role_user ru " + + "where ru.user_id <> ?1 and ru.role_id in (select rp.role_id from role_permission rp " + + "join permissions p on p.id = rp.permission_id where p.resource = 'ROLE' and p.action = 'WRITE')") + .setParameter(1, keepUserId).getResultList(); + List removed = new ArrayList<>(); + for (Object[] row : rows) { + Long userId = ((Number) row[0]).longValue(); + Long roleId = ((Number) row[1]).longValue(); + em.createNativeQuery("delete from role_user where user_id = ?1 and role_id = ?2") + .setParameter(1, userId).setParameter(2, roleId).executeUpdate(); + removed.add(new Link(userId, roleId)); + } + return removed; + }); + } + + /** + * Puts back links removed by {@link #isolateRoleWriteHolders(Long)}, skipping rows whose user or role no + * longer exists. + * + * @param links the links to restore + */ + public void restoreLinks(List links) { + QuarkusTransaction.requiringNew().run(() -> links.forEach(l -> em.createNativeQuery( + "insert into role_user (user_id, role_id) select ?1, ?2 where exists " + + "(select 1 from users where id = ?1) and exists (select 1 from roles where id = ?2) " + + "on conflict do nothing").setParameter(1, l.userId()).setParameter(2, l.roleId()) + .executeUpdate())); + } + + /** + * Deletes every tracked user, role and permission (join rows cascade). + */ + public void cleanup() { + QuarkusTransaction.requiringNew().run(() -> { + delete("users", users); + delete("roles", roles); + delete("permissions", permissions); + }); + users.clear(); + roles.clear(); + permissions.clear(); + } + + private void delete(String table, List ids) { + ids.forEach(id -> em.createNativeQuery("delete from " + table + " where id = ?1").setParameter(1, id) + .executeUpdate()); + } +} From e48f41784b238469b2ce81d7fbfd248538825f4c Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 09:23:00 +0400 Subject: [PATCH 070/158] test(resource): cover role and permission CRUD Both resources are exercised over HTTP for creation, reading, update and deletion, with duplicates refused with 422, unknown ids with 404, invalid bodies with 400, and access denied with 403 or 401. Every error is checked to be a problem document. A caller without the permission gets 403 and none of the state changes, which proves the declarative checks are wired to the augmentor. --- .../resource/PermissionResourceTest.java | 134 ++++++++++++++ .../resource/RoleResourceTest.java | 175 ++++++++++++++++++ 2 files changed, 309 insertions(+) create mode 100644 src/test/java/com/edgareldy/quarkustutorial/resource/PermissionResourceTest.java create mode 100644 src/test/java/com/edgareldy/quarkustutorial/resource/RoleResourceTest.java diff --git a/src/test/java/com/edgareldy/quarkustutorial/resource/PermissionResourceTest.java b/src/test/java/com/edgareldy/quarkustutorial/resource/PermissionResourceTest.java new file mode 100644 index 0000000..0a5003d --- /dev/null +++ b/src/test/java/com/edgareldy/quarkustutorial/resource/PermissionResourceTest.java @@ -0,0 +1,134 @@ +package com.edgareldy.quarkustutorial.resource; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.*; + +import com.edgareldy.quarkustutorial.rbac.RbacTestSupport; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * End-to-end tests of the permission catalog endpoints. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +@QuarkusTest +class PermissionResourceTest { + + private static final String PROBLEM_JSON = "application/problem+json"; + private static final String BASE = "/api/v1/permissions"; + + @Inject + RbacTestSupport support; + + private String admin; + + @BeforeEach + void setUp() { + admin = support.token(support.createUser("ADMIN")); + } + + @AfterEach + void tearDown() { + support.cleanup(); + } + + private Long createViaApi(String resource, String action) { + Long id = given().auth().oauth2(admin).contentType("application/json") + .body("{\"resource\":\"" + resource + "\",\"action\":\"" + action + "\"}") + .when().post(BASE).then().statusCode(201).extract().jsonPath().getLong("data.id"); + support.trackPermission(id); + return id; + } + + @Test + void listReturnsSeededCatalog() { + given().auth().oauth2(admin).when().get(BASE) + .then().statusCode(200).contentType("application/json") + .body("success", is(true)) + .body("data.size()", greaterThanOrEqualTo(14)) + .body("data.find { it.resource == 'ORDER' && it.action == 'WRITE' }", notNullValue()); + } + + @Test + void createNormalisesToUpperCase() { + String resource = RbacTestSupport.unique("res").toUpperCase(); + given().auth().oauth2(admin).contentType("application/json") + .body("{\"resource\":\"" + resource.toLowerCase() + "\",\"action\":\"exec\"}") + .when().post(BASE) + .then().statusCode(201).contentType("application/json") + .body("data.resource", is(resource)).body("data.action", is("EXEC")); + support.trackPermission(support.permissionId(resource, "EXEC")); + } + + @Test + void duplicatePairIs422Problem() { + String resource = RbacTestSupport.unique("res").toUpperCase(); + createViaApi(resource, "READ"); + given().auth().oauth2(admin).contentType("application/json") + .body("{\"resource\":\"" + resource + "\",\"action\":\"READ\"}") + .when().post(BASE) + .then().statusCode(422).contentType(PROBLEM_JSON) + .body("status", is(422)).body("title", is("Business Rule Violation")) + .body("$", not(hasKey("success"))); + } + + @Test + void blankFieldsAre400ValidationProblem() { + given().auth().oauth2(admin).contentType("application/json").body("{\"resource\":\"\",\"action\":\"\"}") + .when().post(BASE) + .then().statusCode(400).contentType(PROBLEM_JSON).body("status", is(400)); + } + + @Test + void updateChangesPairAndRejectsDuplicateOrUnknown() { + String resource = RbacTestSupport.unique("res").toUpperCase(); + Long id = createViaApi(resource, "READ"); + createViaApi(resource, "WRITE"); + given().auth().oauth2(admin).contentType("application/json") + .body("{\"resource\":\"" + resource + "\",\"action\":\"DELETE\"}") + .when().put(BASE + "/" + id) + .then().statusCode(200).body("data.action", is("DELETE")); + given().auth().oauth2(admin).contentType("application/json") + .body("{\"resource\":\"" + resource + "\",\"action\":\"WRITE\"}") + .when().put(BASE + "/" + id) + .then().statusCode(422).contentType(PROBLEM_JSON); + given().auth().oauth2(admin).contentType("application/json").body("{\"resource\":\"A\",\"action\":\"B\"}") + .when().put(BASE + "/999999999") + .then().statusCode(404).contentType(PROBLEM_JSON).body("title", is("Resource Not Found")); + } + + @Test + void deleteRemovesPermissionThenIs404() { + Long id = createViaApi(RbacTestSupport.unique("res").toUpperCase(), "READ"); + given().auth().oauth2(admin).when().delete(BASE + "/" + id) + .then().statusCode(200).body("success", is(true)); + given().auth().oauth2(admin).when().delete(BASE + "/" + id) + .then().statusCode(404).contentType(PROBLEM_JSON); + } + + @Test + void readerCanListButNotWrite() { + support.createRole("perm-reader", "PERMISSION:READ"); + String token = support.token(support.createUser("perm-reader")); + given().auth().oauth2(token).when().get(BASE).then().statusCode(200); + given().auth().oauth2(token).contentType("application/json").body("{\"resource\":\"A\",\"action\":\"B\"}") + .when().post(BASE) + .then().statusCode(403).contentType(PROBLEM_JSON).body("status", is(403)); + given().auth().oauth2(token).when().delete(BASE + "/1") + .then().statusCode(403).contentType(PROBLEM_JSON); + } + + @Test + void userWithoutRolesIsForbiddenAndAnonymousIs401() { + String token = support.token(support.createUser()); + given().auth().oauth2(token).when().get(BASE).then().statusCode(403).contentType(PROBLEM_JSON); + given().when().get(BASE).then().statusCode(401).contentType(PROBLEM_JSON).body("status", is(401)); + } +} diff --git a/src/test/java/com/edgareldy/quarkustutorial/resource/RoleResourceTest.java b/src/test/java/com/edgareldy/quarkustutorial/resource/RoleResourceTest.java new file mode 100644 index 0000000..5a636ae --- /dev/null +++ b/src/test/java/com/edgareldy/quarkustutorial/resource/RoleResourceTest.java @@ -0,0 +1,175 @@ +package com.edgareldy.quarkustutorial.resource; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.*; + +import com.edgareldy.quarkustutorial.rbac.RbacTestSupport; +import com.edgareldy.quarkustutorial.rbac.RbacTestSupport.TestUser; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * End-to-end tests of the role administration endpoints, including permission assignment and denial cases. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +// @QuarkusTest runs the whole application against a Dev Services PostgreSQL that all test classes share, so +// each test creates its own uniquely named data and RbacTestSupport.cleanup() removes it afterwards. +@QuarkusTest +class RoleResourceTest { + + private static final String PROBLEM_JSON = "application/problem+json"; + private static final String BASE = "/api/v1/roles"; + + @Inject + RbacTestSupport support; + + private String admin; + + @BeforeEach + void setUp() { + admin = support.token(support.createUser("ADMIN")); + } + + @AfterEach + void tearDown() { + support.cleanup(); + } + + private Long createRoleViaApi(String name) { + Long id = given().auth().oauth2(admin).contentType("application/json").body("{\"roleName\":\"" + name + "\"}") + .when().post(BASE).then().statusCode(201).extract().jsonPath().getLong("data.id"); + support.trackRole(id); + return id; + } + + @Test + void listIncludesSeededAdminWithItsPermissions() { + given().auth().oauth2(admin).when().get(BASE) + .then().statusCode(200).contentType("application/json") + .body("success", is(true)) + .body("data.find { it.roleName == 'ADMIN' }.permissions.size()", greaterThanOrEqualTo(14)) + .body("data.find { it.roleName == 'ADMIN' }.permissions.resource", hasItem("ROLE")); + } + + @Test + void createReturns201WithEnvelope() { + String name = RbacTestSupport.unique("role"); + given().auth().oauth2(admin).contentType("application/json").body("{\"roleName\":\"" + name + "\"}") + .when().post(BASE) + .then().statusCode(201).contentType("application/json") + .body("success", is(true)) + .body("data.roleName", is(name)) + .body("data.permissions", empty()) + .body("data.id", notNullValue()); + support.trackRole(support.roleId(name)); + } + + @Test + void duplicateNameIs422Problem() { + String name = RbacTestSupport.unique("role"); + createRoleViaApi(name); + given().auth().oauth2(admin).contentType("application/json").body("{\"roleName\":\"" + name + "\"}") + .when().post(BASE) + .then().statusCode(422).contentType(PROBLEM_JSON) + .body("status", is(422)) + .body("title", is("Business Rule Violation")) + .body("detail", containsString(name)) + .body("$", not(hasKey("success"))); + } + + @Test + void blankNameIs400ValidationProblem() { + given().auth().oauth2(admin).contentType("application/json").body("{\"roleName\":\" \"}") + .when().post(BASE) + .then().statusCode(400).contentType(PROBLEM_JSON) + .body("status", is(400)) + .body("$", not(hasKey("success"))); + } + + @Test + void updateRenamesRoleAndRejectsDuplicateOrUnknown() { + Long id = createRoleViaApi(RbacTestSupport.unique("role")); + Long other = createRoleViaApi(RbacTestSupport.unique("role")); + String renamed = RbacTestSupport.unique("renamed"); + given().auth().oauth2(admin).contentType("application/json").body("{\"roleName\":\"" + renamed + "\"}") + .when().put(BASE + "/" + id) + .then().statusCode(200).body("data.roleName", is(renamed)); + + given().auth().oauth2(admin).contentType("application/json").body("{\"roleName\":\"" + renamed + "\"}") + .when().put(BASE + "/" + other) + .then().statusCode(422).contentType(PROBLEM_JSON).body("status", is(422)); + + given().auth().oauth2(admin).contentType("application/json").body("{\"roleName\":\"x\"}") + .when().put(BASE + "/999999999") + .then().statusCode(404).contentType(PROBLEM_JSON) + .body("title", is("Resource Not Found")).body("$", not(hasKey("success"))); + } + + @Test + void deleteRemovesRoleThenIs404() { + Long id = createRoleViaApi(RbacTestSupport.unique("role")); + given().auth().oauth2(admin).when().delete(BASE + "/" + id) + .then().statusCode(200).body("success", is(true)).body("message", is("Role deleted")); + given().auth().oauth2(admin).when().delete(BASE + "/" + id) + .then().statusCode(404).contentType(PROBLEM_JSON); + } + + @Test + void assignAndRemovePermission() { + Long id = createRoleViaApi(RbacTestSupport.unique("role")); + Long readCategory = support.permissionId("CATEGORY", "READ"); + given().auth().oauth2(admin).when().post(BASE + "/" + id + "/permissions/" + readCategory) + .then().statusCode(200) + .body("data.permissions.size()", is(1)) + .body("data.permissions[0].resource", is("CATEGORY")) + .body("data.permissions[0].action", is("READ")); + // Assigning twice is idempotent. + given().auth().oauth2(admin).when().post(BASE + "/" + id + "/permissions/" + readCategory) + .then().statusCode(200).body("data.permissions.size()", is(1)); + given().auth().oauth2(admin).when().delete(BASE + "/" + id + "/permissions/" + readCategory) + .then().statusCode(200).body("data.permissions", empty()); + } + + @Test + void assignUnknownPermissionOrRoleIs404() { + Long id = createRoleViaApi(RbacTestSupport.unique("role")); + given().auth().oauth2(admin).when().post(BASE + "/" + id + "/permissions/999999999") + .then().statusCode(404).contentType(PROBLEM_JSON); + given().auth().oauth2(admin).when().post(BASE + "/999999999/permissions/" + support.permissionId("USER", "READ")) + .then().statusCode(404).contentType(PROBLEM_JSON); + } + + @Test + void readerCanListButNotWrite() { + support.createRole("reader-role", "ROLE:READ"); + TestUser reader = support.createUser("reader-role"); + String token = support.token(reader); + given().auth().oauth2(token).when().get(BASE).then().statusCode(200); + given().auth().oauth2(token).contentType("application/json").body("{\"roleName\":\"nope\"}") + .when().post(BASE) + .then().statusCode(403).contentType(PROBLEM_JSON).body("status", is(403)) + .body("$", not(hasKey("success"))); + given().auth().oauth2(token).when().delete(BASE + "/1").then().statusCode(403).contentType(PROBLEM_JSON); + } + + @Test + void userWithoutAnyRoleIsForbidden() { + String token = support.token(support.createUser()); + given().auth().oauth2(token).when().get(BASE) + .then().statusCode(403).contentType(PROBLEM_JSON).body("status", is(403)); + } + + @Test + void missingTokenIs401Problem() { + given().when().get(BASE) + .then().statusCode(401).contentType(PROBLEM_JSON).body("status", is(401)) + .body("$", not(hasKey("success"))); + } +} From b2abfb49d2ab517e68210a1ed80702ca5211ddfc Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 09:23:01 +0400 Subject: [PATCH 071/158] test(resource): cover the administration of users The tests check the paginated list, the detail with roles, the assignment and removal of a role, the refusal of a page size of zero, and the absence of any way to create a user from this resource. They also check the access rules for a user without USER:READ or USER:WRITE. --- .../resource/UserResourceTest.java | 138 ++++++++++++++++++ 1 file changed, 138 insertions(+) create mode 100644 src/test/java/com/edgareldy/quarkustutorial/resource/UserResourceTest.java diff --git a/src/test/java/com/edgareldy/quarkustutorial/resource/UserResourceTest.java b/src/test/java/com/edgareldy/quarkustutorial/resource/UserResourceTest.java new file mode 100644 index 0000000..c9e6b84 --- /dev/null +++ b/src/test/java/com/edgareldy/quarkustutorial/resource/UserResourceTest.java @@ -0,0 +1,138 @@ +package com.edgareldy.quarkustutorial.resource; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.*; + +import com.edgareldy.quarkustutorial.rbac.RbacTestSupport; +import com.edgareldy.quarkustutorial.rbac.RbacTestSupport.TestUser; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * End-to-end tests of the user administration endpoints: listing, detail and role assignment. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +@QuarkusTest +class UserResourceTest { + + private static final String PROBLEM_JSON = "application/problem+json"; + private static final String BASE = "/api/v1/users"; + + @Inject + RbacTestSupport support; + + private String admin; + + @BeforeEach + void setUp() { + admin = support.token(support.createUser("ADMIN")); + } + + @AfterEach + void tearDown() { + support.cleanup(); + } + + @Test + void listIsPaginatedInsideTheEnvelope() { + support.createUser(); + support.createUser(); + given().auth().oauth2(admin).queryParam("page", 0).queryParam("size", 2).when().get(BASE) + .then().statusCode(200).contentType("application/json") + .body("success", is(true)) + .body("data.content.size()", is(2)) + .body("data.page", is(0)) + .body("data.size", is(2)) + .body("data.totalElements", greaterThanOrEqualTo(3)) + .body("data.totalPages", greaterThanOrEqualTo(2)) + .body("data.content[0]", not(hasKey("password"))); + } + + @Test + void invalidPagingIs400Problem() { + given().auth().oauth2(admin).queryParam("size", 0).when().get(BASE) + .then().statusCode(400).contentType(PROBLEM_JSON).body("status", is(400)) + .body("$", not(hasKey("success"))); + given().auth().oauth2(admin).queryParam("size", 101).when().get(BASE) + .then().statusCode(400).contentType(PROBLEM_JSON); + given().auth().oauth2(admin).queryParam("page", -1).when().get(BASE) + .then().statusCode(400).contentType(PROBLEM_JSON); + } + + @Test + void detailIncludesAssignedRoles() { + TestUser target = support.createUser("ADMIN"); + given().auth().oauth2(admin).when().get(BASE + "/" + target.id()) + .then().statusCode(200) + .body("data.email", is(target.email())) + .body("data.roles.size()", is(1)) + .body("data.roles[0].roleName", is("ADMIN")) + .body("data", not(hasKey("password"))); + } + + @Test + void unknownUserIs404Problem() { + given().auth().oauth2(admin).when().get(BASE + "/999999999") + .then().statusCode(404).contentType(PROBLEM_JSON).body("title", is("Resource Not Found")); + } + + @Test + void assignThenRemoveRole() { + Long roleId = support.createRole(RbacTestSupport.unique("plain")); + TestUser target = support.createUser(); + given().auth().oauth2(admin).when().patch(BASE + "/" + target.id() + "/roles/" + roleId) + .then().statusCode(200) + .body("data.roles.size()", is(1)) + .body("data.roles[0].id", is(roleId.intValue())); + // Assigning twice is idempotent. + given().auth().oauth2(admin).when().patch(BASE + "/" + target.id() + "/roles/" + roleId) + .then().statusCode(200).body("data.roles.size()", is(1)); + given().auth().oauth2(admin).when().delete(BASE + "/" + target.id() + "/roles/" + roleId) + .then().statusCode(200).body("data.roles", empty()); + } + + @Test + void assignWithUnknownUserOrRoleIs404() { + TestUser target = support.createUser(); + given().auth().oauth2(admin).when().patch(BASE + "/999999999/roles/" + support.roleId("ADMIN")) + .then().statusCode(404).contentType(PROBLEM_JSON); + given().auth().oauth2(admin).when().patch(BASE + "/" + target.id() + "/roles/999999999") + .then().statusCode(404).contentType(PROBLEM_JSON); + } + + @Test + void thereIsNoUserCreationEndpoint() { + // Users are created by feature/auth's register endpoint only, never by UserResource. + given().auth().oauth2(admin).contentType("application/json").body("{\"email\":\"a@b.c\"}") + .when().post(BASE).then().statusCode(405); + given().auth().oauth2(admin).contentType("application/json").body("{}") + .when().put(BASE + "/1").then().statusCode(405); + } + + @Test + void readerCanReadButNotAssign() { + support.createRole("user-reader", "USER:READ"); + TestUser reader = support.createUser("user-reader"); + String token = support.token(reader); + given().auth().oauth2(token).when().get(BASE).then().statusCode(200); + given().auth().oauth2(token).when().get(BASE + "/" + reader.id()).then().statusCode(200); + given().auth().oauth2(token).when().patch(BASE + "/" + reader.id() + "/roles/" + support.roleId("ADMIN")) + .then().statusCode(403).contentType(PROBLEM_JSON).body("status", is(403)); + given().auth().oauth2(token).when().delete(BASE + "/" + reader.id() + "/roles/" + support.roleId("ADMIN")) + .then().statusCode(403).contentType(PROBLEM_JSON); + } + + @Test + void userWithoutRolesIsForbiddenAndAnonymousIs401() { + String token = support.token(support.createUser()); + given().auth().oauth2(token).when().get(BASE).then().statusCode(403).contentType(PROBLEM_JSON); + given().when().get(BASE).then().statusCode(401).contentType(PROBLEM_JSON).body("status", is(401)); + } +} From fad7a70e9de228f8f2e83471d896d380242caa23 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 09:23:01 +0400 Subject: [PATCH 072/158] test(resource): check the still referenced rejections Deleting a role a user still holds, or a permission a role still holds, must be refused with 422. The tests then unassign and check the deletion succeeds, which shows the rule is about the current state and not a permanent block. Both rejections are exactly the case the audit trail must keep, which the audit tests check separately. --- .../resource/ReferencedRejectionTest.java | 80 +++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 src/test/java/com/edgareldy/quarkustutorial/resource/ReferencedRejectionTest.java diff --git a/src/test/java/com/edgareldy/quarkustutorial/resource/ReferencedRejectionTest.java b/src/test/java/com/edgareldy/quarkustutorial/resource/ReferencedRejectionTest.java new file mode 100644 index 0000000..e1e5ff0 --- /dev/null +++ b/src/test/java/com/edgareldy/quarkustutorial/resource/ReferencedRejectionTest.java @@ -0,0 +1,80 @@ +package com.edgareldy.quarkustutorial.resource; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.*; + +import com.edgareldy.quarkustutorial.rbac.RbacTestSupport; +import com.edgareldy.quarkustutorial.rbac.RbacTestSupport.TestUser; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * Tests that a role still held by a user, or a permission still assigned to a role, cannot be deleted. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +@QuarkusTest +class ReferencedRejectionTest { + + private static final String PROBLEM_JSON = "application/problem+json"; + + @Inject + RbacTestSupport support; + + private String admin; + + @BeforeEach + void setUp() { + admin = support.token(support.createUser("ADMIN")); + } + + @AfterEach + void tearDown() { + support.cleanup(); + } + + @Test + void roleAssignedToAUserCannotBeDeletedUntilUnassigned() { + Long roleId = support.createRole(RbacTestSupport.unique("held")); + TestUser holder = support.createUser(); + support.grantRole(holder.id(), roleId); + + given().auth().oauth2(admin).when().delete("/api/v1/roles/" + roleId) + .then().statusCode(422).contentType(PROBLEM_JSON) + .body("status", is(422)).body("title", is("Business Rule Violation")) + .body("detail", containsString("still assigned")) + .body("$", not(hasKey("success"))); + // The role survived the rejected delete. + given().auth().oauth2(admin).when().get("/api/v1/roles") + .then().body("data.id", hasItem(roleId.intValue())); + + given().auth().oauth2(admin).when().delete("/api/v1/users/" + holder.id() + "/roles/" + roleId) + .then().statusCode(200); + given().auth().oauth2(admin).when().delete("/api/v1/roles/" + roleId) + .then().statusCode(200).body("success", is(true)); + } + + @Test + void permissionAssignedToARoleCannotBeDeletedUntilUnassigned() { + Long permissionId = support.createPermission(RbacTestSupport.unique("res").toUpperCase(), "READ"); + Long roleId = support.createRole(RbacTestSupport.unique("carrier")); + given().auth().oauth2(admin).when().post("/api/v1/roles/" + roleId + "/permissions/" + permissionId) + .then().statusCode(200); + + given().auth().oauth2(admin).when().delete("/api/v1/permissions/" + permissionId) + .then().statusCode(422).contentType(PROBLEM_JSON) + .body("status", is(422)).body("detail", containsString("still assigned")) + .body("$", not(hasKey("success"))); + + given().auth().oauth2(admin).when().delete("/api/v1/roles/" + roleId + "/permissions/" + permissionId) + .then().statusCode(200); + given().auth().oauth2(admin).when().delete("/api/v1/permissions/" + permissionId) + .then().statusCode(200).body("success", is(true)); + } +} From cc596f63925c64e353abc0753bedb8ea96125af4 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 09:23:01 +0400 Subject: [PATCH 073/158] test(resource): prove the last administrator can never be removed The rule is tested in both required directions: removing the role from the last user who holds a ROLE:WRITE granting role, and removing the permission from the role that is their only source of it. Both answer 422 and leave an audit row. Allowed cases are covered too, with a second holder, a backup role, and a backup role held by another user, so the rule is shown to block only what it should. The test isolates the other holders before each case and restores them after, because the rule counts users across the shared database. --- .../resource/LastAdminProtectionTest.java | 114 ++++++++++++++++++ 1 file changed, 114 insertions(+) create mode 100644 src/test/java/com/edgareldy/quarkustutorial/resource/LastAdminProtectionTest.java diff --git a/src/test/java/com/edgareldy/quarkustutorial/resource/LastAdminProtectionTest.java b/src/test/java/com/edgareldy/quarkustutorial/resource/LastAdminProtectionTest.java new file mode 100644 index 0000000..eb3c597 --- /dev/null +++ b/src/test/java/com/edgareldy/quarkustutorial/resource/LastAdminProtectionTest.java @@ -0,0 +1,114 @@ +package com.edgareldy.quarkustutorial.resource; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.*; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import com.edgareldy.quarkustutorial.rbac.RbacTestSupport; +import com.edgareldy.quarkustutorial.rbac.RbacTestSupport.AuditRow; +import com.edgareldy.quarkustutorial.rbac.RbacTestSupport.Link; +import com.edgareldy.quarkustutorial.rbac.RbacTestSupport.TestUser; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import java.util.List; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * Tests the anti-last-admin rule in both directions: role removal from a user and permission removal from a role. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +// The rule counts ROLE:WRITE holders across the whole database, and the database is shared by every +// @QuarkusTest class. Each test therefore detaches every other holder first (isolateRoleWriteHolders) and +// puts them back afterwards, so the test's own admin is deterministically the only holder. +@QuarkusTest +class LastAdminProtectionTest { + + private static final String PROBLEM_JSON = "application/problem+json"; + + @Inject + RbacTestSupport support; + + private TestUser admin; + private String token; + private Long roleId; + private Long roleWritePermissionId; + private List detached; + + @BeforeEach + void setUp() { + roleWritePermissionId = support.permissionId("ROLE", "WRITE"); + // A dedicated role granting what the admin needs to call the endpoints, plus ROLE:WRITE itself. + roleId = support.createRole(RbacTestSupport.unique("last-admin"), "ROLE:WRITE", "ROLE:READ", "USER:WRITE", "USER:READ"); + admin = support.createUser(); + support.grantRole(admin.id(), roleId); + token = support.token(admin); + detached = support.isolateRoleWriteHolders(admin.id()); + } + + @AfterEach + void tearDown() { + support.cleanup(); + support.restoreLinks(detached); + } + + @Test + void removingTheRoleFromTheLastHolderIsRejectedAndAudited() { + given().auth().oauth2(token).when().delete("/api/v1/users/" + admin.id() + "/roles/" + roleId) + .then().statusCode(422).contentType(PROBLEM_JSON) + .body("status", is(422)).body("detail", containsString("ROLE:WRITE")) + .body("$", not(hasKey("success"))); + + // The business transaction rolled back: the admin still holds the role. + given().auth().oauth2(token).when().get("/api/v1/users/" + admin.id()) + .then().statusCode(200).body("data.roles.id", hasItem(roleId.intValue())); + // The rejection is audited on its own transaction, so it survives that rollback. + List rows = support.audit("ROLE_UNASSIGN_REJECTED", "USER", admin.id()); + assertEquals(1, rows.size()); + assertEquals(admin.id(), rows.get(0).actorUserId()); + } + + @Test + void removingRoleWritePermissionFromTheOnlySourceIsRejectedAndAudited() { + given().auth().oauth2(token).when().delete("/api/v1/roles/" + roleId + "/permissions/" + roleWritePermissionId) + .then().statusCode(422).contentType(PROBLEM_JSON) + .body("status", is(422)).body("detail", containsString("ROLE:WRITE")) + .body("$", not(hasKey("success"))); + + given().auth().oauth2(token).when().get("/api/v1/roles") + .then().body("data.find { it.id == " + roleId + " }.permissions.action", hasItem("WRITE")); + List rows = support.audit("PERMISSION_REMOVE_FROM_ROLE_REJECTED", "ROLE", roleId); + assertEquals(1, rows.size()); + assertEquals(admin.id(), rows.get(0).actorUserId()); + } + + @Test + void roleRemovalIsAllowedWhenAnotherUserStillHoldsRoleWrite() { + TestUser second = support.createUser(); + support.grantRole(second.id(), roleId); + given().auth().oauth2(token).when().delete("/api/v1/users/" + admin.id() + "/roles/" + roleId) + .then().statusCode(200).body("data.roles", empty()); + } + + @Test + void roleRemovalIsAllowedWhenTheUserKeepsRoleWriteThroughAnotherRole() { + Long backup = support.createRole(RbacTestSupport.unique("backup"), "ROLE:WRITE"); + support.grantRole(admin.id(), backup); + given().auth().oauth2(token).when().delete("/api/v1/users/" + admin.id() + "/roles/" + roleId) + .then().statusCode(200).body("data.roles.id", hasItem(backup.intValue())); + } + + @Test + void permissionRemovalIsAllowedWhenAnotherRoleStillGrantsItToAHolder() { + Long backup = support.createRole(RbacTestSupport.unique("backup"), "ROLE:WRITE"); + TestUser second = support.createUser(); + support.grantRole(second.id(), backup); + given().auth().oauth2(token).when().delete("/api/v1/roles/" + roleId + "/permissions/" + roleWritePermissionId) + .then().statusCode(200); + } +} From b3d2dfbaf2eb52ee2efd9dc8d10e5cfc32bc8fdb Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 09:23:01 +0400 Subject: [PATCH 074/158] test(resource): assert every RBAC mutation is audited Each mutation of roles, permissions and their assignments must produce one audit row naming the action, the entity and the caller. The tests check that for every mutation, and that rejected deletions also leave a row even though the business transaction rolled back. This is the check that turns the audit requirement into something the build enforces. --- .../resource/RbacAuditLogTest.java | 132 ++++++++++++++++++ 1 file changed, 132 insertions(+) create mode 100644 src/test/java/com/edgareldy/quarkustutorial/resource/RbacAuditLogTest.java diff --git a/src/test/java/com/edgareldy/quarkustutorial/resource/RbacAuditLogTest.java b/src/test/java/com/edgareldy/quarkustutorial/resource/RbacAuditLogTest.java new file mode 100644 index 0000000..7a24d7e --- /dev/null +++ b/src/test/java/com/edgareldy/quarkustutorial/resource/RbacAuditLogTest.java @@ -0,0 +1,132 @@ +package com.edgareldy.quarkustutorial.resource; + +import static io.restassured.RestAssured.given; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.edgareldy.quarkustutorial.rbac.RbacTestSupport; +import com.edgareldy.quarkustutorial.rbac.RbacTestSupport.AuditRow; +import com.edgareldy.quarkustutorial.rbac.RbacTestSupport.TestUser; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import java.util.List; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * Tests that every RBAC mutation, and every rejected attempt, leaves an audit row naming the acting user. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +@QuarkusTest +class RbacAuditLogTest { + + @Inject + RbacTestSupport support; + + private TestUser admin; + private String token; + + @BeforeEach + void setUp() { + admin = support.createUser("ADMIN"); + token = support.token(admin); + } + + @AfterEach + void tearDown() { + support.cleanup(); + } + + private void assertAudited(String action, String type, Long entityId) { + List rows = support.audit(action, type, entityId); + assertEquals(1, rows.size(), action + " should be audited exactly once"); + assertEquals(admin.id(), rows.get(0).actorUserId(), action + " should name the caller as actor"); + assertTrue(rows.get(0).details() != null && !rows.get(0).details().isBlank()); + } + + private Long post(String url, String body) { + return given().auth().oauth2(token).contentType("application/json").body(body).when().post(url) + .then().statusCode(201).extract().jsonPath().getLong("data.id"); + } + + @Test + void roleCreateUpdateDeleteAreAudited() { + Long id = post("/api/v1/roles", "{\"roleName\":\"" + RbacTestSupport.unique("audit") + "\"}"); + support.trackRole(id); + assertAudited("ROLE_CREATED", "ROLE", id); + + given().auth().oauth2(token).contentType("application/json") + .body("{\"roleName\":\"" + RbacTestSupport.unique("audit2") + "\"}") + .when().put("/api/v1/roles/" + id).then().statusCode(200); + assertAudited("ROLE_UPDATED", "ROLE", id); + + given().auth().oauth2(token).when().delete("/api/v1/roles/" + id).then().statusCode(200); + assertAudited("ROLE_DELETED", "ROLE", id); + } + + @Test + void permissionCreateUpdateDeleteAreAudited() { + String resource = RbacTestSupport.unique("res").toUpperCase(); + Long id = post("/api/v1/permissions", "{\"resource\":\"" + resource + "\",\"action\":\"READ\"}"); + support.trackPermission(id); + assertAudited("PERMISSION_CREATED", "PERMISSION", id); + + given().auth().oauth2(token).contentType("application/json") + .body("{\"resource\":\"" + resource + "\",\"action\":\"WRITE\"}") + .when().put("/api/v1/permissions/" + id).then().statusCode(200); + assertAudited("PERMISSION_UPDATED", "PERMISSION", id); + + given().auth().oauth2(token).when().delete("/api/v1/permissions/" + id).then().statusCode(200); + assertAudited("PERMISSION_DELETED", "PERMISSION", id); + } + + @Test + void permissionAssignAndRemoveOnARoleAreAudited() { + Long roleId = support.createRole(RbacTestSupport.unique("audit")); + Long permissionId = support.permissionId("CATEGORY", "READ"); + given().auth().oauth2(token).when().post("/api/v1/roles/" + roleId + "/permissions/" + permissionId) + .then().statusCode(200); + // A repeated assign changes nothing, so it must not add a second row. + given().auth().oauth2(token).when().post("/api/v1/roles/" + roleId + "/permissions/" + permissionId) + .then().statusCode(200); + assertAudited("PERMISSION_ASSIGNED_TO_ROLE", "ROLE", roleId); + + given().auth().oauth2(token).when().delete("/api/v1/roles/" + roleId + "/permissions/" + permissionId) + .then().statusCode(200); + assertAudited("PERMISSION_REMOVED_FROM_ROLE", "ROLE", roleId); + } + + @Test + void roleAssignAndRemoveOnAUserAreAudited() { + Long roleId = support.createRole(RbacTestSupport.unique("audit")); + TestUser target = support.createUser(); + given().auth().oauth2(token).when().patch("/api/v1/users/" + target.id() + "/roles/" + roleId) + .then().statusCode(200); + assertAudited("ROLE_ASSIGNED_TO_USER", "USER", target.id()); + + given().auth().oauth2(token).when().delete("/api/v1/users/" + target.id() + "/roles/" + roleId) + .then().statusCode(200); + assertAudited("ROLE_REMOVED_FROM_USER", "USER", target.id()); + } + + @Test + void rejectedDeletesAreAuditedDespiteTheRollback() { + Long roleId = support.createRole(RbacTestSupport.unique("audit")); + TestUser holder = support.createUser(); + support.grantRole(holder.id(), roleId); + given().auth().oauth2(token).when().delete("/api/v1/roles/" + roleId).then().statusCode(422); + assertAudited("ROLE_DELETE_REJECTED", "ROLE", roleId); + assertEquals(0, support.audit("ROLE_DELETED", "ROLE", roleId).size()); + + Long permissionId = support.createPermission(RbacTestSupport.unique("res").toUpperCase(), "READ"); + given().auth().oauth2(token).when().post("/api/v1/roles/" + roleId + "/permissions/" + permissionId) + .then().statusCode(200); + given().auth().oauth2(token).when().delete("/api/v1/permissions/" + permissionId).then().statusCode(422); + assertAudited("PERMISSION_DELETE_REJECTED", "PERMISSION", permissionId); + } +} From 447b84e9a11964d41aa28133a06e64ff8fa6b5a2 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 09:23:01 +0400 Subject: [PATCH 075/158] test(security): verify the permission augmentor and the annotation checks A user with several roles receives the union of their permissions, a user without roles receives none, and an anonymous identity is left unchanged. One focused test then shows a @PermissionsAllowed protected endpoint accepting and refusing accordingly. Testing the augmentor directly pins down the format of the permissions it adds, which is the part most likely to break silently. --- ...rmissionSecurityIdentityAugmentorTest.java | 100 ++++++++++++++++++ 1 file changed, 100 insertions(+) create mode 100644 src/test/java/com/edgareldy/quarkustutorial/security/PermissionSecurityIdentityAugmentorTest.java diff --git a/src/test/java/com/edgareldy/quarkustutorial/security/PermissionSecurityIdentityAugmentorTest.java b/src/test/java/com/edgareldy/quarkustutorial/security/PermissionSecurityIdentityAugmentorTest.java new file mode 100644 index 0000000..02314ba --- /dev/null +++ b/src/test/java/com/edgareldy/quarkustutorial/security/PermissionSecurityIdentityAugmentorTest.java @@ -0,0 +1,100 @@ +package com.edgareldy.quarkustutorial.security; + +import static io.restassured.RestAssured.given; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.edgareldy.quarkustutorial.rbac.RbacTestSupport; +import com.edgareldy.quarkustutorial.rbac.RbacTestSupport.TestUser; +import io.quarkus.security.StringPermission; +import io.quarkus.security.identity.AuthenticationRequestContext; +import io.quarkus.security.identity.SecurityIdentity; +import io.quarkus.security.runtime.QuarkusPrincipal; +import io.quarkus.security.runtime.QuarkusSecurityIdentity; +import io.smallrye.mutiny.Uni; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import java.util.function.Supplier; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +/** + * Tests that the augmentor resolves permissions from all of a user's roles and leaves anonymous identities alone. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +// The augmentor is a real CDI bean backed by the Dev Services database, so it is injected and called directly +// with hand-built identities; a stub AuthenticationRequestContext runs the blocking supplier on the caller +// thread, which is fine here because the test thread is not an event loop. +@QuarkusTest +class PermissionSecurityIdentityAugmentorTest { + + @Inject + PermissionSecurityIdentityAugmentor augmentor; + + @Inject + RbacTestSupport support; + + private static final AuthenticationRequestContext DIRECT = new AuthenticationRequestContext() { + @Override + public Uni runBlocking(Supplier function) { + return Uni.createFrom().item(function); + } + }; + + @AfterEach + void tearDown() { + support.cleanup(); + } + + private SecurityIdentity augmentFor(Long userId) { + SecurityIdentity input = QuarkusSecurityIdentity.builder() + .setPrincipal(new QuarkusPrincipal(String.valueOf(userId))).build(); + return augmentor.augment(input, DIRECT).await().indefinitely(); + } + + private static boolean has(SecurityIdentity identity, String resource, String action) { + return identity.checkPermission(new StringPermission(resource, action)).await().indefinitely(); + } + + @Test + void multiRoleUserGetsTheUnionOfPermissions() { + support.createRole("aug-a", "USER:READ", "CATEGORY:READ"); + support.createRole("aug-b", "CATEGORY:READ", "ORDER:WRITE"); + TestUser user = support.createUser("aug-a", "aug-b"); + + SecurityIdentity identity = augmentFor(user.id()); + assertTrue(has(identity, "USER", "READ")); + assertTrue(has(identity, "CATEGORY", "READ")); + assertTrue(has(identity, "ORDER", "WRITE")); + assertFalse(has(identity, "ROLE", "WRITE")); + } + + @Test + void userWithoutRolesGetsNoPermission() { + TestUser user = support.createUser(); + SecurityIdentity identity = augmentFor(user.id()); + assertFalse(has(identity, "USER", "READ")); + assertFalse(has(identity, "ROLE", "WRITE")); + } + + @Test + void anonymousIdentityIsReturnedUnchanged() { + SecurityIdentity anonymous = QuarkusSecurityIdentity.builder().setAnonymous(true).build(); + assertSame(anonymous, augmentor.augment(anonymous, DIRECT).await().indefinitely()); + } + + @Test + void permissionsAllowedEndpointFollowsTheAugmentedPermissions() { + support.createRole("aug-c", "PERMISSION:READ"); + String token = support.token(support.createUser("aug-c")); + // PERMISSION:READ was resolved by the augmentor at request time: accepted here, rejected for USER:READ. + given().auth().oauth2(token).when().get("/api/v1/permissions").then().statusCode(200); + assertEquals(403, given().auth().oauth2(token).when().get("/api/v1/users").statusCode()); + } +} From 69d997df738485131ceb838b21f967f21c8f4f3f Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 09:23:01 +0400 Subject: [PATCH 076/158] test(scheduler): check the expired token cleanup The cleanup method is called directly rather than waiting for the cron: expired rows of the three token tables are deleted, unexpired rows are kept, and the returned count matches. A first purge makes the expected count exact even though other tests share the database. --- .../scheduler/ExpiredTokenCleanupJobTest.java | 109 ++++++++++++++++++ 1 file changed, 109 insertions(+) create mode 100644 src/test/java/com/edgareldy/quarkustutorial/scheduler/ExpiredTokenCleanupJobTest.java diff --git a/src/test/java/com/edgareldy/quarkustutorial/scheduler/ExpiredTokenCleanupJobTest.java b/src/test/java/com/edgareldy/quarkustutorial/scheduler/ExpiredTokenCleanupJobTest.java new file mode 100644 index 0000000..f93173f --- /dev/null +++ b/src/test/java/com/edgareldy/quarkustutorial/scheduler/ExpiredTokenCleanupJobTest.java @@ -0,0 +1,109 @@ +package com.edgareldy.quarkustutorial.scheduler; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import com.edgareldy.quarkustutorial.entity.ActivationToken; +import com.edgareldy.quarkustutorial.entity.BlacklistedToken; +import com.edgareldy.quarkustutorial.entity.PasswordResetToken; +import com.edgareldy.quarkustutorial.repository.ActivationTokenRepository; +import com.edgareldy.quarkustutorial.repository.BlacklistedTokenRepository; +import com.edgareldy.quarkustutorial.repository.PasswordResetTokenRepository; +import com.edgareldy.quarkustutorial.repository.UserRepository; +import com.edgareldy.quarkustutorial.rbac.RbacTestSupport; +import com.edgareldy.quarkustutorial.rbac.RbacTestSupport.TestUser; +import io.quarkus.narayana.jta.QuarkusTransaction; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import java.time.Duration; +import java.time.Instant; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +/** + * Tests that the cleanup job deletes expired rows from the three token tables and keeps the live ones. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +// The job is called directly instead of waiting for its 03:00 cron trigger: @Scheduled only decides when the +// method runs, the behaviour worth testing is in cleanup() itself. +@QuarkusTest +class ExpiredTokenCleanupJobTest { + + @Inject + ExpiredTokenCleanupJob job; + + @Inject + RbacTestSupport support; + + @Inject + UserRepository userRepository; + + @Inject + BlacklistedTokenRepository blacklistedTokenRepository; + + @Inject + ActivationTokenRepository activationTokenRepository; + + @Inject + PasswordResetTokenRepository passwordResetTokenRepository; + + @AfterEach + void tearDown() { + support.cleanup(); + } + + private void insertTokens(TestUser owner, String tag, Instant expiry) { + QuarkusTransaction.requiringNew().run(() -> { + var user = userRepository.findById(owner.id()); + Instant now = Instant.now(); + BlacklistedToken b = new BlacklistedToken(); + b.setUser(user); + b.setToken("t-" + tag); + b.setJti("jti-" + tag); + b.setBlacklistedAt(now); + b.setCreatedAt(now); + b.setExpiresAt(expiry); + blacklistedTokenRepository.persist(b); + ActivationToken a = new ActivationToken(); + a.setUser(user); + a.setToken("a-" + tag); + a.setCreatedAt(now); + a.setExpiresAt(expiry); + activationTokenRepository.persist(a); + PasswordResetToken p = new PasswordResetToken(); + p.setUser(user); + p.setToken("p-" + tag); + p.setType(PasswordResetToken.TYPE_PASSWORD_RESET); + p.setExpiryDate(expiry); + passwordResetTokenRepository.persist(p); + }); + } + + private long count(String tag) { + return QuarkusTransaction.requiringNew().call(() -> + blacklistedTokenRepository.count("jti", "jti-" + tag) + + activationTokenRepository.count("token", "a-" + tag) + + passwordResetTokenRepository.count("token", "p-" + tag)); + } + + @Test + void deletesExpiredRowsOfAllThreeTablesAndKeepsTheRest() { + // Purge anything expired that other test classes left, so the count below is exact. + job.cleanup(); + TestUser owner = support.createUser(); + String tag = RbacTestSupport.unique("clean"); + insertTokens(owner, tag + "-old", Instant.now().minus(Duration.ofHours(2))); + insertTokens(owner, tag + "-live", Instant.now().plus(Duration.ofHours(2))); + + int deleted = job.cleanup(); + + assertEquals(3, deleted); + assertEquals(0, count(tag + "-old")); + assertEquals(3, count(tag + "-live")); + // A second run finds nothing left of ours to delete. + assertEquals(0, job.cleanup()); + } +} From a34d71af64e4fb18bdbe00f77aeb1d3370fd4131 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 09:31:48 +0400 Subject: [PATCH 077/158] fix(repository): count only active accounts as administrators The last administrator rule compared holders of ROLE:WRITE without looking at their state. A disabled or locked account cannot log in, so it satisfied the rule while nobody able to authenticate could still administer roles, and the lockout the rule exists to prevent could happen anyway. The holder queries now only count enabled and unlocked users, which is the meaning of the rule: somebody who can actually act must remain. --- .../quarkustutorial/repository/UserRepository.java | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/edgareldy/quarkustutorial/repository/UserRepository.java b/src/main/java/com/edgareldy/quarkustutorial/repository/UserRepository.java index 59009a6..217a35b 100644 --- a/src/main/java/com/edgareldy/quarkustutorial/repository/UserRepository.java +++ b/src/main/java/com/edgareldy/quarkustutorial/repository/UserRepository.java @@ -63,10 +63,11 @@ public Optional findWithRolesById(Long id) { /** * @param resource the permission resource * @param action the permission action - * @return whether (count above zero) users hold a role granting this permission + * @return how many ENABLED, unlocked users hold a role granting this permission (an account that + * cannot log in must not count as an administrator) */ public long countHolders(String resource, String action) { - return count("from User u join u.roles r join r.permissions p where p.resource = ?1 and p.action = ?2", + return count("from User u join u.roles r join r.permissions p where p.resource = ?1 and p.action = ?2 and u.enabled = true and u.accountLocked = false", resource, action); } @@ -78,7 +79,8 @@ public long countHolders(String resource, String action) { */ public long countHoldersExcludingUser(String resource, String action, Long userId) { return count("from User u join u.roles r join r.permissions p " - + "where p.resource = ?1 and p.action = ?2 and u.id <> ?3", resource, action, userId); + + "where p.resource = ?1 and p.action = ?2 and u.id <> ?3 " + + "and u.enabled = true and u.accountLocked = false", resource, action, userId); } /** @@ -89,7 +91,8 @@ public long countHoldersExcludingUser(String resource, String action, Long userI */ public long countHoldersExcludingRole(String resource, String action, Long roleId) { return count("from User u join u.roles r join r.permissions p " - + "where p.resource = ?1 and p.action = ?2 and r.id <> ?3", resource, action, roleId); + + "where p.resource = ?1 and p.action = ?2 and r.id <> ?3 " + + "and u.enabled = true and u.accountLocked = false", resource, action, roleId); } /** From 6d5bb59d7c228261cb135baad006a8bba9ea27cc Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 09:31:48 +0400 Subject: [PATCH 078/158] fix(security): keep success audit rows transactional and serialise last admin checks The audit logger used a separate transaction for every row, so a success entry was committed before the business operation and stayed in the log even if that operation then failed. Success rows now join the caller's transaction and disappear with it on rollback, and only refused attempts, which must survive the rollback the refusal causes, use their own transaction through logRejected. This also stops every mutation from holding two connections at once. The last administrator checks count holders and then write, so two administrators removing each other at the same moment could both pass and leave nobody with ROLE:WRITE. The operations that can remove a holder now take a PostgreSQL advisory lock scoped to the transaction, which makes them queue and released automatically at commit or rollback, so the second one counts after the first has committed. --- .../quarkustutorial/security/AuditLogger.java | 31 +++++++++++++++--- .../service/impl/RbacServiceImpl.java | 32 ++++++++++++++++--- 2 files changed, 53 insertions(+), 10 deletions(-) diff --git a/src/main/java/com/edgareldy/quarkustutorial/security/AuditLogger.java b/src/main/java/com/edgareldy/quarkustutorial/security/AuditLogger.java index bb73f4e..43fdb30 100644 --- a/src/main/java/com/edgareldy/quarkustutorial/security/AuditLogger.java +++ b/src/main/java/com/edgareldy/quarkustutorial/security/AuditLogger.java @@ -28,18 +28,39 @@ public class AuditLogger { JsonWebToken jwt; /** - * Stores one audit row. It runs in its own transaction so that a REJECTED attempt is kept even - * though the caller's business transaction is then rolled back by the exception it throws. + * Stores the audit row of an operation that succeeded. It joins the caller's transaction, so the + * row is committed with the change it describes and vanishes with it if that change is rolled back. * - * @param action what happened, for example ROLE_CREATED or ROLE_DELETE_REJECTED + * @param action what happened, for example ROLE_CREATED + * @param entityType the kind of entity concerned, for example ROLE + * @param entityId the entity id, or null + * @param details free text with the context + */ + // A plain @Transactional (REQUIRED) joins the transaction of the caller, or starts one if there is + // none. A success entry must not outlive a business transaction that later fails. + @Transactional + public void log(String action, String entityType, Long entityId, String details) { + store(action, entityType, entityId, details); + } + + /** + * Stores the audit row of a REFUSED attempt. It runs in its own transaction so the row is kept + * even though the caller's business transaction is then rolled back by the exception it throws. + * + * @param action what was refused, for example ROLE_DELETE_REJECTED * @param entityType the kind of entity concerned, for example ROLE * @param entityId the entity id, or null * @param details free text with the context */ // Transactional.TxType.REQUIRES_NEW suspends the caller's transaction and commits this insert - // independently: a plain @Transactional would join the caller's and vanish with its rollback. + // independently. It holds a second connection for a moment, which is acceptable because it only + // happens on refusals, not on every mutation. @Transactional(Transactional.TxType.REQUIRES_NEW) - public void log(String action, String entityType, Long entityId, String details) { + public void logRejected(String action, String entityType, Long entityId, String details) { + store(action, entityType, entityId, details); + } + + private void store(String action, String entityType, Long entityId, String details) { AuditLog entry = new AuditLog(); entry.setActorUserId(currentActor()); entry.setAction(action); diff --git a/src/main/java/com/edgareldy/quarkustutorial/service/impl/RbacServiceImpl.java b/src/main/java/com/edgareldy/quarkustutorial/service/impl/RbacServiceImpl.java index 5f37d47..8aba8b9 100644 --- a/src/main/java/com/edgareldy/quarkustutorial/service/impl/RbacServiceImpl.java +++ b/src/main/java/com/edgareldy/quarkustutorial/service/impl/RbacServiceImpl.java @@ -20,6 +20,7 @@ import io.quarkus.panache.common.Sort; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; +import jakarta.persistence.EntityManager; import jakarta.transaction.Transactional; import java.util.Comparator; import java.util.List; @@ -52,6 +53,12 @@ public class RbacServiceImpl implements RbacService { @Inject AuditLogger auditLogger; + @Inject + EntityManager entityManager; + + // Arbitrary constant identifying the "last administrator" rule to PostgreSQL advisory locks. + private static final long LAST_ADMIN_LOCK_KEY = 7_301_001L; + // ---- users ------------------------------------------------------------------------------- @Override @@ -86,6 +93,7 @@ public UserDetailResponse assignRoleToUser(Long userId, Long roleId) { @Override @Transactional public UserDetailResponse removeRoleFromUser(Long userId, Long roleId) { + lockLastAdminRule(); User user = findUser(userId); Role role = findRole(roleId); if (!user.getRoles().contains(role)) { @@ -96,7 +104,7 @@ public UserDetailResponse removeRoleFromUser(Long userId, Long roleId) { && userRepository.countHoldersExcludingUser(ADMIN_RESOURCE, ADMIN_ACTION, userId) == 0) { // Logged before throwing: the audit insert commits on its own (REQUIRES_NEW), so it // survives the rollback this exception triggers. - auditLogger.log("ROLE_UNASSIGN_REJECTED", "USER", userId, + auditLogger.logRejected("ROLE_UNASSIGN_REJECTED", "USER", userId, "role " + role.getRoleName() + " (" + roleId + "): " + LAST_ADMIN); throw new BusinessRuleException(LAST_ADMIN); } @@ -149,7 +157,7 @@ public void deleteRole(Long id) { // ROLE:WRITE from the last holder: no separate last-admin check is needed here. long holders = userRepository.countByRoleId(id); if (holders > 0) { - auditLogger.log("ROLE_DELETE_REJECTED", "ROLE", id, "still assigned to " + holders + " user(s)"); + auditLogger.logRejected("ROLE_DELETE_REJECTED", "ROLE", id, "still assigned to " + holders + " user(s)"); throw new BusinessRuleException("Role " + role.getRoleName() + " is still assigned to " + holders + " user(s); remove it from them first"); } @@ -172,6 +180,7 @@ public RoleResponse assignPermissionToRole(Long roleId, Long permissionId) { @Override @Transactional public RoleResponse removePermissionFromRole(Long roleId, Long permissionId) { + lockLastAdminRule(); Role role = findRole(roleId); Permission permission = findPermission(permissionId); if (!role.getPermissions().contains(permission)) { @@ -182,7 +191,7 @@ public RoleResponse removePermissionFromRole(Long roleId, Long permissionId) { if (ADMIN_RESOURCE.equals(permission.getResource()) && ADMIN_ACTION.equals(permission.getAction()) && userRepository.countByRoleId(roleId) > 0 && userRepository.countHoldersExcludingRole(ADMIN_RESOURCE, ADMIN_ACTION, roleId) == 0) { - auditLogger.log("PERMISSION_REMOVE_FROM_ROLE_REJECTED", "ROLE", roleId, + auditLogger.logRejected("PERMISSION_REMOVE_FROM_ROLE_REJECTED", "ROLE", roleId, "permission " + label(permission) + ": " + LAST_ADMIN); throw new BusinessRuleException(LAST_ADMIN); } @@ -220,6 +229,7 @@ public PermissionResponse createPermission(PermissionRequest request) { @Override @Transactional public PermissionResponse updatePermission(Long id, PermissionRequest request) { + lockLastAdminRule(); Permission permission = findPermission(id); String resource = normalize(request.resource()); String action = normalize(request.action()); @@ -231,7 +241,7 @@ public PermissionResponse updatePermission(Long id, PermissionRequest request) { boolean wasAdmin = ADMIN_RESOURCE.equals(permission.getResource()) && ADMIN_ACTION.equals(permission.getAction()); boolean stillAdmin = ADMIN_RESOURCE.equals(resource) && ADMIN_ACTION.equals(action); if (wasAdmin && !stillAdmin && userRepository.countHolders(ADMIN_RESOURCE, ADMIN_ACTION) > 0) { - auditLogger.log("PERMISSION_UPDATE_REJECTED", "PERMISSION", id, "renaming " + label(permission) + ": " + LAST_ADMIN); + auditLogger.logRejected("PERMISSION_UPDATE_REJECTED", "PERMISSION", id, "renaming " + label(permission) + ": " + LAST_ADMIN); throw new BusinessRuleException(LAST_ADMIN); } String previous = label(permission); @@ -249,7 +259,7 @@ public void deletePermission(Long id) { // ROLE:WRITE from the last holder either: no separate last-admin check is needed here. long roles = roleRepository.countByPermissionId(id); if (roles > 0) { - auditLogger.log("PERMISSION_DELETE_REJECTED", "PERMISSION", id, "still assigned to " + roles + " role(s)"); + auditLogger.logRejected("PERMISSION_DELETE_REJECTED", "PERMISSION", id, "still assigned to " + roles + " role(s)"); throw new BusinessRuleException("Permission " + label(permission) + " is still assigned to " + roles + " role(s); remove it from them first"); } @@ -307,4 +317,16 @@ private static UserDetailResponse toResponse(User u) { u.getRoles().stream().sorted(Comparator.comparing(Role::getId)) .map(r -> new UserDetailResponse.RoleSummary(r.getId(), r.getRoleName())).toList()); } + + /** + * Serialises the operations that can strip the last ROLE:WRITE holder. Each of them counts the + * holders and then writes, and two concurrent transactions could each see the other holder still + * in place and both commit. A transaction scoped advisory lock makes them queue: it is released + * automatically at commit or rollback, so the second one counts after the first has committed. + */ + private void lockLastAdminRule() { + entityManager.createNativeQuery("select cast(pg_advisory_xact_lock(?1) as text)") + .setParameter(1, LAST_ADMIN_LOCK_KEY) + .getResultList(); + } } From a02f6d971bfa323b68d722e4dbd0d90b85b4abd8 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 09:32:21 +0400 Subject: [PATCH 079/158] docs(readme): check off feature/rbac and document the bootstrap administrator The feature/rbac checklist is ticked now that every task is implemented and covered by the build. The seeding task now says how it was done: a Flyway data migration for the baseline permissions and the ADMIN role. Because nobody can hold ADMIN after that seed alone, the task also records the optional bootstrap administrator, created at startup only when its email and password are configured and given clearly fake defaults in the dev profile only. It is an addition to the original task list, so it is written down where the list is. --- README.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 43b278b..0ae441a 100644 --- a/README.md +++ b/README.md @@ -313,18 +313,18 @@ Full CRUD for users, roles, and permissions. Assignments always flow in one dire ### Tasks -- [ ] `Role`, `Permission`, `AuditLog` entities, `RoleRepository`, `PermissionRepository`, `AuditLogRepository` -- [ ] `RbacService` (interface) + implementation: +- [x] `Role`, `Permission`, `AuditLog` entities, `RoleRepository`, `PermissionRepository`, `AuditLogRepository` +- [x] `RbacService` (interface) + implementation: - `createRole`/`updateRole`/`deleteRole` - `deleteRole` rejects if any user is still assigned this role (must be unassigned first) - `createPermission`/`updatePermission`/`deletePermission` - `deletePermission` rejects if any role still has this permission assigned - `assignPermissionToRole`/`removePermissionFromRole` - `removePermissionFromRole` rejects removing `ROLE:WRITE` from a role if doing so would leave **zero** users anywhere holding a role that grants `ROLE:WRITE` - `assignRoleToUser`/`removeRoleFromUser` - `removeRoleFromUser` applies the same last-admin check at the point of removal from a specific user, so a self-lockout is caught however it's attempted -- [ ] `AuditLogger`: a single `log(String action, String entityType, Long entityId, String details)` method, called from every method above - every RBAC mutation is traceable (who did what, to what, when), not just the happy-path ones -- [ ] `PermissionSecurityIdentityAugmentor` (`SecurityIdentityAugmentor`): after JWT validation, loads the user's roles and permissions, adds each `RESOURCE:ACTION` string to the identity as a `StringPermission` -- [ ] `UserResource`, `RoleResource`, `PermissionResource`, each method annotated `@PermissionsAllowed("...")` as listed above - `UserResource` only manages role assignment on existing users, it never creates a user directly (registration stays exclusively `feature/auth`'s job) -- [ ] A seeding step (a `@Observes StartupEvent` method, or a Flyway data-migration): baseline permissions covering every resource/action this project defines, assigned to a seeded `ADMIN` role - without this, nobody could ever be granted `ROLE:WRITE`/`PERMISSION:WRITE` to create the first assignment -- [ ] `ExpiredTokenCleanupJob` (`@Scheduled(cron = "0 0 3 * * ?")`, `quarkus-scheduler`): daily job deleting `BlacklistedToken`/`ActivationToken`/`PasswordResetToken` rows past their expiry, so both tables stay bounded over time - revocation and expiry checks never depend on the row still existing, so deleting it later is purely housekeeping, not a correctness concern -- [ ] Tests: full CRUD on roles and permissions, the "still referenced" rejection on both `deleteRole` and `deletePermission`, the augmentor granting the expected permissions for a multi-role user, a `@PermissionsAllowed`-protected endpoint accepting/rejecting correctly, and specifically the last-admin rejection triggered both ways (removing the role from the last user who has it, and removing the permission from the role that was their only source of it), plus an assertion that every mutation above produces a matching `AuditLog` row +- [x] `AuditLogger`: a single `log(String action, String entityType, Long entityId, String details)` method, called from every method above - every RBAC mutation is traceable (who did what, to what, when), not just the happy-path ones +- [x] `PermissionSecurityIdentityAugmentor` (`SecurityIdentityAugmentor`): after JWT validation, loads the user's roles and permissions, adds each `RESOURCE:ACTION` string to the identity as a `StringPermission` +- [x] `UserResource`, `RoleResource`, `PermissionResource`, each method annotated `@PermissionsAllowed("...")` as listed above - `UserResource` only manages role assignment on existing users, it never creates a user directly (registration stays exclusively `feature/auth`'s job) +- [x] A seeding step (a `@Observes StartupEvent` method, or a Flyway data-migration): baseline permissions covering every resource/action this project defines, assigned to a seeded `ADMIN` role - without this, nobody could ever be granted `ROLE:WRITE`/`PERMISSION:WRITE` to create the first assignment (done as the Flyway migration `V2__seed_baseline_rbac.sql`; an optional `AdminBootstrap` startup observer, active only when `app.bootstrap-admin.email` and `app.bootstrap-admin.password` are set and given dev-only defaults in `%dev`, creates the first administrator, since nobody can otherwise hold `ADMIN`) +- [x] `ExpiredTokenCleanupJob` (`@Scheduled(cron = "0 0 3 * * ?")`, `quarkus-scheduler`): daily job deleting `BlacklistedToken`/`ActivationToken`/`PasswordResetToken` rows past their expiry, so both tables stay bounded over time - revocation and expiry checks never depend on the row still existing, so deleting it later is purely housekeeping, not a correctness concern +- [x] Tests: full CRUD on roles and permissions, the "still referenced" rejection on both `deleteRole` and `deletePermission`, the augmentor granting the expected permissions for a multi-role user, a `@PermissionsAllowed`-protected endpoint accepting/rejecting correctly, and specifically the last-admin rejection triggered both ways (removing the role from the last user who has it, and removing the permission from the role that was their only source of it), plus an assertion that every mutation above produces a matching `AuditLog` row ## feature/categories From f06a4731024f1657bfdebabed20eb090c7941923 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 09:39:43 +0400 Subject: [PATCH 080/158] test(security): pin down the transaction behaviour of the audit logger Success rows must follow the fate of the business operation and refusal rows must not. The tests check that a row written with log disappears when the caller's transaction is rolled back and stays when it commits, and that a row written with logRejected survives the rollback of its caller. This is the property the two methods exist for, so it is tested directly instead of being inferred from the endpoint tests. --- .../security/AuditLoggerTransactionTest.java | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 src/test/java/com/edgareldy/quarkustutorial/security/AuditLoggerTransactionTest.java diff --git a/src/test/java/com/edgareldy/quarkustutorial/security/AuditLoggerTransactionTest.java b/src/test/java/com/edgareldy/quarkustutorial/security/AuditLoggerTransactionTest.java new file mode 100644 index 0000000..65fe5e5 --- /dev/null +++ b/src/test/java/com/edgareldy/quarkustutorial/security/AuditLoggerTransactionTest.java @@ -0,0 +1,57 @@ +package com.edgareldy.quarkustutorial.security; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import com.edgareldy.quarkustutorial.rbac.RbacTestSupport; +import io.quarkus.narayana.jta.QuarkusTransaction; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import org.junit.jupiter.api.Test; + +/** + * Tests the transactional contract of AuditLogger: successes join the caller's transaction, refusals do not. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +// The caller's transaction is opened by hand with QuarkusTransaction and rolled back by throwing, which is the +// same situation as a BusinessRuleException leaving a @Transactional service method. +@QuarkusTest +class AuditLoggerTransactionTest { + + @Inject + AuditLogger auditLogger; + + @Inject + RbacTestSupport support; + + @Test + void successRowIsRolledBackWithTheBusinessTransaction() { + String action = RbacTestSupport.unique("TX_SUCCESS"); + assertThrows(IllegalStateException.class, () -> QuarkusTransaction.requiringNew().run(() -> { + auditLogger.log(action, "TEST", 1L, "must vanish"); + throw new IllegalStateException("rollback"); + })); + assertEquals(0, support.audit(action, "TEST", 1L).size()); + } + + @Test + void successRowIsKeptWhenTheTransactionCommits() { + String action = RbacTestSupport.unique("TX_COMMIT"); + QuarkusTransaction.requiringNew().run(() -> auditLogger.log(action, "TEST", 2L, "kept")); + assertEquals(1, support.audit(action, "TEST", 2L).size()); + } + + @Test + void rejectedRowSurvivesTheCallersRollback() { + String action = RbacTestSupport.unique("TX_REJECTED"); + assertThrows(IllegalStateException.class, () -> QuarkusTransaction.requiringNew().run(() -> { + auditLogger.logRejected(action, "TEST", 3L, "must survive"); + throw new IllegalStateException("rollback"); + })); + assertEquals(1, support.audit(action, "TEST", 3L).size()); + } +} From 5165ede62504bfe55a10ab8c24db92a5fa1608ac Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 09:39:43 +0400 Subject: [PATCH 081/158] test(resource): cover inactive holders and concurrent removals in the last admin rule A disabled or a locked account no longer counts as an administrator, in both directions of the rule, while an enabled unlocked holder allows the removal. The support class gained helpers to change an account state and to count the active holders. A concurrency test makes two administrators remove each other's role at the same instant over several iterations. It asserts that the two calls are never both accepted and that somebody able to administer remains. It does not require a 422, because the loser can legitimately get a 403 once the winner has committed and stripped its permissions before its request is authorised. --- .../quarkustutorial/rbac/RbacTestSupport.java | 27 +++++++ .../resource/LastAdminProtectionTest.java | 76 +++++++++++++++++++ 2 files changed, 103 insertions(+) diff --git a/src/test/java/com/edgareldy/quarkustutorial/rbac/RbacTestSupport.java b/src/test/java/com/edgareldy/quarkustutorial/rbac/RbacTestSupport.java index f055229..16cc166 100644 --- a/src/test/java/com/edgareldy/quarkustutorial/rbac/RbacTestSupport.java +++ b/src/test/java/com/edgareldy/quarkustutorial/rbac/RbacTestSupport.java @@ -193,6 +193,33 @@ public void grantRole(Long userId, Long roleId) { .add(roleRepository.findById(roleId))); } + /** + * Sets the enabled and locked flags of a user directly in the database. + * + * @param userId the user id + * @param enabled the enabled flag + * @param locked the account locked flag + */ + public void setStatus(Long userId, boolean enabled, boolean locked) { + QuarkusTransaction.requiringNew().run(() -> { + User user = userRepository.findById(userId); + user.setEnabled(enabled); + user.setAccountLocked(locked); + }); + } + + /** + * @return how many enabled, unlocked users currently hold a role granting ROLE:WRITE + */ + public long countActiveRoleWriteHolders() { + return QuarkusTransaction.requiringNew().call(() -> ((Number) em.createNativeQuery( + "select count(distinct u.id) from users u join role_user ru on ru.user_id = u.id " + + "join role_permission rp on rp.role_id = ru.role_id " + + "join permissions p on p.id = rp.permission_id " + + "where p.resource = 'ROLE' and p.action = 'WRITE' and u.enabled = true " + + "and u.account_locked = false").getSingleResult()).longValue()); + } + /** * Makes sure a role created through the API is deleted by cleanup(). * diff --git a/src/test/java/com/edgareldy/quarkustutorial/resource/LastAdminProtectionTest.java b/src/test/java/com/edgareldy/quarkustutorial/resource/LastAdminProtectionTest.java index eb3c597..5d8bb1c 100644 --- a/src/test/java/com/edgareldy/quarkustutorial/resource/LastAdminProtectionTest.java +++ b/src/test/java/com/edgareldy/quarkustutorial/resource/LastAdminProtectionTest.java @@ -3,6 +3,7 @@ import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.*; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import com.edgareldy.quarkustutorial.rbac.RbacTestSupport; import com.edgareldy.quarkustutorial.rbac.RbacTestSupport.AuditRow; @@ -10,7 +11,15 @@ import com.edgareldy.quarkustutorial.rbac.RbacTestSupport.TestUser; import io.quarkus.test.junit.QuarkusTest; import jakarta.inject.Inject; +import java.util.ArrayList; import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -111,4 +120,71 @@ void permissionRemovalIsAllowedWhenAnotherRoleStillGrantsItToAHolder() { given().auth().oauth2(token).when().delete("/api/v1/roles/" + roleId + "/permissions/" + roleWritePermissionId) .then().statusCode(200); } + + @ParameterizedTest + @CsvSource({"false,false", "true,true"}) + void inactiveOtherHolderDoesNotCountAsAnotherAdmin(boolean enabled, boolean locked) { + // The other holder is disabled (or locked): they cannot act, so the caller is the last active admin. + TestUser other = support.createUser(); + support.grantRole(other.id(), roleId); + support.setStatus(other.id(), enabled, locked); + + given().auth().oauth2(token).when().delete("/api/v1/users/" + admin.id() + "/roles/" + roleId) + .then().statusCode(422).contentType(PROBLEM_JSON).body("status", is(422)); + given().auth().oauth2(token).when().delete("/api/v1/roles/" + roleId + "/permissions/" + roleWritePermissionId) + .then().statusCode(422).contentType(PROBLEM_JSON).body("status", is(422)); + } + + @Test + void enabledUnlockedOtherHolderAllowsRemoval() { + TestUser other = support.createUser(); + support.grantRole(other.id(), roleId); + support.setStatus(other.id(), true, false); + given().auth().oauth2(token).when().delete("/api/v1/users/" + admin.id() + "/roles/" + roleId) + .then().statusCode(200); + } + + @Test + void concurrentCrossRemovalsNeverLeaveZeroActiveAdmins() throws Exception { + // Admin A holds roleId, admin B holds roleB; each removes the other's role at the same instant. + // The advisory lock in removeRoleFromUser serialises them, so the second one sees the first commit. + Long roleB = support.createRole(RbacTestSupport.unique("last-admin-b"), "ROLE:WRITE", "ROLE:READ", + "USER:WRITE", "USER:READ"); + TestUser adminB = support.createUser(); + support.grantRole(adminB.id(), roleB); + String tokenB = support.token(adminB); + detached.addAll(support.isolateRoleWriteHolders(admin.id())); + // isolate keeps only the given user, so re-detach nobody else: B is meant to stay, restore is a no-op. + ExecutorService pool = Executors.newFixedThreadPool(2); + try { + for (int i = 0; i < 5; i++) { + support.grantRole(admin.id(), roleId); + support.grantRole(adminB.id(), roleB); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch go = new CountDownLatch(1); + List> results = new ArrayList<>(); + results.add(pool.submit(removal(ready, go, token, adminB.id(), roleB))); + results.add(pool.submit(removal(ready, go, tokenB, admin.id(), roleId))); + ready.await(); + go.countDown(); + int first = results.get(0).get(); + int second = results.get(1).get(); + // The loser is refused: 422 from the rule, or 403 if the winner already stripped its permissions. + assertTrue(!(first == 200 && second == 200), "both removals succeeded: " + first + "," + second); + assertTrue(support.countActiveRoleWriteHolders() >= 1, "no active ROLE:WRITE holder left"); + } + } finally { + pool.shutdownNow(); + } + } + + private Callable removal(CountDownLatch ready, CountDownLatch go, String bearer, Long userId, + Long role) { + return () -> { + ready.countDown(); + go.await(); + return given().auth().oauth2(bearer).when().delete("/api/v1/users/" + userId + "/roles/" + role) + .statusCode(); + }; + } } From 8e7823cbcbf0f6b42b475e0697e09db42ac2aa59 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 10:08:59 +0400 Subject: [PATCH 082/158] feat(entity): add the Category entity and its repository A category groups products and is mapped to the categories table created by the Flyway migration, following the same plain entity and Panache repository pattern as the rest of the project. There is no Product entity yet, so the rule that forbids deleting a category that still has products cannot use one. The repository counts products with a native query on the products table instead, and says so in a comment: once the products feature adds its own repository, this count should move there. Writing the rule now against the table keeps it enforced from the first day, without waiting for a later branch. --- .../quarkustutorial/entity/Category.java | 33 ++++++++++++++++++ .../repository/CategoryRepository.java | 34 +++++++++++++++++++ 2 files changed, 67 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/entity/Category.java create mode 100644 src/main/java/com/edgareldy/quarkustutorial/repository/CategoryRepository.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/entity/Category.java b/src/main/java/com/edgareldy/quarkustutorial/entity/Category.java new file mode 100644 index 0000000..e7e290b --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/entity/Category.java @@ -0,0 +1,33 @@ +package com.edgareldy.quarkustutorial.entity; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; + +/** + * A product category of the e-commerce domain. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +@Entity +@Table(name = "categories") +public class Category { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "category_name", nullable = false, length = 150) + private String categoryName; + + public Long getId() { return id; } + public void setId(Long id) { this.id = id; } + public String getCategoryName() { return categoryName; } + public void setCategoryName(String categoryName) { this.categoryName = categoryName; } +} diff --git a/src/main/java/com/edgareldy/quarkustutorial/repository/CategoryRepository.java b/src/main/java/com/edgareldy/quarkustutorial/repository/CategoryRepository.java new file mode 100644 index 0000000..5333d28 --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/repository/CategoryRepository.java @@ -0,0 +1,34 @@ +package com.edgareldy.quarkustutorial.repository; + +import com.edgareldy.quarkustutorial.entity.Category; +import io.quarkus.hibernate.orm.panache.PanacheRepository; +import jakarta.enterprise.context.ApplicationScoped; + +/** + * Panache repository for categories. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +@ApplicationScoped +public class CategoryRepository implements PanacheRepository { + + /** + * Counts the products of a category with a native query on the products table. + *

+ * TODO(feature/products): there is no Product entity yet, hence the native SQL. Once it exists, + * replace this with a ProductRepository count by category and remove this method. + * + * @param categoryId the category id + * @return how many products reference this category + */ + public long countProducts(Long categoryId) { + Number count = (Number) getEntityManager() + .createNativeQuery("select count(*) from products where category_id = :categoryId") + .setParameter("categoryId", categoryId) + .getSingleResult(); + return count.longValue(); + } +} From 160be122f4fd16699d354c05dc6e265a1a92ea0c Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 10:08:59 +0400 Subject: [PATCH 083/158] feat(dto): add the category request and response records The request carries the category name, which must not be blank and is limited to the length of the column, so a bad body is refused with a Problem Details response before reaching the service. The response exposes the id and the name and never the entity. These are the first records of the e-commerce domain, which lives in its own package next to the identity and RBAC ones. --- .../dto/ecommerce/CategoryRequest.java | 15 +++++++++++++++ .../dto/ecommerce/CategoryResponse.java | 12 ++++++++++++ 2 files changed, 27 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/dto/ecommerce/CategoryRequest.java create mode 100644 src/main/java/com/edgareldy/quarkustutorial/dto/ecommerce/CategoryResponse.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/dto/ecommerce/CategoryRequest.java b/src/main/java/com/edgareldy/quarkustutorial/dto/ecommerce/CategoryRequest.java new file mode 100644 index 0000000..422ac36 --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/dto/ecommerce/CategoryRequest.java @@ -0,0 +1,15 @@ +package com.edgareldy.quarkustutorial.dto.ecommerce; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Size; + +/** + * Payload to create or update a category. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +public record CategoryRequest(@NotBlank @Size(max = 150) String categoryName) { +} diff --git a/src/main/java/com/edgareldy/quarkustutorial/dto/ecommerce/CategoryResponse.java b/src/main/java/com/edgareldy/quarkustutorial/dto/ecommerce/CategoryResponse.java new file mode 100644 index 0000000..7058911 --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/dto/ecommerce/CategoryResponse.java @@ -0,0 +1,12 @@ +package com.edgareldy.quarkustutorial.dto.ecommerce; + +/** + * Category as returned by the API. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +public record CategoryResponse(Long id, String categoryName) { +} From cd6d680bbeab57041c5c32af6fa9ca8dc0a78d18 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 10:08:59 +0400 Subject: [PATCH 084/158] feat(service): add the CategoryService contract The contract offers a paginated list, a lookup by id, and creation, update and deletion, all in terms of DTOs. Deletion is where the business rule lives, which is why it belongs in the service and not in the resource. As elsewhere, resources depend on this interface and tests can replace its implementation. --- .../service/CategoryService.java | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/service/CategoryService.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/service/CategoryService.java b/src/main/java/com/edgareldy/quarkustutorial/service/CategoryService.java new file mode 100644 index 0000000..6c7619e --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/service/CategoryService.java @@ -0,0 +1,31 @@ +package com.edgareldy.quarkustutorial.service; + +import com.edgareldy.quarkustutorial.dto.common.PageResponse; +import com.edgareldy.quarkustutorial.dto.ecommerce.CategoryRequest; +import com.edgareldy.quarkustutorial.dto.ecommerce.CategoryResponse; + +/** + * Contract for category management. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +public interface CategoryService { + + /** @return one page of categories ordered by id */ + PageResponse list(int page, int size); + + /** @return the category, or throws ResourceNotFoundException (404) */ + CategoryResponse findById(Long id); + + /** @return the created category */ + CategoryResponse create(CategoryRequest request); + + /** @return the updated category, or throws ResourceNotFoundException (404) */ + CategoryResponse update(Long id, CategoryRequest request); + + /** Deletes a category; 404 if missing, BusinessRuleException (422) if it still has products. */ + void delete(Long id); +} From a8799ab447668e6112f98950f0b51ca22dc766ff Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 10:08:59 +0400 Subject: [PATCH 085/158] feat(service): implement CategoryService with the deletion rule Reading a missing category answers 404 through ResourceNotFoundException, and deleting a category that still has products answers 422 through BusinessRuleException, since the request is well formed and it is the state of the data that forbids it. Write methods run in a transaction so the check and the deletion are one unit. The list orders by id so pages are stable, and builds the page from the requested index, the size and the total count. --- .../service/impl/CategoryServiceImpl.java | 84 +++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/service/impl/CategoryServiceImpl.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/service/impl/CategoryServiceImpl.java b/src/main/java/com/edgareldy/quarkustutorial/service/impl/CategoryServiceImpl.java new file mode 100644 index 0000000..eeba735 --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/service/impl/CategoryServiceImpl.java @@ -0,0 +1,84 @@ +package com.edgareldy.quarkustutorial.service.impl; + +import com.edgareldy.quarkustutorial.dto.common.PageResponse; +import com.edgareldy.quarkustutorial.dto.ecommerce.CategoryRequest; +import com.edgareldy.quarkustutorial.dto.ecommerce.CategoryResponse; +import com.edgareldy.quarkustutorial.entity.Category; +import com.edgareldy.quarkustutorial.exception.BusinessRuleException; +import com.edgareldy.quarkustutorial.exception.ResourceNotFoundException; +import com.edgareldy.quarkustutorial.repository.CategoryRepository; +import com.edgareldy.quarkustutorial.service.CategoryService; +import io.quarkus.panache.common.Page; +import io.quarkus.panache.common.Sort; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import jakarta.transaction.Transactional; +import java.util.List; + +/** + * Default {@link CategoryService} backed by Panache. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +@ApplicationScoped +public class CategoryServiceImpl implements CategoryService { + + @Inject + CategoryRepository categoryRepository; + + @Override + @Transactional + public PageResponse list(int page, int size) { + List content = categoryRepository.findAll(Sort.by("id")).page(Page.of(page, size)) + .list().stream().map(CategoryServiceImpl::toResponse).toList(); + return PageResponse.of(content, page, size, categoryRepository.count()); + } + + @Override + @Transactional + public CategoryResponse findById(Long id) { + return toResponse(find(id)); + } + + @Override + @Transactional + public CategoryResponse create(CategoryRequest request) { + Category category = new Category(); + category.setCategoryName(request.categoryName()); + categoryRepository.persist(category); + return toResponse(category); + } + + @Override + @Transactional + public CategoryResponse update(Long id, CategoryRequest request) { + Category category = find(id); + category.setCategoryName(request.categoryName()); + return toResponse(category); + } + + @Override + @Transactional + public void delete(Long id) { + Category category = find(id); + if (categoryRepository.countProducts(id) > 0) { + throw new BusinessRuleException("Category " + id + " still has products and cannot be deleted"); + } + categoryRepository.delete(category); + } + + private Category find(Long id) { + Category category = categoryRepository.findById(id); + if (category == null) { + throw new ResourceNotFoundException("Category " + id + " not found"); + } + return category; + } + + private static CategoryResponse toResponse(Category category) { + return new CategoryResponse(category.getId(), category.getCategoryName()); + } +} From 14e274dea03876d6a55e86247d5a90dc637b5a06 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 10:08:59 +0400 Subject: [PATCH 086/158] feat(resource): add CategoryResource The five endpoints of the specification are protected with @PermissionsAllowed, CATEGORY:READ for reading and CATEGORY:WRITE for the rest, and the resource only validates, delegates and wraps the result in the success envelope. Creating answers 201. The page parameters are bounded like the user list, so a size of zero is refused instead of producing an empty page count. --- .../resource/CategoryResource.java | 81 +++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/resource/CategoryResource.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/resource/CategoryResource.java b/src/main/java/com/edgareldy/quarkustutorial/resource/CategoryResource.java new file mode 100644 index 0000000..e08b5fe --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/resource/CategoryResource.java @@ -0,0 +1,81 @@ +package com.edgareldy.quarkustutorial.resource; + +import com.edgareldy.quarkustutorial.dto.common.ApiResponse; +import com.edgareldy.quarkustutorial.dto.common.PageResponse; +import com.edgareldy.quarkustutorial.dto.ecommerce.CategoryRequest; +import com.edgareldy.quarkustutorial.dto.ecommerce.CategoryResponse; +import com.edgareldy.quarkustutorial.service.CategoryService; +import io.quarkus.security.PermissionsAllowed; +import jakarta.inject.Inject; +import jakarta.validation.Valid; +import jakarta.validation.constraints.Max; +import jakarta.validation.constraints.Min; +import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.DELETE; +import jakarta.ws.rs.DefaultValue; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.PUT; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.PathParam; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.QueryParam; +import jakarta.ws.rs.core.MediaType; +import org.eclipse.microprofile.openapi.annotations.security.SecurityRequirement; +import org.jboss.resteasy.reactive.ResponseStatus; + +/** + * CRUD endpoints for product categories. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +@Path("/api/v1/categories") +@Produces(MediaType.APPLICATION_JSON) +@SecurityRequirement(name = "jwt") +public class CategoryResource { + + @Inject + CategoryService categoryService; + + @GET + @PermissionsAllowed("CATEGORY:READ") + public ApiResponse> list( + @QueryParam("page") @DefaultValue("0") @Min(0) int page, + @QueryParam("size") @DefaultValue("20") @Min(1) @Max(100) int size) { + return ApiResponse.success(categoryService.list(page, size), "Categories"); + } + + @GET + @Path("/{id}") + @PermissionsAllowed("CATEGORY:READ") + public ApiResponse get(@PathParam("id") Long id) { + return ApiResponse.success(categoryService.findById(id), "Category"); + } + + @POST + @Consumes(MediaType.APPLICATION_JSON) + @PermissionsAllowed("CATEGORY:WRITE") + @ResponseStatus(201) + public ApiResponse create(@Valid CategoryRequest request) { + return ApiResponse.success(categoryService.create(request), "Category created"); + } + + @PUT + @Path("/{id}") + @Consumes(MediaType.APPLICATION_JSON) + @PermissionsAllowed("CATEGORY:WRITE") + public ApiResponse update(@PathParam("id") Long id, @Valid CategoryRequest request) { + return ApiResponse.success(categoryService.update(id, request), "Category updated"); + } + + @DELETE + @Path("/{id}") + @PermissionsAllowed("CATEGORY:WRITE") + public ApiResponse delete(@PathParam("id") Long id) { + categoryService.delete(id); + return ApiResponse.success(null, "Category deleted"); + } +} From 176cb944adff2211a6c522238b04b6d109ca7a17 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 10:08:59 +0400 Subject: [PATCH 087/158] test(resource): cover every category endpoint and its access rules Each endpoint is exercised over HTTP, including pagination and ordering, missing ids, invalid bodies, and the rejection case: deleting a category that still has a product answers 422 as a problem document, then succeeds once the product is gone. The permission tests use a user with read access only, who can list but gets 403 on every write, a user with no permission at all, and a request without a token. The fixtures come from the shared RBAC test support instead of being rebuilt. --- .../resource/CategoryResourceTest.java | 209 ++++++++++++++++++ 1 file changed, 209 insertions(+) create mode 100644 src/test/java/com/edgareldy/quarkustutorial/resource/CategoryResourceTest.java diff --git a/src/test/java/com/edgareldy/quarkustutorial/resource/CategoryResourceTest.java b/src/test/java/com/edgareldy/quarkustutorial/resource/CategoryResourceTest.java new file mode 100644 index 0000000..3e09a1f --- /dev/null +++ b/src/test/java/com/edgareldy/quarkustutorial/resource/CategoryResourceTest.java @@ -0,0 +1,209 @@ +package com.edgareldy.quarkustutorial.resource; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.*; + +import com.edgareldy.quarkustutorial.rbac.RbacTestSupport; +import io.quarkus.narayana.jta.QuarkusTransaction; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import jakarta.persistence.EntityManager; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * End-to-end tests of the category endpoints: CRUD, pagination, validation, the delete-with-products + * rejection and permission denial. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +// Same approach as RoleResourceTest: real HTTP against a Dev Services database, with users created through +// RbacTestSupport. Categories and products created here are tracked and removed in tearDown(). +@QuarkusTest +class CategoryResourceTest { + + private static final String PROBLEM_JSON = "application/problem+json"; + private static final String BASE = "/api/v1/categories"; + + @Inject + RbacTestSupport support; + + @Inject + EntityManager em; + + private final List categories = new ArrayList<>(); + private final List products = new ArrayList<>(); + private String admin; + + @BeforeEach + void setUp() { + admin = support.token(support.createUser("ADMIN")); + } + + @AfterEach + void tearDown() { + QuarkusTransaction.requiringNew().run(() -> { + products.forEach(id -> em.createNativeQuery("delete from products where id = ?1").setParameter(1, id) + .executeUpdate()); + categories.forEach(id -> em.createNativeQuery("delete from categories where id = ?1") + .setParameter(1, id).executeUpdate()); + }); + categories.clear(); + products.clear(); + support.cleanup(); + } + + private Long createViaApi(String name) { + Long id = given().auth().oauth2(admin).contentType("application/json") + .body("{\"categoryName\":\"" + name + "\"}").when().post(BASE) + .then().statusCode(201).extract().jsonPath().getLong("data.id"); + categories.add(id); + return id; + } + + private Long insertProduct(Long categoryId) { + Long id = QuarkusTransaction.requiringNew().call(() -> ((Number) em.createNativeQuery( + "insert into products (category_id, product_name, unit_price) values (?1, 'P', 1.00) returning id") + .setParameter(1, categoryId).getSingleResult()).longValue()); + products.add(id); + return id; + } + + private String tokenWith(String... permissions) { + Long role = support.createRole(RbacTestSupport.unique("cat-role"), permissions); + RbacTestSupport.TestUser user = support.createUser(); + support.grantRole(user.id(), role); + return support.token(user); + } + + @Test + void createReturns201WithEnvelope() { + String name = RbacTestSupport.unique("cat"); + Long id = given().auth().oauth2(admin).contentType("application/json") + .body("{\"categoryName\":\"" + name + "\"}").when().post(BASE) + .then().statusCode(201).contentType("application/json") + .body("success", is(true)) + .body("data.categoryName", is(name)) + .body("data.id", notNullValue()) + .extract().jsonPath().getLong("data.id"); + categories.add(id); + } + + @Test + void getByIdAndUpdate() { + Long id = createViaApi(RbacTestSupport.unique("cat")); + given().auth().oauth2(admin).when().get(BASE + "/" + id) + .then().statusCode(200).body("success", is(true)).body("data.id", is(id.intValue())); + given().auth().oauth2(admin).contentType("application/json").body("{\"categoryName\":\"Renamed\"}") + .when().put(BASE + "/" + id) + .then().statusCode(200).body("data.categoryName", is("Renamed")); + given().auth().oauth2(admin).when().get(BASE + "/" + id) + .then().statusCode(200).body("data.categoryName", is("Renamed")); + } + + @Test + void listIsPaginatedAndOrderedById() { + Long a = createViaApi(RbacTestSupport.unique("cat")); + Long b = createViaApi(RbacTestSupport.unique("cat")); + Long c = createViaApi(RbacTestSupport.unique("cat")); + given().auth().oauth2(admin).queryParam("size", 100).when().get(BASE) + .then().statusCode(200).body("success", is(true)) + .body("data.content.id", hasItems(a.intValue(), b.intValue(), c.intValue())) + .body("data.content.id", contains(given().auth().oauth2(admin).queryParam("size", 100).get(BASE) + .jsonPath().getList("data.content.id").stream().sorted().toArray())); + given().auth().oauth2(admin).queryParam("page", 1).queryParam("size", 1).when().get(BASE) + .then().statusCode(200) + .body("data.page", is(1)).body("data.size", is(1)) + .body("data.content.size()", is(1)) + .body("data.totalElements", greaterThanOrEqualTo(3)) + .body("data.totalPages", equalTo(given().auth().oauth2(admin).queryParam("size", 1).get(BASE) + .jsonPath().getInt("data.totalElements"))); + } + + @Test + void invalidPageSizeIs400Problem() { + given().auth().oauth2(admin).queryParam("size", 0).when().get(BASE) + .then().statusCode(400).contentType(PROBLEM_JSON).body("$", not(hasKey("success"))); + } + + @Test + void unknownIdIs404Problem() { + given().auth().oauth2(admin).when().get(BASE + "/999999999") + .then().statusCode(404).contentType(PROBLEM_JSON).body("status", is(404)) + .body("$", not(hasKey("success"))); + given().auth().oauth2(admin).contentType("application/json").body("{\"categoryName\":\"x\"}") + .when().put(BASE + "/999999999") + .then().statusCode(404).contentType(PROBLEM_JSON); + given().auth().oauth2(admin).when().delete(BASE + "/999999999") + .then().statusCode(404).contentType(PROBLEM_JSON); + } + + @Test + void invalidBodyIs400ProblemWithViolations() { + String tooLong = "x".repeat(151); + for (String body : List.of("{\"categoryName\":\" \"}", "{\"categoryName\":\"" + tooLong + "\"}")) { + given().auth().oauth2(admin).contentType("application/json").body(body).when().post(BASE) + .then().statusCode(400).contentType(PROBLEM_JSON) + .body("status", is(400)) + .body("violations", not(empty())) + .body("$", not(hasKey("success"))); + } + Long id = createViaApi(RbacTestSupport.unique("cat")); + given().auth().oauth2(admin).contentType("application/json").body("{\"categoryName\":\"\"}") + .when().put(BASE + "/" + id) + .then().statusCode(400).contentType(PROBLEM_JSON); + } + + @Test + void deleteRemovesCategory() { + Long id = createViaApi(RbacTestSupport.unique("cat")); + given().auth().oauth2(admin).when().delete(BASE + "/" + id) + .then().statusCode(200).body("success", is(true)); + given().auth().oauth2(admin).when().get(BASE + "/" + id).then().statusCode(404).contentType(PROBLEM_JSON); + } + + @Test + void deleteWithProductsIs422UntilProductRemoved() { + Long id = createViaApi(RbacTestSupport.unique("cat")); + Long productId = insertProduct(id); + given().auth().oauth2(admin).when().delete(BASE + "/" + id) + .then().statusCode(422).contentType(PROBLEM_JSON).body("status", is(422)) + .body("$", not(hasKey("success"))); + given().auth().oauth2(admin).when().get(BASE + "/" + id).then().statusCode(200); + + QuarkusTransaction.requiringNew().run(() -> em.createNativeQuery("delete from products where id = ?1") + .setParameter(1, productId).executeUpdate()); + given().auth().oauth2(admin).when().delete(BASE + "/" + id).then().statusCode(200); + } + + @Test + void readOnlyUserCanReadButNotWrite() { + Long id = createViaApi(RbacTestSupport.unique("cat")); + String reader = tokenWith("CATEGORY:READ"); + given().auth().oauth2(reader).when().get(BASE).then().statusCode(200); + given().auth().oauth2(reader).when().get(BASE + "/" + id).then().statusCode(200); + given().auth().oauth2(reader).contentType("application/json").body("{\"categoryName\":\"n\"}") + .when().post(BASE).then().statusCode(403).contentType(PROBLEM_JSON).body("status", is(403)); + given().auth().oauth2(reader).contentType("application/json").body("{\"categoryName\":\"n\"}") + .when().put(BASE + "/" + id).then().statusCode(403).contentType(PROBLEM_JSON); + given().auth().oauth2(reader).when().delete(BASE + "/" + id) + .then().statusCode(403).contentType(PROBLEM_JSON); + given().auth().oauth2(admin).when().get(BASE + "/" + id).then().statusCode(200); + } + + @Test + void userWithoutPermissionIs403AndNoTokenIs401() { + String nobody = support.token(support.createUser()); + given().auth().oauth2(nobody).when().get(BASE).then().statusCode(403).contentType(PROBLEM_JSON); + given().auth().oauth2(nobody).when().get(BASE + "/1").then().statusCode(403).contentType(PROBLEM_JSON); + given().when().get(BASE).then().statusCode(401); + given().contentType("application/json").body("{\"categoryName\":\"n\"}").when().post(BASE) + .then().statusCode(401); + } +} From 8e0a0ecf8a902d6ea01321a0a53b40e63fda431a Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 10:08:59 +0400 Subject: [PATCH 088/158] test(service): unit test the category deletion and lookup rules With the repository mocked, the tests check that a category with products is not deleted, that a missing category gives 404 on deletion and on update, and that the page returned by the list is built from the requested page and size. A captor verifies the page requested from the repository, since comparing paging objects by equality is not reliable. --- .../service/impl/CategoryServiceImplTest.java | 110 ++++++++++++++++++ 1 file changed, 110 insertions(+) create mode 100644 src/test/java/com/edgareldy/quarkustutorial/service/impl/CategoryServiceImplTest.java diff --git a/src/test/java/com/edgareldy/quarkustutorial/service/impl/CategoryServiceImplTest.java b/src/test/java/com/edgareldy/quarkustutorial/service/impl/CategoryServiceImplTest.java new file mode 100644 index 0000000..0ae01ee --- /dev/null +++ b/src/test/java/com/edgareldy/quarkustutorial/service/impl/CategoryServiceImplTest.java @@ -0,0 +1,110 @@ +package com.edgareldy.quarkustutorial.service.impl; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +import com.edgareldy.quarkustutorial.dto.common.PageResponse; +import com.edgareldy.quarkustutorial.dto.ecommerce.CategoryRequest; +import com.edgareldy.quarkustutorial.dto.ecommerce.CategoryResponse; +import com.edgareldy.quarkustutorial.entity.Category; +import com.edgareldy.quarkustutorial.exception.BusinessRuleException; +import com.edgareldy.quarkustutorial.exception.ResourceNotFoundException; +import com.edgareldy.quarkustutorial.repository.CategoryRepository; +import io.quarkus.hibernate.orm.panache.PanacheQuery; +import io.quarkus.panache.common.Page; +import io.quarkus.panache.common.Sort; +import java.util.List; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +/** + * Isolated unit tests of CategoryServiceImpl with the repository mocked. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +// Plain Mockito with the package-private injected field assigned directly (same approach as +// AuthServiceImplTest): no container is needed to test the business rules. +class CategoryServiceImplTest { + + private CategoryRepository repository; + private CategoryServiceImpl service; + + @BeforeEach + void setUp() { + repository = mock(CategoryRepository.class); + service = new CategoryServiceImpl(); + service.categoryRepository = repository; + } + + private static Category category(Long id, String name) { + Category c = new Category(); + c.setId(id); + c.setCategoryName(name); + return c; + } + + @Test + void deleteIsRefusedWhenCategoryHasProducts() { + Category c = category(1L, "Books"); + when(repository.findById(1L)).thenReturn(c); + when(repository.countProducts(1L)).thenReturn(2L); + + assertThrows(BusinessRuleException.class, () -> service.delete(1L)); + verify(repository, never()).delete(any(Category.class)); + } + + @Test + void deleteRemovesCategoryWithoutProducts() { + Category c = category(1L, "Books"); + when(repository.findById(1L)).thenReturn(c); + when(repository.countProducts(1L)).thenReturn(0L); + + service.delete(1L); + + verify(repository).delete(c); + } + + @Test + void deleteMissingCategoryIsNotFound() { + when(repository.findById(9L)).thenReturn(null); + + assertThrows(ResourceNotFoundException.class, () -> service.delete(9L)); + verify(repository, never()).delete(any(Category.class)); + } + + @Test + void updateMissingCategoryIsNotFound() { + when(repository.findById(9L)).thenReturn(null); + + assertThrows(ResourceNotFoundException.class, () -> service.update(9L, new CategoryRequest("x"))); + } + + @Test + @SuppressWarnings("unchecked") + void listBuildsPageResponse() { + PanacheQuery all = mock(PanacheQuery.class); + PanacheQuery paged = mock(PanacheQuery.class); + when(repository.findAll(any(Sort.class))).thenReturn(all); + when(all.page(any(Page.class))).thenReturn(paged); + when(paged.list()).thenReturn(List.of(category(1L, "A"), category(2L, "B"))); + when(repository.count()).thenReturn(5L); + + PageResponse page = service.list(1, 2); + + assertEquals(2, page.content().size()); + assertEquals("A", page.content().get(0).categoryName()); + assertEquals(1, page.page()); + assertEquals(2, page.size()); + assertEquals(5L, page.totalElements()); + assertEquals(3, page.totalPages()); + ArgumentCaptor requested = ArgumentCaptor.forClass(Page.class); + verify(all).page(requested.capture()); + assertEquals(1, requested.getValue().index); + assertEquals(2, requested.getValue().size); + } +} From 7014f6bf033f3a80031c4ca5f0fb667eb04ae8ee Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 10:08:59 +0400 Subject: [PATCH 089/158] test(repository): check the product count against PostgreSQL The native count is exactly the kind of query a mock cannot verify, so it runs against the real schema that Dev Services provides: zero for a new category, then the right number after products are inserted. Nothing is set up by hand for the database, the test only inserts and removes its own rows. --- .../repository/CategoryRepositoryTest.java | 77 +++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 src/test/java/com/edgareldy/quarkustutorial/repository/CategoryRepositoryTest.java diff --git a/src/test/java/com/edgareldy/quarkustutorial/repository/CategoryRepositoryTest.java b/src/test/java/com/edgareldy/quarkustutorial/repository/CategoryRepositoryTest.java new file mode 100644 index 0000000..cdac027 --- /dev/null +++ b/src/test/java/com/edgareldy/quarkustutorial/repository/CategoryRepositoryTest.java @@ -0,0 +1,77 @@ +package com.edgareldy.quarkustutorial.repository; + +import static org.junit.jupiter.api.Assertions.*; + +import com.edgareldy.quarkustutorial.entity.Category; +import io.quarkus.narayana.jta.QuarkusTransaction; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import jakarta.persistence.EntityManager; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +/** + * Repository tests of CategoryRepository against the Dev Services PostgreSQL. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +// @QuarkusTest boots the real datasource (Dev Services PostgreSQL, Flyway schema), so the native +// products count runs against the real table. Data is committed in QuarkusTransaction and removed afterwards. +@QuarkusTest +class CategoryRepositoryTest { + + @Inject + CategoryRepository repository; + + @Inject + EntityManager em; + + private Long categoryId; + + @AfterEach + void tearDown() { + if (categoryId != null) { + QuarkusTransaction.requiringNew().run(() -> { + em.createNativeQuery("delete from products where category_id = ?1").setParameter(1, categoryId) + .executeUpdate(); + em.createNativeQuery("delete from categories where id = ?1").setParameter(1, categoryId) + .executeUpdate(); + }); + } + } + + private Long persist(String name) { + return QuarkusTransaction.requiringNew().call(() -> { + Category c = new Category(); + c.setCategoryName(name); + repository.persist(c); + return c.getId(); + }); + } + + @Test + void persistAndFind() { + categoryId = persist("Repo test"); + Category found = QuarkusTransaction.requiringNew().call(() -> repository.findById(categoryId)); + assertNotNull(found); + assertEquals("Repo test", found.getCategoryName()); + } + + @Test + void countProductsReflectsInsertedRows() { + categoryId = persist("Repo count"); + assertEquals(0L, QuarkusTransaction.requiringNew().call(() -> repository.countProducts(categoryId))); + + QuarkusTransaction.requiringNew().run(() -> { + for (int i = 0; i < 3; i++) { + em.createNativeQuery("insert into products (category_id, product_name, unit_price) " + + "values (?1, 'P', 1.00)").setParameter(1, categoryId).executeUpdate(); + } + }); + + assertEquals(3L, QuarkusTransaction.requiringNew().call(() -> repository.countProducts(categoryId))); + } +} From 8653d296f9f12cf0cd9d266fa3d205c16929c2f7 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 10:09:41 +0400 Subject: [PATCH 090/158] docs(readme): check off feature/categories Every task of the categories branch is implemented and covered by the build, so its checklist is ticked, following the two previous branches. The deletion rule and the endpoints are exactly those of the specification, with no addition to record. --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 0ae441a..ce18f64 100644 --- a/README.md +++ b/README.md @@ -340,10 +340,10 @@ Full CRUD for users, roles, and permissions. Assignments always flow in one dire ### Tasks -- [ ] `Category` entity, repository, contract/implementation service -- [ ] Business rule: deleting a category that still has products is rejected (`BusinessRuleException` → 422) -- [ ] `CategoryResource` -- [ ] Tests for every endpoint, including the rejection case and a permission-denied case +- [x] `Category` entity, repository, contract/implementation service +- [x] Business rule: deleting a category that still has products is rejected (`BusinessRuleException` → 422) +- [x] `CategoryResource` +- [x] Tests for every endpoint, including the rejection case and a permission-denied case ## feature/products From 4296bb4894682600498d8d6621f93801c4c94dda Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 10:47:51 +0400 Subject: [PATCH 091/158] feat(entity): add the Product entity Product maps the products table created by the initial Flyway migration, with a many-to-one link to Category. The association is LAZY and non-optional: the category row is only fetched when read, and a product can never exist without one, which matches the NOT NULL foreign key in the schema. Prices use BigDecimal with the same precision and scale as the NUMERIC(12, 2) column, so money is never handled as a floating point number. --- .../quarkustutorial/entity/Product.java | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/entity/Product.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/entity/Product.java b/src/main/java/com/edgareldy/quarkustutorial/entity/Product.java new file mode 100644 index 0000000..2a4aa61 --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/entity/Product.java @@ -0,0 +1,49 @@ +package com.edgareldy.quarkustutorial.entity; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; +import java.math.BigDecimal; + +/** + * A product of the e-commerce domain, always attached to one category. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +@Entity +@Table(name = "products") +public class Product { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + // LAZY: the category row is only loaded when someone actually reads it. + @ManyToOne(fetch = FetchType.LAZY, optional = false) + @JoinColumn(name = "category_id", nullable = false) + private Category category; + + @Column(name = "product_name", nullable = false, length = 150) + private String productName; + + @Column(name = "unit_price", nullable = false, precision = 12, scale = 2) + private BigDecimal unitPrice; + + public Long getId() { return id; } + public void setId(Long id) { this.id = id; } + public Category getCategory() { return category; } + public void setCategory(Category category) { this.category = category; } + public String getProductName() { return productName; } + public void setProductName(String productName) { this.productName = productName; } + public BigDecimal getUnitPrice() { return unitPrice; } + public void setUnitPrice(BigDecimal unitPrice) { this.unitPrice = unitPrice; } +} From 63c99aa32071b571aa3ca2ebb43cbeee24d70f43 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 10:47:51 +0400 Subject: [PATCH 092/158] feat(repository): add ProductRepository with the category filter The repository implements PanacheRepository directly, so persist, find and count come for free and only what Panache does not provide is written by hand. Here that is a query ordered by id that can be restricted to one category, returned as a PanacheQuery so the service decides which page to ask for. countByCategoryId gives the category deletion rule a real count over the Product entity, replacing the temporary native query that was standing in until this entity existed. --- .../repository/ProductRepository.java | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/repository/ProductRepository.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/repository/ProductRepository.java b/src/main/java/com/edgareldy/quarkustutorial/repository/ProductRepository.java new file mode 100644 index 0000000..39d87bf --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/repository/ProductRepository.java @@ -0,0 +1,41 @@ +package com.edgareldy.quarkustutorial.repository; + +import com.edgareldy.quarkustutorial.entity.Product; +import io.quarkus.hibernate.orm.panache.PanacheQuery; +import io.quarkus.hibernate.orm.panache.PanacheRepository; +import io.quarkus.panache.common.Sort; +import jakarta.enterprise.context.ApplicationScoped; + +/** + * Panache repository for products, with the category filter and count. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +@ApplicationScoped +public class ProductRepository implements PanacheRepository { + + /** + * Products ordered by id, optionally restricted to one category. + * + * @param categoryId the category to filter on, or null for every product + * @return a query the caller can page + */ + public PanacheQuery findByCategory(Long categoryId) { + if (categoryId == null) { + return findAll(Sort.by("id")); + } + // Panache shortcut: a bare "category.id = ?1" is expanded into a full HQL query. + return find("category.id = ?1", Sort.by("id"), categoryId); + } + + /** + * @param categoryId the category id + * @return how many products reference this category + */ + public long countByCategoryId(Long categoryId) { + return count("category.id", categoryId); + } +} From 3f19abf3843d048e337da4678067027ce5feb228 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 10:47:51 +0400 Subject: [PATCH 093/158] refactor(repository): drop the native product count from CategoryRepository The native SQL count on the products table only existed because there was no Product entity yet, and carried a TODO to be replaced. Now that ProductRepository counts by category through the entity model, keeping a second way to answer the same question would let the two drift apart. The repository goes back to being a plain PanacheRepository with no custom method. --- .../repository/CategoryRepository.java | 17 ----------------- 1 file changed, 17 deletions(-) diff --git a/src/main/java/com/edgareldy/quarkustutorial/repository/CategoryRepository.java b/src/main/java/com/edgareldy/quarkustutorial/repository/CategoryRepository.java index 5333d28..07d019e 100644 --- a/src/main/java/com/edgareldy/quarkustutorial/repository/CategoryRepository.java +++ b/src/main/java/com/edgareldy/quarkustutorial/repository/CategoryRepository.java @@ -14,21 +14,4 @@ */ @ApplicationScoped public class CategoryRepository implements PanacheRepository { - - /** - * Counts the products of a category with a native query on the products table. - *

- * TODO(feature/products): there is no Product entity yet, hence the native SQL. Once it exists, - * replace this with a ProductRepository count by category and remove this method. - * - * @param categoryId the category id - * @return how many products reference this category - */ - public long countProducts(Long categoryId) { - Number count = (Number) getEntityManager() - .createNativeQuery("select count(*) from products where category_id = :categoryId") - .setParameter("categoryId", categoryId) - .getSingleResult(); - return count.longValue(); - } } From 2c01925853e0b93a2ac56ddb8a30a84c7d850e3c Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 10:47:51 +0400 Subject: [PATCH 094/158] refactor(service): count a category's products through ProductRepository The deletion rule keeps its behaviour, a category that still has products is refused with a 422, but the count now comes from the repository that owns products. Each repository stays responsible for its own entity, and the service composes them. The check is still a check-then-act inside one transaction; a product inserted concurrently would hit the foreign key instead, which is an accepted limit. --- .../quarkustutorial/service/impl/CategoryServiceImpl.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/edgareldy/quarkustutorial/service/impl/CategoryServiceImpl.java b/src/main/java/com/edgareldy/quarkustutorial/service/impl/CategoryServiceImpl.java index eeba735..b558d4b 100644 --- a/src/main/java/com/edgareldy/quarkustutorial/service/impl/CategoryServiceImpl.java +++ b/src/main/java/com/edgareldy/quarkustutorial/service/impl/CategoryServiceImpl.java @@ -7,6 +7,7 @@ import com.edgareldy.quarkustutorial.exception.BusinessRuleException; import com.edgareldy.quarkustutorial.exception.ResourceNotFoundException; import com.edgareldy.quarkustutorial.repository.CategoryRepository; +import com.edgareldy.quarkustutorial.repository.ProductRepository; import com.edgareldy.quarkustutorial.service.CategoryService; import io.quarkus.panache.common.Page; import io.quarkus.panache.common.Sort; @@ -29,6 +30,9 @@ public class CategoryServiceImpl implements CategoryService { @Inject CategoryRepository categoryRepository; + @Inject + ProductRepository productRepository; + @Override @Transactional public PageResponse list(int page, int size) { @@ -64,7 +68,7 @@ public CategoryResponse update(Long id, CategoryRequest request) { @Transactional public void delete(Long id) { Category category = find(id); - if (categoryRepository.countProducts(id) > 0) { + if (productRepository.countByCategoryId(id) > 0) { throw new BusinessRuleException("Category " + id + " still has products and cannot be deleted"); } categoryRepository.delete(category); From 80fca59f4ded1c5348df53dc053c9ff31287ff55 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 10:47:51 +0400 Subject: [PATCH 095/158] feat(dto): add ProductRequest with Bean Validation The payload is a record validated declaratively: the category id and price are required, the name is not blank and bounded to the column length, and the price must be strictly positive with at most two decimals. This mirrors the CHECK constraint and the NUMERIC scale of the database, so bad input is refused with a 400 before it can reach a constraint violation. Validation runs when the resource method declares the parameter with @Valid, which keeps the rules on the DTO and out of the service. --- .../dto/ecommerce/ProductRequest.java | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/dto/ecommerce/ProductRequest.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/dto/ecommerce/ProductRequest.java b/src/main/java/com/edgareldy/quarkustutorial/dto/ecommerce/ProductRequest.java new file mode 100644 index 0000000..8c275f2 --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/dto/ecommerce/ProductRequest.java @@ -0,0 +1,22 @@ +package com.edgareldy.quarkustutorial.dto.ecommerce; + +import jakarta.validation.constraints.DecimalMin; +import jakarta.validation.constraints.Digits; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; +import java.math.BigDecimal; + +/** + * Payload to create or update a product. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +public record ProductRequest( + @NotNull Long categoryId, + @NotBlank @Size(max = 150) String productName, + @NotNull @DecimalMin(value = "0.0", inclusive = false) @Digits(integer = 10, fraction = 2) BigDecimal unitPrice) { +} From 02b82ca7928a5df093e39f1443384d51e6dbbccb Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 10:47:51 +0400 Subject: [PATCH 096/158] feat(dto): add ProductResponse The response exposes the product with the id of its category, never the entity itself, so the API shape does not depend on the persistence model. It is also the value stored in the product cache, and a DTO is safe to keep there because it is immutable and detached from any session. It deliberately carries no category name: a cached copy would keep serving the old name after the category is renamed, since only product writes evict the entry. Clients that need the name read the category by id. --- .../dto/ecommerce/ProductResponse.java | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/dto/ecommerce/ProductResponse.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/dto/ecommerce/ProductResponse.java b/src/main/java/com/edgareldy/quarkustutorial/dto/ecommerce/ProductResponse.java new file mode 100644 index 0000000..6c09e1f --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/dto/ecommerce/ProductResponse.java @@ -0,0 +1,16 @@ +package com.edgareldy.quarkustutorial.dto.ecommerce; + +import java.math.BigDecimal; + +/** + * Product as returned by the API (and the value held in the product cache). + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +// Deliberately no categoryName: this DTO is cached by ProductService.findById, and a cached copy +// would keep serving the old name after the category is renamed (only product writes evict it). +public record ProductResponse(Long id, Long categoryId, String productName, BigDecimal unitPrice) { +} From b401bdf6e96b57e6108c5c120e727b2d93f91e5b Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 10:47:51 +0400 Subject: [PATCH 097/158] feat(service): add the ProductService contract The contract offers a paginated list with an optional category filter, a lookup, and creation, update and deletion, all in terms of DTOs. Resources depend on this interface, and tests can replace its implementation. The cache annotations are not on this interface but on the implementation: interceptor bindings declared on an interface method are not applied by the CDI container, so a cached read must be annotated on the class that ArC actually intercepts. --- .../service/ProductService.java | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/service/ProductService.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/service/ProductService.java b/src/main/java/com/edgareldy/quarkustutorial/service/ProductService.java new file mode 100644 index 0000000..e23ff47 --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/service/ProductService.java @@ -0,0 +1,31 @@ +package com.edgareldy.quarkustutorial.service; + +import com.edgareldy.quarkustutorial.dto.common.PageResponse; +import com.edgareldy.quarkustutorial.dto.ecommerce.ProductRequest; +import com.edgareldy.quarkustutorial.dto.ecommerce.ProductResponse; + +/** + * Contract for product management. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +public interface ProductService { + + /** @return one page of products ordered by id, optionally filtered by category (null means all) */ + PageResponse list(int page, int size, Long categoryId); + + /** @return the product, or throws ResourceNotFoundException (404). Cached, see the implementation. */ + ProductResponse findById(Long id); + + /** @return the created product; BusinessRuleException (422) if the category does not exist */ + ProductResponse create(ProductRequest request); + + /** @return the updated product; 404 if missing, BusinessRuleException (422) if the category does not exist */ + ProductResponse update(Long id, ProductRequest request); + + /** Deletes a product; 404 if missing. */ + void delete(Long id); +} From dc38ddb92b51ffde0f89a98bac3edcc21c4210cc Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 10:47:51 +0400 Subject: [PATCH 098/158] build(config): configure the product cache quarkus-cache is backed by Caffeine, and each named cache can be tuned with a quarkus.cache.caffeine. property. The product cache is bounded to 500 entries and expires ten minutes after being written. The two limits are a safety net rather than the mechanism: writes evict their own entry explicitly, and the size and age bounds only make sure a missed invalidation can never serve stale data for long or let memory grow without limit. --- src/main/resources/application.properties | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 37f1950..6ec6ce6 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -49,3 +49,9 @@ smallrye.jwt.new-token.lifespan=3600 # Dev only, with a clearly fake password; nothing for test or prod (set them explicitly if wanted). %dev.app.bootstrap-admin.email=admin@dev.local %dev.app.bootstrap-admin.password=dev-only-admin-password + +# --- Cache (quarkus-cache, Caffeine) ---------------------------------------- +# "product-cache" holds ProductResponse DTOs keyed by product id. Bounded in size and in age so a +# missed invalidation can never serve stale data for long and memory use stays predictable. +quarkus.cache.caffeine."product-cache".maximum-size=500 +quarkus.cache.caffeine."product-cache".expire-after-write=10M From 18cd6377ed71b572d18334edbd070a9e64a13f2b Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 10:47:51 +0400 Subject: [PATCH 099/158] feat(service): implement ProductService with a per-product cache findById is annotated with @CacheResult, so the first read of an id runs the query and stores the DTO, and later reads return it without touching the database. update and delete carry the symmetric @CacheInvalidate on the same cache name and the same key, marked with @CacheKey on the id, so a write can never leave a stale entry behind. Only the DTO is cached, and a 404 is not, because an exception is never stored. Creating or updating a product with an unknown category answers 422 through BusinessRuleException, since the request is well formed and it is the state of the data that refuses it. The list orders by id so pages are stable, and counts either every product or those of the requested category. --- .../service/impl/ProductServiceImpl.java | 111 ++++++++++++++++++ 1 file changed, 111 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/service/impl/ProductServiceImpl.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/service/impl/ProductServiceImpl.java b/src/main/java/com/edgareldy/quarkustutorial/service/impl/ProductServiceImpl.java new file mode 100644 index 0000000..13929a1 --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/service/impl/ProductServiceImpl.java @@ -0,0 +1,111 @@ +package com.edgareldy.quarkustutorial.service.impl; + +import com.edgareldy.quarkustutorial.dto.common.PageResponse; +import com.edgareldy.quarkustutorial.dto.ecommerce.ProductRequest; +import com.edgareldy.quarkustutorial.dto.ecommerce.ProductResponse; +import com.edgareldy.quarkustutorial.entity.Category; +import com.edgareldy.quarkustutorial.entity.Product; +import com.edgareldy.quarkustutorial.exception.BusinessRuleException; +import com.edgareldy.quarkustutorial.exception.ResourceNotFoundException; +import com.edgareldy.quarkustutorial.repository.CategoryRepository; +import com.edgareldy.quarkustutorial.repository.ProductRepository; +import com.edgareldy.quarkustutorial.service.ProductService; +import io.quarkus.cache.CacheInvalidate; +import io.quarkus.cache.CacheKey; +import io.quarkus.cache.CacheResult; +import io.quarkus.panache.common.Page; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import jakarta.transaction.Transactional; +import java.util.List; + +/** + * Default {@link ProductService} backed by Panache, with a per-product cache on reads. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +@ApplicationScoped +public class ProductServiceImpl implements ProductService { + + @Inject + ProductRepository productRepository; + + @Inject + CategoryRepository categoryRepository; + + @Override + @Transactional + public PageResponse list(int page, int size, Long categoryId) { + List content = productRepository.findByCategory(categoryId).page(Page.of(page, size)) + .list().stream().map(ProductServiceImpl::toResponse).toList(); + long total = categoryId == null ? productRepository.count() : productRepository.countByCategoryId(categoryId); + return PageResponse.of(content, page, size, total); + } + + // @CacheResult (quarkus-cache): the first call for a given id runs the method and stores the returned + // DTO in "product-cache"; later calls with the same key return it without touching the database. + // @CacheKey makes the key explicit (the product id), so the invalidations below agree on it. + // Only the ProductResponse DTO is cached, never a Hibernate entity. Exceptions (404) are not cached. + // Deviation from the README: the annotation sits on this implementation method, not on the + // ProductService interface. Verified empirically: ArC does not apply interceptor bindings declared on + // an interface method (the cache stayed empty), whereas on the class method the entry is stored. + @Override + @Transactional + @CacheResult(cacheName = "product-cache") + public ProductResponse findById(@CacheKey Long id) { + return toResponse(find(id)); + } + + @Override + @Transactional + public ProductResponse create(ProductRequest request) { + Product product = new Product(); + apply(product, request); + productRepository.persist(product); + return toResponse(product); + } + + // @CacheInvalidate: once this write succeeds, the entry stored by findById under the same cache name + // and the same key (the id) is evicted, so the next read reloads the fresh value. + @Override + @Transactional + @CacheInvalidate(cacheName = "product-cache") + public ProductResponse update(@CacheKey Long id, ProductRequest request) { + Product product = find(id); + apply(product, request); + return toResponse(product); + } + + @Override + @Transactional + @CacheInvalidate(cacheName = "product-cache") + public void delete(@CacheKey Long id) { + productRepository.delete(find(id)); + } + + private Product find(Long id) { + Product product = productRepository.findById(id); + if (product == null) { + throw new ResourceNotFoundException("Product " + id + " not found"); + } + return product; + } + + private void apply(Product product, ProductRequest request) { + Category category = categoryRepository.findById(request.categoryId()); + if (category == null) { + throw new BusinessRuleException("Category " + request.categoryId() + " does not exist"); + } + product.setCategory(category); + product.setProductName(request.productName()); + product.setUnitPrice(request.unitPrice()); + } + + private static ProductResponse toResponse(Product product) { + return new ProductResponse(product.getId(), product.getCategory().getId(), product.getProductName(), + product.getUnitPrice()); + } +} From e1c5c7f11c252de1ac803167bb747951979b69dd Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 10:47:51 +0400 Subject: [PATCH 100/158] feat(resource): add ProductResource The five endpoints are protected with @PermissionsAllowed, PRODUCT:READ for reading and PRODUCT:WRITE for the rest, and the resource only validates, delegates and wraps the result in the success envelope. Creating answers 201. The list takes an optional categoryId filter and bounds the page size, so a size of zero is refused before it can produce an empty page count. --- .../resource/ProductResource.java | 82 +++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/resource/ProductResource.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/resource/ProductResource.java b/src/main/java/com/edgareldy/quarkustutorial/resource/ProductResource.java new file mode 100644 index 0000000..15ed6af --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/resource/ProductResource.java @@ -0,0 +1,82 @@ +package com.edgareldy.quarkustutorial.resource; + +import com.edgareldy.quarkustutorial.dto.common.ApiResponse; +import com.edgareldy.quarkustutorial.dto.common.PageResponse; +import com.edgareldy.quarkustutorial.dto.ecommerce.ProductRequest; +import com.edgareldy.quarkustutorial.dto.ecommerce.ProductResponse; +import com.edgareldy.quarkustutorial.service.ProductService; +import io.quarkus.security.PermissionsAllowed; +import jakarta.inject.Inject; +import jakarta.validation.Valid; +import jakarta.validation.constraints.Max; +import jakarta.validation.constraints.Min; +import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.DELETE; +import jakarta.ws.rs.DefaultValue; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.PUT; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.PathParam; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.QueryParam; +import jakarta.ws.rs.core.MediaType; +import org.eclipse.microprofile.openapi.annotations.security.SecurityRequirement; +import org.jboss.resteasy.reactive.ResponseStatus; + +/** + * CRUD endpoints for products, with an optional category filter on the list. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +@Path("/api/v1/products") +@Produces(MediaType.APPLICATION_JSON) +@SecurityRequirement(name = "jwt") +public class ProductResource { + + @Inject + ProductService productService; + + @GET + @PermissionsAllowed("PRODUCT:READ") + public ApiResponse> list( + @QueryParam("page") @DefaultValue("0") @Min(0) int page, + @QueryParam("size") @DefaultValue("20") @Min(1) @Max(100) int size, + @QueryParam("categoryId") Long categoryId) { + return ApiResponse.success(productService.list(page, size, categoryId), "Products"); + } + + @GET + @Path("/{id}") + @PermissionsAllowed("PRODUCT:READ") + public ApiResponse get(@PathParam("id") Long id) { + return ApiResponse.success(productService.findById(id), "Product"); + } + + @POST + @Consumes(MediaType.APPLICATION_JSON) + @PermissionsAllowed("PRODUCT:WRITE") + @ResponseStatus(201) + public ApiResponse create(@Valid ProductRequest request) { + return ApiResponse.success(productService.create(request), "Product created"); + } + + @PUT + @Path("/{id}") + @Consumes(MediaType.APPLICATION_JSON) + @PermissionsAllowed("PRODUCT:WRITE") + public ApiResponse update(@PathParam("id") Long id, @Valid ProductRequest request) { + return ApiResponse.success(productService.update(id, request), "Product updated"); + } + + @DELETE + @Path("/{id}") + @PermissionsAllowed("PRODUCT:WRITE") + public ApiResponse delete(@PathParam("id") Long id) { + productService.delete(id); + return ApiResponse.success(null, "Product deleted"); + } +} From 23befed04e1ae6bc54f2df44ce94b0b7e0af2929 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 10:47:51 +0400 Subject: [PATCH 101/158] test(repository): cover the category filter and count on PostgreSQL The tests run against the PostgreSQL container that Dev Services starts, with the schema built by Flyway, so the filter, the ordering and the count are checked against the real database and not an in-memory stand-in. --- .../repository/ProductRepositoryTest.java | 126 ++++++++++++++++++ 1 file changed, 126 insertions(+) create mode 100644 src/test/java/com/edgareldy/quarkustutorial/repository/ProductRepositoryTest.java diff --git a/src/test/java/com/edgareldy/quarkustutorial/repository/ProductRepositoryTest.java b/src/test/java/com/edgareldy/quarkustutorial/repository/ProductRepositoryTest.java new file mode 100644 index 0000000..e946429 --- /dev/null +++ b/src/test/java/com/edgareldy/quarkustutorial/repository/ProductRepositoryTest.java @@ -0,0 +1,126 @@ +package com.edgareldy.quarkustutorial.repository; + +import static org.junit.jupiter.api.Assertions.*; + +import com.edgareldy.quarkustutorial.entity.Category; +import com.edgareldy.quarkustutorial.entity.Product; +import io.quarkus.narayana.jta.QuarkusTransaction; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import jakarta.persistence.EntityManager; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +/** + * Repository tests of ProductRepository against the Dev Services PostgreSQL. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +// Real PostgreSQL through Dev Services (see CategoryRepositoryTest): numeric(12,2) and the foreign key are +// database behaviours that only a real instance can prove. Data is committed and cleaned up afterwards. +@QuarkusTest +class ProductRepositoryTest { + + @Inject + ProductRepository repository; + + @Inject + CategoryRepository categoryRepository; + + @Inject + EntityManager em; + + private final List categories = new ArrayList<>(); + + @AfterEach + void tearDown() { + QuarkusTransaction.requiringNew().run(() -> categories.forEach(id -> { + em.createNativeQuery("delete from products where category_id = ?1").setParameter(1, id) + .executeUpdate(); + em.createNativeQuery("delete from categories where id = ?1").setParameter(1, id).executeUpdate(); + })); + categories.clear(); + } + + private Long category() { + Long id = QuarkusTransaction.requiringNew().call(() -> { + Category c = new Category(); + c.setCategoryName("prod-repo-" + System.nanoTime()); + categoryRepository.persist(c); + return c.getId(); + }); + categories.add(id); + return id; + } + + private Long product(Long categoryId, String name, String price) { + return QuarkusTransaction.requiringNew().call(() -> { + Product p = new Product(); + p.setCategory(categoryRepository.findById(categoryId)); + p.setProductName(name); + p.setUnitPrice(new BigDecimal(price)); + repository.persist(p); + return p.getId(); + }); + } + + @Test + void findByCategoryFiltersAndOrdersById() { + Long catA = category(); + Long catB = category(); + Long a1 = product(catA, "A1", "1.00"); + Long b1 = product(catB, "B1", "2.00"); + Long a2 = product(catA, "A2", "3.00"); + + List forA = QuarkusTransaction.requiringNew() + .call(() -> repository.findByCategory(catA).list().stream().map(Product::getId).toList()); + List forB = QuarkusTransaction.requiringNew() + .call(() -> repository.findByCategory(catB).list().stream().map(Product::getId).toList()); + List all = QuarkusTransaction.requiringNew() + .call(() -> repository.findByCategory(null).list().stream().map(Product::getId).toList()); + + assertEquals(List.of(a1, a2), forA); + assertEquals(List.of(b1), forB); + assertTrue(all.containsAll(List.of(a1, b1, a2))); + assertEquals(all.stream().sorted().toList(), all); + } + + @Test + void countByCategoryIdCountsOnlyThatCategory() { + Long catA = category(); + Long catB = category(); + product(catA, "A1", "1.00"); + product(catA, "A2", "1.00"); + product(catB, "B1", "1.00"); + + assertEquals(2L, QuarkusTransaction.requiringNew().call(() -> repository.countByCategoryId(catA))); + assertEquals(1L, QuarkusTransaction.requiringNew().call(() -> repository.countByCategoryId(catB))); + assertEquals(0L, QuarkusTransaction.requiringNew().call(() -> repository.countByCategoryId(999999999L))); + } + + @Test + void unitPriceRoundTripsAsNumeric12Scale2() { + Long cat = category(); + Long id = product(cat, "Precise", "79.99"); + Long big = product(cat, "Big", "9999999999.99"); + + Product found = QuarkusTransaction.requiringNew().call(() -> repository.findById(id)); + Product foundBig = QuarkusTransaction.requiringNew().call(() -> repository.findById(big)); + + assertEquals(new BigDecimal("79.99"), found.getUnitPrice()); + assertEquals(new BigDecimal("9999999999.99"), foundBig.getUnitPrice()); + } + + @Test + void missingCategoryViolatesForeignKey() { + assertThrows(RuntimeException.class, () -> QuarkusTransaction.requiringNew().run(() -> em + .createNativeQuery("insert into products (category_id, product_name, unit_price) " + + "values (999999999, 'Orphan', 1.00)").executeUpdate())); + } +} From 9ba235d6ffae90850b23b8efb86c242181cef231 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 10:47:51 +0400 Subject: [PATCH 102/158] test(repository): count products through ProductRepository The category test now asks the product repository for the count, following the method that moved, and still checks the figure against inserted rows. --- .../quarkustutorial/repository/CategoryRepositoryTest.java | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/test/java/com/edgareldy/quarkustutorial/repository/CategoryRepositoryTest.java b/src/test/java/com/edgareldy/quarkustutorial/repository/CategoryRepositoryTest.java index cdac027..3cb6f9c 100644 --- a/src/test/java/com/edgareldy/quarkustutorial/repository/CategoryRepositoryTest.java +++ b/src/test/java/com/edgareldy/quarkustutorial/repository/CategoryRepositoryTest.java @@ -26,6 +26,9 @@ class CategoryRepositoryTest { @Inject CategoryRepository repository; + @Inject + ProductRepository productRepository; + @Inject EntityManager em; @@ -63,7 +66,7 @@ void persistAndFind() { @Test void countProductsReflectsInsertedRows() { categoryId = persist("Repo count"); - assertEquals(0L, QuarkusTransaction.requiringNew().call(() -> repository.countProducts(categoryId))); + assertEquals(0L, QuarkusTransaction.requiringNew().call(() -> productRepository.countByCategoryId(categoryId))); QuarkusTransaction.requiringNew().run(() -> { for (int i = 0; i < 3; i++) { @@ -72,6 +75,6 @@ void countProductsReflectsInsertedRows() { } }); - assertEquals(3L, QuarkusTransaction.requiringNew().call(() -> repository.countProducts(categoryId))); + assertEquals(3L, QuarkusTransaction.requiringNew().call(() -> productRepository.countByCategoryId(categoryId))); } } From 0e6aec514431dfe12bdf5ab8449e44eb6048fde5 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 10:47:51 +0400 Subject: [PATCH 103/158] test(service): mock ProductRepository in the category deletion tests The deletion rule now depends on the product repository, so the isolated service tests stub its count instead of the removed category method. The two cases, refusal with products and deletion without, are unchanged. --- .../service/impl/CategoryServiceImplTest.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/test/java/com/edgareldy/quarkustutorial/service/impl/CategoryServiceImplTest.java b/src/test/java/com/edgareldy/quarkustutorial/service/impl/CategoryServiceImplTest.java index 0ae01ee..7d12dfc 100644 --- a/src/test/java/com/edgareldy/quarkustutorial/service/impl/CategoryServiceImplTest.java +++ b/src/test/java/com/edgareldy/quarkustutorial/service/impl/CategoryServiceImplTest.java @@ -11,6 +11,7 @@ import com.edgareldy.quarkustutorial.exception.BusinessRuleException; import com.edgareldy.quarkustutorial.exception.ResourceNotFoundException; import com.edgareldy.quarkustutorial.repository.CategoryRepository; +import com.edgareldy.quarkustutorial.repository.ProductRepository; import io.quarkus.hibernate.orm.panache.PanacheQuery; import io.quarkus.panache.common.Page; import io.quarkus.panache.common.Sort; @@ -32,13 +33,16 @@ class CategoryServiceImplTest { private CategoryRepository repository; + private ProductRepository productRepository; private CategoryServiceImpl service; @BeforeEach void setUp() { repository = mock(CategoryRepository.class); service = new CategoryServiceImpl(); + productRepository = mock(ProductRepository.class); service.categoryRepository = repository; + service.productRepository = productRepository; } private static Category category(Long id, String name) { @@ -52,7 +56,7 @@ private static Category category(Long id, String name) { void deleteIsRefusedWhenCategoryHasProducts() { Category c = category(1L, "Books"); when(repository.findById(1L)).thenReturn(c); - when(repository.countProducts(1L)).thenReturn(2L); + when(productRepository.countByCategoryId(1L)).thenReturn(2L); assertThrows(BusinessRuleException.class, () -> service.delete(1L)); verify(repository, never()).delete(any(Category.class)); @@ -62,7 +66,7 @@ void deleteIsRefusedWhenCategoryHasProducts() { void deleteRemovesCategoryWithoutProducts() { Category c = category(1L, "Books"); when(repository.findById(1L)).thenReturn(c); - when(repository.countProducts(1L)).thenReturn(0L); + when(productRepository.countByCategoryId(1L)).thenReturn(0L); service.delete(1L); From b2e6267fa4d7675897d2503158b8c574db4b80d6 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 10:47:51 +0400 Subject: [PATCH 104/158] test(service): unit test product creation, update, deletion and lookup The service is tested in isolation with mocked repositories, without starting Quarkus. The cases cover the missing product answering 404 and an unknown category answering 422, for both creation and update, and the category filter choosing the matching count. --- .../service/impl/ProductServiceImplTest.java | 170 ++++++++++++++++++ 1 file changed, 170 insertions(+) create mode 100644 src/test/java/com/edgareldy/quarkustutorial/service/impl/ProductServiceImplTest.java diff --git a/src/test/java/com/edgareldy/quarkustutorial/service/impl/ProductServiceImplTest.java b/src/test/java/com/edgareldy/quarkustutorial/service/impl/ProductServiceImplTest.java new file mode 100644 index 0000000..907b4ed --- /dev/null +++ b/src/test/java/com/edgareldy/quarkustutorial/service/impl/ProductServiceImplTest.java @@ -0,0 +1,170 @@ +package com.edgareldy.quarkustutorial.service.impl; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +import com.edgareldy.quarkustutorial.dto.common.PageResponse; +import com.edgareldy.quarkustutorial.dto.ecommerce.ProductRequest; +import com.edgareldy.quarkustutorial.dto.ecommerce.ProductResponse; +import com.edgareldy.quarkustutorial.entity.Category; +import com.edgareldy.quarkustutorial.entity.Product; +import com.edgareldy.quarkustutorial.exception.BusinessRuleException; +import com.edgareldy.quarkustutorial.exception.ResourceNotFoundException; +import com.edgareldy.quarkustutorial.repository.CategoryRepository; +import com.edgareldy.quarkustutorial.repository.ProductRepository; +import io.quarkus.hibernate.orm.panache.PanacheQuery; +import io.quarkus.panache.common.Page; +import java.math.BigDecimal; +import java.util.List; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * Isolated unit tests of ProductServiceImpl with both repositories mocked. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +// Plain Mockito, no container: caching annotations are not active here (no CDI interceptors), so only the +// business rules are exercised. Caching is covered by ProductCacheTest. +class ProductServiceImplTest { + + private ProductRepository productRepository; + private CategoryRepository categoryRepository; + private ProductServiceImpl service; + + @BeforeEach + void setUp() { + productRepository = mock(ProductRepository.class); + categoryRepository = mock(CategoryRepository.class); + service = new ProductServiceImpl(); + service.productRepository = productRepository; + service.categoryRepository = categoryRepository; + } + + private static Category category(Long id) { + Category c = new Category(); + c.setId(id); + c.setCategoryName("C" + id); + return c; + } + + private static Product product(Long id, Category category, String name, String price) { + Product p = new Product(); + p.setId(id); + p.setCategory(category); + p.setProductName(name); + p.setUnitPrice(new BigDecimal(price)); + return p; + } + + @Test + void createWithUnknownCategoryIsRefused() { + when(categoryRepository.findById(7L)).thenReturn(null); + + assertThrows(BusinessRuleException.class, + () -> service.create(new ProductRequest(7L, "X", new BigDecimal("1.00")))); + verify(productRepository, never()).persist(any(Product.class)); + } + + @Test + void createPersistsAndMapsResponse() { + when(categoryRepository.findById(1L)).thenReturn(category(1L)); + + ProductResponse response = service.create(new ProductRequest(1L, "Pen", new BigDecimal("2.50"))); + + assertEquals(1L, response.categoryId()); + assertEquals("Pen", response.productName()); + assertEquals(new BigDecimal("2.50"), response.unitPrice()); + verify(productRepository).persist(any(Product.class)); + } + + @Test + void updateWithUnknownCategoryIsRefused() { + Product existing = product(3L, category(1L), "Old", "1.00"); + when(productRepository.findById(3L)).thenReturn(existing); + when(categoryRepository.findById(7L)).thenReturn(null); + + assertThrows(BusinessRuleException.class, + () -> service.update(3L, new ProductRequest(7L, "New", new BigDecimal("2.00")))); + assertEquals("Old", existing.getProductName()); + } + + @Test + void updateChangesFields() { + Product existing = product(3L, category(1L), "Old", "1.00"); + when(productRepository.findById(3L)).thenReturn(existing); + when(categoryRepository.findById(2L)).thenReturn(category(2L)); + + ProductResponse response = service.update(3L, new ProductRequest(2L, "New", new BigDecimal("2.00"))); + + assertEquals(2L, response.categoryId()); + assertEquals("New", existing.getProductName()); + assertEquals(new BigDecimal("2.00"), existing.getUnitPrice()); + } + + @Test + void missingProductIsNotFoundOnFindUpdateDelete() { + when(productRepository.findById(9L)).thenReturn(null); + + assertThrows(ResourceNotFoundException.class, () -> service.findById(9L)); + assertThrows(ResourceNotFoundException.class, + () -> service.update(9L, new ProductRequest(1L, "x", new BigDecimal("1.00")))); + assertThrows(ResourceNotFoundException.class, () -> service.delete(9L)); + verify(productRepository, never()).delete(any(Product.class)); + } + + @Test + void deleteRemovesProduct() { + Product existing = product(3L, category(1L), "Old", "1.00"); + when(productRepository.findById(3L)).thenReturn(existing); + + service.delete(3L); + + verify(productRepository).delete(existing); + } + + @Test + @SuppressWarnings("unchecked") + void listWithoutFilterUsesGlobalCount() { + PanacheQuery query = mock(PanacheQuery.class); + PanacheQuery paged = mock(PanacheQuery.class); + when(productRepository.findByCategory(null)).thenReturn(query); + when(query.page(any(Page.class))).thenReturn(paged); + Category c = category(1L); + when(paged.list()).thenReturn(List.of(product(1L, c, "A", "1.00"), product(2L, c, "B", "2.00"))); + when(productRepository.count()).thenReturn(5L); + + PageResponse page = service.list(1, 2, null); + + assertEquals(2, page.content().size()); + assertEquals("A", page.content().get(0).productName()); + assertEquals(1, page.page()); + assertEquals(2, page.size()); + assertEquals(5L, page.totalElements()); + assertEquals(3, page.totalPages()); + verify(productRepository, never()).countByCategoryId(any()); + } + + @Test + @SuppressWarnings("unchecked") + void listWithCategoryFilterUsesCategoryCount() { + PanacheQuery query = mock(PanacheQuery.class); + PanacheQuery paged = mock(PanacheQuery.class); + when(productRepository.findByCategory(4L)).thenReturn(query); + when(query.page(any(Page.class))).thenReturn(paged); + when(paged.list()).thenReturn(List.of(product(1L, category(4L), "A", "1.00"))); + when(productRepository.countByCategoryId(4L)).thenReturn(1L); + + PageResponse page = service.list(0, 20, 4L); + + assertEquals(1, page.content().size()); + assertEquals(4L, page.content().get(0).categoryId()); + assertEquals(1L, page.totalElements()); + assertEquals(1, page.totalPages()); + verify(productRepository, never()).count(); + } +} From f7d09599555e9905939f227aee1c8c1e40204155 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 10:47:51 +0400 Subject: [PATCH 105/158] test(service): prove the product cache hits, invalidates and skips errors This test starts Quarkus, because the cache interceptors only exist inside the container, and spies on the repository to count how often it is really called. A second read must not reach the repository, an update or a delete must evict the entry so the next read loads the fresh value, and a missing product must not be cached. --- .../service/impl/ProductCacheTest.java | 151 ++++++++++++++++++ 1 file changed, 151 insertions(+) create mode 100644 src/test/java/com/edgareldy/quarkustutorial/service/impl/ProductCacheTest.java diff --git a/src/test/java/com/edgareldy/quarkustutorial/service/impl/ProductCacheTest.java b/src/test/java/com/edgareldy/quarkustutorial/service/impl/ProductCacheTest.java new file mode 100644 index 0000000..5f5c88e --- /dev/null +++ b/src/test/java/com/edgareldy/quarkustutorial/service/impl/ProductCacheTest.java @@ -0,0 +1,151 @@ +package com.edgareldy.quarkustutorial.service.impl; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.*; + +import com.edgareldy.quarkustutorial.dto.ecommerce.ProductRequest; +import com.edgareldy.quarkustutorial.dto.ecommerce.ProductResponse; +import com.edgareldy.quarkustutorial.entity.Category; +import com.edgareldy.quarkustutorial.exception.ResourceNotFoundException; +import com.edgareldy.quarkustutorial.repository.CategoryRepository; +import com.edgareldy.quarkustutorial.repository.ProductRepository; +import com.edgareldy.quarkustutorial.service.ProductService; +import io.quarkus.cache.Cache; +import io.quarkus.cache.CacheName; +import io.quarkus.narayana.jta.QuarkusTransaction; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.mockito.InjectSpy; +import jakarta.inject.Inject; +import jakarta.persistence.EntityManager; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +/** + * Verifies the product cache: reads are served from cache, writes evict the entry, misses are not cached. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +// @QuarkusTest is needed because @CacheResult/@CacheInvalidate are CDI interceptors that only exist inside +// the container. @InjectSpy (quarkus-junit-mockito) wraps the real ProductRepository bean in a Mockito spy, +// so the real database is still used but the test can count how many times the service reached it. +@QuarkusTest +class ProductCacheTest { + + @Inject + ProductService service; + + @InjectSpy + ProductRepository productRepository; + + @Inject + CategoryRepository categoryRepository; + + @Inject + EntityManager em; + + @CacheName("product-cache") + Cache cache; + + private final List products = new ArrayList<>(); + private Long categoryId; + + @BeforeEach + void setUp() { + // The cache lives for the whole application run and is shared by every test class: start empty so + // one test can never be served an entry stored by another. + cache.invalidateAll().await().indefinitely(); + categoryId = QuarkusTransaction.requiringNew().call(() -> { + Category c = new Category(); + c.setCategoryName("cache-" + System.nanoTime()); + categoryRepository.persist(c); + return c.getId(); + }); + Mockito.clearInvocations(productRepository); + } + + @AfterEach + void tearDown() { + cache.invalidateAll().await().indefinitely(); + QuarkusTransaction.requiringNew().run(() -> { + products.forEach(id -> em.createNativeQuery("delete from products where id = ?1").setParameter(1, id) + .executeUpdate()); + em.createNativeQuery("delete from categories where id = ?1").setParameter(1, categoryId) + .executeUpdate(); + }); + products.clear(); + } + + private ProductResponse create(String name, String price) { + ProductResponse created = service.create(new ProductRequest(categoryId, name, new BigDecimal(price))); + products.add(created.id()); + return created; + } + + @Test + void secondReadIsServedFromCache() { + Long id = create("Cached", "5.00").id(); + Mockito.clearInvocations(productRepository); + + ProductResponse first = service.findById(id); + ProductResponse second = service.findById(id); + + assertEquals(first, second); + verify(productRepository, times(1)).findById(id); + } + + @Test + void updateEvictsEntryAndNextReadReloadsFreshData() { + Long id = create("Before", "5.00").id(); + assertEquals("Before", service.findById(id).productName()); + + service.update(id, new ProductRequest(categoryId, "After", new BigDecimal("6.50"))); + Mockito.clearInvocations(productRepository); + + ProductResponse reloaded = service.findById(id); + + assertEquals("After", reloaded.productName()); + assertEquals(0, new BigDecimal("6.50").compareTo(reloaded.unitPrice())); + verify(productRepository, times(1)).findById(id); + service.findById(id); + verify(productRepository, times(1)).findById(id); + } + + @Test + void deleteEvictsEntryAndNextReadIsNotFound() { + Long id = create("Doomed", "5.00").id(); + service.findById(id); + + service.delete(id); + + assertThrows(ResourceNotFoundException.class, () -> service.findById(id)); + } + + @Test + void notFoundIsNotCached() { + assertThrows(ResourceNotFoundException.class, () -> service.findById(999999999L)); + assertThrows(ResourceNotFoundException.class, () -> service.findById(999999999L)); + + verify(productRepository, times(2)).findById(999999999L); + } + + @Test + void createThenReadWorksAndIsCached() { + Long id = create("Fresh", "7.25").id(); + Mockito.clearInvocations(productRepository); + + assertEquals("Fresh", service.findById(id).productName()); + assertEquals("Fresh", service.findById(id).productName()); + + verify(productRepository, times(1)).findById(id); + verify(productRepository, never()).findById(Mockito.argThat(v -> v != null && v != id.longValue())); + } +} From e27f53ba698e291c9a4dc37c9e49a4d01265e490 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 10:47:51 +0400 Subject: [PATCH 106/158] test(resource): cover every product endpoint and its access rules The tests exercise the five endpoints over HTTP with RestAssured, including the category filter, validation errors, the 404 and 422 problem responses, and a token without the required permission being refused with a 403. Authentication and permissions go through the real JWT and augmentor path, as in the other resource tests. --- .../resource/ProductResourceTest.java | 282 ++++++++++++++++++ 1 file changed, 282 insertions(+) create mode 100644 src/test/java/com/edgareldy/quarkustutorial/resource/ProductResourceTest.java diff --git a/src/test/java/com/edgareldy/quarkustutorial/resource/ProductResourceTest.java b/src/test/java/com/edgareldy/quarkustutorial/resource/ProductResourceTest.java new file mode 100644 index 0000000..8203e69 --- /dev/null +++ b/src/test/java/com/edgareldy/quarkustutorial/resource/ProductResourceTest.java @@ -0,0 +1,282 @@ +package com.edgareldy.quarkustutorial.resource; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.*; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import com.edgareldy.quarkustutorial.rbac.RbacTestSupport; +import io.quarkus.narayana.jta.QuarkusTransaction; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import jakarta.persistence.EntityManager; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * End-to-end tests of the product endpoints: CRUD, pagination, category filter, validation, money + * round trip, category deletion rule and permission denial. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +// Same approach as CategoryResourceTest: real HTTP against the Dev Services database, users from +// RbacTestSupport, and every category/product created here is tracked and removed in tearDown(). +@QuarkusTest +class ProductResourceTest { + + private static final String PROBLEM_JSON = "application/problem+json"; + private static final String BASE = "/api/v1/products"; + private static final String CATEGORIES = "/api/v1/categories"; + + @Inject + RbacTestSupport support; + + @Inject + EntityManager em; + + private final List categories = new ArrayList<>(); + private final List products = new ArrayList<>(); + private String admin; + + @BeforeEach + void setUp() { + admin = support.token(support.createUser("ADMIN")); + } + + @AfterEach + void tearDown() { + QuarkusTransaction.requiringNew().run(() -> { + products.forEach(id -> em.createNativeQuery("delete from products where id = ?1").setParameter(1, id) + .executeUpdate()); + categories.forEach(id -> em.createNativeQuery("delete from categories where id = ?1") + .setParameter(1, id).executeUpdate()); + }); + categories.clear(); + products.clear(); + support.cleanup(); + } + + private Long category() { + Long id = given().auth().oauth2(admin).contentType("application/json") + .body("{\"categoryName\":\"" + RbacTestSupport.unique("cat") + "\"}").when().post(CATEGORIES) + .then().statusCode(201).extract().jsonPath().getLong("data.id"); + categories.add(id); + return id; + } + + private static String body(Object categoryId, String name, String price) { + return "{\"categoryId\":" + categoryId + ",\"productName\":\"" + name + "\",\"unitPrice\":" + price + "}"; + } + + private Long product(Long categoryId, String name, String price) { + Long id = given().auth().oauth2(admin).contentType("application/json").body(body(categoryId, name, price)) + .when().post(BASE).then().statusCode(201).extract().jsonPath().getLong("data.id"); + products.add(id); + return id; + } + + private String tokenWith(String... permissions) { + Long role = support.createRole(RbacTestSupport.unique("prod-role"), permissions); + RbacTestSupport.TestUser user = support.createUser(); + support.grantRole(user.id(), role); + return support.token(user); + } + + @Test + void createReturns201WithEnvelopeAndMoneyRoundTrips() { + Long cat = category(); + String json = given().auth().oauth2(admin).contentType("application/json") + .body(body(cat, "Keyboard", "79.99")).when().post(BASE) + .then().statusCode(201).contentType("application/json") + .body("success", is(true)) + .body("data.id", notNullValue()) + .body("data.categoryId", is(cat.intValue())) + .body("data.productName", is("Keyboard")) + .extract().asString(); + Long id = io.restassured.path.json.JsonPath.from(json).getLong("data.id"); + products.add(id); + assertEquals(0, new BigDecimal("79.99") + .compareTo(new BigDecimal(io.restassured.path.json.JsonPath.from(json).getString("data.unitPrice")))); + + String read = given().auth().oauth2(admin).when().get(BASE + "/" + id) + .then().statusCode(200).extract().jsonPath().getString("data.unitPrice"); + assertEquals(0, new BigDecimal("79.99").compareTo(new BigDecimal(read))); + } + + @Test + void getByIdAndUpdate() { + Long cat = category(); + Long other = category(); + Long id = product(cat, "Mouse", "10.50"); + given().auth().oauth2(admin).when().get(BASE + "/" + id) + .then().statusCode(200).body("success", is(true)).body("data.id", is(id.intValue())) + .body("data.productName", is("Mouse")); + given().auth().oauth2(admin).contentType("application/json").body(body(other, "Mouse 2", "12.25")) + .when().put(BASE + "/" + id) + .then().statusCode(200).body("data.productName", is("Mouse 2")) + .body("data.categoryId", is(other.intValue())); + String price = given().auth().oauth2(admin).when().get(BASE + "/" + id) + .then().statusCode(200).body("data.productName", is("Mouse 2")) + .body("data.categoryId", is(other.intValue())) + .extract().jsonPath().getString("data.unitPrice"); + assertEquals(0, new BigDecimal("12.25").compareTo(new BigDecimal(price))); + } + + @Test + void listIsPaginatedAndOrderedById() { + Long cat = category(); + Long a = product(cat, "A", "1.00"); + Long b = product(cat, "B", "2.00"); + Long c = product(cat, "C", "3.00"); + List ids = given().auth().oauth2(admin).queryParam("size", 100).when().get(BASE) + .then().statusCode(200).body("success", is(true)) + .body("data.content.id", hasItems(a.intValue(), b.intValue(), c.intValue())) + .extract().jsonPath().getList("data.content.id"); + assertEquals(ids.stream().sorted().toList(), ids); + + int total = given().auth().oauth2(admin).queryParam("size", 1).get(BASE) + .jsonPath().getInt("data.totalElements"); + given().auth().oauth2(admin).queryParam("page", 1).queryParam("size", 1).when().get(BASE) + .then().statusCode(200) + .body("data.page", is(1)).body("data.size", is(1)) + .body("data.content.size()", is(1)) + .body("data.totalElements", greaterThanOrEqualTo(3)) + .body("data.totalPages", is(total)); + } + + @Test + void categoryFilterReturnsOnlyRequestedCategory() { + Long catA = category(); + Long catB = category(); + Long a1 = product(catA, "A1", "1.00"); + Long a2 = product(catA, "A2", "2.00"); + Long a3 = product(catA, "A3", "3.00"); + Long b1 = product(catB, "B1", "4.00"); + Long b2 = product(catB, "B2", "5.00"); + + given().auth().oauth2(admin).queryParam("categoryId", catA).when().get(BASE) + .then().statusCode(200) + .body("data.content.id", contains(a1.intValue(), a2.intValue(), a3.intValue())) + .body("data.content.categoryId", everyItem(is(catA.intValue()))) + .body("data.totalElements", is(3)); + given().auth().oauth2(admin).queryParam("categoryId", catB).when().get(BASE) + .then().statusCode(200) + .body("data.content.id", contains(b1.intValue(), b2.intValue())) + .body("data.totalElements", is(2)); + given().auth().oauth2(admin).queryParam("categoryId", catA).queryParam("page", 1).queryParam("size", 2) + .when().get(BASE) + .then().statusCode(200) + .body("data.content.id", contains(a3.intValue())) + .body("data.totalElements", is(3)).body("data.totalPages", is(2)); + } + + @Test + void invalidPageSizeIs400Problem() { + given().auth().oauth2(admin).queryParam("size", 0).when().get(BASE) + .then().statusCode(400).contentType(PROBLEM_JSON).body("$", not(hasKey("success"))); + } + + @Test + void unknownIdIs404Problem() { + Long cat = category(); + given().auth().oauth2(admin).when().get(BASE + "/999999999") + .then().statusCode(404).contentType(PROBLEM_JSON).body("status", is(404)) + .body("$", not(hasKey("success"))); + given().auth().oauth2(admin).contentType("application/json").body(body(cat, "x", "1.00")) + .when().put(BASE + "/999999999") + .then().statusCode(404).contentType(PROBLEM_JSON); + given().auth().oauth2(admin).when().delete(BASE + "/999999999") + .then().statusCode(404).contentType(PROBLEM_JSON); + } + + @Test + void invalidBodyIs400ProblemWithViolations() { + Long cat = category(); + List bodies = List.of( + body(cat, " ", "1.00"), + body(cat, "x".repeat(151), "1.00"), + body(cat, "Bad", "0"), + body(cat, "Bad", "-5.00"), + body(cat, "Bad", "1.234"), + "{\"productName\":\"Bad\",\"unitPrice\":1.00}"); + for (String json : bodies) { + given().auth().oauth2(admin).contentType("application/json").body(json).when().post(BASE) + .then().statusCode(400).contentType(PROBLEM_JSON) + .body("status", is(400)) + .body("violations", not(empty())) + .body("$", not(hasKey("success"))); + } + Long id = product(cat, "Ok", "1.00"); + given().auth().oauth2(admin).contentType("application/json").body(body(cat, "", "1.00")) + .when().put(BASE + "/" + id) + .then().statusCode(400).contentType(PROBLEM_JSON).body("violations", not(empty())); + } + + @Test + void unknownCategoryIs422ProblemOnCreateAndUpdate() { + Long cat = category(); + given().auth().oauth2(admin).contentType("application/json").body(body(999999999, "Ghost", "1.00")) + .when().post(BASE) + .then().statusCode(422).contentType(PROBLEM_JSON).body("status", is(422)) + .body("$", not(hasKey("success"))); + Long id = product(cat, "Real", "1.00"); + given().auth().oauth2(admin).contentType("application/json").body(body(999999999, "Ghost", "1.00")) + .when().put(BASE + "/" + id) + .then().statusCode(422).contentType(PROBLEM_JSON).body("status", is(422)); + given().auth().oauth2(admin).when().get(BASE + "/" + id) + .then().statusCode(200).body("data.categoryId", is(cat.intValue())) + .body("data.productName", is("Real")); + } + + @Test + void deleteRemovesProduct() { + Long id = product(category(), "Gone", "1.00"); + given().auth().oauth2(admin).when().delete(BASE + "/" + id) + .then().statusCode(200).body("success", is(true)); + given().auth().oauth2(admin).when().get(BASE + "/" + id).then().statusCode(404).contentType(PROBLEM_JSON); + } + + @Test + void categoryWithProductsCannotBeDeletedUntilProductIsDeleted() { + Long cat = category(); + Long id = product(cat, "Blocker", "1.00"); + given().auth().oauth2(admin).when().delete(CATEGORIES + "/" + cat) + .then().statusCode(422).contentType(PROBLEM_JSON).body("status", is(422)) + .body("$", not(hasKey("success"))); + given().auth().oauth2(admin).when().delete(BASE + "/" + id).then().statusCode(200); + given().auth().oauth2(admin).when().delete(CATEGORIES + "/" + cat).then().statusCode(200); + } + + @Test + void readOnlyUserCanReadButNotWrite() { + Long cat = category(); + Long id = product(cat, "Shared", "1.00"); + String reader = tokenWith("PRODUCT:READ"); + given().auth().oauth2(reader).when().get(BASE).then().statusCode(200); + given().auth().oauth2(reader).when().get(BASE + "/" + id).then().statusCode(200); + given().auth().oauth2(reader).contentType("application/json").body(body(cat, "n", "1.00")) + .when().post(BASE).then().statusCode(403).contentType(PROBLEM_JSON).body("status", is(403)); + given().auth().oauth2(reader).contentType("application/json").body(body(cat, "n", "1.00")) + .when().put(BASE + "/" + id).then().statusCode(403).contentType(PROBLEM_JSON); + given().auth().oauth2(reader).when().delete(BASE + "/" + id) + .then().statusCode(403).contentType(PROBLEM_JSON); + given().auth().oauth2(admin).when().get(BASE + "/" + id).then().statusCode(200) + .body("data.productName", is("Shared")); + } + + @Test + void userWithoutPermissionIs403AndNoTokenIs401() { + String nobody = support.token(support.createUser()); + given().auth().oauth2(nobody).when().get(BASE).then().statusCode(403).contentType(PROBLEM_JSON); + given().auth().oauth2(nobody).when().get(BASE + "/1").then().statusCode(403).contentType(PROBLEM_JSON); + given().when().get(BASE).then().statusCode(401); + given().contentType("application/json").body(body(1, "n", "1.00")).when().post(BASE) + .then().statusCode(401); + } +} From ff0af23f9b93b399b9e54fcc7549ad94a224c7c9 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 10:48:14 +0400 Subject: [PATCH 107/158] docs(readme): check off feature/products The four tasks of the branch are ticked. The cache task now says where the annotations really live: on ProductServiceImpl and not on the ProductService interface, because the CDI container only applies interceptor bindings declared on the class it intercepts, and the cache stayed empty when they were placed on the interface. The wording also records the explicit @CacheKey on the id, which is what makes the read and the two invalidations agree on the same entry. --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index ce18f64..82ec2ff 100644 --- a/README.md +++ b/README.md @@ -361,10 +361,10 @@ Depends on `feature/categories` existing, since every product references one. ### Tasks -- [ ] `Product` entity, repository, contract/implementation service -- [ ] `ProductService.findById` annotated `@CacheResult(cacheName = "product-cache")`; `ProductServiceImpl.update`/`delete` annotated `@CacheInvalidate(cacheName = "product-cache")` on the same key - a product read hits Panache once and the cache for every subsequent read until it's changed, and every write explicitly clears its own entry rather than leaving a stale cached value silently served -- [ ] `ProductResource` -- [ ] Tests, including the category filter, a permission-denied case, and a cache test asserting a second read doesn't hit the repository while an update correctly invalidates the entry +- [x] `Product` entity, repository, contract/implementation service +- [x] `ProductServiceImpl.findById` annotated `@CacheResult(cacheName = "product-cache")`; `ProductServiceImpl.update`/`delete` annotated `@CacheInvalidate(cacheName = "product-cache")` on the same key (`@CacheKey` on the id) - a product read hits Panache once and the cache for every subsequent read until it's changed, and every write explicitly clears its own entry rather than leaving a stale cached value silently served. The annotations sit on the implementation class, not on the `ProductService` interface: ArC does not apply interceptor bindings declared on an interface method +- [x] `ProductResource` +- [x] Tests, including the category filter, a permission-denied case, and a cache test asserting a second read doesn't hit the repository while an update correctly invalidates the entry ## feature/customers From ba38305c4b17535ef97d2d78fe76cf2e32c74de3 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 10:51:57 +0400 Subject: [PATCH 108/158] fix(service): scale the product price to two decimals on write The entity kept the BigDecimal exactly as the client sent it, so creating a product with 10.5 answered 10.5 while a later read returned 10.50 from the NUMERIC(12, 2) column. The price is now scaled to two decimals when it is applied, which is always exact because the request validation already allows at most two. A write response and a read response therefore show the same value, and the value stored in the cache has the same scale as one loaded from the database. --- .../quarkustutorial/service/impl/ProductServiceImpl.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/edgareldy/quarkustutorial/service/impl/ProductServiceImpl.java b/src/main/java/com/edgareldy/quarkustutorial/service/impl/ProductServiceImpl.java index 13929a1..6e37ef8 100644 --- a/src/main/java/com/edgareldy/quarkustutorial/service/impl/ProductServiceImpl.java +++ b/src/main/java/com/edgareldy/quarkustutorial/service/impl/ProductServiceImpl.java @@ -101,7 +101,9 @@ private void apply(Product product, ProductRequest request) { } product.setCategory(category); product.setProductName(request.productName()); - product.setUnitPrice(request.unitPrice()); + // Scale to 2 decimals like the NUMERIC(12, 2) column (ProductRequest allows at most 2), so the + // response to a write shows the same value a later read returns from the database. + product.setUnitPrice(request.unitPrice().setScale(2)); } private static ProductResponse toResponse(Product product) { From 09e824cd3b7302b8e215d8d0db45541983f43ec0 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 10:51:57 +0400 Subject: [PATCH 109/158] test(service): check the price scale returned on creation A price sent as 10.5 must come back as 10.50, the scale of the database column. BigDecimal equality is scale sensitive, so the assertion fails if the value is returned unscaled. --- .../service/impl/ProductServiceImplTest.java | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/test/java/com/edgareldy/quarkustutorial/service/impl/ProductServiceImplTest.java b/src/test/java/com/edgareldy/quarkustutorial/service/impl/ProductServiceImplTest.java index 907b4ed..cd5f6cc 100644 --- a/src/test/java/com/edgareldy/quarkustutorial/service/impl/ProductServiceImplTest.java +++ b/src/test/java/com/edgareldy/quarkustutorial/service/impl/ProductServiceImplTest.java @@ -70,6 +70,15 @@ void createWithUnknownCategoryIsRefused() { verify(productRepository, never()).persist(any(Product.class)); } + @Test + void createScalesThePriceLikeTheDatabaseColumn() { + when(categoryRepository.findById(1L)).thenReturn(category(1L)); + + ProductResponse response = service.create(new ProductRequest(1L, "Pen", new BigDecimal("10.5"))); + + assertEquals(new BigDecimal("10.50"), response.unitPrice()); + } + @Test void createPersistsAndMapsResponse() { when(categoryRepository.findById(1L)).thenReturn(category(1L)); From c576e5ebb6f330cf85daa821d20dece6c865dc4f Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 10:59:51 +0400 Subject: [PATCH 110/158] feat(entity): add the Customer entity Customer maps the customers table of the initial Flyway migration. The two names are required and the telephone, email and address are nullable, with the same lengths as the columns, so the entity and the schema agree on what may be missing. The customers belong to the e-commerce domain and hold no reference to users or roles: the identity and e-commerce domains share one database but stay independent. --- .../quarkustutorial/entity/Customer.java | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/entity/Customer.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/entity/Customer.java b/src/main/java/com/edgareldy/quarkustutorial/entity/Customer.java new file mode 100644 index 0000000..09d372e --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/entity/Customer.java @@ -0,0 +1,53 @@ +package com.edgareldy.quarkustutorial.entity; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; + +/** + * A customer of the e-commerce domain. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +@Entity +@Table(name = "customers") +public class Customer { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "first_name", nullable = false, length = 100) + private String firstName; + + @Column(name = "last_name", nullable = false, length = 100) + private String lastName; + + @Column(length = 50) + private String telephone; + + @Column(length = 255) + private String email; + + @Column(length = 255) + private String address; + + public Long getId() { return id; } + public void setId(Long id) { this.id = id; } + public String getFirstName() { return firstName; } + public void setFirstName(String firstName) { this.firstName = firstName; } + public String getLastName() { return lastName; } + public void setLastName(String lastName) { this.lastName = lastName; } + public String getTelephone() { return telephone; } + public void setTelephone(String telephone) { this.telephone = telephone; } + public String getEmail() { return email; } + public void setEmail(String email) { this.email = email; } + public String getAddress() { return address; } + public void setAddress(String address) { this.address = address; } +} From 3dc898801c49a107e2012270bb9605448ff16101 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 10:59:51 +0400 Subject: [PATCH 111/158] feat(repository): add CustomerRepository A plain PanacheRepository is enough here: persist, find, count and delete come with it, and no query goes beyond what Panache already provides, so nothing is added by hand. Ordering and paging are decided by the service, which keeps the repository free of presentation concerns. --- .../repository/CustomerRepository.java | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/repository/CustomerRepository.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/repository/CustomerRepository.java b/src/main/java/com/edgareldy/quarkustutorial/repository/CustomerRepository.java new file mode 100644 index 0000000..16129f8 --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/repository/CustomerRepository.java @@ -0,0 +1,17 @@ +package com.edgareldy.quarkustutorial.repository; + +import com.edgareldy.quarkustutorial.entity.Customer; +import io.quarkus.hibernate.orm.panache.PanacheRepository; +import jakarta.enterprise.context.ApplicationScoped; + +/** + * Panache repository for customers. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +@ApplicationScoped +public class CustomerRepository implements PanacheRepository { +} From 2cd9c45b4cfccb051f879fdae605f9cccf73cf3c Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 10:59:51 +0400 Subject: [PATCH 112/158] feat(dto): add CustomerRequest with Bean Validation Both names are required, not blank and bounded to their column length. The telephone, email and address are optional, but when present they must fit their column and the email must be well formed. Keeping these rules on the record means a bad payload is refused with a 400 listing each violation, before the service or the database is involved. --- .../dto/ecommerce/CustomerRequest.java | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/dto/ecommerce/CustomerRequest.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/dto/ecommerce/CustomerRequest.java b/src/main/java/com/edgareldy/quarkustutorial/dto/ecommerce/CustomerRequest.java new file mode 100644 index 0000000..9cf6724 --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/dto/ecommerce/CustomerRequest.java @@ -0,0 +1,21 @@ +package com.edgareldy.quarkustutorial.dto.ecommerce; + +import jakarta.validation.constraints.Email; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Size; + +/** + * Payload to create or update a customer. Telephone, email and address are optional. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +public record CustomerRequest( + @NotBlank @Size(max = 100) String firstName, + @NotBlank @Size(max = 100) String lastName, + @Size(max = 50) String telephone, + @Email @Size(max = 255) String email, + @Size(max = 255) String address) { +} From 0de2653a959d87d6604f8c0290182cb75187da8b Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 10:59:51 +0400 Subject: [PATCH 113/158] feat(dto): add CustomerResponse The response exposes the customer fields without leaking the entity, so the API shape does not depend on the persistence model. Optional fields are simply null when absent. --- .../dto/ecommerce/CustomerResponse.java | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/dto/ecommerce/CustomerResponse.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/dto/ecommerce/CustomerResponse.java b/src/main/java/com/edgareldy/quarkustutorial/dto/ecommerce/CustomerResponse.java new file mode 100644 index 0000000..ecb0bc2 --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/dto/ecommerce/CustomerResponse.java @@ -0,0 +1,13 @@ +package com.edgareldy.quarkustutorial.dto.ecommerce; + +/** + * Customer as returned by the API. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +public record CustomerResponse(Long id, String firstName, String lastName, String telephone, String email, + String address) { +} From 7efc8e2550715bf71aed9730aaa82b9751e85d14 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 10:59:51 +0400 Subject: [PATCH 114/158] feat(service): add the CustomerService contract The contract offers a paginated list, a lookup by id, and creation, update and deletion in terms of DTOs. Resources depend on this interface and tests can replace its implementation. Deletion is a plain delete for now; the rule that refuses to delete a customer who has orders can only exist once orders do, and belongs to that later change. --- .../service/CustomerService.java | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/service/CustomerService.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/service/CustomerService.java b/src/main/java/com/edgareldy/quarkustutorial/service/CustomerService.java new file mode 100644 index 0000000..7a5e6dc --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/service/CustomerService.java @@ -0,0 +1,31 @@ +package com.edgareldy.quarkustutorial.service; + +import com.edgareldy.quarkustutorial.dto.common.PageResponse; +import com.edgareldy.quarkustutorial.dto.ecommerce.CustomerRequest; +import com.edgareldy.quarkustutorial.dto.ecommerce.CustomerResponse; + +/** + * Contract for customer management. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +public interface CustomerService { + + /** @return one page of customers ordered by id */ + PageResponse list(int page, int size); + + /** @return the customer, or throws ResourceNotFoundException (404) */ + CustomerResponse findById(Long id); + + /** @return the created customer */ + CustomerResponse create(CustomerRequest request); + + /** @return the updated customer, or throws ResourceNotFoundException (404) */ + CustomerResponse update(Long id, CustomerRequest request); + + /** Deletes a customer; throws ResourceNotFoundException (404) if missing. */ + void delete(Long id); +} From e0a3b79782878f05fd96743a4ec32ac0b2678ada Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 10:59:52 +0400 Subject: [PATCH 115/158] feat(service): implement CustomerService Reading, updating or deleting a missing customer answers 404 through ResourceNotFoundException. Write methods are transactional so a change is one unit of work, and the list orders by id so pages are stable. Unlike products, nothing is cached: customers have no hot read path that justifies an entry that would need invalidating on every write. --- .../service/impl/CustomerServiceImpl.java | 88 +++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/service/impl/CustomerServiceImpl.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/service/impl/CustomerServiceImpl.java b/src/main/java/com/edgareldy/quarkustutorial/service/impl/CustomerServiceImpl.java new file mode 100644 index 0000000..a5b8f7e --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/service/impl/CustomerServiceImpl.java @@ -0,0 +1,88 @@ +package com.edgareldy.quarkustutorial.service.impl; + +import com.edgareldy.quarkustutorial.dto.common.PageResponse; +import com.edgareldy.quarkustutorial.dto.ecommerce.CustomerRequest; +import com.edgareldy.quarkustutorial.dto.ecommerce.CustomerResponse; +import com.edgareldy.quarkustutorial.entity.Customer; +import com.edgareldy.quarkustutorial.exception.ResourceNotFoundException; +import com.edgareldy.quarkustutorial.repository.CustomerRepository; +import com.edgareldy.quarkustutorial.service.CustomerService; +import io.quarkus.panache.common.Page; +import io.quarkus.panache.common.Sort; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import jakarta.transaction.Transactional; +import java.util.List; + +/** + * Default {@link CustomerService} backed by Panache. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +@ApplicationScoped +public class CustomerServiceImpl implements CustomerService { + + @Inject + CustomerRepository customerRepository; + + @Override + @Transactional + public PageResponse list(int page, int size) { + List content = customerRepository.findAll(Sort.by("id")).page(Page.of(page, size)) + .list().stream().map(CustomerServiceImpl::toResponse).toList(); + return PageResponse.of(content, page, size, customerRepository.count()); + } + + @Override + @Transactional + public CustomerResponse findById(Long id) { + return toResponse(find(id)); + } + + @Override + @Transactional + public CustomerResponse create(CustomerRequest request) { + Customer customer = new Customer(); + apply(customer, request); + customerRepository.persist(customer); + return toResponse(customer); + } + + @Override + @Transactional + public CustomerResponse update(Long id, CustomerRequest request) { + Customer customer = find(id); + apply(customer, request); + return toResponse(customer); + } + + @Override + @Transactional + public void delete(Long id) { + customerRepository.delete(find(id)); + } + + private Customer find(Long id) { + Customer customer = customerRepository.findById(id); + if (customer == null) { + throw new ResourceNotFoundException("Customer " + id + " not found"); + } + return customer; + } + + private static void apply(Customer customer, CustomerRequest request) { + customer.setFirstName(request.firstName()); + customer.setLastName(request.lastName()); + customer.setTelephone(request.telephone()); + customer.setEmail(request.email()); + customer.setAddress(request.address()); + } + + private static CustomerResponse toResponse(Customer customer) { + return new CustomerResponse(customer.getId(), customer.getFirstName(), customer.getLastName(), + customer.getTelephone(), customer.getEmail(), customer.getAddress()); + } +} From da679ffc1e61064bf19002c28feb5a1d50839b4f Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 10:59:52 +0400 Subject: [PATCH 116/158] feat(resource): add CustomerResource The five endpoints are protected with @PermissionsAllowed, CUSTOMER:READ for reading and CUSTOMER:WRITE for the rest, and the resource only validates, delegates and wraps the result in the success envelope. Creating answers 201. The page size is bounded like the other lists, so a size of zero is refused before it can produce an empty page count. --- .../resource/CustomerResource.java | 81 +++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/resource/CustomerResource.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/resource/CustomerResource.java b/src/main/java/com/edgareldy/quarkustutorial/resource/CustomerResource.java new file mode 100644 index 0000000..7766617 --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/resource/CustomerResource.java @@ -0,0 +1,81 @@ +package com.edgareldy.quarkustutorial.resource; + +import com.edgareldy.quarkustutorial.dto.common.ApiResponse; +import com.edgareldy.quarkustutorial.dto.common.PageResponse; +import com.edgareldy.quarkustutorial.dto.ecommerce.CustomerRequest; +import com.edgareldy.quarkustutorial.dto.ecommerce.CustomerResponse; +import com.edgareldy.quarkustutorial.service.CustomerService; +import io.quarkus.security.PermissionsAllowed; +import jakarta.inject.Inject; +import jakarta.validation.Valid; +import jakarta.validation.constraints.Max; +import jakarta.validation.constraints.Min; +import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.DELETE; +import jakarta.ws.rs.DefaultValue; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.PUT; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.PathParam; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.QueryParam; +import jakarta.ws.rs.core.MediaType; +import org.eclipse.microprofile.openapi.annotations.security.SecurityRequirement; +import org.jboss.resteasy.reactive.ResponseStatus; + +/** + * CRUD endpoints for customers. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +@Path("/api/v1/customers") +@Produces(MediaType.APPLICATION_JSON) +@SecurityRequirement(name = "jwt") +public class CustomerResource { + + @Inject + CustomerService customerService; + + @GET + @PermissionsAllowed("CUSTOMER:READ") + public ApiResponse> list( + @QueryParam("page") @DefaultValue("0") @Min(0) int page, + @QueryParam("size") @DefaultValue("20") @Min(1) @Max(100) int size) { + return ApiResponse.success(customerService.list(page, size), "Customers"); + } + + @GET + @Path("/{id}") + @PermissionsAllowed("CUSTOMER:READ") + public ApiResponse get(@PathParam("id") Long id) { + return ApiResponse.success(customerService.findById(id), "Customer"); + } + + @POST + @Consumes(MediaType.APPLICATION_JSON) + @PermissionsAllowed("CUSTOMER:WRITE") + @ResponseStatus(201) + public ApiResponse create(@Valid CustomerRequest request) { + return ApiResponse.success(customerService.create(request), "Customer created"); + } + + @PUT + @Path("/{id}") + @Consumes(MediaType.APPLICATION_JSON) + @PermissionsAllowed("CUSTOMER:WRITE") + public ApiResponse update(@PathParam("id") Long id, @Valid CustomerRequest request) { + return ApiResponse.success(customerService.update(id, request), "Customer updated"); + } + + @DELETE + @Path("/{id}") + @PermissionsAllowed("CUSTOMER:WRITE") + public ApiResponse delete(@PathParam("id") Long id) { + customerService.delete(id); + return ApiResponse.success(null, "Customer deleted"); + } +} From e07999dc94e61e014a7635234bdf989020d86b2b Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 10:59:52 +0400 Subject: [PATCH 117/158] test(repository): round trip customers on PostgreSQL The tests persist, read back and delete customers against the container that Dev Services starts, including the nullable columns coming back as null, so the mapping is checked against the real schema built by Flyway. --- .../repository/CustomerRepositoryTest.java | 83 +++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 src/test/java/com/edgareldy/quarkustutorial/repository/CustomerRepositoryTest.java diff --git a/src/test/java/com/edgareldy/quarkustutorial/repository/CustomerRepositoryTest.java b/src/test/java/com/edgareldy/quarkustutorial/repository/CustomerRepositoryTest.java new file mode 100644 index 0000000..35b59fd --- /dev/null +++ b/src/test/java/com/edgareldy/quarkustutorial/repository/CustomerRepositoryTest.java @@ -0,0 +1,83 @@ +package com.edgareldy.quarkustutorial.repository; + +import static org.junit.jupiter.api.Assertions.*; + +import com.edgareldy.quarkustutorial.entity.Customer; +import io.quarkus.narayana.jta.QuarkusTransaction; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import jakarta.persistence.EntityManager; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +/** + * Repository tests of CustomerRepository against the Dev Services PostgreSQL. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +// @QuarkusTest boots the real datasource (Dev Services PostgreSQL, Flyway schema) so the mapping and the +// nullable columns are checked against the real customers table. Data is committed then removed afterwards. +@QuarkusTest +class CustomerRepositoryTest { + + @Inject + CustomerRepository repository; + + @Inject + EntityManager em; + + private Long customerId; + + @AfterEach + void tearDown() { + if (customerId != null) { + QuarkusTransaction.requiringNew().run(() -> em.createNativeQuery("delete from customers where id = ?1") + .setParameter(1, customerId).executeUpdate()); + } + } + + private Long persist(String telephone, String email, String address) { + return QuarkusTransaction.requiringNew().call(() -> { + Customer c = new Customer(); + c.setFirstName("Ada"); + c.setLastName("Lovelace"); + c.setTelephone(telephone); + c.setEmail(email); + c.setAddress(address); + repository.persist(c); + return c.getId(); + }); + } + + @Test + void persistAndFindRoundTrip() { + customerId = persist("123", "ada@example.com", "London"); + Customer found = QuarkusTransaction.requiringNew().call(() -> repository.findById(customerId)); + assertNotNull(found); + assertEquals("Ada", found.getFirstName()); + assertEquals("Lovelace", found.getLastName()); + assertEquals("123", found.getTelephone()); + assertEquals("ada@example.com", found.getEmail()); + assertEquals("London", found.getAddress()); + } + + @Test + void nullableColumnsRoundTripAsNull() { + customerId = persist(null, null, null); + Customer found = QuarkusTransaction.requiringNew().call(() -> repository.findById(customerId)); + assertNotNull(found); + assertNull(found.getTelephone()); + assertNull(found.getEmail()); + assertNull(found.getAddress()); + } + + @Test + void deleteRemovesRow() { + customerId = persist(null, null, null); + QuarkusTransaction.requiringNew().run(() -> repository.deleteById(customerId)); + assertNull(QuarkusTransaction.requiringNew().call(() -> repository.findById(customerId))); + } +} From e7172a5b8b7aeacaa98566dcf7528ccf20b0af56 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 10:59:52 +0400 Subject: [PATCH 118/158] test(service): unit test the customer service with mocks The service runs in isolation with a mocked repository. The cases cover the mapping to the response, update overwriting every field, 404 on a missing customer for lookup, update and deletion, and the page being requested with the right index and size. --- .../service/impl/CustomerServiceImplTest.java | 149 ++++++++++++++++++ 1 file changed, 149 insertions(+) create mode 100644 src/test/java/com/edgareldy/quarkustutorial/service/impl/CustomerServiceImplTest.java diff --git a/src/test/java/com/edgareldy/quarkustutorial/service/impl/CustomerServiceImplTest.java b/src/test/java/com/edgareldy/quarkustutorial/service/impl/CustomerServiceImplTest.java new file mode 100644 index 0000000..c4893f5 --- /dev/null +++ b/src/test/java/com/edgareldy/quarkustutorial/service/impl/CustomerServiceImplTest.java @@ -0,0 +1,149 @@ +package com.edgareldy.quarkustutorial.service.impl; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +import com.edgareldy.quarkustutorial.dto.common.PageResponse; +import com.edgareldy.quarkustutorial.dto.ecommerce.CustomerRequest; +import com.edgareldy.quarkustutorial.dto.ecommerce.CustomerResponse; +import com.edgareldy.quarkustutorial.entity.Customer; +import com.edgareldy.quarkustutorial.exception.ResourceNotFoundException; +import com.edgareldy.quarkustutorial.repository.CustomerRepository; +import io.quarkus.hibernate.orm.panache.PanacheQuery; +import io.quarkus.panache.common.Page; +import io.quarkus.panache.common.Sort; +import java.util.List; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +/** + * Isolated unit tests of CustomerServiceImpl with the repository mocked. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +// Plain Mockito with the package-private injected field assigned directly (same approach as +// CategoryServiceImplTest): no container is needed to test the mapping and not-found rules. +class CustomerServiceImplTest { + + private CustomerRepository repository; + private CustomerServiceImpl service; + + @BeforeEach + void setUp() { + repository = mock(CustomerRepository.class); + service = new CustomerServiceImpl(); + service.customerRepository = repository; + } + + private static Customer customer(Long id, String first) { + Customer c = new Customer(); + c.setId(id); + c.setFirstName(first); + c.setLastName("Last"); + c.setTelephone("1"); + c.setEmail("a@b.co"); + c.setAddress("Addr"); + return c; + } + + @Test + void findByIdMapsEntity() { + when(repository.findById(1L)).thenReturn(customer(1L, "Ada")); + + CustomerResponse r = service.findById(1L); + + assertEquals(new CustomerResponse(1L, "Ada", "Last", "1", "a@b.co", "Addr"), r); + } + + @Test + void findByIdMissingIsNotFound() { + when(repository.findById(9L)).thenReturn(null); + + assertThrows(ResourceNotFoundException.class, () -> service.findById(9L)); + } + + @Test + void createPersistsMappedEntityIncludingNullOptionals() { + CustomerResponse r = service.create(new CustomerRequest("Ada", "Lovelace", null, null, null)); + + ArgumentCaptor saved = ArgumentCaptor.forClass(Customer.class); + verify(repository).persist(saved.capture()); + assertEquals("Ada", saved.getValue().getFirstName()); + assertEquals("Lovelace", saved.getValue().getLastName()); + assertNull(saved.getValue().getTelephone()); + assertNull(saved.getValue().getEmail()); + assertNull(saved.getValue().getAddress()); + assertEquals("Ada", r.firstName()); + assertNull(r.email()); + } + + @Test + void updateOverwritesAllFields() { + Customer existing = customer(1L, "Old"); + when(repository.findById(1L)).thenReturn(existing); + + CustomerResponse r = service.update(1L, new CustomerRequest("New", "Name", null, "n@e.io", "Here")); + + assertEquals("New", existing.getFirstName()); + assertEquals("Name", existing.getLastName()); + assertNull(existing.getTelephone()); + assertEquals("n@e.io", existing.getEmail()); + assertEquals("Here", r.address()); + assertEquals(1L, r.id()); + } + + @Test + void updateMissingIsNotFound() { + when(repository.findById(9L)).thenReturn(null); + + assertThrows(ResourceNotFoundException.class, + () -> service.update(9L, new CustomerRequest("a", "b", null, null, null))); + } + + @Test + void deleteRemovesCustomer() { + Customer c = customer(1L, "Ada"); + when(repository.findById(1L)).thenReturn(c); + + service.delete(1L); + + verify(repository).delete(c); + } + + @Test + void deleteMissingIsNotFound() { + when(repository.findById(9L)).thenReturn(null); + + assertThrows(ResourceNotFoundException.class, () -> service.delete(9L)); + verify(repository, never()).delete(any(Customer.class)); + } + + @Test + @SuppressWarnings("unchecked") + void listBuildsPageResponse() { + PanacheQuery all = mock(PanacheQuery.class); + PanacheQuery paged = mock(PanacheQuery.class); + when(repository.findAll(any(Sort.class))).thenReturn(all); + when(all.page(any(Page.class))).thenReturn(paged); + when(paged.list()).thenReturn(List.of(customer(1L, "A"), customer(2L, "B"))); + when(repository.count()).thenReturn(5L); + + PageResponse page = service.list(1, 2); + + assertEquals(2, page.content().size()); + assertEquals("A", page.content().get(0).firstName()); + assertEquals(1, page.page()); + assertEquals(2, page.size()); + assertEquals(5L, page.totalElements()); + assertEquals(3, page.totalPages()); + ArgumentCaptor requested = ArgumentCaptor.forClass(Page.class); + verify(all).page(requested.capture()); + assertEquals(1, requested.getValue().index); + assertEquals(2, requested.getValue().size); + } +} From 3c8eea7d9e9e722cdeb25bbc3949e900fcf51b05 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 10:59:52 +0400 Subject: [PATCH 119/158] test(resource): cover every customer endpoint and its access rules The tests call the five endpoints over HTTP, checking the 201 on creation, optional fields, paging errors, validation violations on create and update, 404 problems, and the 401 and 403 cases for a missing token and for users lacking the required permission. --- .../resource/CustomerResourceTest.java | 224 ++++++++++++++++++ 1 file changed, 224 insertions(+) create mode 100644 src/test/java/com/edgareldy/quarkustutorial/resource/CustomerResourceTest.java diff --git a/src/test/java/com/edgareldy/quarkustutorial/resource/CustomerResourceTest.java b/src/test/java/com/edgareldy/quarkustutorial/resource/CustomerResourceTest.java new file mode 100644 index 0000000..3df8469 --- /dev/null +++ b/src/test/java/com/edgareldy/quarkustutorial/resource/CustomerResourceTest.java @@ -0,0 +1,224 @@ +package com.edgareldy.quarkustutorial.resource; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.*; + +import com.edgareldy.quarkustutorial.rbac.RbacTestSupport; +import io.quarkus.narayana.jta.QuarkusTransaction; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import jakarta.persistence.EntityManager; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * End-to-end tests of the customer endpoints: CRUD, pagination, validation, optional fields and permission denial. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +// Same approach as CategoryResourceTest: real HTTP against Dev Services, users built via RbacTestSupport. +// Customers created here are tracked and removed in tearDown(). +@QuarkusTest +class CustomerResourceTest { + + private static final String PROBLEM_JSON = "application/problem+json"; + private static final String BASE = "/api/v1/customers"; + private static final String VALID = "{\"firstName\":\"Ada\",\"lastName\":\"Lovelace\"," + + "\"telephone\":\"123\",\"email\":\"ada@example.com\",\"address\":\"London\"}"; + + @Inject + RbacTestSupport support; + + @Inject + EntityManager em; + + private final List customers = new ArrayList<>(); + private String admin; + + @BeforeEach + void setUp() { + admin = support.token(support.createUser("ADMIN")); + } + + @AfterEach + void tearDown() { + QuarkusTransaction.requiringNew().run(() -> customers.forEach(id -> em + .createNativeQuery("delete from customers where id = ?1").setParameter(1, id).executeUpdate())); + customers.clear(); + support.cleanup(); + } + + private Long createViaApi(String body) { + Long id = given().auth().oauth2(admin).contentType("application/json").body(body).when().post(BASE) + .then().statusCode(201).extract().jsonPath().getLong("data.id"); + customers.add(id); + return id; + } + + private String tokenWith(String... permissions) { + Long role = support.createRole(RbacTestSupport.unique("cust-role"), permissions); + RbacTestSupport.TestUser user = support.createUser(); + support.grantRole(user.id(), role); + return support.token(user); + } + + @Test + void createReturns201WithEnvelope() { + Long id = given().auth().oauth2(admin).contentType("application/json").body(VALID).when().post(BASE) + .then().statusCode(201).contentType("application/json") + .body("success", is(true)) + .body("data.id", notNullValue()) + .body("data.firstName", is("Ada")) + .body("data.lastName", is("Lovelace")) + .body("data.telephone", is("123")) + .body("data.email", is("ada@example.com")) + .body("data.address", is("London")) + .extract().jsonPath().getLong("data.id"); + customers.add(id); + } + + @Test + void optionalFieldsMayBeOmittedOrNull() { + Long id = createViaApi("{\"firstName\":\"Min\",\"lastName\":\"Imal\"}"); + given().auth().oauth2(admin).when().get(BASE + "/" + id) + .then().statusCode(200) + .body("data.firstName", is("Min")) + .body("data.telephone", nullValue()) + .body("data.email", nullValue()) + .body("data.address", nullValue()); + Long other = createViaApi("{\"firstName\":\"N\",\"lastName\":\"U\",\"telephone\":null,\"email\":null," + + "\"address\":null}"); + given().auth().oauth2(admin).when().get(BASE + "/" + other) + .then().statusCode(200).body("data.email", nullValue()); + } + + @Test + void getByIdAndUpdate() { + Long id = createViaApi(VALID); + given().auth().oauth2(admin).when().get(BASE + "/" + id) + .then().statusCode(200).body("success", is(true)).body("data.id", is(id.intValue())); + given().auth().oauth2(admin).contentType("application/json") + .body("{\"firstName\":\"Grace\",\"lastName\":\"Hopper\"}") + .when().put(BASE + "/" + id) + .then().statusCode(200).body("data.firstName", is("Grace")).body("data.email", nullValue()); + given().auth().oauth2(admin).when().get(BASE + "/" + id) + .then().statusCode(200).body("data.lastName", is("Hopper")).body("data.address", nullValue()); + } + + @Test + void listIsPaginatedAndOrderedById() { + Long a = createViaApi(VALID); + Long b = createViaApi(VALID); + Long c = createViaApi(VALID); + List ids = given().auth().oauth2(admin).queryParam("size", 100).when().get(BASE) + .then().statusCode(200).body("success", is(true)) + .body("data.content.id", hasItems(a.intValue(), b.intValue(), c.intValue())) + .extract().jsonPath().getList("data.content.id", Integer.class); + org.junit.jupiter.api.Assertions.assertEquals(ids.stream().sorted().toList(), ids); + given().auth().oauth2(admin).queryParam("page", 1).queryParam("size", 1).when().get(BASE) + .then().statusCode(200) + .body("data.page", is(1)).body("data.size", is(1)) + .body("data.content.size()", is(1)) + .body("data.totalElements", greaterThanOrEqualTo(3)) + .body("data.totalPages", equalTo(given().auth().oauth2(admin).queryParam("size", 1).get(BASE) + .jsonPath().getInt("data.totalElements"))); + } + + @Test + void invalidPageSizeIs400Problem() { + given().auth().oauth2(admin).queryParam("size", 0).when().get(BASE) + .then().statusCode(400).contentType(PROBLEM_JSON).body("$", not(hasKey("success"))); + given().auth().oauth2(admin).queryParam("size", 101).when().get(BASE) + .then().statusCode(400).contentType(PROBLEM_JSON); + given().auth().oauth2(admin).queryParam("page", -1).when().get(BASE) + .then().statusCode(400).contentType(PROBLEM_JSON); + } + + @Test + void unknownIdIs404Problem() { + given().auth().oauth2(admin).when().get(BASE + "/999999999") + .then().statusCode(404).contentType(PROBLEM_JSON).body("status", is(404)) + .body("$", not(hasKey("success"))); + given().auth().oauth2(admin).contentType("application/json").body(VALID) + .when().put(BASE + "/999999999") + .then().statusCode(404).contentType(PROBLEM_JSON); + given().auth().oauth2(admin).when().delete(BASE + "/999999999") + .then().statusCode(404).contentType(PROBLEM_JSON); + } + + @Test + void invalidBodyIs400ProblemWithViolations() { + List bodies = List.of( + "{\"firstName\":\" \",\"lastName\":\"L\"}", + "{\"firstName\":\"F\",\"lastName\":\"\"}", + "{\"lastName\":\"L\"}", + "{\"firstName\":\"F\",\"lastName\":\"L\",\"email\":\"not-an-email\"}", + "{\"firstName\":\"" + "x".repeat(101) + "\",\"lastName\":\"L\"}", + "{\"firstName\":\"F\",\"lastName\":\"" + "x".repeat(101) + "\"}", + "{\"firstName\":\"F\",\"lastName\":\"L\",\"telephone\":\"" + "1".repeat(51) + "\"}", + "{\"firstName\":\"F\",\"lastName\":\"L\",\"address\":\"" + "a".repeat(256) + "\"}", + "{\"firstName\":\"F\",\"lastName\":\"L\",\"email\":\"" + "a".repeat(250) + "@example.com\"}"); + Long id = createViaApi(VALID); + for (String body : bodies) { + given().auth().oauth2(admin).contentType("application/json").body(body).when().post(BASE) + .then().statusCode(400).contentType(PROBLEM_JSON) + .body("status", is(400)) + .body("violations", not(empty())) + .body("$", not(hasKey("success"))); + given().auth().oauth2(admin).contentType("application/json").body(body).when().put(BASE + "/" + id) + .then().statusCode(400).contentType(PROBLEM_JSON); + } + given().auth().oauth2(admin).when().get(BASE + "/" + id).then().statusCode(200) + .body("data.firstName", is("Ada")); + } + + @Test + void deleteRemovesCustomer() { + Long id = createViaApi(VALID); + given().auth().oauth2(admin).when().delete(BASE + "/" + id) + .then().statusCode(200).body("success", is(true)); + given().auth().oauth2(admin).when().get(BASE + "/" + id).then().statusCode(404).contentType(PROBLEM_JSON); + } + + @Test + void readOnlyUserCanReadButNotWrite() { + Long id = createViaApi(VALID); + String reader = tokenWith("CUSTOMER:READ"); + given().auth().oauth2(reader).when().get(BASE).then().statusCode(200); + given().auth().oauth2(reader).when().get(BASE + "/" + id).then().statusCode(200); + given().auth().oauth2(reader).contentType("application/json").body(VALID) + .when().post(BASE).then().statusCode(403).contentType(PROBLEM_JSON).body("status", is(403)); + given().auth().oauth2(reader).contentType("application/json").body(VALID) + .when().put(BASE + "/" + id).then().statusCode(403).contentType(PROBLEM_JSON); + given().auth().oauth2(reader).when().delete(BASE + "/" + id) + .then().statusCode(403).contentType(PROBLEM_JSON); + given().auth().oauth2(admin).when().get(BASE + "/" + id).then().statusCode(200); + } + + @Test + void writeOnlyUserCannotRead() { + String writer = tokenWith("CUSTOMER:WRITE"); + given().auth().oauth2(writer).when().get(BASE).then().statusCode(403).contentType(PROBLEM_JSON); + Long id = given().auth().oauth2(writer).contentType("application/json").body(VALID).when().post(BASE) + .then().statusCode(201).extract().jsonPath().getLong("data.id"); + customers.add(id); + } + + @Test + void userWithoutPermissionIs403AndNoTokenIs401() { + String nobody = support.token(support.createUser()); + given().auth().oauth2(nobody).when().get(BASE).then().statusCode(403).contentType(PROBLEM_JSON); + given().auth().oauth2(nobody).when().get(BASE + "/1").then().statusCode(403).contentType(PROBLEM_JSON); + given().when().get(BASE).then().statusCode(401); + given().when().get(BASE + "/1").then().statusCode(401); + given().contentType("application/json").body(VALID).when().post(BASE).then().statusCode(401); + given().contentType("application/json").body(VALID).when().put(BASE + "/1").then().statusCode(401); + given().when().delete(BASE + "/1").then().statusCode(401); + } +} From 5c09feb40b8dc7e5aa3c0dcfc033224fa3d2d924 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 10:59:58 +0400 Subject: [PATCH 120/158] docs(readme): check off feature/customers The three tasks of the branch are ticked: the entity with its repository and service, the resource, and the tests. The rule refusing to delete a customer who still has orders is left to feature/orders, where orders first exist. --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 82ec2ff..0fafa17 100644 --- a/README.md +++ b/README.md @@ -380,9 +380,9 @@ Depends on `feature/categories` existing, since every product references one. ### Tasks -- [ ] `Customer` entity, repository, contract/implementation service -- [ ] `CustomerResource` -- [ ] Tests +- [x] `Customer` entity, repository, contract/implementation service +- [x] `CustomerResource` +- [x] Tests ## feature/orders From 495f250b91ff9bb9794c5ba23c87126a7df43bd1 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 11:12:04 +0400 Subject: [PATCH 121/158] feat(entity): add the Order entity under the CustomerOrder name Order maps the orders table with two lazy, non-optional links, to the customer and to the product, and a total stored as NUMERIC(14, 2). The total is a snapshot taken when the order is created, so a later price change never rewrites history. ORDER is a keyword of HQL, the query language behind Panache, and a generated query such as FROM Order would collide with ORDER BY. The JPA entity name is therefore CustomerOrder, while @Table keeps the real table name, so queries stay valid and the schema does not change. --- .../quarkustutorial/entity/Order.java | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/entity/Order.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/entity/Order.java b/src/main/java/com/edgareldy/quarkustutorial/entity/Order.java new file mode 100644 index 0000000..1f83339 --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/entity/Order.java @@ -0,0 +1,57 @@ +package com.edgareldy.quarkustutorial.entity; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; +import java.math.BigDecimal; + +/** + * A customer order for a quantity of one product, with the total frozen at creation time. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +// The JPA entity name is "CustomerOrder" (not the default "Order") because ORDER is an HQL keyword: +// Panache builds queries such as "FROM Order", which would collide with "ORDER BY". The table +// keeps its real name, "orders", through @Table. +@Entity(name = "CustomerOrder") +@Table(name = "orders") +public class Order { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @ManyToOne(fetch = FetchType.LAZY, optional = false) + @JoinColumn(name = "customer_id", nullable = false) + private Customer customer; + + @ManyToOne(fetch = FetchType.LAZY, optional = false) + @JoinColumn(name = "product_id", nullable = false) + private Product product; + + @Column(nullable = false) + private Integer quantity; + + @Column(nullable = false, precision = 14, scale = 2) + private BigDecimal total; + + public Long getId() { return id; } + public void setId(Long id) { this.id = id; } + public Customer getCustomer() { return customer; } + public void setCustomer(Customer customer) { this.customer = customer; } + public Product getProduct() { return product; } + public void setProduct(Product product) { this.product = product; } + public Integer getQuantity() { return quantity; } + public void setQuantity(Integer quantity) { this.quantity = quantity; } + public BigDecimal getTotal() { return total; } + public void setTotal(BigDecimal total) { this.total = total; } +} From a566f8729a2bb5cee28a4b74ffd66795e9a2193c Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 11:12:04 +0400 Subject: [PATCH 122/158] feat(repository): add OrderRepository with customer and product filters The repository offers one query ordered by id whose two filters, customer and product, are optional and combine with AND, and a count that answers the same filters so paging totals match the page content. countByCustomerId and countByProductId give the customer and product services what they need to refuse deleting a row that orders still reference. --- .../repository/OrderRepository.java | 73 +++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/repository/OrderRepository.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/repository/OrderRepository.java b/src/main/java/com/edgareldy/quarkustutorial/repository/OrderRepository.java new file mode 100644 index 0000000..14a1af1 --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/repository/OrderRepository.java @@ -0,0 +1,73 @@ +package com.edgareldy.quarkustutorial.repository; + +import com.edgareldy.quarkustutorial.entity.Order; +import io.quarkus.hibernate.orm.panache.PanacheQuery; +import io.quarkus.hibernate.orm.panache.PanacheRepository; +import io.quarkus.panache.common.Sort; +import jakarta.enterprise.context.ApplicationScoped; + +/** + * Panache repository for orders, with optional customer and product filters and counts. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +@ApplicationScoped +public class OrderRepository implements PanacheRepository { + + /** + * Orders ordered by id, optionally restricted by customer and/or product (filters combine with AND). + * + * @param customerId the customer to filter on, or null + * @param productId the product to filter on, or null + * @return a query the caller can page + */ + public PanacheQuery search(Long customerId, Long productId) { + if (customerId == null && productId == null) { + return findAll(Sort.by("id")); + } + if (productId == null) { + return find("customer.id = ?1", Sort.by("id"), customerId); + } + if (customerId == null) { + return find("product.id = ?1", Sort.by("id"), productId); + } + return find("customer.id = ?1 and product.id = ?2", Sort.by("id"), customerId, productId); + } + + /** + * @param customerId the customer to filter on, or null + * @param productId the product to filter on, or null + * @return how many orders match the same filters as {@link #search} + */ + public long countFiltered(Long customerId, Long productId) { + if (customerId == null && productId == null) { + return count(); + } + if (productId == null) { + return countByCustomerId(customerId); + } + if (customerId == null) { + return countByProductId(productId); + } + return count("customer.id = ?1 and product.id = ?2", customerId, productId); + } + + /** + * @param customerId the customer id + * @return how many orders reference this customer + */ + public long countByCustomerId(Long customerId) { + return count("customer.id", customerId); + } + + /** + * @param productId the product id + * @return how many orders reference this product + */ + public long countByProductId(Long productId) { + return count("product.id", productId); + } +} From 5fa3bf574c925ea0c33917dd09473081a01049a7 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 11:12:04 +0400 Subject: [PATCH 123/158] feat(dto): add OrderRequest with Bean Validation An order names a customer and a product and a quantity of at least one. There is no total in the payload: it is computed by the server from the current price, so a client can never set its own price. --- .../dto/ecommerce/OrderRequest.java | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/dto/ecommerce/OrderRequest.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/dto/ecommerce/OrderRequest.java b/src/main/java/com/edgareldy/quarkustutorial/dto/ecommerce/OrderRequest.java new file mode 100644 index 0000000..afd684e --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/dto/ecommerce/OrderRequest.java @@ -0,0 +1,15 @@ +package com.edgareldy.quarkustutorial.dto.ecommerce; + +import jakarta.validation.constraints.Min; +import jakarta.validation.constraints.NotNull; + +/** + * Payload to place an order (the total is computed by the server, never sent by the client). + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +public record OrderRequest(@NotNull Long customerId, @NotNull Long productId, @NotNull @Min(1) Integer quantity) { +} From 6f581f4515efb0e91b4cc4af118daab472c77e79 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 11:12:04 +0400 Subject: [PATCH 124/158] feat(dto): add OrderResponse The response is flat, with the ids of the customer and product, the quantity and the frozen total. Names are left out so the payload does not depend on rows that can change after the order was placed. --- .../dto/ecommerce/OrderResponse.java | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/dto/ecommerce/OrderResponse.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/dto/ecommerce/OrderResponse.java b/src/main/java/com/edgareldy/quarkustutorial/dto/ecommerce/OrderResponse.java new file mode 100644 index 0000000..74d9174 --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/dto/ecommerce/OrderResponse.java @@ -0,0 +1,14 @@ +package com.edgareldy.quarkustutorial.dto.ecommerce; + +import java.math.BigDecimal; + +/** + * Order as returned by the API (flat: ids only, no customer or product names). + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +public record OrderResponse(Long id, Long customerId, Long productId, Integer quantity, BigDecimal total) { +} From a1b1f9c31331fa1a00d7391ad81a22f7e51dfede Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 11:12:04 +0400 Subject: [PATCH 125/158] feat(service): add the OrderService contract The contract has a filterable list, a lookup and a creation, and nothing else: an order is a record of a sale, so it is not updated or deleted through the API. The create operation is where the business rule, the total, lives, hence in the service and not in the resource. --- .../quarkustutorial/service/OrderService.java | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/service/OrderService.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/service/OrderService.java b/src/main/java/com/edgareldy/quarkustutorial/service/OrderService.java new file mode 100644 index 0000000..56f9e53 --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/service/OrderService.java @@ -0,0 +1,25 @@ +package com.edgareldy.quarkustutorial.service; + +import com.edgareldy.quarkustutorial.dto.common.PageResponse; +import com.edgareldy.quarkustutorial.dto.ecommerce.OrderRequest; +import com.edgareldy.quarkustutorial.dto.ecommerce.OrderResponse; + +/** + * Contract for order management (read and create only: an order is never edited or deleted). + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +public interface OrderService { + + /** @return one page of orders ordered by id, optionally filtered by customer and/or product (null means any) */ + PageResponse list(int page, int size, Long customerId, Long productId); + + /** @return the order, or throws ResourceNotFoundException (404) */ + OrderResponse findById(Long id); + + /** @return the created order with its computed total; BusinessRuleException (422) if the customer or product does not exist */ + OrderResponse create(OrderRequest request); +} From 274457471787adb45607af3c9335bfcf55a73a84 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 11:12:04 +0400 Subject: [PATCH 126/158] feat(service): implement OrderService and compute the total Creating an order loads the customer and the product, and the total is the unit price times the quantity, scaled to two decimals like the column. An unknown customer or product answers 422 through BusinessRuleException, and so does a total too large for NUMERIC(14, 2), which would otherwise surface as a 500 from the database. The product is read through its repository and not through the cached product service, so an order is always priced from the current row and never from a cached copy. --- .../service/impl/OrderServiceImpl.java | 94 +++++++++++++++++++ 1 file changed, 94 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/service/impl/OrderServiceImpl.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/service/impl/OrderServiceImpl.java b/src/main/java/com/edgareldy/quarkustutorial/service/impl/OrderServiceImpl.java new file mode 100644 index 0000000..099e3de --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/service/impl/OrderServiceImpl.java @@ -0,0 +1,94 @@ +package com.edgareldy.quarkustutorial.service.impl; + +import com.edgareldy.quarkustutorial.dto.common.PageResponse; +import com.edgareldy.quarkustutorial.dto.ecommerce.OrderRequest; +import com.edgareldy.quarkustutorial.dto.ecommerce.OrderResponse; +import com.edgareldy.quarkustutorial.entity.Customer; +import com.edgareldy.quarkustutorial.entity.Order; +import com.edgareldy.quarkustutorial.entity.Product; +import com.edgareldy.quarkustutorial.exception.BusinessRuleException; +import com.edgareldy.quarkustutorial.exception.ResourceNotFoundException; +import com.edgareldy.quarkustutorial.repository.CustomerRepository; +import com.edgareldy.quarkustutorial.repository.OrderRepository; +import com.edgareldy.quarkustutorial.repository.ProductRepository; +import com.edgareldy.quarkustutorial.service.OrderService; +import io.quarkus.panache.common.Page; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import jakarta.transaction.Transactional; +import java.math.BigDecimal; +import java.util.List; + +/** + * Default {@link OrderService} backed by Panache; the total is computed from the current product price. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +@ApplicationScoped +public class OrderServiceImpl implements OrderService { + + // NUMERIC(14, 2) holds at most 14 significant digits. + private static final int MAX_TOTAL_PRECISION = 14; + + @Inject + OrderRepository orderRepository; + + @Inject + CustomerRepository customerRepository; + + // The repository is used directly, not the cached ProductService.findById: an order must be priced + // from the row as it is now, never from a cached copy. + @Inject + ProductRepository productRepository; + + @Override + @Transactional + public PageResponse list(int page, int size, Long customerId, Long productId) { + List content = orderRepository.search(customerId, productId).page(Page.of(page, size)) + .list().stream().map(OrderServiceImpl::toResponse).toList(); + return PageResponse.of(content, page, size, orderRepository.countFiltered(customerId, productId)); + } + + @Override + @Transactional + public OrderResponse findById(Long id) { + Order order = orderRepository.findById(id); + if (order == null) { + throw new ResourceNotFoundException("Order " + id + " not found"); + } + return toResponse(order); + } + + @Override + @Transactional + public OrderResponse create(OrderRequest request) { + Customer customer = customerRepository.findById(request.customerId()); + if (customer == null) { + throw new BusinessRuleException("Customer " + request.customerId() + " does not exist"); + } + Product product = productRepository.findById(request.productId()); + if (product == null) { + throw new BusinessRuleException("Product " + request.productId() + " does not exist"); + } + // unitPrice has scale 2 and the quantity is an integer, so the product keeps scale 2. + BigDecimal total = product.getUnitPrice().multiply(BigDecimal.valueOf(request.quantity())).setScale(2); + if (total.precision() > MAX_TOTAL_PRECISION) { + throw new BusinessRuleException("The order total is too large"); + } + Order order = new Order(); + order.setCustomer(customer); + order.setProduct(product); + order.setQuantity(request.quantity()); + order.setTotal(total); + orderRepository.persist(order); + return toResponse(order); + } + + private static OrderResponse toResponse(Order order) { + return new OrderResponse(order.getId(), order.getCustomer().getId(), order.getProduct().getId(), + order.getQuantity(), order.getTotal()); + } +} From 47aec91fa6ae92ca06cdbd478a3b7a6efe217707 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 11:12:04 +0400 Subject: [PATCH 127/158] feat(resource): add OrderResource The three endpoints are protected with @PermissionsAllowed, ORDER:READ for the list and the detail and ORDER:WRITE for creation, and the resource only validates, delegates and wraps the result in the success envelope. Creating answers 201. The list takes the optional customerId and productId filters and bounds the page size like the other lists. --- .../resource/OrderResource.java | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/resource/OrderResource.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/resource/OrderResource.java b/src/main/java/com/edgareldy/quarkustutorial/resource/OrderResource.java new file mode 100644 index 0000000..af35818 --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/resource/OrderResource.java @@ -0,0 +1,65 @@ +package com.edgareldy.quarkustutorial.resource; + +import com.edgareldy.quarkustutorial.dto.common.ApiResponse; +import com.edgareldy.quarkustutorial.dto.common.PageResponse; +import com.edgareldy.quarkustutorial.dto.ecommerce.OrderRequest; +import com.edgareldy.quarkustutorial.dto.ecommerce.OrderResponse; +import com.edgareldy.quarkustutorial.service.OrderService; +import io.quarkus.security.PermissionsAllowed; +import jakarta.inject.Inject; +import jakarta.validation.Valid; +import jakarta.validation.constraints.Max; +import jakarta.validation.constraints.Min; +import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.DefaultValue; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.PathParam; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.QueryParam; +import jakarta.ws.rs.core.MediaType; +import org.eclipse.microprofile.openapi.annotations.security.SecurityRequirement; +import org.jboss.resteasy.reactive.ResponseStatus; + +/** + * Endpoints to list, read and place orders, with optional customer and product filters on the list. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +@Path("/api/v1/orders") +@Produces(MediaType.APPLICATION_JSON) +@SecurityRequirement(name = "jwt") +public class OrderResource { + + @Inject + OrderService orderService; + + @GET + @PermissionsAllowed("ORDER:READ") + public ApiResponse> list( + @QueryParam("page") @DefaultValue("0") @Min(0) int page, + @QueryParam("size") @DefaultValue("20") @Min(1) @Max(100) int size, + @QueryParam("customerId") Long customerId, + @QueryParam("productId") Long productId) { + return ApiResponse.success(orderService.list(page, size, customerId, productId), "Orders"); + } + + @GET + @Path("/{id}") + @PermissionsAllowed("ORDER:READ") + public ApiResponse get(@PathParam("id") Long id) { + return ApiResponse.success(orderService.findById(id), "Order"); + } + + @POST + @Consumes(MediaType.APPLICATION_JSON) + @PermissionsAllowed("ORDER:WRITE") + @ResponseStatus(201) + public ApiResponse create(@Valid OrderRequest request) { + return ApiResponse.success(orderService.create(request), "Order created"); + } +} From de08351ed702a28157480231ab3ea409ae833593 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 11:12:04 +0400 Subject: [PATCH 128/158] feat(service): refuse to delete a product that has orders Orders reference products through a foreign key, so deleting a referenced product would fail in the database and answer 500. The service now checks first and answers 422 through BusinessRuleException, as the category deletion does, since the request is well formed and the state of the data forbids it. The cache invalidation stays on the method, so the entry is evicted only when the delete is actually allowed to go through. --- .../service/impl/ProductServiceImpl.java | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/edgareldy/quarkustutorial/service/impl/ProductServiceImpl.java b/src/main/java/com/edgareldy/quarkustutorial/service/impl/ProductServiceImpl.java index 6e37ef8..897f0b3 100644 --- a/src/main/java/com/edgareldy/quarkustutorial/service/impl/ProductServiceImpl.java +++ b/src/main/java/com/edgareldy/quarkustutorial/service/impl/ProductServiceImpl.java @@ -8,6 +8,7 @@ import com.edgareldy.quarkustutorial.exception.BusinessRuleException; import com.edgareldy.quarkustutorial.exception.ResourceNotFoundException; import com.edgareldy.quarkustutorial.repository.CategoryRepository; +import com.edgareldy.quarkustutorial.repository.OrderRepository; import com.edgareldy.quarkustutorial.repository.ProductRepository; import com.edgareldy.quarkustutorial.service.ProductService; import io.quarkus.cache.CacheInvalidate; @@ -36,6 +37,9 @@ public class ProductServiceImpl implements ProductService { @Inject CategoryRepository categoryRepository; + @Inject + OrderRepository orderRepository; + @Override @Transactional public PageResponse list(int page, int size, Long categoryId) { @@ -83,7 +87,11 @@ public ProductResponse update(@CacheKey Long id, ProductRequest request) { @Transactional @CacheInvalidate(cacheName = "product-cache") public void delete(@CacheKey Long id) { - productRepository.delete(find(id)); + Product product = find(id); + if (orderRepository.countByProductId(id) > 0) { + throw new BusinessRuleException("Product " + id + " is still referenced by orders and cannot be deleted"); + } + productRepository.delete(product); } private Product find(Long id) { From f3614dceae47203ad105206ce6d94f6205891cde Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 11:12:04 +0400 Subject: [PATCH 129/158] feat(service): refuse to delete a customer that has orders The same rule as for products: a customer referenced by orders cannot be deleted, and the answer is a 422 instead of a 500 from the foreign key. The check and the deletion run in one transaction. --- .../service/impl/CustomerServiceImpl.java | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/edgareldy/quarkustutorial/service/impl/CustomerServiceImpl.java b/src/main/java/com/edgareldy/quarkustutorial/service/impl/CustomerServiceImpl.java index a5b8f7e..a19c036 100644 --- a/src/main/java/com/edgareldy/quarkustutorial/service/impl/CustomerServiceImpl.java +++ b/src/main/java/com/edgareldy/quarkustutorial/service/impl/CustomerServiceImpl.java @@ -4,8 +4,10 @@ import com.edgareldy.quarkustutorial.dto.ecommerce.CustomerRequest; import com.edgareldy.quarkustutorial.dto.ecommerce.CustomerResponse; import com.edgareldy.quarkustutorial.entity.Customer; +import com.edgareldy.quarkustutorial.exception.BusinessRuleException; import com.edgareldy.quarkustutorial.exception.ResourceNotFoundException; import com.edgareldy.quarkustutorial.repository.CustomerRepository; +import com.edgareldy.quarkustutorial.repository.OrderRepository; import com.edgareldy.quarkustutorial.service.CustomerService; import io.quarkus.panache.common.Page; import io.quarkus.panache.common.Sort; @@ -28,6 +30,9 @@ public class CustomerServiceImpl implements CustomerService { @Inject CustomerRepository customerRepository; + @Inject + OrderRepository orderRepository; + @Override @Transactional public PageResponse list(int page, int size) { @@ -62,7 +67,11 @@ public CustomerResponse update(Long id, CustomerRequest request) { @Override @Transactional public void delete(Long id) { - customerRepository.delete(find(id)); + Customer customer = find(id); + if (orderRepository.countByCustomerId(id) > 0) { + throw new BusinessRuleException("Customer " + id + " still has orders and cannot be deleted"); + } + customerRepository.delete(customer); } private Customer find(Long id) { From 4f3c50138a0938ae096dd0cc88f5878953aa4d85 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 11:12:04 +0400 Subject: [PATCH 130/158] test(repository): check the CustomerOrder queries against PostgreSQL These tests are the runtime proof of the entity name choice: the derived and Panache queries run on CustomerOrder against the real schema, with every filter combination, both counts, and the foreign key and quantity constraints. --- .../repository/OrderRepositoryTest.java | 181 ++++++++++++++++++ 1 file changed, 181 insertions(+) create mode 100644 src/test/java/com/edgareldy/quarkustutorial/repository/OrderRepositoryTest.java diff --git a/src/test/java/com/edgareldy/quarkustutorial/repository/OrderRepositoryTest.java b/src/test/java/com/edgareldy/quarkustutorial/repository/OrderRepositoryTest.java new file mode 100644 index 0000000..f0410ab --- /dev/null +++ b/src/test/java/com/edgareldy/quarkustutorial/repository/OrderRepositoryTest.java @@ -0,0 +1,181 @@ +package com.edgareldy.quarkustutorial.repository; + +import static org.junit.jupiter.api.Assertions.*; + +import com.edgareldy.quarkustutorial.entity.Category; +import com.edgareldy.quarkustutorial.entity.Customer; +import com.edgareldy.quarkustutorial.entity.Order; +import com.edgareldy.quarkustutorial.entity.Product; +import io.quarkus.narayana.jta.QuarkusTransaction; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import jakarta.persistence.EntityManager; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * Repository tests of OrderRepository against the Dev Services PostgreSQL, including the HQL entity name. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +// Real PostgreSQL through Dev Services (see CategoryRepositoryTest). This is the runtime proof that the +// "CustomerOrder" entity name works: Panache generates HQL such as "FROM CustomerOrder" for count() and +// findAll(), which would not parse with the reserved word "Order". +@QuarkusTest +class OrderRepositoryTest { + + @Inject + OrderRepository repository; + + @Inject + CustomerRepository customerRepository; + + @Inject + ProductRepository productRepository; + + @Inject + CategoryRepository categoryRepository; + + @Inject + EntityManager em; + + private Long categoryId; + private Long customerA; + private Long customerB; + private Long productA; + private Long productB; + + @BeforeEach + void setUp() { + QuarkusTransaction.requiringNew().run(() -> { + Category cat = new Category(); + cat.setCategoryName("order-repo-" + System.nanoTime()); + categoryRepository.persist(cat); + categoryId = cat.getId(); + customerA = customer(); + customerB = customer(); + productA = product(cat); + productB = product(cat); + }); + } + + @AfterEach + void tearDown() { + QuarkusTransaction.requiringNew().run(() -> { + for (Long id : List.of(customerA, customerB)) { + em.createNativeQuery("delete from orders where customer_id = ?1").setParameter(1, id) + .executeUpdate(); + em.createNativeQuery("delete from customers where id = ?1").setParameter(1, id).executeUpdate(); + } + em.createNativeQuery("delete from products where category_id = ?1").setParameter(1, categoryId) + .executeUpdate(); + em.createNativeQuery("delete from categories where id = ?1").setParameter(1, categoryId) + .executeUpdate(); + }); + } + + private Long customer() { + Customer c = new Customer(); + c.setFirstName("Ada"); + c.setLastName("Lovelace"); + customerRepository.persist(c); + return c.getId(); + } + + private Long product(Category category) { + Product p = new Product(); + p.setCategory(category); + p.setProductName("P" + System.nanoTime()); + p.setUnitPrice(new BigDecimal("2.50")); + productRepository.persist(p); + return p.getId(); + } + + private Long order(Long customerId, Long productId, int quantity, String total) { + return QuarkusTransaction.requiringNew().call(() -> { + Order o = new Order(); + o.setCustomer(customerRepository.findById(customerId)); + o.setProduct(productRepository.findById(productId)); + o.setQuantity(quantity); + o.setTotal(new BigDecimal(total)); + repository.persist(o); + return o.getId(); + }); + } + + private List ids(Long customerId, Long productId) { + return QuarkusTransaction.requiringNew() + .call(() -> repository.search(customerId, productId).list().stream().map(Order::getId).toList()); + } + + @Test + void persistAndFindRoundTripOnTheCustomerOrderEntity() { + Long id = order(customerA, productA, 3, "7.50"); + + Order found = QuarkusTransaction.requiringNew().call(() -> { + Order o = repository.findById(id); + // Touch the lazy associations inside the transaction. + assertEquals(customerA, o.getCustomer().getId()); + assertEquals(productA, o.getProduct().getId()); + return o; + }); + + assertEquals(3, found.getQuantity()); + assertEquals(new BigDecimal("7.50"), found.getTotal()); + } + + @Test + void searchAndCountWorkWithEveryFilterCombination() { + Long o1 = order(customerA, productA, 1, "2.50"); + Long o2 = order(customerA, productB, 2, "5.00"); + Long o3 = order(customerB, productA, 3, "7.50"); + + assertEquals(List.of(o1, o2), ids(customerA, null)); + assertEquals(List.of(o3), ids(customerB, null)); + assertEquals(List.of(o1, o3), ids(null, productA)); + assertEquals(List.of(o2), ids(customerA, productB)); + assertTrue(ids(customerB, productB).isEmpty()); + List all = ids(null, null); + assertTrue(all.containsAll(List.of(o1, o2, o3))); + assertEquals(all.stream().sorted().toList(), all); + + assertEquals(2L, QuarkusTransaction.requiringNew().call(() -> repository.countFiltered(customerA, null))); + assertEquals(2L, QuarkusTransaction.requiringNew().call(() -> repository.countFiltered(null, productA))); + assertEquals(1L, + QuarkusTransaction.requiringNew().call(() -> repository.countFiltered(customerA, productB))); + assertEquals(0L, + QuarkusTransaction.requiringNew().call(() -> repository.countFiltered(customerB, productB))); + assertTrue(QuarkusTransaction.requiringNew().call(() -> repository.countFiltered(null, null)) >= 3L); + } + + @Test + void countByCustomerAndProductCountOnlyReferencingOrders() { + order(customerA, productA, 1, "2.50"); + order(customerA, productB, 1, "2.50"); + order(customerB, productA, 1, "2.50"); + + assertEquals(2L, QuarkusTransaction.requiringNew().call(() -> repository.countByCustomerId(customerA))); + assertEquals(1L, QuarkusTransaction.requiringNew().call(() -> repository.countByCustomerId(customerB))); + assertEquals(2L, QuarkusTransaction.requiringNew().call(() -> repository.countByProductId(productA))); + assertEquals(1L, QuarkusTransaction.requiringNew().call(() -> repository.countByProductId(productB))); + assertEquals(0L, QuarkusTransaction.requiringNew().call(() -> repository.countByCustomerId(999999999L))); + assertEquals(0L, QuarkusTransaction.requiringNew().call(() -> repository.countByProductId(999999999L))); + } + + @Test + void foreignKeysAndChecksAreEnforced() { + assertThrows(RuntimeException.class, () -> QuarkusTransaction.requiringNew().run(() -> em + .createNativeQuery("insert into orders (customer_id, product_id, quantity, total) " + + "values (999999999, " + productA + ", 1, 1.00)").executeUpdate())); + assertThrows(RuntimeException.class, () -> QuarkusTransaction.requiringNew().run(() -> em + .createNativeQuery("insert into orders (customer_id, product_id, quantity, total) " + + "values (" + customerA + ", " + productA + ", 0, 1.00)").executeUpdate())); + } +} From 1381b75c64134275ec9e472aecea171e6b0505ba Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 11:12:04 +0400 Subject: [PATCH 131/158] test(service): unit test the order total and its refusals With mocked repositories, the tests check the total computation, that the price is read fresh from the product repository, the 422 for an unknown customer or product and for a total at the limit of the column, and the 404 and the paging. --- .../service/impl/OrderServiceImplTest.java | 164 ++++++++++++++++++ 1 file changed, 164 insertions(+) create mode 100644 src/test/java/com/edgareldy/quarkustutorial/service/impl/OrderServiceImplTest.java diff --git a/src/test/java/com/edgareldy/quarkustutorial/service/impl/OrderServiceImplTest.java b/src/test/java/com/edgareldy/quarkustutorial/service/impl/OrderServiceImplTest.java new file mode 100644 index 0000000..efebf54 --- /dev/null +++ b/src/test/java/com/edgareldy/quarkustutorial/service/impl/OrderServiceImplTest.java @@ -0,0 +1,164 @@ +package com.edgareldy.quarkustutorial.service.impl; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +import com.edgareldy.quarkustutorial.dto.common.PageResponse; +import com.edgareldy.quarkustutorial.dto.ecommerce.OrderRequest; +import com.edgareldy.quarkustutorial.dto.ecommerce.OrderResponse; +import com.edgareldy.quarkustutorial.entity.Customer; +import com.edgareldy.quarkustutorial.entity.Order; +import com.edgareldy.quarkustutorial.entity.Product; +import com.edgareldy.quarkustutorial.exception.BusinessRuleException; +import com.edgareldy.quarkustutorial.exception.ResourceNotFoundException; +import com.edgareldy.quarkustutorial.repository.CustomerRepository; +import com.edgareldy.quarkustutorial.repository.OrderRepository; +import com.edgareldy.quarkustutorial.repository.ProductRepository; +import io.quarkus.hibernate.orm.panache.PanacheQuery; +import io.quarkus.panache.common.Page; +import java.math.BigDecimal; +import java.util.List; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +/** + * Isolated unit tests of OrderServiceImpl with its three repositories mocked. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +// Plain Mockito with the package-private injected fields assigned directly (same approach as the other +// service tests): the total computation and the refusal rules need no container. +class OrderServiceImplTest { + + private OrderRepository orderRepository; + private CustomerRepository customerRepository; + private ProductRepository productRepository; + private OrderServiceImpl service; + + @BeforeEach + void setUp() { + orderRepository = mock(OrderRepository.class); + customerRepository = mock(CustomerRepository.class); + productRepository = mock(ProductRepository.class); + service = new OrderServiceImpl(); + service.orderRepository = orderRepository; + service.customerRepository = customerRepository; + service.productRepository = productRepository; + } + + private static Customer customer(Long id) { + Customer c = new Customer(); + c.setId(id); + return c; + } + + private static Product product(Long id, String price) { + Product p = new Product(); + p.setId(id); + p.setUnitPrice(new BigDecimal(price)); + return p; + } + + private static Order order(Long id, Customer c, Product p, int quantity, String total) { + Order o = new Order(); + o.setId(id); + o.setCustomer(c); + o.setProduct(p); + o.setQuantity(quantity); + o.setTotal(new BigDecimal(total)); + return o; + } + + @Test + void createComputesTotalFromCurrentUnitPriceWithScale2() { + when(customerRepository.findById(1L)).thenReturn(customer(1L)); + when(productRepository.findById(2L)).thenReturn(product(2L, "2.50")); + + OrderResponse response = service.create(new OrderRequest(1L, 2L, 3)); + + assertEquals(new BigDecimal("7.50"), response.total()); + assertEquals(1L, response.customerId()); + assertEquals(2L, response.productId()); + assertEquals(3, response.quantity()); + ArgumentCaptor captor = ArgumentCaptor.forClass(Order.class); + verify(orderRepository).persist(captor.capture()); + assertEquals(new BigDecimal("7.50"), captor.getValue().getTotal()); + // The price is read fresh from the repository, never from the cached ProductService. + verify(productRepository).findById(2L); + } + + @Test + void createWithUnknownCustomerIsRefused() { + when(customerRepository.findById(1L)).thenReturn(null); + + assertThrows(BusinessRuleException.class, () -> service.create(new OrderRequest(1L, 2L, 1))); + verify(orderRepository, never()).persist(any(Order.class)); + } + + @Test + void createWithUnknownProductIsRefused() { + when(customerRepository.findById(1L)).thenReturn(customer(1L)); + when(productRepository.findById(2L)).thenReturn(null); + + assertThrows(BusinessRuleException.class, () -> service.create(new OrderRequest(1L, 2L, 1))); + verify(orderRepository, never()).persist(any(Order.class)); + } + + @Test + void createWithTotalBeyondNumeric14IsRefused() { + when(customerRepository.findById(1L)).thenReturn(customer(1L)); + when(productRepository.findById(2L)).thenReturn(product(2L, "9999999999.99")); + + assertThrows(BusinessRuleException.class, () -> service.create(new OrderRequest(1L, 2L, 101))); + verify(orderRepository, never()).persist(any(Order.class)); + } + + @Test + void createAcceptsTheLargestTotalThatFits() { + when(customerRepository.findById(1L)).thenReturn(customer(1L)); + when(productRepository.findById(2L)).thenReturn(product(2L, "9999999999.99")); + + OrderResponse response = service.create(new OrderRequest(1L, 2L, 100)); + + // 14 significant digits: the widest value NUMERIC(14, 2) accepts. + assertEquals(new BigDecimal("999999999999.00"), response.total()); + } + + @Test + void findByIdMapsAndMissingIsNotFound() { + when(orderRepository.findById(5L)).thenReturn(order(5L, customer(1L), product(2L, "1.00"), 2, "2.00")); + when(orderRepository.findById(9L)).thenReturn(null); + + OrderResponse response = service.findById(5L); + + assertEquals(5L, response.id()); + assertEquals(new BigDecimal("2.00"), response.total()); + assertThrows(ResourceNotFoundException.class, () -> service.findById(9L)); + } + + @Test + @SuppressWarnings("unchecked") + void listBuildsPageResponseFromFilteredQueryAndCount() { + PanacheQuery query = mock(PanacheQuery.class); + PanacheQuery paged = mock(PanacheQuery.class); + when(orderRepository.search(1L, null)).thenReturn(query); + when(query.page(any(Page.class))).thenReturn(paged); + Customer c = customer(1L); + Product p = product(2L, "1.00"); + when(paged.list()).thenReturn(List.of(order(1L, c, p, 1, "1.00"), order(2L, c, p, 2, "2.00"))); + when(orderRepository.countFiltered(1L, null)).thenReturn(5L); + + PageResponse page = service.list(1, 2, 1L, null); + + assertEquals(2, page.content().size()); + assertEquals(1, page.page()); + assertEquals(2, page.size()); + assertEquals(5L, page.totalElements()); + assertEquals(3, page.totalPages()); + } +} From 3037d511acef22528006d7d8f665196728e41f02 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 11:12:04 +0400 Subject: [PATCH 132/158] test(resource): cover the order endpoints and the deletion rules The tests call the endpoints over HTTP: creation with the computed total, a total that stays frozen when the price changes, the filters, validation, the 422 cases, and the 401 and 403 cases. They also check that a product or a customer with orders answers 422 on deletion and can be deleted once the orders are gone. --- .../resource/OrderResourceTest.java | 318 ++++++++++++++++++ 1 file changed, 318 insertions(+) create mode 100644 src/test/java/com/edgareldy/quarkustutorial/resource/OrderResourceTest.java diff --git a/src/test/java/com/edgareldy/quarkustutorial/resource/OrderResourceTest.java b/src/test/java/com/edgareldy/quarkustutorial/resource/OrderResourceTest.java new file mode 100644 index 0000000..b026414 --- /dev/null +++ b/src/test/java/com/edgareldy/quarkustutorial/resource/OrderResourceTest.java @@ -0,0 +1,318 @@ +package com.edgareldy.quarkustutorial.resource; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.*; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import com.edgareldy.quarkustutorial.rbac.RbacTestSupport; +import io.quarkus.narayana.jta.QuarkusTransaction; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import jakarta.persistence.EntityManager; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * End-to-end tests of the order endpoints: creation with computed total, reads, paging, filters, + * validation, business refusals, permission denial and the customer/product deletion rules. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +// Same approach as ProductResourceTest: real HTTP against Dev Services, users from RbacTestSupport. The +// API has no order deletion, so tearDown() removes orders (then customers, products, categories) with +// native SQL, in foreign key order. +@QuarkusTest +class OrderResourceTest { + + private static final String PROBLEM_JSON = "application/problem+json"; + private static final String BASE = "/api/v1/orders"; + private static final String JSON = "application/json"; + + @Inject + RbacTestSupport support; + + @Inject + EntityManager em; + + private final List categories = new ArrayList<>(); + private final List products = new ArrayList<>(); + private final List customers = new ArrayList<>(); + private String admin; + + @BeforeEach + void setUp() { + admin = support.token(support.createUser("ADMIN")); + } + + @AfterEach + void tearDown() { + QuarkusTransaction.requiringNew().run(() -> { + customers.forEach(id -> em.createNativeQuery("delete from orders where customer_id = ?1") + .setParameter(1, id).executeUpdate()); + products.forEach(id -> em.createNativeQuery("delete from orders where product_id = ?1") + .setParameter(1, id).executeUpdate()); + customers.forEach(id -> em.createNativeQuery("delete from customers where id = ?1") + .setParameter(1, id).executeUpdate()); + products.forEach(id -> em.createNativeQuery("delete from products where id = ?1") + .setParameter(1, id).executeUpdate()); + categories.forEach(id -> em.createNativeQuery("delete from categories where id = ?1") + .setParameter(1, id).executeUpdate()); + }); + categories.clear(); + products.clear(); + customers.clear(); + support.cleanup(); + } + + private Long category() { + Long id = given().auth().oauth2(admin).contentType(JSON) + .body("{\"categoryName\":\"" + RbacTestSupport.unique("cat") + "\"}").when() + .post("/api/v1/categories").then().statusCode(201).extract().jsonPath().getLong("data.id"); + categories.add(id); + return id; + } + + private Long product(Long categoryId, String price) { + Long id = given().auth().oauth2(admin).contentType(JSON) + .body("{\"categoryId\":" + categoryId + ",\"productName\":\"P\",\"unitPrice\":" + price + "}") + .when().post("/api/v1/products").then().statusCode(201).extract().jsonPath().getLong("data.id"); + products.add(id); + return id; + } + + private Long customer() { + Long id = given().auth().oauth2(admin).contentType(JSON) + .body("{\"firstName\":\"Ada\",\"lastName\":\"Lovelace\"}").when().post("/api/v1/customers") + .then().statusCode(201).extract().jsonPath().getLong("data.id"); + customers.add(id); + return id; + } + + private static String body(Object customerId, Object productId, Object quantity) { + return "{\"customerId\":" + customerId + ",\"productId\":" + productId + ",\"quantity\":" + quantity + "}"; + } + + private Long order(Long customerId, Long productId, int quantity) { + return given().auth().oauth2(admin).contentType(JSON).body(body(customerId, productId, quantity)) + .when().post(BASE).then().statusCode(201).extract().jsonPath().getLong("data.id"); + } + + private String tokenWith(String... permissions) { + Long role = support.createRole(RbacTestSupport.unique("order-role"), permissions); + RbacTestSupport.TestUser user = support.createUser(); + support.grantRole(user.id(), role); + return support.token(user); + } + + @Test + void createReturns201WithComputedTotalAndDetailRoundTrips() { + Long cust = customer(); + Long prod = product(category(), "2.50"); + + String json = given().auth().oauth2(admin).contentType(JSON).body(body(cust, prod, 3)) + .when().post(BASE) + .then().statusCode(201).contentType("application/json") + .body("success", is(true)) + .body("data.id", notNullValue()) + .body("data.customerId", is(cust.intValue())) + .body("data.productId", is(prod.intValue())) + .body("data.quantity", is(3)) + .extract().asString(); + io.restassured.path.json.JsonPath created = io.restassured.path.json.JsonPath.from(json); + BigDecimal total = new BigDecimal(created.getString("data.total")); + assertEquals(new BigDecimal("7.50"), total.setScale(2)); + + String read = given().auth().oauth2(admin).when().get(BASE + "/" + created.getLong("data.id")) + .then().statusCode(200).body("success", is(true)) + .body("data.customerId", is(cust.intValue())) + .body("data.quantity", is(3)) + .extract().jsonPath().getString("data.total"); + assertEquals(0, new BigDecimal("7.50").compareTo(new BigDecimal(read))); + } + + @Test + void totalIsFrozenWhenTheProductPriceChangesLater() { + Long cat = category(); + Long cust = customer(); + Long prod = product(cat, "4.00"); + Long id = order(cust, prod, 2); + given().auth().oauth2(admin).contentType(JSON) + .body("{\"categoryId\":" + cat + ",\"productName\":\"P\",\"unitPrice\":10.00}") + .when().put("/api/v1/products/" + prod).then().statusCode(200); + + String old = given().auth().oauth2(admin).when().get(BASE + "/" + id) + .then().statusCode(200).extract().jsonPath().getString("data.total"); + assertEquals(0, new BigDecimal("8.00").compareTo(new BigDecimal(old))); + // A new order uses the fresh price (not a stale cached product). + String fresh = given().auth().oauth2(admin).contentType(JSON).body(body(cust, prod, 2)) + .when().post(BASE).then().statusCode(201).extract().jsonPath().getString("data.total"); + assertEquals(0, new BigDecimal("20.00").compareTo(new BigDecimal(fresh))); + } + + @Test + void unknownOrderIs404Problem() { + given().auth().oauth2(admin).when().get(BASE + "/999999999") + .then().statusCode(404).contentType(PROBLEM_JSON).body("status", is(404)) + .body("$", not(hasKey("success"))); + } + + @Test + void listIsPaginatedAndFilteredByCustomerProductOrBoth() { + Long cat = category(); + Long custA = customer(); + Long custB = customer(); + Long prodA = product(cat, "1.00"); + Long prodB = product(cat, "2.00"); + Long o1 = order(custA, prodA, 1); + Long o2 = order(custA, prodB, 2); + Long o3 = order(custB, prodA, 3); + + List ids = given().auth().oauth2(admin).queryParam("size", 100).when().get(BASE) + .then().statusCode(200).body("success", is(true)) + .body("data.content.id", hasItems(o1.intValue(), o2.intValue(), o3.intValue())) + .extract().jsonPath().getList("data.content.id"); + assertEquals(ids.stream().sorted().toList(), ids); + + given().auth().oauth2(admin).queryParam("customerId", custA).when().get(BASE) + .then().statusCode(200) + .body("data.content.id", contains(o1.intValue(), o2.intValue())) + .body("data.totalElements", is(2)); + given().auth().oauth2(admin).queryParam("productId", prodA).when().get(BASE) + .then().statusCode(200) + .body("data.content.id", contains(o1.intValue(), o3.intValue())) + .body("data.totalElements", is(2)); + given().auth().oauth2(admin).queryParam("customerId", custA).queryParam("productId", prodB).when() + .get(BASE) + .then().statusCode(200) + .body("data.content.id", contains(o2.intValue())) + .body("data.totalElements", is(1)); + given().auth().oauth2(admin).queryParam("customerId", custB).queryParam("productId", prodB).when() + .get(BASE) + .then().statusCode(200).body("data.content", empty()).body("data.totalElements", is(0)); + given().auth().oauth2(admin).queryParam("customerId", custA).queryParam("page", 1).queryParam("size", 1) + .when().get(BASE) + .then().statusCode(200) + .body("data.content.id", contains(o2.intValue())) + .body("data.page", is(1)).body("data.size", is(1)) + .body("data.totalElements", is(2)).body("data.totalPages", is(2)); + } + + @Test + void invalidPageSizeIs400Problem() { + given().auth().oauth2(admin).queryParam("size", 0).when().get(BASE) + .then().statusCode(400).contentType(PROBLEM_JSON).body("$", not(hasKey("success"))); + } + + @Test + void invalidBodyIs400ProblemWithViolations() { + Long cust = customer(); + Long prod = product(category(), "1.00"); + List bodies = List.of( + body("null", prod, 1), + body(cust, "null", 1), + body(cust, prod, "null"), + body(cust, prod, 0), + body(cust, prod, -2), + "{}"); + for (String json : bodies) { + given().auth().oauth2(admin).contentType(JSON).body(json).when().post(BASE) + .then().statusCode(400).contentType(PROBLEM_JSON) + .body("status", is(400)) + .body("violations", not(empty())) + .body("$", not(hasKey("success"))); + } + } + + @Test + void unknownCustomerOrProductIs422Problem() { + Long cust = customer(); + Long prod = product(category(), "1.00"); + given().auth().oauth2(admin).contentType(JSON).body(body(999999999, prod, 1)).when().post(BASE) + .then().statusCode(422).contentType(PROBLEM_JSON).body("status", is(422)) + .body("$", not(hasKey("success"))); + given().auth().oauth2(admin).contentType(JSON).body(body(cust, 999999999, 1)).when().post(BASE) + .then().statusCode(422).contentType(PROBLEM_JSON).body("status", is(422)); + } + + @Test + void totalBeyondNumeric14Is422ProblemAndLargestFittingTotalIsAccepted() { + Long cust = customer(); + Long prod = product(category(), "9999999999.99"); + given().auth().oauth2(admin).contentType(JSON).body(body(cust, prod, 100)).when().post(BASE) + .then().statusCode(201); + given().auth().oauth2(admin).contentType(JSON).body(body(cust, prod, 101)).when().post(BASE) + .then().statusCode(422).contentType(PROBLEM_JSON).body("status", is(422)) + .body("$", not(hasKey("success"))); + given().auth().oauth2(admin).contentType(JSON).body(body(cust, prod, Integer.MAX_VALUE)).when() + .post(BASE) + .then().statusCode(422).contentType(PROBLEM_JSON); + } + + @Test + void readerCanReadButNotCreateAndWriterCanCreate() { + Long cust = customer(); + Long prod = product(category(), "1.00"); + Long id = order(cust, prod, 1); + String reader = tokenWith("ORDER:READ"); + given().auth().oauth2(reader).when().get(BASE).then().statusCode(200); + given().auth().oauth2(reader).when().get(BASE + "/" + id).then().statusCode(200); + given().auth().oauth2(reader).contentType(JSON).body(body(cust, prod, 1)).when().post(BASE) + .then().statusCode(403).contentType(PROBLEM_JSON).body("status", is(403)); + + String writer = tokenWith("ORDER:WRITE"); + given().auth().oauth2(writer).contentType(JSON).body(body(cust, prod, 1)).when().post(BASE) + .then().statusCode(201); + given().auth().oauth2(writer).when().get(BASE).then().statusCode(403).contentType(PROBLEM_JSON); + } + + @Test + void userWithoutPermissionIs403AndNoTokenIs401() { + String nobody = support.token(support.createUser()); + given().auth().oauth2(nobody).when().get(BASE).then().statusCode(403).contentType(PROBLEM_JSON); + given().auth().oauth2(nobody).when().get(BASE + "/1").then().statusCode(403).contentType(PROBLEM_JSON); + given().auth().oauth2(nobody).contentType(JSON).body(body(1, 1, 1)).when().post(BASE) + .then().statusCode(403).contentType(PROBLEM_JSON); + given().when().get(BASE).then().statusCode(401); + given().contentType(JSON).body(body(1, 1, 1)).when().post(BASE).then().statusCode(401); + } + + @Test + void productWithOrdersCannotBeDeletedUntilOrdersAreGone() { + Long cust = customer(); + Long prod = product(category(), "1.00"); + order(cust, prod, 1); + given().auth().oauth2(admin).when().delete("/api/v1/products/" + prod) + .then().statusCode(422).contentType(PROBLEM_JSON).body("status", is(422)) + .body("$", not(hasKey("success"))); + given().auth().oauth2(admin).when().get("/api/v1/products/" + prod).then().statusCode(200); + + removeOrders(cust); + given().auth().oauth2(admin).when().delete("/api/v1/products/" + prod).then().statusCode(200); + } + + @Test + void customerWithOrdersCannotBeDeletedUntilOrdersAreGone() { + Long cust = customer(); + Long prod = product(category(), "1.00"); + order(cust, prod, 1); + given().auth().oauth2(admin).when().delete("/api/v1/customers/" + cust) + .then().statusCode(422).contentType(PROBLEM_JSON).body("status", is(422)) + .body("$", not(hasKey("success"))); + given().auth().oauth2(admin).when().get("/api/v1/customers/" + cust).then().statusCode(200); + + removeOrders(cust); + given().auth().oauth2(admin).when().delete("/api/v1/customers/" + cust).then().statusCode(200); + } + + private void removeOrders(Long customerId) { + QuarkusTransaction.requiringNew().run(() -> em.createNativeQuery("delete from orders where customer_id = ?1") + .setParameter(1, customerId).executeUpdate()); + } +} From ca1d05facf052587ca73255990ac2a9eac287f20 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 11:12:04 +0400 Subject: [PATCH 133/158] test(service): cover the refusal to delete a product with orders The service test now mocks the order repository and adds the refusal case, while the existing case still covers deletion without orders. --- .../service/impl/ProductServiceImplTest.java | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/test/java/com/edgareldy/quarkustutorial/service/impl/ProductServiceImplTest.java b/src/test/java/com/edgareldy/quarkustutorial/service/impl/ProductServiceImplTest.java index cd5f6cc..2b04b3e 100644 --- a/src/test/java/com/edgareldy/quarkustutorial/service/impl/ProductServiceImplTest.java +++ b/src/test/java/com/edgareldy/quarkustutorial/service/impl/ProductServiceImplTest.java @@ -12,6 +12,7 @@ import com.edgareldy.quarkustutorial.exception.BusinessRuleException; import com.edgareldy.quarkustutorial.exception.ResourceNotFoundException; import com.edgareldy.quarkustutorial.repository.CategoryRepository; +import com.edgareldy.quarkustutorial.repository.OrderRepository; import com.edgareldy.quarkustutorial.repository.ProductRepository; import io.quarkus.hibernate.orm.panache.PanacheQuery; import io.quarkus.panache.common.Page; @@ -34,6 +35,7 @@ class ProductServiceImplTest { private ProductRepository productRepository; private CategoryRepository categoryRepository; + private OrderRepository orderRepository; private ProductServiceImpl service; @BeforeEach @@ -43,6 +45,8 @@ void setUp() { service = new ProductServiceImpl(); service.productRepository = productRepository; service.categoryRepository = categoryRepository; + orderRepository = mock(OrderRepository.class); + service.orderRepository = orderRepository; } private static Category category(Long id) { @@ -136,6 +140,16 @@ void deleteRemovesProduct() { verify(productRepository).delete(existing); } + @Test + void deleteIsRefusedWhileOrdersReferenceTheProduct() { + Product existing = product(3L, category(1L), "Old", "1.00"); + when(productRepository.findById(3L)).thenReturn(existing); + when(orderRepository.countByProductId(3L)).thenReturn(1L); + + assertThrows(BusinessRuleException.class, () -> service.delete(3L)); + verify(productRepository, never()).delete(any(Product.class)); + } + @Test @SuppressWarnings("unchecked") void listWithoutFilterUsesGlobalCount() { From 767fb50a5a2f520ca974b17a077a1bbd428c70bf Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 11:12:04 +0400 Subject: [PATCH 134/158] test(service): cover the refusal to delete a customer with orders The service test mocks the order repository and adds the refusal case next to the deletion without orders. --- .../service/impl/CustomerServiceImplTest.java | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/test/java/com/edgareldy/quarkustutorial/service/impl/CustomerServiceImplTest.java b/src/test/java/com/edgareldy/quarkustutorial/service/impl/CustomerServiceImplTest.java index c4893f5..efe59a5 100644 --- a/src/test/java/com/edgareldy/quarkustutorial/service/impl/CustomerServiceImplTest.java +++ b/src/test/java/com/edgareldy/quarkustutorial/service/impl/CustomerServiceImplTest.java @@ -8,8 +8,10 @@ import com.edgareldy.quarkustutorial.dto.ecommerce.CustomerRequest; import com.edgareldy.quarkustutorial.dto.ecommerce.CustomerResponse; import com.edgareldy.quarkustutorial.entity.Customer; +import com.edgareldy.quarkustutorial.exception.BusinessRuleException; import com.edgareldy.quarkustutorial.exception.ResourceNotFoundException; import com.edgareldy.quarkustutorial.repository.CustomerRepository; +import com.edgareldy.quarkustutorial.repository.OrderRepository; import io.quarkus.hibernate.orm.panache.PanacheQuery; import io.quarkus.panache.common.Page; import io.quarkus.panache.common.Sort; @@ -31,13 +33,16 @@ class CustomerServiceImplTest { private CustomerRepository repository; + private OrderRepository orderRepository; private CustomerServiceImpl service; @BeforeEach void setUp() { repository = mock(CustomerRepository.class); service = new CustomerServiceImpl(); + orderRepository = mock(OrderRepository.class); service.customerRepository = repository; + service.orderRepository = orderRepository; } private static Customer customer(Long id, String first) { @@ -115,6 +120,16 @@ void deleteRemovesCustomer() { verify(repository).delete(c); } + @Test + void deleteIsRefusedWhileOrdersReferenceTheCustomer() { + Customer c = customer(1L, "Ada"); + when(repository.findById(1L)).thenReturn(c); + when(orderRepository.countByCustomerId(1L)).thenReturn(2L); + + assertThrows(BusinessRuleException.class, () -> service.delete(1L)); + verify(repository, never()).delete(any(Customer.class)); + } + @Test void deleteMissingIsNotFound() { when(repository.findById(9L)).thenReturn(null); From 9e7cd9cdefa8e7be2183de5a0f6877f2c85c8d90 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 11:12:05 +0400 Subject: [PATCH 135/158] docs(readme): check off feature/orders The three tasks are ticked: the entity, repository and service with the computed total, the resource, and the tests. --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 0fafa17..55cd57c 100644 --- a/README.md +++ b/README.md @@ -396,9 +396,9 @@ Depends on `feature/categories` existing, since every product references one. ### Tasks -- [ ] `Order` entity, repository, contract/implementation service: computes `total = quantity * product.unitPrice` -- [ ] `OrderResource` -- [ ] Tests, including the total computation +- [x] `Order` entity, repository, contract/implementation service: computes `total = quantity * product.unitPrice` +- [x] `OrderResource` +- [x] Tests, including the total computation ## feature/native-build (bonus) From 849b1471a2cbe9dd3ea1c5bc59e48a7fb3e78283 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 11:24:30 +0400 Subject: [PATCH 136/158] build(docker): let the Maven wrapper into the build context The ignore file excludes everything except what the image builds need. The native image is built by a Mandrel builder image that ships no Maven, so it runs the project's Maven wrapper, and the wrapper script and its .mvn directory must therefore be part of the context. Everything else stays excluded, so the context remains small and free of local files such as keys and build output. --- .dockerignore | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.dockerignore b/.dockerignore index f685a3c..5f628d0 100644 --- a/.dockerignore +++ b/.dockerignore @@ -2,3 +2,5 @@ * !pom.xml !src/ +!mvnw +!.mvn/ From 505baf779cb13ce5ee1e5d3604949f39dcee70d6 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 11:24:30 +0400 Subject: [PATCH 137/158] build(docker): add the multi-stage Dockerfile.native The first stage compiles the application to a native executable with Mandrel, Red Hat's GraalVM distribution, through the pom's native profile. The second stage copies only that binary onto a micro runtime image with the few C libraries it links against: no JVM, no Maven and no sources ship, which is where the small image and the fast start come from. It mirrors Dockerfile.jvm on purpose, with the dependency download cached before the sources are copied, tests skipped in the build stage because Dev Services needs a Docker daemon, and a non-root user at runtime. --- Dockerfile.native | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Dockerfile.native diff --git a/Dockerfile.native b/Dockerfile.native new file mode 100644 index 0000000..b6115f6 --- /dev/null +++ b/Dockerfile.native @@ -0,0 +1,30 @@ +# Multi-stage image for the GraalVM native executable. +# Stage 1 compiles the application to a native binary with Mandrel (Red Hat's GraalVM distribution), +# stage 2 keeps only that binary on a minimal runtime image: no JVM, no Maven, no sources. + +FROM quay.io/quarkus/ubi9-quarkus-mandrel-builder-image:jdk-21 AS build +USER root +WORKDIR /build + +# The builder image ships Mandrel but not Maven, so the Maven wrapper is used. Copying the wrapper and +# the pom alone first lets Docker cache the dependency download until the pom changes. +COPY mvnw . +COPY .mvn .mvn +COPY pom.xml . +RUN ./mvnw -B -q dependency:go-offline + +COPY src ./src +# -Dnative switches on the pom's native profile. Tests are skipped here: they rely on Dev Services, +# which needs a Docker daemon a build stage does not have, and they run in CI with mvn verify. +RUN ./mvnw -B -q package -Dnative -DskipTests + +# The runtime image only needs the C libraries the native binary links against. +FROM quay.io/quarkus/ubi9-quarkus-micro-image:2.0 +WORKDIR /work + +# Same idea as Dockerfile.jvm: never run as root. +COPY --from=build --chown=1001:root --chmod=0755 /build/target/*-runner /work/application + +EXPOSE 8080 +USER 1001 +ENTRYPOINT ["./application", "-Dquarkus.http.host=0.0.0.0"] From ad8b01b92527fe5bd62748dd41a618edbb7c901f Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 11:24:30 +0400 Subject: [PATCH 138/158] build(scripts): add a startup and memory measurement script The script starts the application in the mode it is given, waits for the readiness endpoint, sends the same fixed mix of requests, and prints one table row with the time until ready, the startup time Quarkus reports and the resident memory after the load. Running the identical script on the JVM jar and on the native binary is what makes the comparison fair. The memory is read after the load and not at idle, since a JVM grows once it has served traffic while a native binary starts close to its steady size. --- scripts/measure-startup.sh | 46 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100755 scripts/measure-startup.sh diff --git a/scripts/measure-startup.sh b/scripts/measure-startup.sh new file mode 100755 index 0000000..03ae30a --- /dev/null +++ b/scripts/measure-startup.sh @@ -0,0 +1,46 @@ +#!/usr/bin/env bash +# Starts the application, waits until it is ready, sends a fixed request load, then prints one +# markdown table row: time until /q/health/ready answers, the startup time Quarkus itself reports, +# and the resident memory of the process after the load. +# +# Usage: scripts/measure-startup.sh

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +// Hibernate ORM (blocking) and Hibernate Reactive cannot share one persistence unit: a unit is either +// blocking (JDBC) or reactive (Vert.x client). This entity therefore lives in its own package, bound to +// the "reactive" unit only, and maps customer_id/product_id as plain columns so that Customer and +// Product (which belong to the blocking unit) never have to be dragged into the reactive one. +// It is never written: Flyway owns the schema and the blocking OrderServiceImpl owns the writes. +@Entity(name = "ReactiveOrder") +@Table(name = "orders") +public class ReactiveOrder { + + @Id + private Long id; + + @Column(name = "customer_id", nullable = false, insertable = false, updatable = false) + private Long customerId; + + @Column(name = "product_id", nullable = false, insertable = false, updatable = false) + private Long productId; + + @Column(nullable = false, insertable = false, updatable = false) + private Integer quantity; + + @Column(nullable = false, insertable = false, updatable = false) + private BigDecimal total; + + public Long getId() { return id; } + public Long getCustomerId() { return customerId; } + public Long getProductId() { return productId; } + public Integer getQuantity() { return quantity; } + public BigDecimal getTotal() { return total; } +} From 540740d443886d61660378eb6033c6df3e1fde11 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 13:01:18 +0400 Subject: [PATCH 149/158] feat(repository): add the reactive order repository It follows the same repository pattern as the blocking side, taken from the reactive Panache variant: every method returns a Mutiny Uni, an asynchronous result of zero or one item, instead of a value. It is used only by the streaming endpoint, and the blocking repository and service keep serving everything else. --- .../OrderPanacheRepositoryReactive.java | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/repository/OrderPanacheRepositoryReactive.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/repository/OrderPanacheRepositoryReactive.java b/src/main/java/com/edgareldy/quarkustutorial/repository/OrderPanacheRepositoryReactive.java new file mode 100644 index 0000000..6149502 --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/repository/OrderPanacheRepositoryReactive.java @@ -0,0 +1,21 @@ +package com.edgareldy.quarkustutorial.repository; + +import com.edgareldy.quarkustutorial.reactive.ReactiveOrder; +import io.quarkus.hibernate.reactive.panache.PanacheRepositoryBase; +import jakarta.enterprise.context.ApplicationScoped; + +/** + * Reactive Panache repository used only by the order streaming endpoint to reload a committed order. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +// Same repository pattern as the blocking side, but from the reactive Panache variant: every method +// returns a Mutiny Uni (0 or 1 item, asynchronous) instead of a value, and runs on the Vert.x event +// loop through the "reactive" persistence unit. PanacheRepositoryBase is used (not PanacheRepository) +// because the id type is given explicitly. +@ApplicationScoped +public class OrderPanacheRepositoryReactive implements PanacheRepositoryBase { +} From 9d102f68418af5416f9534caaa87553dd960d914 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 13:01:18 +0400 Subject: [PATCH 150/158] feat(service): add the OrderCreatedEvent The event is a plain record carrying only the id of the order. Consumers reload the row after the commit, so the event never holds an entity that could be stale or attached to a closed session. --- .../service/event/OrderCreatedEvent.java | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/service/event/OrderCreatedEvent.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/service/event/OrderCreatedEvent.java b/src/main/java/com/edgareldy/quarkustutorial/service/event/OrderCreatedEvent.java new file mode 100644 index 0000000..de2ee65 --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/service/event/OrderCreatedEvent.java @@ -0,0 +1,14 @@ +package com.edgareldy.quarkustutorial.service.event; + +/** + * Plain CDI event fired by the blocking order service once a new order has been persisted. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +// Only the id travels: the reactive side reloads the committed row itself, so it never publishes +// state that a rollback could still undo and never shares entity instances across persistence units. +public record OrderCreatedEvent(Long orderId) { +} From c24323044f647c99804e4a6dc344610f706c1577 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 13:01:18 +0400 Subject: [PATCH 151/158] feat(service): broadcast committed orders as a reactive stream The bean observes the order created event with the AFTER_SUCCESS transaction phase, so the observer only runs once the creating transaction commits and never for a rolled back order. It pushes the id into a hot broadcast processor, which delivers it to every current subscriber and replays nothing to late ones. Each subscription gets its own bounded buffer, so a slow client fails alone and order creation never waits for anyone. It also hops back onto the Vert.x context of the request before reloading the order through the reactive repository, since Hibernate Reactive must run on such a context. --- .../service/impl/OrderEventBroadcaster.java | 76 +++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 src/main/java/com/edgareldy/quarkustutorial/service/impl/OrderEventBroadcaster.java diff --git a/src/main/java/com/edgareldy/quarkustutorial/service/impl/OrderEventBroadcaster.java b/src/main/java/com/edgareldy/quarkustutorial/service/impl/OrderEventBroadcaster.java new file mode 100644 index 0000000..666c2a6 --- /dev/null +++ b/src/main/java/com/edgareldy/quarkustutorial/service/impl/OrderEventBroadcaster.java @@ -0,0 +1,76 @@ +package com.edgareldy.quarkustutorial.service.impl; + +import com.edgareldy.quarkustutorial.dto.ecommerce.OrderResponse; +import com.edgareldy.quarkustutorial.repository.OrderPanacheRepositoryReactive; +import com.edgareldy.quarkustutorial.service.event.OrderCreatedEvent; +import io.quarkus.hibernate.reactive.panache.Panache; +import io.smallrye.mutiny.Multi; +import io.smallrye.mutiny.Uni; +import io.smallrye.mutiny.operators.multi.processors.BroadcastProcessor; +import io.smallrye.mutiny.operators.multi.processors.SerializedProcessor; +import io.vertx.core.Context; +import io.vertx.core.Vertx; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.enterprise.event.Observes; +import jakarta.enterprise.event.TransactionPhase; +import jakarta.inject.Inject; + +/** + * Bridges the blocking order creation to the reactive world: turns committed-order CDI events into a + * hot {@code Multi} of {@link OrderResponse} that any number of SSE clients can subscribe to. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +@ApplicationScoped +public class OrderEventBroadcaster { + + // Mutiny is Quarkus's reactive library: a Uni is an asynchronous result of 0 or 1 item, a Multi is + // an asynchronous stream of 0..n items. A BroadcastProcessor is both a Multi and a sink: items + // pushed with onNext are delivered to every current subscriber (a "hot" stream, nothing is + // replayed to late subscribers). serialized() makes concurrent onNext calls from different + // request threads safe. + private final SerializedProcessor processor = BroadcastProcessor.create().serialized(); + + @Inject + OrderPanacheRepositoryReactive orderRepository; + + /** + * Receives the event only after the creating transaction committed successfully. + * + * @param event the order created event + */ + // TransactionPhase.AFTER_SUCCESS defers this observer until the transaction that fired the event + // commits, and skips it entirely on rollback: an order that was rolled back is never broadcast. + void onOrderCreated(@Observes(during = TransactionPhase.AFTER_SUCCESS) OrderCreatedEvent event) { + processor.onNext(event.orderId()); + } + + /** + * @return a stream of the orders created from now on, one independent subscription per caller + */ + public Multi stream() { + // Hibernate Reactive needs a Vert.x context. The event is published from a blocking worker + // thread, so each subscription remembers the context it was opened on (the event loop of the + // SSE request) and hops back onto it before touching the database. + Context context = Vertx.currentContext(); + Multi ids = Multi.createFrom().publisher(processor) + // Per-subscriber buffer: a slow client fills its own buffer and is failed alone, + // order creation (the publisher) never waits for anyone. + .onOverflow().buffer(64); + if (context != null) { + ids = ids.emitOn(command -> context.runOnContext(ignored -> command.run())); + } + return ids.onItem().transformToUniAndConcatenate(this::load); + } + + private Uni load(Long id) { + // Opens a reactive session on the named "reactive" persistence unit for the duration of the + // lookup (the no-argument variant would look for the default unit, which is blocking). + return Panache.withSession("reactive", () -> orderRepository.findById(id)) + .map(order -> new OrderResponse(order.getId(), order.getCustomerId(), order.getProductId(), + order.getQuantity(), order.getTotal())); + } +} From 3291c6b29eb2f9a052357a801560d59a4c8d92b0 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 13:01:18 +0400 Subject: [PATCH 152/158] feat(service): publish an event when an order is created After persisting the order, the blocking service fires a synchronous CDI event inside its transaction. It knows nothing about who listens, which keeps the imperative code untouched and lets the reactive side decide when to react: observers declared for the after-success phase only run once the transaction commits. --- .../quarkustutorial/service/impl/OrderServiceImpl.java | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/main/java/com/edgareldy/quarkustutorial/service/impl/OrderServiceImpl.java b/src/main/java/com/edgareldy/quarkustutorial/service/impl/OrderServiceImpl.java index 099e3de..0e2d867 100644 --- a/src/main/java/com/edgareldy/quarkustutorial/service/impl/OrderServiceImpl.java +++ b/src/main/java/com/edgareldy/quarkustutorial/service/impl/OrderServiceImpl.java @@ -12,8 +12,10 @@ import com.edgareldy.quarkustutorial.repository.OrderRepository; import com.edgareldy.quarkustutorial.repository.ProductRepository; import com.edgareldy.quarkustutorial.service.OrderService; +import com.edgareldy.quarkustutorial.service.event.OrderCreatedEvent; import io.quarkus.panache.common.Page; import jakarta.enterprise.context.ApplicationScoped; +import jakarta.enterprise.event.Event; import jakarta.inject.Inject; import jakarta.transaction.Transactional; import java.math.BigDecimal; @@ -44,6 +46,11 @@ public class OrderServiceImpl implements OrderService { @Inject ProductRepository productRepository; + // Synchronous CDI event, fired inside the transaction: observers declared with + // TransactionPhase.AFTER_SUCCESS (see OrderEventBroadcaster) only run once it commits. + @Inject + Event orderCreatedEvent; + @Override @Transactional public PageResponse list(int page, int size, Long customerId, Long productId) { @@ -84,6 +91,7 @@ public OrderResponse create(OrderRequest request) { order.setQuantity(request.quantity()); order.setTotal(total); orderRepository.persist(order); + orderCreatedEvent.fire(new OrderCreatedEvent(order.getId())); return toResponse(order); } From b1c9052e44d70c65f867eeadb764dabe1cf3f597 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 13:01:18 +0400 Subject: [PATCH 153/158] feat(resource): add the order SSE stream endpoint GET /api/v1/orders/stream returns a Mutiny Multi as Server-Sent Events: one long-lived response with one JSON event per new order. Quarkus REST subscribes and applies backpressure, so there is no manual thread handling. The success envelope does not apply to a stream, each element is a bare order response, and the same ORDER:READ permission protects it. The method is marked blocking because the token blacklist filter runs a JDBC query, which is forbidden on the event loop where a Multi endpoint would otherwise be dispatched. That only concerns the request pipeline, the stream itself stays reactive. --- .../resource/OrderResource.java | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/src/main/java/com/edgareldy/quarkustutorial/resource/OrderResource.java b/src/main/java/com/edgareldy/quarkustutorial/resource/OrderResource.java index af35818..a05e10e 100644 --- a/src/main/java/com/edgareldy/quarkustutorial/resource/OrderResource.java +++ b/src/main/java/com/edgareldy/quarkustutorial/resource/OrderResource.java @@ -5,6 +5,9 @@ import com.edgareldy.quarkustutorial.dto.ecommerce.OrderRequest; import com.edgareldy.quarkustutorial.dto.ecommerce.OrderResponse; import com.edgareldy.quarkustutorial.service.OrderService; +import com.edgareldy.quarkustutorial.service.impl.OrderEventBroadcaster; +import io.smallrye.common.annotation.Blocking; +import io.smallrye.mutiny.Multi; import io.quarkus.security.PermissionsAllowed; import jakarta.inject.Inject; import jakarta.validation.Valid; @@ -21,6 +24,7 @@ import jakarta.ws.rs.core.MediaType; import org.eclipse.microprofile.openapi.annotations.security.SecurityRequirement; import org.jboss.resteasy.reactive.ResponseStatus; +import org.jboss.resteasy.reactive.RestStreamElementType; /** * Endpoints to list, read and place orders, with optional customer and product filters on the list. @@ -48,6 +52,26 @@ public ApiResponse> list( return ApiResponse.success(orderService.list(page, size, customerId, productId), "Orders"); } + @Inject + OrderEventBroadcaster broadcaster; + + // Server-Sent Events: one long-lived HTTP response, one event per new order. Returning a Mutiny + // Multi is enough, Quarkus REST subscribes, honours backpressure and writes each item as it arrives + // (no manual thread handling). The ApiResponse envelope does not apply to a stream of events, each + // element is a bare OrderResponse. The literal segment "stream" wins over the "/{id}" template. + @GET + @Path("/stream") + @Produces(MediaType.SERVER_SENT_EVENTS) + @RestStreamElementType(MediaType.APPLICATION_JSON) + // @Blocking only concerns the request pipeline: the JWT blacklist filter runs a JDBC query, which + // is forbidden on the event loop where a Multi endpoint would otherwise be dispatched. The stream + // itself stays fully reactive. + @Blocking + @PermissionsAllowed("ORDER:READ") + public Multi stream() { + return broadcaster.stream(); + } + @GET @Path("/{id}") @PermissionsAllowed("ORDER:READ") From 47a9e04fe371b0bf7e145ca9e5735d284624ffc3 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 13:01:18 +0400 Subject: [PATCH 154/158] test(service): give the order service a mocked event in the unit tests Creating an order now fires an event, so the plain Mockito tests, which build the service without a container, need a mock of the event source to avoid a null pointer. Their assertions are unchanged. --- .../quarkustutorial/service/impl/OrderServiceImplTest.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/test/java/com/edgareldy/quarkustutorial/service/impl/OrderServiceImplTest.java b/src/test/java/com/edgareldy/quarkustutorial/service/impl/OrderServiceImplTest.java index efebf54..4d3883b 100644 --- a/src/test/java/com/edgareldy/quarkustutorial/service/impl/OrderServiceImplTest.java +++ b/src/test/java/com/edgareldy/quarkustutorial/service/impl/OrderServiceImplTest.java @@ -17,6 +17,8 @@ import com.edgareldy.quarkustutorial.repository.ProductRepository; import io.quarkus.hibernate.orm.panache.PanacheQuery; import io.quarkus.panache.common.Page; +import com.edgareldy.quarkustutorial.service.event.OrderCreatedEvent; +import jakarta.enterprise.event.Event; import java.math.BigDecimal; import java.util.List; import org.junit.jupiter.api.BeforeEach; @@ -39,13 +41,16 @@ class OrderServiceImplTest { private CustomerRepository customerRepository; private ProductRepository productRepository; private OrderServiceImpl service; + private Event orderCreatedEvent; @BeforeEach void setUp() { orderRepository = mock(OrderRepository.class); customerRepository = mock(CustomerRepository.class); productRepository = mock(ProductRepository.class); + orderCreatedEvent = mock(Event.class); service = new OrderServiceImpl(); + service.orderCreatedEvent = orderCreatedEvent; service.orderRepository = orderRepository; service.customerRepository = customerRepository; service.productRepository = productRepository; From f5e96e17d0e27c60ca4b9a64cc33fb1903602fbf Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 13:01:18 +0400 Subject: [PATCH 155/158] test(service): assert the broadcast with a Mutiny subscriber The tests subscribe with an AssertSubscriber and wait with a timeout, so the test thread is never blocked. They check that a committed order arrives with all its fields, that a rolled back one emits nothing, that two subscribers both receive it, and that a late subscriber gets no replay. The subscription runs in a duplicated Vert.x context marked safe, which is what Quarkus REST provides for each request and what Hibernate Reactive Panache requires. --- .../impl/OrderEventBroadcasterTest.java | 200 ++++++++++++++++++ 1 file changed, 200 insertions(+) create mode 100644 src/test/java/com/edgareldy/quarkustutorial/service/impl/OrderEventBroadcasterTest.java diff --git a/src/test/java/com/edgareldy/quarkustutorial/service/impl/OrderEventBroadcasterTest.java b/src/test/java/com/edgareldy/quarkustutorial/service/impl/OrderEventBroadcasterTest.java new file mode 100644 index 0000000..bf441cb --- /dev/null +++ b/src/test/java/com/edgareldy/quarkustutorial/service/impl/OrderEventBroadcasterTest.java @@ -0,0 +1,200 @@ +package com.edgareldy.quarkustutorial.service.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.edgareldy.quarkustutorial.dto.ecommerce.OrderRequest; +import com.edgareldy.quarkustutorial.dto.ecommerce.OrderResponse; +import com.edgareldy.quarkustutorial.entity.Category; +import com.edgareldy.quarkustutorial.entity.Customer; +import com.edgareldy.quarkustutorial.entity.Product; +import com.edgareldy.quarkustutorial.exception.BusinessRuleException; +import com.edgareldy.quarkustutorial.repository.CategoryRepository; +import com.edgareldy.quarkustutorial.repository.CustomerRepository; +import com.edgareldy.quarkustutorial.repository.ProductRepository; +import com.edgareldy.quarkustutorial.service.OrderService; +import io.quarkus.narayana.jta.QuarkusTransaction; +import io.quarkus.test.junit.QuarkusTest; +import io.smallrye.mutiny.helpers.test.AssertSubscriber; +import io.quarkus.vertx.core.runtime.context.VertxContextSafetyToggle; +import io.smallrye.common.vertx.VertxContext; +import io.vertx.core.Context; +import io.vertx.core.Vertx; +import jakarta.inject.Inject; +import jakarta.persistence.EntityManager; +import java.math.BigDecimal; +import java.time.Duration; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * Tests the CDI to Mutiny bridge: committed orders reach every current subscriber, rolled back ones + * reach nobody, and late subscribers get no replay (hot stream). + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +// @QuarkusTest boots the real application (Dev Services PostgreSQL, blocking and reactive units). The +// AssertSubscriber from Mutiny's test helpers records the events of a Multi without blocking the test +// thread: awaitItems(n, timeout) polls with a deadline, so a missing event fails fast instead of hanging. +@QuarkusTest +class OrderEventBroadcasterTest { + + private static final Duration TIMEOUT = Duration.ofSeconds(10); + + @Inject + OrderEventBroadcaster broadcaster; + + @Inject + OrderService orderService; + + @Inject + CategoryRepository categoryRepository; + + @Inject + CustomerRepository customerRepository; + + @Inject + ProductRepository productRepository; + + @Inject + EntityManager em; + + // The test thread has no Vert.x context, and stream() captures Vertx.currentContext() to hop back + // onto it before the reactive DB lookup. Hibernate Reactive also insists on a duplicated context (the per-request child context Quarkus REST + // creates), a plain root context fails with "not a duplicated context", and it must be flagged safe + // (isolated, one request only) or Panache refuses it. Subscribing from inside one reproduces what + // the SSE endpoint does on its event loop. + @Inject + Vertx vertx; + + private Long categoryId; + private Long customerId; + private Long productId; + + @BeforeEach + void setUp() { + QuarkusTransaction.requiringNew().run(() -> { + Category cat = new Category(); + cat.setCategoryName("stream-" + System.nanoTime()); + categoryRepository.persist(cat); + categoryId = cat.getId(); + Customer c = new Customer(); + c.setFirstName("Ada"); + c.setLastName("Lovelace"); + customerRepository.persist(c); + customerId = c.getId(); + Product p = new Product(); + p.setCategory(cat); + p.setProductName("P" + System.nanoTime()); + p.setUnitPrice(new BigDecimal("2.50")); + productRepository.persist(p); + productId = p.getId(); + }); + } + + @AfterEach + void tearDown() { + QuarkusTransaction.requiringNew().run(() -> { + em.createNativeQuery("delete from orders where customer_id = ?1").setParameter(1, customerId) + .executeUpdate(); + em.createNativeQuery("delete from customers where id = ?1").setParameter(1, customerId) + .executeUpdate(); + em.createNativeQuery("delete from products where id = ?1").setParameter(1, productId) + .executeUpdate(); + em.createNativeQuery("delete from categories where id = ?1").setParameter(1, categoryId) + .executeUpdate(); + }); + } + + private AssertSubscriber subscribe() { + AssertSubscriber subscriber = AssertSubscriber.create(Long.MAX_VALUE); + Context context = VertxContext.getOrCreateDuplicatedContext(vertx); + VertxContextSafetyToggle.setContextSafe(context, true); + context.runOnContext(ignored -> broadcaster.stream().subscribe().withSubscriber(subscriber)); + // Give the subscription time to reach the BroadcastProcessor before the order is created + // (a hot stream drops anything emitted before the subscriber is attached). + sleep(300); + return subscriber; + } + + private static void sleep(long millis) { + try { + Thread.sleep(millis); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + + private OrderResponse create() { + return orderService.create(new OrderRequest(customerId, productId, 3)); + } + + private void assertMatches(OrderResponse expected, OrderResponse received) { + assertEquals(expected.id(), received.id()); + assertEquals(customerId, received.customerId()); + assertEquals(productId, received.productId()); + assertEquals(3, received.quantity()); + assertEquals(0, new BigDecimal("7.50").compareTo(received.total())); + } + + @Test + void committedOrderIsEmittedToTheSubscriber() { + AssertSubscriber subscriber = subscribe(); + OrderResponse created = create(); + + subscriber.awaitItems(1, TIMEOUT); + assertEquals(1, subscriber.getItems().size()); + assertMatches(created, subscriber.getItems().get(0)); + subscriber.cancel(); + } + + @Test + void rolledBackCreationEmitsNothing() { + AssertSubscriber subscriber = subscribe(); + + assertThrows(BusinessRuleException.class, + () -> orderService.create(new OrderRequest(customerId, 999_999_999L, 1))); + + sleep(1000); + assertTrue(subscriber.getItems().isEmpty()); + subscriber.cancel(); + } + + @Test + void everyCurrentSubscriberReceivesTheEvent() { + AssertSubscriber first = subscribe(); + AssertSubscriber second = subscribe(); + OrderResponse created = create(); + + first.awaitItems(1, TIMEOUT); + second.awaitItems(1, TIMEOUT); + assertMatches(created, first.getItems().get(0)); + assertMatches(created, second.getItems().get(0)); + first.cancel(); + second.cancel(); + } + + @Test + void lateSubscriberDoesNotReceiveAnAlreadyCreatedOrder() { + AssertSubscriber early = subscribe(); + create(); + early.awaitItems(1, TIMEOUT); + + AssertSubscriber late = subscribe(); + sleep(1000); + assertTrue(late.getItems().isEmpty()); + + // The late subscriber is live, though: it gets the next order. + OrderResponse next = create(); + late.awaitItems(1, TIMEOUT); + assertEquals(1, late.getItems().size()); + assertEquals(next.id(), late.getItems().get(0).id()); + early.cancel(); + late.cancel(); + } +} From feb83cc448ece14c755000018b2faa89ccf7bea8 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 13:01:18 +0400 Subject: [PATCH 156/158] test(resource): cover the SSE endpoint over HTTP A JDK HTTP client opens the stream asynchronously, an order is then posted through the normal endpoint, and a data line with the new order must arrive within a timeout. The test also checks the event stream content type, the 401 without a token and the 403 without the read permission, and closes the stream at the end so no connection leaks. --- .../resource/OrderStreamResourceTest.java | 163 ++++++++++++++++++ 1 file changed, 163 insertions(+) create mode 100644 src/test/java/com/edgareldy/quarkustutorial/resource/OrderStreamResourceTest.java diff --git a/src/test/java/com/edgareldy/quarkustutorial/resource/OrderStreamResourceTest.java b/src/test/java/com/edgareldy/quarkustutorial/resource/OrderStreamResourceTest.java new file mode 100644 index 0000000..4e316ef --- /dev/null +++ b/src/test/java/com/edgareldy/quarkustutorial/resource/OrderStreamResourceTest.java @@ -0,0 +1,163 @@ +package com.edgareldy.quarkustutorial.resource; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.startsWith; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import com.edgareldy.quarkustutorial.rbac.RbacTestSupport; +import io.quarkus.narayana.jta.QuarkusTransaction; +import io.quarkus.test.common.http.TestHTTPResource; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.path.json.JsonPath; +import jakarta.inject.Inject; +import jakarta.persistence.EntityManager; +import java.net.URI; +import java.net.URL; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; +import java.util.stream.Stream; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * HTTP-level tests of the order Server-Sent Events endpoint: content type, authentication, + * permission and delivery of a newly created order as a {@code data:} event. + *

+ * Created edgar.muhamyangabo on 9/19/26 + * Author : edgar.muhamyangabo + * Date : 9/19/26 + * Project : quarkus-tutorial + */ +// RestAssured cannot consume an endless response, so the stream is opened with the JDK HttpClient in +// asynchronous mode (sendAsync + BodyHandlers.ofLines): the call returns once the headers arrive and +// the event lines are read on a separate thread. @TestHTTPResource injects the running test server URL +// (port from %test.quarkus.http.test-port). +@QuarkusTest +class OrderStreamResourceTest { + + private static final String PROBLEM_JSON = "application/problem+json"; + private static final String STREAM = "/api/v1/orders/stream"; + private static final String JSON = "application/json"; + + @TestHTTPResource("/") + URL root; + + @Inject + RbacTestSupport support; + + @Inject + EntityManager em; + + private final List categories = new ArrayList<>(); + private final List products = new ArrayList<>(); + private final List customers = new ArrayList<>(); + private String admin; + + @BeforeEach + void setUp() { + admin = support.token(support.createUser("ADMIN")); + } + + @AfterEach + void tearDown() { + QuarkusTransaction.requiringNew().run(() -> { + customers.forEach(id -> em.createNativeQuery("delete from orders where customer_id = ?1") + .setParameter(1, id).executeUpdate()); + customers.forEach(id -> em.createNativeQuery("delete from customers where id = ?1") + .setParameter(1, id).executeUpdate()); + products.forEach(id -> em.createNativeQuery("delete from products where id = ?1") + .setParameter(1, id).executeUpdate()); + categories.forEach(id -> em.createNativeQuery("delete from categories where id = ?1") + .setParameter(1, id).executeUpdate()); + }); + categories.clear(); + products.clear(); + customers.clear(); + support.cleanup(); + } + + private String tokenWith(String... permissions) { + Long role = support.createRole(RbacTestSupport.unique("stream-role"), permissions); + RbacTestSupport.TestUser user = support.createUser(); + support.grantRole(user.id(), role); + return support.token(user); + } + + private HttpRequest.Builder streamRequest(String token) { + return HttpRequest.newBuilder(URI.create(root.toString().replaceAll("/$", "") + STREAM)) + .header("Authorization", "Bearer " + token).header("Accept", "text/event-stream").GET(); + } + + @Test + void streamWithoutTokenIs401() { + given().accept("text/event-stream").when().get(STREAM).then().statusCode(401); + } + + @Test + void streamWithoutOrderReadIs403Problem() { + String token = tokenWith("ORDER:WRITE"); + given().auth().oauth2(token).accept("text/event-stream").when().get(STREAM) + .then().statusCode(403).contentType(PROBLEM_JSON); + } + + @Test + void createdOrderIsPushedAsADataEventWithEventStreamContentType() throws Exception { + Long category = given().auth().oauth2(admin).contentType(JSON) + .body("{\"categoryName\":\"" + RbacTestSupport.unique("cat") + "\"}").when() + .post("/api/v1/categories").then().statusCode(201).extract().jsonPath().getLong("data.id"); + categories.add(category); + Long product = given().auth().oauth2(admin).contentType(JSON) + .body("{\"categoryId\":" + category + ",\"productName\":\"P\",\"unitPrice\":2.50}") + .when().post("/api/v1/products").then().statusCode(201).extract().jsonPath().getLong("data.id"); + products.add(product); + Long customer = given().auth().oauth2(admin).contentType(JSON) + .body("{\"firstName\":\"Ada\",\"lastName\":\"Lovelace\"}").when().post("/api/v1/customers") + .then().statusCode(201).extract().jsonPath().getLong("data.id"); + customers.add(customer); + String reader = tokenWith("ORDER:READ"); + String writer = tokenWith("ORDER:WRITE"); + + HttpClient client = HttpClient.newHttpClient(); + HttpResponse> response = client + .sendAsync(streamRequest(reader).build(), HttpResponse.BodyHandlers.ofLines()) + .get(10, TimeUnit.SECONDS); + try { + assertEquals(200, response.statusCode()); + String contentType = response.headers().firstValue("Content-Type").orElse(""); + org.hamcrest.MatcherAssert.assertThat(contentType, startsWith("text/event-stream")); + + // Read on another thread: findFirst() blocks until a data line arrives. + CompletableFuture dataLine = CompletableFuture.supplyAsync( + () -> response.body().filter(line -> line.startsWith("data:")).findFirst().orElse(null)); + // The response headers are out, so the subscription is in place; a short pause covers the + // hop onto the reactive side before the order is committed. + Thread.sleep(500); + + Long orderId = given().auth().oauth2(writer).contentType(JSON) + .body("{\"customerId\":" + customer + ",\"productId\":" + product + ",\"quantity\":3}") + .when().post("/api/v1/orders").then().statusCode(201).extract().jsonPath() + .getLong("data.id"); + + String line = dataLine.get(10, TimeUnit.SECONDS); + assertNotNull(line); + JsonPath event = JsonPath.from(line.substring("data:".length()).trim()); + assertEquals(orderId, event.getLong("id")); + assertEquals(customer, event.getLong("customerId")); + assertEquals(product, event.getLong("productId")); + assertEquals(3, event.getInt("quantity")); + assertEquals(0, new java.math.BigDecimal("7.50").compareTo(new java.math.BigDecimal(event.getString("total")))); + } finally { + // Closing the line stream cancels the HTTP response subscription and drops the connection, + // so the server side subscriber is released and nothing leaks into other tests. + response.body().close(); + } + } +} From 29dea799bad29501a0f170bc7cd352860d16da6f Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 13:01:18 +0400 Subject: [PATCH 157/158] docs(readme): check off feature/reactive-endpoints The five tasks are ticked: the reactive dependencies and persistence unit, the reactive repository, the CDI event bridged into a Multi, the SSE endpoint, and the tests. --- README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 7fcb6ee..b8f6951 100644 --- a/README.md +++ b/README.md @@ -421,11 +421,11 @@ Quarkus lets imperative (blocking, Panache-based) and reactive (Mutiny-based) co ### Tasks -- [ ] `quarkus-hibernate-reactive-panache`, `quarkus-reactive-pg-client` added alongside the existing blocking `quarkus-jdbc-postgresql` stack - both drivers coexist against the same PostgreSQL database, Dev Services provisions the container either way -- [ ] `OrderPanacheRepositoryReactive` (`PanacheRepositoryBase` from the reactive variant), used only by the streaming endpoint - the rest of `feature/orders`' blocking repository and service stay untouched -- [ ] A CDI event or a `Multi`-backed broadcast: `OrderServiceImpl.create` (blocking) publishes a plain CDI event after a successful commit; a reactive listener adapts that into a `Multi` that the streaming endpoint subscribes to -- [ ] `OrderResource.stream()`: returns `Multi` with `@Produces(MediaType.SERVER_SENT_EVENTS)` - no manual thread management, Mutiny's operators handle backpressure -- [ ] Tests: a `Multi` assertion subscriber (`AssertSubscriber`) verifying an event arrives on the stream after a `POST /api/v1/orders`, run without blocking the test thread +- [x] `quarkus-hibernate-reactive-panache`, `quarkus-reactive-pg-client` added alongside the existing blocking `quarkus-jdbc-postgresql` stack - both drivers coexist against the same PostgreSQL database, Dev Services provisions the container either way +- [x] `OrderPanacheRepositoryReactive` (`PanacheRepositoryBase` from the reactive variant), used only by the streaming endpoint - the rest of `feature/orders`' blocking repository and service stay untouched +- [x] A CDI event or a `Multi`-backed broadcast: `OrderServiceImpl.create` (blocking) publishes a plain CDI event after a successful commit; a reactive listener adapts that into a `Multi` that the streaming endpoint subscribes to +- [x] `OrderResource.stream()`: returns `Multi` with `@Produces(MediaType.SERVER_SENT_EVENTS)` - no manual thread management, Mutiny's operators handle backpressure +- [x] Tests: a `Multi` assertion subscriber (`AssertSubscriber`) verifying an event arrives on the stream after a `POST /api/v1/orders`, run without blocking the test thread ## Order of work From 455553e4104826a9b0133ce108bfa6bd93aa76b9 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 19 Sep 2026 13:05:32 +0400 Subject: [PATCH 158/158] fix(service): keep the order stream alive when one reload fails Each broadcast id is reloaded from the database before it is sent. A missing row or a transient error used to fail that step and terminate the whole subscription, so a client would silently lose every later order until it reconnected. A missing row is now skipped, and a failed reload is logged and dropped, so one bad element costs one event and not the connection. --- .../service/impl/OrderEventBroadcaster.java | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/edgareldy/quarkustutorial/service/impl/OrderEventBroadcaster.java b/src/main/java/com/edgareldy/quarkustutorial/service/impl/OrderEventBroadcaster.java index 666c2a6..1e1036f 100644 --- a/src/main/java/com/edgareldy/quarkustutorial/service/impl/OrderEventBroadcaster.java +++ b/src/main/java/com/edgareldy/quarkustutorial/service/impl/OrderEventBroadcaster.java @@ -14,6 +14,7 @@ import jakarta.enterprise.event.Observes; import jakarta.enterprise.event.TransactionPhase; import jakarta.inject.Inject; +import org.jboss.logging.Logger; /** * Bridges the blocking order creation to the reactive world: turns committed-order CDI events into a @@ -34,6 +35,8 @@ public class OrderEventBroadcaster { // request threads safe. private final SerializedProcessor processor = BroadcastProcessor.create().serialized(); + private static final Logger LOG = Logger.getLogger(OrderEventBroadcaster.class); + @Inject OrderPanacheRepositoryReactive orderRepository; @@ -70,7 +73,11 @@ private Uni load(Long id) { // Opens a reactive session on the named "reactive" persistence unit for the duration of the // lookup (the no-argument variant would look for the default unit, which is blocking). return Panache.withSession("reactive", () -> orderRepository.findById(id)) - .map(order -> new OrderResponse(order.getId(), order.getCustomerId(), order.getProductId(), - order.getQuantity(), order.getTotal())); + // A missing row (null) is simply skipped by the stream, and a failed reload is logged and + // dropped: one bad element must not terminate the whole subscription for that client. + .onItem().ifNotNull().transform(order -> new OrderResponse(order.getId(), order.getCustomerId(), + order.getProductId(), order.getQuantity(), order.getTotal())) + .onFailure().invoke(e -> LOG.warnf(e, "Could not reload order %d for the stream", id)) + .onFailure().recoverWithNull(); } }