diff --git a/code-samples/multitenancy/.dockerignore b/code-samples/multitenancy/.dockerignore new file mode 100644 index 0000000..94810d0 --- /dev/null +++ b/code-samples/multitenancy/.dockerignore @@ -0,0 +1,5 @@ +* +!target/*-runner +!target/*-runner.jar +!target/lib/* +!target/quarkus-app/* \ No newline at end of file diff --git a/code-samples/multitenancy/.gitignore b/code-samples/multitenancy/.gitignore new file mode 100644 index 0000000..91a800a --- /dev/null +++ b/code-samples/multitenancy/.gitignore @@ -0,0 +1,45 @@ +#Maven +target/ +pom.xml.tag +pom.xml.releaseBackup +pom.xml.versionsBackup +release.properties +.flattened-pom.xml + +# Eclipse +.project +.classpath +.settings/ +bin/ + +# IntelliJ +.idea +*.ipr +*.iml +*.iws + +# NetBeans +nb-configuration.xml + +# Visual Studio Code +.vscode +.factorypath + +# OSX +.DS_Store + +# Vim +*.swp +*.swo + +# patch +*.orig +*.rej + +# Local environment +.env + +# Plugin directory +/.quarkus/cli/plugins/ +# TLS Certificates +.certs/ diff --git a/code-samples/multitenancy/.mvn/wrapper/maven-wrapper.properties b/code-samples/multitenancy/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..a3c407f --- /dev/null +++ b/code-samples/multitenancy/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,4 @@ +wrapperVersion=3.3.4 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.16/apache-maven-3.9.16-bin.zip +distributionSha256Sum=5af3b743dd8b876b5c45da33b676251e5f1687712644abb4ee519ca56e1d89ce diff --git a/code-samples/multitenancy/README.md b/code-samples/multitenancy/README.md new file mode 100644 index 0000000..2358415 --- /dev/null +++ b/code-samples/multitenancy/README.md @@ -0,0 +1,35 @@ +# multitenancy + +This project uses the [quarkus-multitenancy](https://github.com/mathias82/quarkus-multitenancy) extension form +mathias82, which is in the process of becoming an official [quarkiverse extension](https://github.com/quarkiverse/quarkus-multitenancy). + +All parts that I just copied from the quarkus-multitenancy demo project are marked by a comment. + +### quarkus-multitenancy extension +The quarkus-multitenancy extension provides a consistent tenant resolution in quarkus, e.g. via a HTTP-Header. +Hereby the extension lets us implement (if needed) our custom: +- TenantContext +- TenantResolver +- TenantDataSourceRegistry +- TenantResolutionContext +- ... + +The extension itself comes with a filter that resolves the tenant if there is no authorization needed. +The extension supports a database-per-tenant approach. + +### Tenant resolution with authorization +In order to resolve the tenant when making an authorization request it is needed to implement a custom +HTTPAuthenticationMechanism and to implement a custom TenantResolutionContext. + + +Implementing a custom HTTPAuthenticationMechanism is one of the intended ways when customizing Quarkus Security +([see docs](https://quarkus.io/guides/security-customization)). + +The extensions build-in TenantResolutionContext expects an ContainerRequestContext, which is not available in the +authentication step. However, to resolve the Tenant via the TenantResolver we only need to extract a specific HTTP-Header, +which we can also get from the RoutingContext. + + +### Testing +Run `docker compose up -d` to create the databases in the `compose.yaml`, then run `mvn quarkus:dev`. +HTTP Requests for testing are in the `localhost.http`, all passwords are `password`. \ No newline at end of file diff --git a/code-samples/multitenancy/compose.yaml b/code-samples/multitenancy/compose.yaml new file mode 100644 index 0000000..f25c340 --- /dev/null +++ b/code-samples/multitenancy/compose.yaml @@ -0,0 +1,34 @@ +services: + default-db: + image: postgres + environment: + POSTGRES_USER: default + POSTGRES_PASSWORD: default + POSTGRES_DB: default + ports: + - "5432:5432" + volumes: + - ./init-db/init_default.sql:/docker-entrypoint-initdb.d/init.sql:z + + tenant1-db: + image: postgres + environment: + POSTGRES_USER: user1 + POSTGRES_PASSWORD: pass1 + POSTGRES_DB: tenant1 + ports: + - "5433:5432" + volumes: + - ./init-db/init_tenant1.sql:/docker-entrypoint-initdb.d/init.sql:z + + + tenant2-db: + image: postgres + environment: + POSTGRES_USER: user2 + POSTGRES_PASSWORD: pass2 + POSTGRES_DB: tenant2 + ports: + - "5434:5432" + volumes: + - ./init-db/init_tenant2.sql:/docker-entrypoint-initdb.d/init.sql:z diff --git a/code-samples/multitenancy/init-db/init.sql b/code-samples/multitenancy/init-db/init.sql new file mode 100644 index 0000000..b3642e3 --- /dev/null +++ b/code-samples/multitenancy/init-db/init.sql @@ -0,0 +1,10 @@ +CREATE SEQUENCE IF NOT EXISTS users_seq START 1; + +CREATE TABLE IF NOT EXISTS users ( + id BIGINT DEFAULT nextval('users_seq') PRIMARY KEY, + name VARCHAR(255), + email VARCHAR(255) +); + +INSERT INTO users (id, name, email) VALUES (1, 'admin', 'admin@admin.com'); +INSERT INTO users (id, name, email) VALUES (2, 'user','user@user.com'); \ No newline at end of file diff --git a/code-samples/multitenancy/init-db/init_default.sql b/code-samples/multitenancy/init-db/init_default.sql new file mode 100644 index 0000000..3368ce5 --- /dev/null +++ b/code-samples/multitenancy/init-db/init_default.sql @@ -0,0 +1,11 @@ +CREATE SEQUENCE IF NOT EXISTS users_seq START 1; + +CREATE TABLE IF NOT EXISTS users ( + id BIGINT DEFAULT nextval('users_seq') PRIMARY KEY, + username VARCHAR(255), + password VARCHAR(255), + role VARCHAR(255) +); + +INSERT INTO users (id, username, password, role) VALUES (1, 'default_admin', '$2a$10$Uc.SZ0hvGJQlYdsAp7be1.lFjmOnc7aAr4L0YY3/VN3oK.F8zJHRG', 'admin'); +INSERT INTO users (id, username, password, role) VALUES (2, 'default_user', '$2a$10$Uc.SZ0hvGJQlYdsAp7be1.lFjmOnc7aAr4L0YY3/VN3oK.F8zJHRG', 'user'); diff --git a/code-samples/multitenancy/init-db/init_tenant1.sql b/code-samples/multitenancy/init-db/init_tenant1.sql new file mode 100644 index 0000000..c993981 --- /dev/null +++ b/code-samples/multitenancy/init-db/init_tenant1.sql @@ -0,0 +1,11 @@ +CREATE SEQUENCE IF NOT EXISTS users_seq START 1; + +CREATE TABLE IF NOT EXISTS users ( + id BIGINT DEFAULT nextval('users_seq') PRIMARY KEY, + username VARCHAR(255), + password VARCHAR(255), + role VARCHAR(255) +); + +INSERT INTO users (id, username, password, role) VALUES (1, 'tenant1_admin', '$2a$10$Uc.SZ0hvGJQlYdsAp7be1.lFjmOnc7aAr4L0YY3/VN3oK.F8zJHRG', 'admin'); +INSERT INTO users (id, username, password, role) VALUES (2, 'tenant1_user', '$2a$10$Uc.SZ0hvGJQlYdsAp7be1.lFjmOnc7aAr4L0YY3/VN3oK.F8zJHRG', 'user'); diff --git a/code-samples/multitenancy/init-db/init_tenant2.sql b/code-samples/multitenancy/init-db/init_tenant2.sql new file mode 100644 index 0000000..39e4ae7 --- /dev/null +++ b/code-samples/multitenancy/init-db/init_tenant2.sql @@ -0,0 +1,11 @@ +CREATE SEQUENCE IF NOT EXISTS users_seq START 1; + +CREATE TABLE IF NOT EXISTS users ( + id BIGINT DEFAULT nextval('users_seq') PRIMARY KEY, + username VARCHAR(255), + password VARCHAR(255), + role VARCHAR(255) +); + +INSERT INTO users (id, username, password, role) VALUES (1, 'tenant2_admin', '$2a$10$Uc.SZ0hvGJQlYdsAp7be1.lFjmOnc7aAr4L0YY3/VN3oK.F8zJHRG', 'admin'); +INSERT INTO users (id, username, password, role) VALUES (2, 'tenant2_user', '$2a$10$Uc.SZ0hvGJQlYdsAp7be1.lFjmOnc7aAr4L0YY3/VN3oK.F8zJHRG', 'user'); diff --git a/code-samples/multitenancy/localhost.http b/code-samples/multitenancy/localhost.http new file mode 100644 index 0000000..9087e53 --- /dev/null +++ b/code-samples/multitenancy/localhost.http @@ -0,0 +1,37 @@ +### GET current tenant +GET http://localhost:8080/api/tenant_users/tenant +X-Tenant: tenant1 + +### List Users +GET http://localhost:8080/api/tenant_users +X-Tenant: tenant1 + +### GET Admin resource tenant 1 +GET http://localhost:8080/api/admin +X-Tenant: tenant1 +Authorization: Basic dGVuYW50MV9hZG1pbjpwYXNzd29yZA== + +### GET User resource tenant 1 +GET http://localhost:8080/api/users/me +X-Tenant: tenant1 +Authorization: Basic dGVuYW50MV91c2VyOnBhc3N3b3Jk + +### GET Admin resource tenant 2 +GET http://localhost:8080/api/admin +X-Tenant: tenant2 +Authorization: Basic dGVuYW50Ml9hZG1pbjpwYXNzd29yZA== + +### GET User resource tenant 2 +GET http://localhost:8080/api/users/me +X-Tenant: tenant2 +Authorization: Basic dGVuYW50Ml91c2VyOnBhc3N3b3Jk + +### GET Admin resource wrong tenant +GET http://localhost:8080/api/admin +X-Tenant: tenant2 +Authorization: Basic dGVuYW50MV9hZG1pbjpwYXNzd29yZA== + +### GET User resource wrong tenant +GET http://localhost:8080/api/users/me +X-Tenant: tenant2 +Authorization: Basic dGVuYW50MV91c2VyOnBhc3N3b3Jk \ No newline at end of file diff --git a/code-samples/multitenancy/mvnw b/code-samples/multitenancy/mvnw new file mode 100755 index 0000000..bd8896b --- /dev/null +++ b/code-samples/multitenancy/mvnw @@ -0,0 +1,295 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.3.4 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + if [ -n "${JAVA_HOME-}" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +scriptDir="$(dirname "$0")" +scriptName="$(basename "$0")" + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +actualDistributionDir="" + +# First try the expected directory name (for regular distributions) +if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then + if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then + actualDistributionDir="$distributionUrlNameMain" + fi +fi + +# If not found, search for any directory with the Maven executable (for snapshots) +if [ -z "$actualDistributionDir" ]; then + # enable globbing to iterate over items + set +f + for dir in "$TMP_DOWNLOAD_DIR"/*; do + if [ -d "$dir" ]; then + if [ -f "$dir/bin/$MVN_CMD" ]; then + actualDistributionDir="$(basename "$dir")" + break + fi + fi + done + set -f +fi + +if [ -z "$actualDistributionDir" ]; then + verbose "Contents of $TMP_DOWNLOAD_DIR:" + verbose "$(ls -la "$TMP_DOWNLOAD_DIR")" + die "Could not find Maven distribution directory in extracted archive" +fi + +verbose "Found extracted Maven distribution directory: $actualDistributionDir" +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/code-samples/multitenancy/mvnw.cmd b/code-samples/multitenancy/mvnw.cmd new file mode 100644 index 0000000..5761d94 --- /dev/null +++ b/code-samples/multitenancy/mvnw.cmd @@ -0,0 +1,189 @@ +<# : batch portion +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.4 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' + +$MAVEN_M2_PATH = "$HOME/.m2" +if ($env:MAVEN_USER_HOME) { + $MAVEN_M2_PATH = "$env:MAVEN_USER_HOME" +} + +if (-not (Test-Path -Path $MAVEN_M2_PATH)) { + New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null +} + +$MAVEN_WRAPPER_DISTS = $null +if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) { + $MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists" +} else { + $MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists" +} + +$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain" +$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +$actualDistributionDir = "" + +# First try the expected directory name (for regular distributions) +$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain" +$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD" +if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) { + $actualDistributionDir = $distributionUrlNameMain +} + +# If not found, search for any directory with the Maven executable (for snapshots) +if (!$actualDistributionDir) { + Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object { + $testPath = Join-Path $_.FullName "bin/$MVN_CMD" + if (Test-Path -Path $testPath -PathType Leaf) { + $actualDistributionDir = $_.Name + } + } +} + +if (!$actualDistributionDir) { + Write-Error "Could not find Maven distribution directory in extracted archive" +} + +Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir" +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/code-samples/multitenancy/pom.xml b/code-samples/multitenancy/pom.xml new file mode 100644 index 0000000..e641f05 --- /dev/null +++ b/code-samples/multitenancy/pom.xml @@ -0,0 +1,156 @@ + + + 4.0.0 + de.elan + multitenancy + 1.0-SNAPSHOT + quarkus + + + 3.15.0 + 21 + UTF-8 + UTF-8 + quarkus-bom + io.quarkus.platform + 3.36.1 + true + 3.5.6 + + + + + + ${quarkus.platform.group-id} + ${quarkus.platform.artifact-id} + ${quarkus.platform.version} + pom + import + + + + + + + io.quarkus + quarkus-rest-jackson + + + io.quarkus + quarkus-arc + + + io.quarkus + quarkus-rest + + + io.quarkus + quarkus-jdbc-postgresql + + + io.quarkus + quarkus-security-jpa + + + + io.quarkus + quarkus-reactive-routes + + + + + io.quarkus + quarkus-elytron-security-jdbc + + + io.quarkus + quarkus-junit + test + + + io.rest-assured + rest-assured + test + + + io.github.mathias82 + quarkus-multitenancy-http-runtime + 0.1.15 + + + io.github.mathias82 + quarkus-multitenancy-orm-runtime + 0.1.15 + + + io.quarkus + quarkus-hibernate-orm-panache + 3.32.4 + + + + + + + ${quarkus.platform.group-id} + quarkus-maven-plugin + ${quarkus.platform.version} + true + + + maven-compiler-plugin + ${compiler-plugin.version} + + true + + + + maven-surefire-plugin + ${surefire-plugin.version} + + @{argLine} + + org.jboss.logmanager.LogManager + ${maven.home} + + + + + maven-failsafe-plugin + ${surefire-plugin.version} + + + + integration-test + verify + + + + + @{argLine} + + ${project.build.directory}/${project.build.finalName}-runner + org.jboss.logmanager.LogManager + ${maven.home} + + + + + + + + + native + + + native + + + + false + false + true + + + + diff --git a/code-samples/multitenancy/src/main/docker/Dockerfile.jvm b/code-samples/multitenancy/src/main/docker/Dockerfile.jvm new file mode 100644 index 0000000..5dfe788 --- /dev/null +++ b/code-samples/multitenancy/src/main/docker/Dockerfile.jvm @@ -0,0 +1,100 @@ +#### +# 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/multitenancy-jvm . +# +# Then run the container using: +# +# docker run -i --rm -p 8080:8080 quarkus/multitenancy-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/multitenancy-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/code-samples/multitenancy/src/main/docker/Dockerfile.legacy-jar b/code-samples/multitenancy/src/main/docker/Dockerfile.legacy-jar new file mode 100644 index 0000000..12aebaf --- /dev/null +++ b/code-samples/multitenancy/src/main/docker/Dockerfile.legacy-jar @@ -0,0 +1,96 @@ +#### +# 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/multitenancy-legacy-jar . +# +# Then run the container using: +# +# docker run -i --rm -p 8080:8080 quarkus/multitenancy-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/multitenancy-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/code-samples/multitenancy/src/main/docker/Dockerfile.native b/code-samples/multitenancy/src/main/docker/Dockerfile.native new file mode 100644 index 0000000..228bd64 --- /dev/null +++ b/code-samples/multitenancy/src/main/docker/Dockerfile.native @@ -0,0 +1,29 @@ +#### +# 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/multitenancy . +# +# Then run the container using: +# +# docker run -i --rm -p 8080:8080 quarkus/multitenancy +# +# 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/code-samples/multitenancy/src/main/docker/Dockerfile.native-micro b/code-samples/multitenancy/src/main/docker/Dockerfile.native-micro new file mode 100644 index 0000000..c57d854 --- /dev/null +++ b/code-samples/multitenancy/src/main/docker/Dockerfile.native-micro @@ -0,0 +1,32 @@ +#### +# 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/multitenancy . +# +# Then run the container using: +# +# docker run -i --rm -p 8080:8080 quarkus/multitenancy +# +# 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"] diff --git a/code-samples/multitenancy/src/main/java/org/opencastproject/multitenancy/entity/User.java b/code-samples/multitenancy/src/main/java/org/opencastproject/multitenancy/entity/User.java new file mode 100644 index 0000000..73da795 --- /dev/null +++ b/code-samples/multitenancy/src/main/java/org/opencastproject/multitenancy/entity/User.java @@ -0,0 +1,31 @@ +package org.opencastproject.multitenancy.entity; + +import io.quarkus.elytron.security.common.BcryptUtil; +import io.quarkus.hibernate.orm.panache.PanacheEntity; +import io.quarkus.security.jpa.Password; +import io.quarkus.security.jpa.Roles; +import io.quarkus.security.jpa.UserDefinition; +import io.quarkus.security.jpa.Username; +import jakarta.persistence.Entity; +import jakarta.persistence.Table; + +@Entity +@Table(name = "users") +@UserDefinition +public class User extends PanacheEntity { + @Username + public String username; + @Password + public String password; + @Roles + public String role; + + public static void add(String username, String password, String role) { + User user = new User(); + user.username = username; + user.password = BcryptUtil.bcryptHash(password); + user.role = role; + user.persist(); + } +} + diff --git a/code-samples/multitenancy/src/main/java/org/opencastproject/multitenancy/exception/TenantNotFoundException.java b/code-samples/multitenancy/src/main/java/org/opencastproject/multitenancy/exception/TenantNotFoundException.java new file mode 100644 index 0000000..baba04e --- /dev/null +++ b/code-samples/multitenancy/src/main/java/org/opencastproject/multitenancy/exception/TenantNotFoundException.java @@ -0,0 +1,16 @@ +package org.opencastproject.multitenancy.exception; + +// from https://github.com/mathias82/quarkus-multitenancy +public class TenantNotFoundException extends RuntimeException { + + private final String tenantId; + + public TenantNotFoundException(String tenantId) { + super("Tenant not found: " + tenantId); + this.tenantId = tenantId; + } + + public String getTenantId() { + return tenantId; + } +} diff --git a/code-samples/multitenancy/src/main/java/org/opencastproject/multitenancy/exception/TenantNotFoundExceptionMapper.java b/code-samples/multitenancy/src/main/java/org/opencastproject/multitenancy/exception/TenantNotFoundExceptionMapper.java new file mode 100644 index 0000000..feebe87 --- /dev/null +++ b/code-samples/multitenancy/src/main/java/org/opencastproject/multitenancy/exception/TenantNotFoundExceptionMapper.java @@ -0,0 +1,18 @@ +package org.opencastproject.multitenancy.exception; + +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.ext.ExceptionMapper; +import jakarta.ws.rs.ext.Provider; + +// from https://github.com/mathias82/quarkus-multitenancy +@Provider +public class TenantNotFoundExceptionMapper implements ExceptionMapper { + + @Override + public Response toResponse(TenantNotFoundException e) { + return Response.status(Response.Status.NOT_FOUND) + .entity("{\"error\": \"Tenant not found: " + e.getTenantId() + "\"}") + .type("application/json") + .build(); + } +} \ No newline at end of file diff --git a/code-samples/multitenancy/src/main/java/org/opencastproject/multitenancy/resolver/RoutingContextTenantResolutionContext.java b/code-samples/multitenancy/src/main/java/org/opencastproject/multitenancy/resolver/RoutingContextTenantResolutionContext.java new file mode 100644 index 0000000..2a9425a --- /dev/null +++ b/code-samples/multitenancy/src/main/java/org/opencastproject/multitenancy/resolver/RoutingContextTenantResolutionContext.java @@ -0,0 +1,31 @@ +package org.opencastproject.multitenancy.resolver; + +import java.util.Optional; +import org.jboss.logging.Logger; +import io.github.mathias82.quarkus.multitenancy.core.runtime.api.TenantResolutionContext; +import io.vertx.ext.web.RoutingContext; + +public class RoutingContextTenantResolutionContext implements TenantResolutionContext { + private final RoutingContext routingContext; + private static final Logger LOG = Logger.getLogger(RoutingContextTenantResolutionContext.class); + + public RoutingContextTenantResolutionContext(RoutingContext routingContext) { + this.routingContext = routingContext; + } + + @Override + public Optional get(Class type) { + if (type.isInstance(routingContext)) { + return Optional.of(type.cast(routingContext)); + } + + if (type.isAssignableFrom(routingContext.request().getClass())) { + return Optional.of(type.cast(routingContext.request())); + } + + return Optional.empty(); + + } + + +} diff --git a/code-samples/multitenancy/src/main/java/org/opencastproject/multitenancy/resolver/SafeTenantResolver.java b/code-samples/multitenancy/src/main/java/org/opencastproject/multitenancy/resolver/SafeTenantResolver.java new file mode 100644 index 0000000..e90b1e5 --- /dev/null +++ b/code-samples/multitenancy/src/main/java/org/opencastproject/multitenancy/resolver/SafeTenantResolver.java @@ -0,0 +1,58 @@ +package org.opencastproject.multitenancy.resolver; + +import org.jboss.logging.Logger; + +import java.util.Optional; + +import org.opencastproject.multitenancy.exception.TenantNotFoundException; +import io.github.mathias82.quarkus.multitenancy.core.runtime.api.TenantResolutionContext; +import io.github.mathias82.quarkus.multitenancy.core.runtime.api.TenantResolver; +import io.vertx.ext.web.RoutingContext; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import jakarta.ws.rs.container.ContainerRequestContext; + + +@ApplicationScoped +public class SafeTenantResolver implements TenantResolver { + + private static final Logger LOGGER = Logger.getLogger(SafeTenantResolver.class); + private static final String HEADER_NAME = "X-Tenant"; + + @Inject + TenantDataSourceRegistry registry; + + @Override + public Optional resolve(TenantResolutionContext context) { + Optional reqOpt = context.get(ContainerRequestContext.class); + Optional routCxt = context.get(RoutingContext.class); + if (reqOpt.isEmpty() && routCxt.isEmpty()) { + LOGGER.info("No request or routing context found"); + return Optional.empty(); + } + + String tenantId = null; + + if (reqOpt.isPresent()) { + ContainerRequestContext req = reqOpt.get(); + tenantId = req.getHeaderString(HEADER_NAME); + } + if (routCxt.isPresent()) { + RoutingContext routCtx = routCxt.get(); + tenantId = routCtx.request().getHeader(HEADER_NAME); + } + + + if (tenantId == null || tenantId.isBlank()) { + return Optional.empty(); + } + + tenantId = tenantId.trim(); + + if (!registry.exists(tenantId)) { + throw new TenantNotFoundException(tenantId); + } + + return Optional.of(tenantId); + } +} diff --git a/code-samples/multitenancy/src/main/java/org/opencastproject/multitenancy/resolver/TenantDataSourceRegistry.java b/code-samples/multitenancy/src/main/java/org/opencastproject/multitenancy/resolver/TenantDataSourceRegistry.java new file mode 100644 index 0000000..7c7f78a --- /dev/null +++ b/code-samples/multitenancy/src/main/java/org/opencastproject/multitenancy/resolver/TenantDataSourceRegistry.java @@ -0,0 +1,38 @@ +package org.opencastproject.multitenancy.resolver; + +import org.eclipse.microprofile.config.Config; +import org.eclipse.microprofile.config.ConfigProvider; +import org.jboss.logging.Logger; + +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.StreamSupport; + +import jakarta.enterprise.context.ApplicationScoped; + +// from https://github.com/mathias82/quarkus-multitenancy +@ApplicationScoped +public class TenantDataSourceRegistry { + + private static final Logger logger = Logger.getLogger(TenantDataSourceRegistry.class); + private final Set configuredTenants; + + public TenantDataSourceRegistry() { + Config config = ConfigProvider.getConfig(); + + this.configuredTenants = StreamSupport.stream(config.getPropertyNames().spliterator(), false) + .filter(p -> p.startsWith("quarkus.datasource.") && p.endsWith(".jdbc.url")) + .map(p -> p.replace("quarkus.datasource.", "").replace(".jdbc.url", "")) + .collect(Collectors.toSet()); + + logger.info("Configured tenants detected:" + configuredTenants); + } + + public boolean exists(String tenantId) { + return configuredTenants.contains(tenantId); + } + + public Set getConfiguredTenants() { + return configuredTenants; + } +} diff --git a/code-samples/multitenancy/src/main/java/org/opencastproject/multitenancy/resource/AdminResource.java b/code-samples/multitenancy/src/main/java/org/opencastproject/multitenancy/resource/AdminResource.java new file mode 100644 index 0000000..7d3a400 --- /dev/null +++ b/code-samples/multitenancy/src/main/java/org/opencastproject/multitenancy/resource/AdminResource.java @@ -0,0 +1,22 @@ +package org.opencastproject.multitenancy.resource; + +import io.github.mathias82.quarkus.multitenancy.core.runtime.context.TenantContext; +import jakarta.annotation.security.RolesAllowed; +import jakarta.inject.Inject; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.MediaType; + +@Path("/api/admin") +public class AdminResource { + @Inject + TenantContext tenantContext; + + @GET + @RolesAllowed("admin") + @Produces(MediaType.TEXT_PLAIN) + public String adminResource() { + return tenantContext.getTenantId().get() + " admin"; + } +} diff --git a/code-samples/multitenancy/src/main/java/org/opencastproject/multitenancy/resource/TenantUserResource.java b/code-samples/multitenancy/src/main/java/org/opencastproject/multitenancy/resource/TenantUserResource.java new file mode 100644 index 0000000..5058203 --- /dev/null +++ b/code-samples/multitenancy/src/main/java/org/opencastproject/multitenancy/resource/TenantUserResource.java @@ -0,0 +1,34 @@ +package org.opencastproject.multitenancy.resource; + +import java.util.List; +import java.util.Optional; + +import org.opencastproject.multitenancy.entity.User; +import io.github.mathias82.quarkus.multitenancy.core.runtime.context.TenantContext; +import jakarta.inject.Inject; +import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.MediaType; + + +@Path("/api/tenant_users") +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +public class TenantUserResource { + + @Inject + TenantContext tenantContext; + + @GET + public List listAll() { + return User.listAll(); + } + + @GET + @Path("/tenant") + public Optional tenant() { + return tenantContext.getTenantId(); + } +} diff --git a/code-samples/multitenancy/src/main/java/org/opencastproject/multitenancy/resource/UserResource.java b/code-samples/multitenancy/src/main/java/org/opencastproject/multitenancy/resource/UserResource.java new file mode 100644 index 0000000..cb99415 --- /dev/null +++ b/code-samples/multitenancy/src/main/java/org/opencastproject/multitenancy/resource/UserResource.java @@ -0,0 +1,20 @@ +package org.opencastproject.multitenancy.resource; + +import io.github.mathias82.quarkus.multitenancy.core.runtime.context.TenantContext; +import jakarta.annotation.security.RolesAllowed; +import jakarta.inject.Inject; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.core.Context; +import jakarta.ws.rs.core.SecurityContext; + +@Path("/api/users") +public class UserResource { + + @GET + @RolesAllowed("user") + @Path("/me") + public String me(@Context SecurityContext securityContext) { + return securityContext.getUserPrincipal().getName(); + } +} diff --git a/code-samples/multitenancy/src/main/java/org/opencastproject/multitenancy/security/CustomHttpAuthenticationMechanism.java b/code-samples/multitenancy/src/main/java/org/opencastproject/multitenancy/security/CustomHttpAuthenticationMechanism.java new file mode 100644 index 0000000..40db12a --- /dev/null +++ b/code-samples/multitenancy/src/main/java/org/opencastproject/multitenancy/security/CustomHttpAuthenticationMechanism.java @@ -0,0 +1,70 @@ +package org.opencastproject.multitenancy.security; + +import org.jboss.logging.Logger; + +import java.util.Optional; +import java.util.Set; + +import org.opencastproject.multitenancy.resolver.RoutingContextTenantResolutionContext; +import org.opencastproject.multitenancy.resolver.SafeTenantResolver; +import io.github.mathias82.quarkus.multitenancy.core.runtime.context.TenantContext; +import io.quarkus.security.identity.IdentityProviderManager; +import io.quarkus.security.identity.SecurityIdentity; +import io.quarkus.security.identity.request.AuthenticationRequest; +import io.quarkus.vertx.http.runtime.security.BasicAuthenticationMechanism; +import io.quarkus.vertx.http.runtime.security.ChallengeData; +import io.quarkus.vertx.http.runtime.security.HttpAuthenticationMechanism; +import io.quarkus.vertx.http.runtime.security.HttpCredentialTransport; +import io.smallrye.mutiny.Uni; +import io.vertx.ext.web.RoutingContext; +import jakarta.annotation.Priority; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.enterprise.context.control.ActivateRequestContext; +import jakarta.enterprise.inject.Alternative; +import jakarta.inject.Inject; + +// TODO: Resolve Tenant from Header only here +// TODO: Resolve Auth mechanism based on config +// Inject all possible AuthenticationMechanisms? +@Alternative +@Priority(1) +@ApplicationScoped +public class CustomHttpAuthenticationMechanism implements HttpAuthenticationMechanism { + + private static final Logger LOGGER = Logger.getLogger(CustomHttpAuthenticationMechanism.class); + @Inject + BasicAuthenticationMechanism basicAuthenticationMechanism; + @Inject + SafeTenantResolver tenantResolver; + @Inject + TenantContext tenantContext; + + @Override + @ActivateRequestContext + public Uni authenticate(RoutingContext context, IdentityProviderManager identityProviderManager) { + RoutingContextTenantResolutionContext ctx = new RoutingContextTenantResolutionContext(context); + Optional resolveTenantID = tenantResolver.resolve(ctx); + if (resolveTenantID.isPresent()) { + tenantContext.setTenantId(resolveTenantID.get()); + } else { + } + LOGGER.info("Authenticating tenant " + tenantContext.getTenantId().get()); + return basicAuthenticationMechanism.authenticate(context, identityProviderManager); + } + + @Override + public Uni getChallenge(RoutingContext context) { + return basicAuthenticationMechanism.getChallenge(context); + } + + @Override + public Set> getCredentialTypes() { + return basicAuthenticationMechanism.getCredentialTypes(); + } + + @Override + public Uni getCredentialTransport(RoutingContext context) { + return basicAuthenticationMechanism.getCredentialTransport(context); + + } +} diff --git a/code-samples/multitenancy/src/main/resources/application.properties b/code-samples/multitenancy/src/main/resources/application.properties new file mode 100644 index 0000000..9a27dda --- /dev/null +++ b/code-samples/multitenancy/src/main/resources/application.properties @@ -0,0 +1,43 @@ +# ========================================= +# Default datasource (not used by multi-tenancy directly) +# ========================================= +quarkus.datasource.db-kind=postgresql +quarkus.datasource.devservices.enabled=false + +# ========================================= +# Hibernate ORM global settings +# ========================================= +quarkus.hibernate-orm.log.sql=true +quarkus.hibernate-orm.multitenant=DATABASE + +# ========================================= +# Per-tenant datasource definitions +# ========================================= +# Optional default JDBC for schema validation or default tenant +quarkus.datasource.__bootstrap.db-kind=postgresql +quarkus.datasource.__bootstrap.jdbc.url=jdbc:postgresql://localhost:5432/default +quarkus.datasource.__bootstrap.username=default +quarkus.datasource.__bootstrap.password=default + +quarkus.datasource.tenant1.db-kind=postgresql +quarkus.datasource.tenant1.jdbc.url=jdbc:postgresql://localhost:5433/tenant1 +quarkus.datasource.tenant1.username=user1 +quarkus.datasource.tenant1.password=pass1 + +quarkus.datasource.tenant2.db-kind=postgresql +quarkus.datasource.tenant2.jdbc.url=jdbc:postgresql://localhost:5434/tenant2 +quarkus.datasource.tenant2.username=user2 +quarkus.datasource.tenant2.password=pass2 + +# ========================================= +# Multitenancy Extension Configuration +# ========================================= +quarkus.multi-tenant.http.enabled=true +quarkus.multi-tenant.http.strategy=header,jwt,cookie +quarkus.multi-tenant.http.header-name=X-Tenant +quarkus.multi-tenant.http.cookie-name=tenant_cookie +quarkus.multi-tenant.http.default-tenant=public + +quarkus.http.auth.basic=true + +