Compare commits

..
Author SHA1 Message Date
Jon Chambers 4440022796 Update to the latest version of the spam filter 2026-07-28 17:45:43 -04:00
Jon Chambers f1d2ce2814 Add methods for getting phone numbers and phone number identifiers that do not assume presence 2026-07-28 17:30:06 -04:00
Jon Chambers 1072d9d39b Convert Account documentation to Markdown 2026-07-28 17:30:06 -04:00
Jon Chambers 20cf3d7429 Rename Account#getUUID() to Account#getAccountIdentifier() 2026-07-28 17:30:06 -04:00
Jon Chambers 7b472afbcb Remove an ancient test 2026-07-28 17:30:06 -04:00
Katherine Yen c6619c7488 Adjust metric name in TrimOversizedFoundationDbMessageQueuesCommand 2026-07-28 17:29:39 -04:00
Jon Chambers 751b4b6ecc Detect and measure FoundationDB message consumer conflicts 2026-07-28 17:28:58 -04:00
Ravi Khadiwala 888b746294 Remove badges from product configuration 2026-07-28 16:20:05 -05:00
Ravi Khadiwala 8e9253181c Add badges to remote config 2026-07-28 16:20:05 -05:00
Ravi Khadiwala 257dd76b68 Implement grpc remote config 2026-07-28 16:13:16 -05:00
Ravi Khadiwala 76ca81d9f1 Sink remote config logic down a layer 2026-07-28 16:13:16 -05:00
Jon Chambers 0eeb6605db Use a programmatically-generated keystore in OmnibusH2ServerTest 2026-07-24 09:26:06 -04:00
Jon Chambers ac8d5f81bf Use a programmatically-generated keystore in SniMapperTest 2026-07-24 09:26:06 -04:00
Jon Chambers 3447345d02 Update to the latest version of the spam filter 2026-07-23 16:49:40 -04:00
Jon Chambers ab0235a574 Update to Ubuntu 26.04 as a base image 2026-07-23 16:49:05 -04:00
Jon Chambers 38c5a292fb Update test container images 2026-07-23 16:49:05 -04:00
Jon Chambers 35663956b5 Update deployment base image and specify full image rather than just the SHA256 2026-07-23 16:49:05 -04:00
Jon Chambers d5a0c63de8 Update Maven Wrapper 2026-07-23 16:49:05 -04:00
ravi-signal 2f0a081d2e Handle duplicated tokens in /v2/svr/auth/check 2026-07-23 15:48:33 -05:00
Chris Eager adfab44ed6 Opt out of anonymous Stripe telemetry_id 2026-07-23 16:48:09 -04:00
Katherine Yen 24cea1926a Add timeout, retries, and priority to trimQueue operation 2026-07-23 16:47:56 -04:00
Ravi Khadiwala 242a5f6a78 Allow ignoring the return value of status asserts 2026-07-23 16:47:40 -04:00
Katherine Yen 45dab47ea8 Disable flaky FoundationDbMessageStoreTest#trimQueue 2026-07-22 15:15:55 -04:00
Katherine Yen 0587a08017 Disable flaky FoundationDbMessageStoreTest#estimateQueueSizeAndSplitPoints 2026-07-22 15:11:38 -04:00
Ravi Khadiwala 02d6138848 Add marker for unexpected error logs 2026-07-22 14:35:17 -04:00
Jon Chambers 07444bffb4 Limit message range size based on outstanding demand 2026-07-22 14:32:26 -04:00
Katherine 4f8ca893f0 Add a crawler to trim oversized queues in FoundationDB 2026-07-22 11:43:22 -04:00
Ravi Khadiwala 7bb94bc99e Drop username_hash from ConfirmUsernameResponse 2026-07-22 10:34:44 -05:00
Ravi Khadiwala f6ca5e55a5 Make timeout for storage usage queries configurable 2026-07-22 10:34:23 -05:00
Andrew 4e2bca886e Specify AccountIdentifiers contract more tightly 2026-07-22 10:33:55 -05:00
ameya-signal 088037b412 Fix watch leak when watch is set after subscription is disposed 2026-07-21 10:26:38 -05:00
ameya-signal 548c688df2 Add counter for FoundationDB watch operations 2026-07-21 10:26:29 -05:00
Chris Eager 8b103030ed Update to the latest version of the spam filter 2026-07-21 10:26:18 -05:00
Ravi Khadiwala 6a8bf7f78e Temporarily disable flaky test 2026-07-17 13:44:14 -05:00
Jonathan Klabunde Tomer 98ba337787 remove primary-device requirement on three accounts grpc endpoints 2026-07-17 10:54:41 -07:00
Ameya Lokare 4410da5fb2 Use Mono.fromFuture(() ->) instead of Mono.fromFuture() to defer
evaluation
2026-07-17 10:53:44 -07:00
Ameya Lokare 607c839dda Add a utility method that returns a cancellation-safe result from
`database.runAsync`
2026-07-17 10:53:44 -07:00
Chris Eager bb3ad8d116 Add FoundationDB timeouts and retries 2026-07-17 12:47:11 -05:00
Chris Eager 2dcd43318e Update permissions in workflows/test.yml 2026-07-17 12:43:07 -05:00
Ravi Khadiwala b255c37978 Hoist user-agent tag out of publisher in copyMedia 2026-07-17 12:42:27 -05:00
Ravi Khadiwala ea411e2f1e Change ConfigureUnidentifiedAccessRequest to a oneof 2026-07-17 12:41:03 -05:00
Ravi Khadiwala 70f83326ef Make log stripping more consistent 2026-07-17 12:40:47 -05:00
154 changed files with 3140 additions and 1949 deletions

No files matched your search

+16 -11
View File
@@ -1,5 +1,8 @@
name: Service CI
permissions:
contents: read
on:
pull_request:
push:
@@ -9,7 +12,7 @@ on:
jobs:
build:
runs-on: ubuntu-latest
container: ubuntu:24.04
container: ubuntu:26.04
timeout-minutes: 20
services:
@@ -26,22 +29,14 @@ jobs:
steps:
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
- name: Set up JDK
uses: actions/setup-java@1bcf9fb12cf4aa7d266a90ae39939e61372fe520 # v5.4.0
with:
distribution: 'temurin'
java-version-file: .java-version
cache: 'maven'
env:
# work around an issue with actions/runner setting an incorrect HOME in containers, which breaks maven caching
# https://github.com/actions/setup-java/issues/356
HOME: /root
- name: Install APT packages
# ca-certificates: required for AWS CRT client
run: |
# Add Docker's official GPG key:
apt update
apt install -y ca-certificates curl
# Maven Wrapper requires `unzip`; see https://github.com/apache/maven-wrapper/issues/425
apt install -y unzip
install -m 0755 -d /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc
chmod a+r /etc/apt/keyrings/docker.asc
@@ -54,6 +49,16 @@ jobs:
# ca-certificates: required for AWS CRT client
apt update && apt install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin ca-certificates
- name: Set up JDK
uses: actions/setup-java@1bcf9fb12cf4aa7d266a90ae39939e61372fe520 # v5.4.0
with:
distribution: 'temurin'
java-version-file: .java-version
cache: 'maven'
env:
# work around an issue with actions/runner setting an incorrect HOME in containers, which breaks maven caching
# https://github.com/actions/setup-java/issues/356
HOME: /root
- name: Configure FoundationDB0 database
run: docker exec foundationdb0 /usr/bin/fdbcli --exec 'configure new single memory'
- name: Configure FoundationDB1 database
BIN
View File
Binary file not shown.
+4 -3
View File
@@ -14,7 +14,8 @@
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.14/apache-maven-3.9.14-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.3.4/maven-wrapper-3.3.4.jar
distributionSha256Sum=55fadd669532a3205d5db95f490bf13971d8b0843526f407f29db0e61f074ab3
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
wrapperSha256Sum=4e2fbf6554bc8a4702cdfdd3bef464f423393d784ddbb037216320ce55d5e4e1
Vendored
+234 -247
View File
@@ -19,290 +19,277 @@
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Apache Maven Wrapper startup batch script, version 3.2.0
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
# Apache Maven Wrapper startup batch script, version 3.3.4
#
# Optional ENV vars
# -----------------
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# 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
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ] ; then
set -euf
[ "${MVNW_VERBOSE-}" != debug ] || set -x
if [ -f /usr/local/etc/mavenrc ] ; then
. /usr/local/etc/mavenrc
fi
if [ -f /etc/mavenrc ] ; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ] ; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
# OS specific support.
native_path() { printf %s\\n "$1"; }
case "$(uname)" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
if [ -z "$JAVA_HOME" ]; then
if [ -x "/usr/libexec/java_home" ]; then
JAVA_HOME="$(/usr/libexec/java_home)"; export JAVA_HOME
else
JAVA_HOME="/Library/Java/Home"; export JAVA_HOME
fi
fi
;;
CYGWIN* | MINGW*)
[ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")"
native_path() { cygpath --path --windows "$1"; }
;;
esac
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=$(java-config --jre-home)
fi
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=$(cygpath --unix "$JAVA_HOME")
[ -n "$CLASSPATH" ] &&
CLASSPATH=$(cygpath --path --unix "$CLASSPATH")
fi
# For Mingw, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$JAVA_HOME" ] && [ -d "$JAVA_HOME" ] &&
JAVA_HOME="$(cd "$JAVA_HOME" || (echo "cannot cd into $JAVA_HOME."; exit 1); pwd)"
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="$(which javac)"
if [ -n "$javaExecutable" ] && ! [ "$(expr "\"$javaExecutable\"" : '\([^ ]*\)')" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=$(which readlink)
if [ ! "$(expr "$readLink" : '\([^ ]*\)')" = "no" ]; then
if $darwin ; then
javaHome="$(dirname "\"$javaExecutable\"")"
javaExecutable="$(cd "\"$javaHome\"" && pwd -P)/javac"
else
javaExecutable="$(readlink -f "\"$javaExecutable\"")"
fi
javaHome="$(dirname "\"$javaExecutable\"")"
javaHome=$(expr "$javaHome" : '\(.*\)/bin')
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ] ; then
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# 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="$(\unset -f command 2>/dev/null; \command -v java)"
fi
fi
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" ] ; then
echo "Error: JAVA_HOME is not defined correctly." >&2
echo " We cannot execute $JAVACMD" >&2
exit 1
fi
if [ -z "$JAVA_HOME" ] ; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
if [ -z "$1" ]
then
echo "Path not specified to find_maven_basedir"
return 1
fi
basedir="$1"
wdir="$1"
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
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
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
if [ -d "${wdir}" ]; then
wdir=$(cd "$wdir/.." || exit 1; pwd)
fi
# end of workaround
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 '%s' "$(cd "$basedir" || exit 1; pwd)"
printf %x\\n $h
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
# Remove \r in case we run on Windows within Git Bash
# and check out the repository with auto CRLF management
# enabled. Otherwise, we may read lines that are delimited with
# \r\n and produce $'-Xarg\r' rather than -Xarg due to word
# splitting rules.
tr -s '\r\n' ' ' < "$1"
fi
verbose() { :; }
[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; }
die() {
printf %s\\n "$1" >&2
exit 1
}
log() {
if [ "$MVNW_VERBOSE" = true ]; then
printf '%s\n' "$1"
fi
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:]'
}
BASE_DIR=$(find_maven_basedir "$(dirname "$0")")
if [ -z "$BASE_DIR" ]; then
exit 1;
fi
scriptDir="$(dirname "$0")"
scriptName="$(basename "$0")"
MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}; export MAVEN_PROJECTBASEDIR
log "$MAVEN_PROJECTBASEDIR"
##########################################################################################
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
# This allows using the maven wrapper in projects that prohibit checking in binary data.
##########################################################################################
wrapperJarPath="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar"
if [ -r "$wrapperJarPath" ]; then
log "Found $wrapperJarPath"
else
log "Couldn't find $wrapperJarPath, downloading it ..."
if [ -n "$MVNW_REPOURL" ]; then
wrapperUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar"
else
wrapperUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar"
fi
while IFS="=" read -r key value; do
# Remove '\r' from value to allow usage on windows as IFS does not consider '\r' as a separator ( considers space, tab, new line ('\n'), and custom '=' )
safeValue=$(echo "$value" | tr -d '\r')
case "$key" in (wrapperUrl) wrapperUrl="$safeValue"; break ;;
esac
done < "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties"
log "Downloading from: $wrapperUrl"
if $cygwin; then
wrapperJarPath=$(cygpath --path --windows "$wrapperJarPath")
fi
if command -v wget > /dev/null; then
log "Found wget ... using wget"
[ "$MVNW_VERBOSE" = true ] && QUIET="" || QUIET="--quiet"
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
wget $QUIET "$wrapperUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath"
else
wget $QUIET --http-user="$MVNW_USERNAME" --http-password="$MVNW_PASSWORD" "$wrapperUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath"
fi
elif command -v curl > /dev/null; then
log "Found curl ... using curl"
[ "$MVNW_VERBOSE" = true ] && QUIET="" || QUIET="--silent"
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
curl $QUIET -o "$wrapperJarPath" "$wrapperUrl" -f -L || rm -f "$wrapperJarPath"
else
curl $QUIET --user "$MVNW_USERNAME:$MVNW_PASSWORD" -o "$wrapperJarPath" "$wrapperUrl" -f -L || rm -f "$wrapperJarPath"
fi
else
log "Falling back to using Java to download"
javaSource="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/MavenWrapperDownloader.java"
javaClass="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/MavenWrapperDownloader.class"
# For Cygwin, switch paths to Windows format before running javac
if $cygwin; then
javaSource=$(cygpath --path --windows "$javaSource")
javaClass=$(cygpath --path --windows "$javaClass")
fi
if [ -e "$javaSource" ]; then
if [ ! -e "$javaClass" ]; then
log " - Compiling MavenWrapperDownloader.java ..."
("$JAVA_HOME/bin/javac" "$javaSource")
fi
if [ -e "$javaClass" ]; then
log " - Running MavenWrapperDownloader.java ..."
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$wrapperUrl" "$wrapperJarPath") || rm -f "$wrapperJarPath"
fi
fi
fi
fi
##########################################################################################
# End of extension
##########################################################################################
# If specified, validate the SHA-256 sum of the Maven wrapper jar file
wrapperSha256Sum=""
# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties
while IFS="=" read -r key value; do
case "$key" in (wrapperSha256Sum) wrapperSha256Sum=$value; break ;;
case "${key-}" in
distributionUrl) distributionUrl=$(trim "${value-}") ;;
distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;;
esac
done < "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties"
if [ -n "$wrapperSha256Sum" ]; then
wrapperSha256Result=false
if command -v sha256sum > /dev/null; then
if echo "$wrapperSha256Sum $wrapperJarPath" | sha256sum -c - > /dev/null 2>&1; then
wrapperSha256Result=true
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-<version>,maven-mvnd-<version>-<platform>}/<hash>
[ -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 "$wrapperSha256Sum $wrapperJarPath" | shasum -a 256 -c > /dev/null 2>&1; then
wrapperSha256Result=true
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."
echo "Please install either command, or disable validation by removing 'wrapperSha256Sum' from your maven-wrapper.properties."
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 [ $wrapperSha256Result = false ]; then
echo "Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised." >&2
echo "Investigate or delete $wrapperJarPath to attempt a clean download." >&2
echo "If you updated your Maven version, you need to update the specified wrapperSha256Sum property." >&2
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
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=$(cygpath --path --windows "$JAVA_HOME")
[ -n "$CLASSPATH" ] &&
CLASSPATH=$(cygpath --path --windows "$CLASSPATH")
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
MAVEN_PROJECTBASEDIR=$(cygpath --path --windows "$MAVEN_PROJECTBASEDIR")
# 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
# Provide a "standardized" way to retrieve the CLI args that will
# work with both Windows and non-Windows executions.
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $*"
export MAVEN_CMD_LINE_ARGS
# Find the actual extracted directory name (handles snapshots where filename != directory name)
actualDistributionDir=""
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
# 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
# shellcheck disable=SC2086 # safe args
exec "$JAVACMD" \
$MAVEN_OPTS \
$MAVEN_DEBUG_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
# 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 "$@"
Vendored
+154 -170
View File
@@ -1,3 +1,4 @@
<# : batch portion
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@@ -7,7 +8,7 @@
@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 https://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
@@ -18,188 +19,171 @@
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Apache Maven Wrapper startup batch script, version 3.2.0
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM Apache Maven Wrapper startup batch script, version 3.3.4
@REM
@REM Optional ENV vars
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@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 ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %*
if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %*
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set WRAPPER_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar"
FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET WRAPPER_URL=%%B
@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 #>
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET WRAPPER_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %WRAPPER_URL%
)
$ErrorActionPreference = "Stop"
if ($env:MVNW_VERBOSE -eq "true") {
$VerbosePreference = "Continue"
}
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%WRAPPER_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
# 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"
}
@REM If specified, validate the SHA-256 sum of the Maven wrapper jar file
SET WRAPPER_SHA_256_SUM=""
FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperSha256Sum" SET WRAPPER_SHA_256_SUM=%%B
)
IF NOT %WRAPPER_SHA_256_SUM%=="" (
powershell -Command "&{"^
"$hash = (Get-FileHash \"%WRAPPER_JAR%\" -Algorithm SHA256).Hash.ToLower();"^
"If('%WRAPPER_SHA_256_SUM%' -ne $hash){"^
" Write-Output 'Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised.';"^
" Write-Output 'Investigate or delete %WRAPPER_JAR% to attempt a clean download.';"^
" Write-Output 'If you updated your Maven version, you need to update the specified wrapperSha256Sum property.';"^
" exit 1;"^
"}"^
"}"
if ERRORLEVEL 1 goto error
)
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
}
}
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
# apply MVNW_REPOURL and calculate MAVEN_HOME
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
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_JAVA_EXE% ^
%JVM_CONFIG_MAVEN_PROPS% ^
%MAVEN_OPTS% ^
%MAVEN_DEBUG_OPTS% ^
-classpath %WRAPPER_JAR% ^
"-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^
%WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
$MAVEN_M2_PATH = "$HOME/.m2"
if ($env:MAVEN_USER_HOME) {
$MAVEN_M2_PATH = "$env:MAVEN_USER_HOME"
}
:error
set ERROR_CODE=1
if (-not (Test-Path -Path $MAVEN_M2_PATH)) {
New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null
}
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
$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"
}
if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat"
if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd"
:skipRcPost
$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"
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%"=="on" pause
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 "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE%
if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) {
Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl"
}
cmd /C exit /B %ERROR_CODE%
# 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"
+3 -4
View File
@@ -91,12 +91,11 @@
<!-- images to use in tests via testcontainers -->
<dynamodb.image>amazon/dynamodb-local:3.3.0@sha256:d89f8fcc6b1a39cb35976c248ed42a28c66ae00dc043099210f5571e42648ab4</dynamodb.image>
<localstack.image>localstack/localstack:4.13@sha256:46302bcb91a7e8008e6394be8afafdbfa40fb77a54d4046a38be35992042d5de</localstack.image>
<redis.image>redis:7.4-alpine@sha256:af1d0fc3f63b02b13ff7906c9baf7c5b390b8881ca08119cd570677fe2f60b55</redis.image>
<localstack.image>localstack/localstack:4.14@sha256:3ebc37595918b8accb852f8048fef2aff047d465167edd655528065b07bc364a</localstack.image>
<redis.image>redis:7.4-alpine@sha256:6ab0b6e7381779332f97b8ca76193e45b0756f38d4c0dcda72dbb3c32061ab99</redis.image>
<redis-cluster.image>docker.io/bitnamilegacy/redis-cluster:7.4.3@sha256:a53d023fdfaf8a8d7ddc58da040d3494e4cb45772644618ffa44c42dcd32b9af</redis-cluster.image>
<!-- eclipse-temurin:25.0.2_10-jre-noble (note: always use the multi-arch manifest *LIST* here) -->
<docker.image.sha256>d2975fcad8dc9ac2180c0c278c8ae7b3443d36cb80845cb0811c20d9463f5fee</docker.image.sha256>
<docker.image>eclipse-temurin:25-jre-resolute@sha256:17ddcc32b1f296155738c4b2f689208e46bf0cf4eb0b215c717717deb8b74b90</docker.image>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
+4
View File
@@ -544,6 +544,10 @@ hlrLookup:
foundationDbMessages:
maxWatchesPerClient: 10000
transactionTimeout: PT1S
transactionRetryLimit: 3
batchPriorityTransactionTimeout: PT5S
batchPriorityTransactionRetryLimit: 10
versionstampCipherKeys:
0: secret://foundationDbMessages.versionstampCipherKey.0
currentVersionstampCipherKey: 0
+7 -1
View File
@@ -492,6 +492,12 @@
<classifier>linux-x86_64</classifier>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-pkitesting</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-testsuite-common</artifactId>
@@ -726,7 +732,7 @@
</executions>
<configuration>
<from>
<image>eclipse-temurin@sha256:${docker.image.sha256}</image>
<image>${docker.image}</image>
<platforms>
<platform>
<architecture>amd64</architecture>
@@ -110,6 +110,7 @@ import org.whispersystems.textsecuregcm.captcha.CaptchaChecker;
import org.whispersystems.textsecuregcm.captcha.CaptchaClient;
import org.whispersystems.textsecuregcm.captcha.RegistrationCaptchaManager;
import org.whispersystems.textsecuregcm.captcha.ShortCodeExpander;
import org.whispersystems.textsecuregcm.configuration.BadgeConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretStore;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretsModule;
@@ -181,6 +182,7 @@ import org.whispersystems.textsecuregcm.grpc.PaymentsGrpcService;
import org.whispersystems.textsecuregcm.grpc.ProductConfigurationGrpcService;
import org.whispersystems.textsecuregcm.grpc.ProfileAnonymousGrpcService;
import org.whispersystems.textsecuregcm.grpc.ProfileGrpcService;
import org.whispersystems.textsecuregcm.grpc.RemoteConfigurationGrpcService;
import org.whispersystems.textsecuregcm.grpc.RequestAttributesInterceptor;
import org.whispersystems.textsecuregcm.grpc.SubscriptionsGrpcService;
import org.whispersystems.textsecuregcm.grpc.ValidatingInterceptor;
@@ -204,6 +206,7 @@ import org.whispersystems.textsecuregcm.mappers.CompletionExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.DeviceLimitExceededExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.GrpcStatusRuntimeExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.IOExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.IllegalStateExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.ImpossiblePhoneNumberExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.InvalidWebsocketAddressExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.JsonMappingExceptionMapper;
@@ -336,6 +339,7 @@ import org.whispersystems.textsecuregcm.workers.ScheduledApnPushNotificationSend
import org.whispersystems.textsecuregcm.workers.ServerVersionCommand;
import org.whispersystems.textsecuregcm.workers.SetRequestLoggingEnabledTask;
import org.whispersystems.textsecuregcm.workers.SetUserDiscoverabilityCommand;
import org.whispersystems.textsecuregcm.workers.TrimOversizedFoundationDbMessageQueuesCommand;
import org.whispersystems.textsecuregcm.workers.UnlinkDeviceCommand;
import org.whispersystems.textsecuregcm.workers.UnlinkDevicesWithIdlePrimaryCommand;
import org.whispersystems.textsecuregcm.workers.ZkParamsCommand;
@@ -395,6 +399,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
bootstrap.addCommand(new ClearIssuedReceiptRedemptionsCommand());
bootstrap.addCommand(new CopyToS3Command());
bootstrap.addCommand(new ClearExpiredFoundationDbMessagesCommand(Clock.systemUTC()));
bootstrap.addCommand(new TrimOversizedFoundationDbMessageQueuesCommand());
bootstrap.addCommand(new ProcessScheduledJobsServiceCommand("process-idle-device-notification-jobs",
"Processes scheduled jobs to send notifications to idle devices",
@@ -496,6 +501,10 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
try {
final Database database = entry.getValue().build(fdb);
database.options().setMaxWatches(config.getFoundationDbMessagesConfiguration().maxWatchesPerClient());
database.options().setTransactionTimeout(
config.getFoundationDbMessagesConfiguration().transactionTimeout().toMillis());
database.options().setTransactionRetryLimit(
config.getFoundationDbMessagesConfiguration().transactionRetryLimit());
return database;
} catch (final IOException e) {
@@ -758,7 +767,9 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new VersionstampUUIDCipher(config.getFoundationDbMessagesConfiguration().currentVersionstampCipherKey(),
config.getFoundationDbMessagesConfiguration().versionstampCipherKeys().get(config.getFoundationDbMessagesConfiguration().currentVersionstampCipherKey()).value()),
presenceRenewalExecutor,
Clock.systemUTC());
Clock.systemUTC(),
config.getFoundationDbMessagesConfiguration().batchPriorityTransactionTimeout(),
config.getFoundationDbMessagesConfiguration().batchPriorityTransactionRetryLimit());
ClientReleaseManager clientReleaseManager = new ClientReleaseManager(clientReleases,
recurringJobExecutor,
config.getClientReleaseConfiguration().refreshInterval(),
@@ -781,7 +792,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
changeNumberWaitingPeriodManager, secureStorageClient, secureValueRecovery2Client, disconnectionRequestManager,
registrationRecoveryPasswordsManager, accountLockExecutor, messagePollExecutor,
retryExecutor, clock, config.getLinkDeviceSecretConfiguration().secret().value());
RemoteConfigsManager remoteConfigsManager = new RemoteConfigsManager(remoteConfigs);
RemoteConfigsManager remoteConfigsManager = new RemoteConfigsManager(remoteConfigs, config.getRemoteConfigConfiguration().globalConfig());
APNSender apnSender = new APNSender(apnSenderExecutor, Clock.systemUTC(), config.getApnConfiguration());
FcmSender fcmSender = new FcmSender(fcmSenderExecutor, config.getFcmConfiguration().credentials().value());
PushNotificationScheduler pushNotificationScheduler = new PushNotificationScheduler(pushSchedulerCluster,
@@ -1093,8 +1104,11 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new ChallengeGrpcService(accountsManager, rateLimitChallengeManager, challengeConstraintChecker),
new DonationsGrpcService(clock, zkReceiptOperations, redeemedReceiptsManager, accountsManager, config.getBadges(), ReceiptCredentialPresentation::new, donationPermitsManager, rateLimiters),
new ProductConfigurationGrpcService(config.getSubscription(), config.getOneTimeDonations(),
List.of(stripeManager, braintreeManager), profileBadgeConverter,
config.getBackupConfiguration().maxTotalMediaSize()))
List.of(stripeManager, braintreeManager), config.getBackupConfiguration().maxTotalMediaSize()),
new RemoteConfigurationGrpcService(remoteConfigsManager, profileBadgeConverter,
config.getBadges().getBadges().stream()
.map(BadgeConfiguration::getId)
.toList()))
.map(bindableService -> ServerInterceptors.intercept(bindableService,
// Note: interceptors run in the reverse order they are added; the remote deprecation filter
// depends on the user-agent context so it has to come first here!
@@ -1255,7 +1269,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new ProvisioningController(rateLimiters, provisioningManager),
new RegistrationController(accountsManager, phoneVerificationTokenManager, registrationLockVerificationManager,
rateLimiters, registrationFraudChecker),
new RemoteConfigController(remoteConfigsManager, config.getRemoteConfigConfiguration().globalConfig()),
new RemoteConfigController(remoteConfigsManager),
new SecureStorageController(storageCredentialsGenerator),
new SecureValueRecovery2Controller(svr2CredentialsGenerator, accountsManager),
new StickerController(rateLimiters, stickerPolicyGenerator, Clock.systemUTC()),
@@ -1335,6 +1349,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new InvalidWebsocketAddressExceptionMapper(),
new DeviceLimitExceededExceptionMapper(),
new ServerRejectedExceptionMapper(),
new IllegalStateExceptionMapper(),
new ImpossiblePhoneNumberExceptionMapper(),
new NonNormalizedPhoneNumberExceptionMapper(),
new ObsoletePhoneNumberFormatExceptionMapper(),
@@ -126,7 +126,7 @@ public class AccountAuthenticator implements Authenticator<BasicCredentials, Aut
@VisibleForTesting
public Account updateLastSeen(Account account, Device device) {
// compute a non-negative integer between 0 and 86400.
long n = Util.ensureNonNegativeLong(account.getUuid().getLeastSignificantBits());
long n = Util.ensureNonNegativeLong(account.getAccountIdentifier().getLeastSignificantBits());
final long lastSeenOffsetSeconds = n % ChronoUnit.DAYS.getDuration().toSeconds();
// produce a truncated timestamp which is either today at UTC midnight
@@ -39,7 +39,7 @@ public class CertificateGenerator {
.setSenderDevice(Math.toIntExact(deviceId))
.setExpires(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(expiresDays))
.setIdentityKey(ByteString.copyFrom(account.getIdentityKey(IdentityType.ACI).serialize()))
.setSenderUuid(UUIDUtil.toByteString(account.getUuid()));
.setSenderUuid(UUIDUtil.toByteString(account.getAccountIdentifier()));
if (includeE164) {
builder.setSenderE164(account.getNumber());
@@ -7,9 +7,11 @@ package org.whispersystems.textsecuregcm.auth;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
public class ExternalServiceCredentialsSelector {
@@ -44,13 +46,13 @@ public class ExternalServiceCredentialsSelector {
* A credential is valid if it passes validation by the provided credentialsGenerator AND it is the most recent
* credential in the provided list for a username.
*
* @param tokens A list of credentials, potentially with different usernames
* @param tokens A set of credentials, potentially with different usernames
* @param credentialsGenerator To validate these credentials
* @param maxAgeSeconds The maximum allowable age of the credential
* @return A {@link CredentialInfo} for each provided token
* @return An unordered list of {@link CredentialInfo} for each provided token
*/
public static List<CredentialInfo> check(
final List<String> tokens,
final Set<String> tokens,
final ExternalServiceCredentialsGenerator credentialsGenerator,
final long maxAgeSeconds) {
@@ -154,7 +154,7 @@ public class RegistrationLockVerificationManager {
}
final List<Byte> deviceIds = updatedAccount.getDevices().stream().map(Device::getId).toList();
disconnectionRequestManager.requestDisconnection(updatedAccount.getUuid(), deviceIds);
disconnectionRequestManager.requestDisconnection(updatedAccount.getAccountIdentifier(), deviceIds);
try {
// Send a push notification that prompts the client to attempt login and fail due to locked credentials
@@ -176,7 +176,7 @@ public class RegistrationLockVerificationManager {
if (!existingRegistrationLock.needsFailureCredentials()) {
return null;
}
return svr2CredentialGenerator.generateForUuid(account.getUuid());
return svr2CredentialGenerator.generateForUuid(account.getAccountIdentifier());
}
}
@@ -136,11 +136,11 @@ public class BackupAuthManager {
}
if (requiresMessageRotation) {
rateLimiters.forDescriptor(RateLimiters.For.SET_BACKUP_ID).validate(account.getUuid());
rateLimiters.forDescriptor(RateLimiters.For.SET_BACKUP_ID).validate(account.getAccountIdentifier());
}
if (requiresMediaRotation && hasActiveVoucher(account)) {
rateLimiters.forDescriptor(RateLimiters.For.SET_PAID_MEDIA_BACKUP_ID).validate(account.getUuid());
rateLimiters.forDescriptor(RateLimiters.For.SET_PAID_MEDIA_BACKUP_ID).validate(account.getAccountIdentifier());
}
this.accountsManager.update(account, a ->
@@ -156,9 +156,9 @@ public class BackupAuthManager {
final boolean isPaid = hasActiveVoucher(account);
final CompletionStage<Boolean> hasSetMessagesPermits =
messagesLimiter.hasAvailablePermitsAsync(account.getUuid(), 1);
messagesLimiter.hasAvailablePermitsAsync(account.getAccountIdentifier(), 1);
final CompletionStage<Boolean> hasSetMediaPermits = isPaid
? mediaLimiter.hasAvailablePermitsAsync(account.getUuid(), 1)
? mediaLimiter.hasAvailablePermitsAsync(account.getAccountIdentifier(), 1)
: CompletableFuture.completedFuture(true);
return hasSetMessagesPermits.thenCombine(hasSetMediaPermits, (hasMessage, hasMedia) -> {
@@ -266,7 +266,7 @@ public class BackupAuthManager {
}
boolean receiptAllowed = redeemedReceiptsManager
.put(receiptSerial, receiptExpiration.getEpochSecond(), receiptLevel, account.getUuid());
.put(receiptSerial, receiptExpiration.getEpochSecond(), receiptLevel, account.getAccountIdentifier());
if (!receiptAllowed) {
throw new BackupBadReceiptException("receipt serial is already redeemed");
}
@@ -342,7 +342,7 @@ public class BackupAuthManager {
* BackupVoucher.
*/
private BackupLevel configuredBackupLevel(final Account account) {
return this.experimentEnrollmentManager.isEnrolled(account.getUuid(), BACKUP_MEDIA_EXPERIMENT_NAME)
return this.experimentEnrollmentManager.isEnrolled(account.getAccountIdentifier(), BACKUP_MEDIA_EXPERIMENT_NAME)
? BackupLevel.PAID
: BackupLevel.FREE;
}
@@ -42,6 +42,7 @@ public class Cdn3RemoteStorageManager implements RemoteStorageManager {
private final String clientId;
private final String clientSecret;
private final Map<Integer, String> sourceSchemes;
private final Duration usageRequestTimeout;
static final String CLIENT_ID_HEADER = "CF-Access-Client-Id";
static final String CLIENT_SECRET_HEADER = "CF-Access-Client-Secret";
@@ -75,6 +76,7 @@ public class Cdn3RemoteStorageManager implements RemoteStorageManager {
.withNumClients(configuration.numHttpClients())
.build();
this.sourceSchemes = configuration.sourceSchemes();
this.usageRequestTimeout = configuration.usageRequestTimeout();
}
@Override
@@ -231,6 +233,7 @@ public class Cdn3RemoteStorageManager implements RemoteStorageManager {
HttpUtils.queryParamString(Map.of("prefix", prefix).entrySet()))))
.header(CLIENT_ID_HEADER, clientId)
.header(CLIENT_SECRET_HEADER, clientSecret)
.timeout(usageRequestTimeout)
.build();
return this.storageManagerHttpClient.sendAsync(request, HttpResponse.BodyHandlers.ofInputStream())
.thenApply(response -> {
@@ -100,7 +100,7 @@ public class CaptchaChecker {
final Set<String> allowedSiteKeys = client.validSiteKeys(parsedAction);
if (!allowedSiteKeys.contains(siteKey)) {
logger.debug("invalid site-key {}, action={}, token={}", siteKey, action, token);
logger.debug("invalid site-key {}, action={}", siteKey, action);
Metrics.counter(INVALID_SITEKEY_COUNTER_NAME, "action", action).increment();
throw new InvalidCaptchaArgumentException("invalid captcha site-key");
}
@@ -2,6 +2,7 @@ package org.whispersystems.textsecuregcm.configuration;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import java.time.Duration;
import java.util.Collections;
import java.util.Map;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretString;
@@ -21,6 +22,8 @@ import javax.annotation.Nullable;
* client; if `null`, uses the global default configuration
* @param retryConfigurationName The name of a retry configuration for the storage-manager http client; if
* `null`, uses the global default configuration
* @param usageRequestTimeout The per-attempt request timeout for usage requests to the storage-manager; if
* `null`, defaults to 5 minutes
*/
public record Cdn3StorageManagerConfiguration(
@NotNull String baseUri,
@@ -29,7 +32,8 @@ public record Cdn3StorageManagerConfiguration(
@NotNull Map<Integer, String> sourceSchemes,
@NotNull Integer numHttpClients,
@Nullable String circuitBreakerConfigurationName,
@Nullable String retryConfigurationName) {
@Nullable String retryConfigurationName,
@NotNull Duration usageRequestTimeout) {
public Cdn3StorageManagerConfiguration {
if (numHttpClients == null) {
@@ -38,5 +42,8 @@ public record Cdn3StorageManagerConfiguration(
if (sourceSchemes == null) {
sourceSchemes = Collections.emptyMap();
}
if (usageRequestTimeout == null) {
usageRequestTimeout = Duration.ofMinutes(5);
}
}
}
@@ -9,22 +9,35 @@ import jakarta.validation.Valid;
import jakarta.validation.constraints.AssertTrue;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.PositiveOrZero;
import jakarta.validation.constraints.Size;
import java.time.Duration;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretBytes;
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStore;
/// @param transactionTimeout the time limit for a transaction, which may [contain multiple tries](https://forums.foundationdb.org/t/defaults-for-transaction-timeouts-and-retries/315/2).
/// Note that this is independent of the FoundationDB server’s transaction hard limit of 5 seconds.
/// @param transactionRetryLimit the maximum number of retries permitted _within_ a transaction
/// @param batchPriorityTransactionTimeout the maximum time for a batch priority transaction. Should be greater than or equal to {@link transactionTimeout}
/// @param batchPriorityTransactionRetryLimit the maximum number of retries permitted _within_ a batch priority transaction
public record FoundationDbMessagesConfiguration(@NotEmpty Map<String, @Valid FoundationDbDatabaseFactory> clusters,
@NotEmpty Map<@PositiveOrZero @Max(FoundationDbMessageStore.MAX_EPOCHS - 1) Integer, @Size(min = 1, max = FoundationDbMessageStore.MAX_SHARDS - 1) List<String>> epochs,
@PositiveOrZero @Max(FoundationDbMessageStore.MAX_EPOCHS - 1) int activeEpoch,
@NotEmpty Map<@PositiveOrZero @Max(63) Integer, SecretBytes> versionstampCipherKeys,
@PositiveOrZero @Max(63) int currentVersionstampCipherKey,
@PositiveOrZero @Max(1_000_000) long maxWatchesPerClient) {
@PositiveOrZero @Max(1_000_000) long maxWatchesPerClient,
@NotNull Duration transactionTimeout,
@PositiveOrZero long transactionRetryLimit,
@NotNull Duration batchPriorityTransactionTimeout,
@PositiveOrZero long batchPriorityTransactionRetryLimit) {
public static final long DEFAULT_MAX_WATCHES_PER_CLIENT = 10_000;
public static final Duration DEFAULT_TRANSACTION_TIMEOUT = Duration.ofSeconds(1);
public static final long DEFAULT_TRANSACTION_RETRY_LIMIT = 3;
@AssertTrue
boolean isEveryEpochClusterConfigured() {
@@ -389,7 +389,7 @@ public class AccountController {
throw new WebApplicationException(Response.status(422).build());
}
return accounts.getByUsernameHash(hash).thenApply(maybeAccount -> maybeAccount.map(Account::getUuid)
return accounts.getByUsernameHash(hash).thenApply(maybeAccount -> maybeAccount.map(Account::getAccountIdentifier)
.map(AciServiceIdentifier::new)
.map(AccountIdentifierResponse::new)
.orElseThrow(() -> new WebApplicationException(Status.NOT_FOUND)));
@@ -47,7 +47,7 @@ public class AccountIdentityResponseBuilder {
.map(bv -> new Entitlements.BackupEntitlement(bv.receiptLevel(), bv.expiration()))
.orElse(null);
return new AccountIdentityResponse(account.getUuid(),
return new AccountIdentityResponse(account.getAccountIdentifier(),
account.getNumber(),
account.getPhoneNumberIdentifier(),
account.getUsernameHash().filter(h -> h.length > 0).orElse(null),
@@ -41,7 +41,6 @@ import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
@Path("/v1/certificate")
@Tag(name = "Certificate")
public class CertificateController {
@@ -196,7 +196,7 @@ public class DeviceController {
final Account account = accounts.getByAccountIdentifier(auth.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
rateLimiters.getAllocateDeviceLimiter().validate(account.getUuid());
rateLimiters.getAllocateDeviceLimiter().validate(account.getAccountIdentifier());
if (account.getDevices().size() >= MAX_DEVICES) {
throw new DeviceLimitExceededException(account.getDevices().size(), MAX_DEVICES);
@@ -206,7 +206,7 @@ public class DeviceController {
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
}
final String token = accounts.generateLinkDeviceToken(account.getUuid());
final String token = accounts.generateLinkDeviceToken(account.getAccountIdentifier());
return new LinkDeviceToken(token, AccountsManager.getLinkDeviceTokenIdentifier(token));
}
@@ -240,7 +240,7 @@ public class DeviceController {
final DeviceActivationRequest deviceActivationRequest = linkDeviceRequest.deviceActivationRequest();
final DeviceAttributes deviceAttributes = linkDeviceRequest.deviceAttributes();
rateLimiters.getVerifyDeviceLimiter().validate(account.getUuid());
rateLimiters.getVerifyDeviceLimiter().validate(account.getAccountIdentifier());
final boolean allKeysValid =
PreKeySignatureValidator.validatePreKeySignatures(account.getIdentityKey(IdentityType.ACI),
@@ -426,7 +426,7 @@ public class KeysController {
.flatMap(targetAccount::getDevice)
.map(device -> device.getRegistrationId(targetIdentifier.identityType()));
return RateLimitKeys.preKeyLimiterKey(
account.getUuid(),
account.getAccountIdentifier(),
authenticatedDevice.deviceId(),
targetIdentifier,
parsedTargetDeviceId, targetRegistrationId);
@@ -263,7 +263,7 @@ public class MessageController {
final Account destination =
accountsManager.getByServiceIdentifier(destinationIdentifier).orElseThrow(NotFoundException::new);
rateLimiters.getMessagesLimiter().validate(source.accountIdentifier(), destination.getUuid());
rateLimiters.getMessagesLimiter().validate(source.accountIdentifier(), destination.getAccountIdentifier());
sendIndividualMessage(destination,
destinationIdentifier,
@@ -335,7 +335,7 @@ public class MessageController {
final Account destination = accountsManager.getByServiceIdentifier(destinationIdentifier).orElseThrow(() ->
new WebApplicationException(Response.ok(new SendMessageResponse(false)).build()));
rateLimiters.getStoriesLimiter().validate(destination.getUuid());
rateLimiters.getStoriesLimiter().validate(destination.getAccountIdentifier());
sendIndividualMessage(destination,
destinationIdentifier,
@@ -744,7 +744,7 @@ public class MessageController {
sourceNumber = Optional.of(source);
final Optional<Account> maybeAccount = accountsManager.getByE164(source);
if (maybeAccount.isPresent()) {
sourceAci = maybeAccount.map(Account::getUuid);
sourceAci = maybeAccount.map(Account::getAccountIdentifier);
sourcePni = maybeAccount.map(Account::getPhoneNumberIdentifier);
} else {
sourcePni = Optional.ofNullable(phoneNumberIdentifiers.getPhoneNumberIdentifier(source).join());
@@ -245,7 +245,7 @@ public class ProfileController {
return buildVersionedProfileResponse(targetAccount,
version,
maybeRequester.map(requester -> ProfileHelper.isSelfProfileRequest(requester.getUuid(), accountIdentifier)).orElse(false),
maybeRequester.map(requester -> ProfileHelper.isSelfProfileRequest(requester.getAccountIdentifier(), accountIdentifier)).orElse(false),
false,
containerRequestContext);
}
@@ -286,7 +286,7 @@ public class ProfileController {
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED)));
final Account targetAccount = verifyPermissionToReceiveProfile(maybeRequester, accessKey, accountIdentifier, "credentialRequest", userAgent);
final boolean isSelf = maybeRequester.map(requester -> ProfileHelper.isSelfProfileRequest(requester.getUuid(), accountIdentifier)).orElse(false);
final boolean isSelf = maybeRequester.map(requester -> ProfileHelper.isSelfProfileRequest(requester.getAccountIdentifier(), accountIdentifier)).orElse(false);
return buildExpiringProfileKeyCredentialProfileResponse(targetAccount,
version,
@@ -341,7 +341,7 @@ public class ProfileController {
}
return switch (identifier.identityType()) {
case ACI -> buildBaseProfileResponseForAccountIdentity(targetAccount,
maybeRequester.map(requester -> ProfileHelper.isSelfProfileRequest(requester.getUuid(), identifier)).orElse(false),
maybeRequester.map(requester -> ProfileHelper.isSelfProfileRequest(requester.getAccountIdentifier(), identifier)).orElse(false),
containerRequestContext);
case PNI -> buildBaseProfileResponseForPhoneNumberIdentity(targetAccount);
};
@@ -426,13 +426,13 @@ public class ProfileController {
final ExpiringProfileKeyCredentialResponse expiringProfileKeyCredentialResponse;
if (account.getCurrentProfileVersion().map(v -> HexFormat.of().formatHex(v).equals(version)).orElse(false)) {
expiringProfileKeyCredentialResponse = profilesManager.getV1(account.getUuid(), version)
expiringProfileKeyCredentialResponse = profilesManager.getV1(account.getAccountIdentifier(), version)
.map(profile -> {
final ExpiringProfileKeyCredentialResponse profileKeyCredentialResponse;
try {
profileKeyCredentialResponse = ProfileHelper.getExpiringProfileKeyCredential(
new ProfileKeyCredentialRequest(HexFormat.of().parseHex(encodedCredentialRequest)),
new ProfileKeyCommitment(profile.commitment()), new ServiceId.Aci(account.getUuid()),
new ProfileKeyCommitment(profile.commitment()), new ServiceId.Aci(account.getAccountIdentifier()),
zkProfileOperations);
} catch (VerificationFailedException | InvalidInputException e) {
throw new BadRequestException(e);
@@ -455,7 +455,7 @@ public class ProfileController {
final boolean hasCredentialRequest,
final ContainerRequestContext containerRequestContext) {
final Optional<VersionedProfileV1> maybeProfile = profilesManager.getV1(account.getUuid(), version);
final Optional<VersionedProfileV1> maybeProfile = profilesManager.getV1(account.getAccountIdentifier(), version);
if (maybeProfile.isEmpty()) {
// this can happen if an account re-registers, which includes some device-transfer scenarios
@@ -498,7 +498,7 @@ public class ProfileController {
HeaderUtils.getAcceptableLanguagesForRequest(containerRequestContext),
account.getBadges(),
isSelf),
new AciServiceIdentifier(account.getUuid()));
new AciServiceIdentifier(account.getAccountIdentifier()));
}
private BaseProfileResponse buildBaseProfileResponseForPhoneNumberIdentity(final Account account) {
@@ -537,7 +537,7 @@ public class ProfileController {
}
if (maybeRequester.isPresent()) {
rateLimiters.getProfileLimiter().validate(maybeRequester.get().getUuid());
rateLimiters.getProfileLimiter().validate(maybeRequester.get().getAccountIdentifier());
}
final Optional<Account> maybeTargetAccount = accountsManager.getByServiceIdentifier(accountIdentifier);
@@ -5,7 +5,6 @@
package org.whispersystems.textsecuregcm.controllers;
import com.google.common.annotations.VisibleForTesting;
import io.dropwizard.auth.Auth;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
@@ -22,45 +21,21 @@ import jakarta.ws.rs.core.EntityTag;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HexFormat;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.apache.commons.lang3.tuple.Pair;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.entities.RemoteConfigurationResponse;
import org.whispersystems.textsecuregcm.storage.RemoteConfig;
import org.whispersystems.textsecuregcm.storage.RemoteConfigsManager;
import org.whispersystems.textsecuregcm.util.Conversions;
import org.whispersystems.textsecuregcm.util.Util;
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
@Path("/v2/config")
@Tag(name = "Remote Config")
public class RemoteConfigController {
private final RemoteConfigsManager remoteConfigsManager;
private final Map<String, String> globalConfig;
private static final String GLOBAL_CONFIG_PREFIX = "global.";
private static final Set<String> PLATFORM_PREFIXES = Arrays.stream(ClientPlatform.values())
.map(p -> p.name().toLowerCase())
.collect(Collectors.toSet());
public RemoteConfigController(RemoteConfigsManager remoteConfigsManager, Map<String, String> globalConfig) {
public RemoteConfigController(RemoteConfigsManager remoteConfigsManager) {
this.remoteConfigsManager = remoteConfigsManager;
this.globalConfig = globalConfig;
}
@GET
@@ -88,69 +63,17 @@ public class RemoteConfigController {
@HeaderParam(HttpHeaders.USER_AGENT)
String userAgent
) {
final String platformPrefix = platformPrefix(userAgent);
final List<RemoteConfig> remoteConfigs = remoteConfigsManager.getAll();
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
final Map<String, String> configs = remoteConfigsManager.getConfigForAccount(auth.accountIdentifier(), userAgent);
final Map<String, String> configs = Stream.concat(
remoteConfigs.stream()
.filter(config -> {
final String firstNameComponent = config.getName().split("\\.", 2)[0];
return firstNameComponent.equals(platformPrefix) || !PLATFORM_PREFIXES.contains(firstNameComponent);
})
.map(
config -> {
final byte[] hashKey = config.getHashKey() != null
? config.getHashKey().getBytes(StandardCharsets.UTF_8)
: config.getName().getBytes(StandardCharsets.UTF_8);
boolean inBucket = isInBucket(digest, auth.accountIdentifier(), hashKey, config.getPercentage(), config.getUuids());
final String value = inBucket ? config.getValue() : config.getDefaultValue();
return Pair.of(config.getName(), value == null ? String.valueOf(inBucket) : value);
}),
globalConfig.entrySet().stream()
.map(e -> Pair.of(GLOBAL_CONFIG_PREFIX + e.getKey(), e.getValue())))
.collect(Collectors.toMap(Pair::getLeft, Pair::getRight));
final EntityTag newETag = new EntityTag(HexFormat.of().toHexDigits(configs.hashCode()));
if (newETag.equals(eTag)) {
return Response.notModified(eTag).build();
}
return Response.ok(new RemoteConfigurationResponse(configs))
.tag(newETag)
.build();
} catch (NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
}
private static String platformPrefix(final String userAgent) {
try {
return UserAgentUtil.parseUserAgentString(userAgent).platform().name().toLowerCase();
} catch (UnrecognizedUserAgentException e) {
return null;
}
}
@VisibleForTesting
public static boolean isInBucket(MessageDigest digest, UUID uid, byte[] hashKey, int configPercentage,
Set<UUID> uuidsInBucket) {
if (uuidsInBucket.contains(uid)) {
return true;
final EntityTag newETag = new EntityTag(HexFormat.of().toHexDigits(configs.hashCode()));
if (newETag.equals(eTag)) {
return Response.notModified(eTag).build();
}
ByteBuffer bb = ByteBuffer.allocate(16);
bb.putLong(uid.getMostSignificantBits());
bb.putLong(uid.getLeastSignificantBits());
digest.update(bb.array());
byte[] hash = digest.digest(hashKey);
int bucket = (int) (Util.ensureNonNegativeLong(Conversions.byteArrayToLong(hash)) % 100);
return bucket < configPercentage;
return Response.ok(new RemoteConfigurationResponse(configs))
.tag(newETag)
.build();
}
}
@@ -28,6 +28,7 @@ import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
@@ -118,14 +119,14 @@ public class SecureValueRecovery2Controller {
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
@NotNull @Valid final AuthCheckRequest request) {
final List<ExternalServiceCredentialsSelector.CredentialInfo> credentials = ExternalServiceCredentialsSelector.check(
request.tokens(),
new HashSet<>(request.tokens()),
backupServiceCredentialGenerator,
MAX_AGE.getSeconds());
// the username associated with the provided number
final Optional<String> matchingUsername = accountsManager
.getByE164(request.number())
.map(Account::getUuid)
.map(Account::getAccountIdentifier)
.map(backupServiceCredentialGenerator::generateForUuid)
.map(ExternalServiceCredentials::username);
@@ -27,6 +27,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.grpc.RequestAttributesUtil;
import org.whispersystems.textsecuregcm.util.InetAddressRange;
import org.whispersystems.textsecuregcm.util.logging.ImpossibleEvents;
public class ExternalRequestFilter implements Filter, ServerInterceptor {
@@ -85,7 +86,7 @@ public class ExternalRequestFilter implements Filter, ServerInterceptor {
if (response instanceof HttpServletResponse hsr) {
hsr.setStatus(404);
} else {
logger.warn("response was an unexpected type: {}", response.getClass());
ImpossibleEvents.logImpossible(logger, "response was an unexpected type: {}", response.getClass());
}
return;
}
@@ -15,6 +15,7 @@ import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.util.HttpServletRequestUtil;
import org.whispersystems.textsecuregcm.util.logging.ImpossibleEvents;
/**
* Sets a {@link HttpServletRequest} attribute (that will also be available as a
@@ -36,7 +37,7 @@ public class RemoteAddressFilter implements Filter {
request.setAttribute(REMOTE_ADDRESS_ATTRIBUTE_NAME, remoteAddress);
} else {
logger.warn("request was of unexpected type: {}", request.getClass());
ImpossibleEvents.logImpossible(logger, "request was of unexpected type: {}", request.getClass());
}
chain.doFilter(request, response);
@@ -67,7 +67,7 @@ public class AccountsAnonymousGrpcService extends SimpleAccountsAnonymousGrpc.Ac
return accountsManager.getByUsernameHash(request.getUsernameHash().toByteArray()).join()
.map(account -> LookupUsernameHashResponse.newBuilder()
.setServiceIdentifier(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new AciServiceIdentifier(account.getUuid())))
.setServiceIdentifier(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new AciServiceIdentifier(account.getAccountIdentifier())))
.build())
.orElseGet(() -> LookupUsernameHashResponse.newBuilder().setNotFound(NotFound.getDefaultInstance()).build());
}
@@ -16,7 +16,6 @@ import java.util.HexFormat;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.function.Function;
import java.util.stream.Collectors;
@@ -62,7 +61,6 @@ import org.signal.chat.account.StaleDevices;
import org.signal.chat.account.UsernameNotAvailable;
import org.signal.chat.common.AccountIdentifiers;
import org.signal.chat.errors.FailedPrecondition;
import org.signal.chat.errors.NotFound;
import org.signal.chat.messages.SendMessageType;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.InvalidKeyException;
@@ -73,7 +71,6 @@ import org.whispersystems.textsecuregcm.auth.InvalidRegistrationSessionException
import org.whispersystems.textsecuregcm.auth.RecoveryPasswordVerificationFailedException;
import org.whispersystems.textsecuregcm.auth.RegistrationLockFailureException;
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
import org.whispersystems.textsecuregcm.auth.UnverifiedRegistrationSessionException;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
@@ -163,7 +160,7 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
@Override
public DeleteAccountResponse deleteAccount(final DeleteAccountRequest request) {
accountsManager.delete(AuthenticationUtil.requireAuthenticatedPrimaryDevice().accountIdentifier(),
accountsManager.delete(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier(),
AccountsManager.DeletionReason.USER_REQUEST);
return DeleteAccountResponse.getDefaultInstance();
@@ -174,7 +171,7 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
final SaltedTokenHash credentials =
SaltedTokenHash.generateFor(formatRegistrationLock(request.getRegistrationLock().toByteArray()));
accountsManager.update(AuthenticationUtil.requireAuthenticatedPrimaryDevice().accountIdentifier(),
accountsManager.update(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier(),
account -> account.setRegistrationLock(credentials.hash(), credentials.salt()));
return SetRegistrationLockResponse.getDefaultInstance();
@@ -182,7 +179,7 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
@Override
public ClearRegistrationLockResponse clearRegistrationLock(final ClearRegistrationLockRequest request) {
accountsManager.update(AuthenticationUtil.requireAuthenticatedPrimaryDevice().accountIdentifier(),
accountsManager.update(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier(),
account -> account.setRegistrationLock(null, null));
return ClearRegistrationLockResponse.getDefaultInstance();
@@ -235,7 +232,6 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
return ConfirmUsernameHashResponse.newBuilder()
.setConfirmedUsernameHash(ConfirmUsernameHashResponse.ConfirmedUsernameHash.newBuilder()
.setUsernameHash(ByteString.copyFrom(updatedAccount.getUsernameHash().orElseThrow()))
.setUsernameLinkHandle(UUIDUtil.toByteString(updatedAccount.getUsernameLinkHandle())))
.build();
} catch (final UsernameHashNotAvailableException e) {
@@ -297,15 +293,15 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
@Override
public ConfigureUnidentifiedAccessResponse configureUnidentifiedAccess(final ConfigureUnidentifiedAccessRequest request) {
if (!request.getAllowUnrestrictedUnidentifiedAccess() && request.getUnidentifiedAccessKey().size() != UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH) {
throw GrpcExceptions.fieldViolation("unidentified_access_key",
String.format("Unidentified access key must be %d bytes, but was actually %d",
UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH, request.getUnidentifiedAccessKey().size()));
if (request.getConfigurationCase() == ConfigureUnidentifiedAccessRequest.ConfigurationCase.CONFIGURATION_NOT_SET) {
throw GrpcExceptions.fieldViolation("configuration", "a configuration case must be set");
}
accountsManager.update(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier(), account -> {
account.setUnrestrictedUnidentifiedAccess(request.getAllowUnrestrictedUnidentifiedAccess());
account.setUnidentifiedAccessKey(request.getAllowUnrestrictedUnidentifiedAccess() ? null : request.getUnidentifiedAccessKey().toByteArray());
account.setUnidentifiedAccessKey(request.hasUnidentifiedAccessKey()
? request.getUnidentifiedAccessKey().toByteArray()
: null);
account.setUnrestrictedUnidentifiedAccess(request.hasAllowUnrestrictedUnidentifiedAccess());
});
return ConfigureUnidentifiedAccessResponse.getDefaultInstance();
@@ -520,7 +516,7 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
private static AccountIdentifiers buildAccountIdentifiers(final Account account) {
final AccountIdentifiers.Builder accountIdentifiersBuilder = AccountIdentifiers.newBuilder()
.addServiceIdentifiers(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new AciServiceIdentifier(account.getUuid())))
.addServiceIdentifiers(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new AciServiceIdentifier(account.getAccountIdentifier())))
.addServiceIdentifiers(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new PniServiceIdentifier(account.getPhoneNumberIdentifier())))
.setE164(account.getNumber());
@@ -8,6 +8,7 @@ import com.google.protobuf.ByteString;
import com.google.protobuf.Empty;
import java.util.Optional;
import java.util.concurrent.Flow;
import io.micrometer.core.instrument.Tag;
import org.signal.chat.backup.BackupStreamClosed;
import org.signal.chat.backup.CopyMediaRequest;
import org.signal.chat.backup.CopyMediaResponse;
@@ -235,10 +236,10 @@ public class BackupsAnonymousGrpcService extends SimpleBackupsAnonymousGrpc.Back
.build())
.build())));
}
final Tag platformTag = UserAgentTagUtil.getPlatformTag(RequestAttributesUtil.getUserAgent().orElse(null));
return JdkFlowAdapter.publisherToFlowPublisher(backupManager.copyToBackup(copyQuota)
.doOnNext(result -> backupMetrics.updateCopyCounter(
result,
UserAgentTagUtil.getPlatformTag(RequestAttributesUtil.getUserAgent().orElse(null))))
.doOnNext(result -> backupMetrics.updateCopyCounter(result, platformTag))
.map(copyResult -> {
CopyMediaResponse.Builder builder = CopyMediaResponse
.newBuilder()
@@ -14,6 +14,7 @@ import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsSelector;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
@@ -34,15 +35,15 @@ public class CredentialsAnonymousGrpcService extends SimpleCredentialsAnonymousG
@Override
public CheckSvrCredentialsResponse checkSvrCredentials(final CheckSvrCredentialsRequest request) {
final List<String> tokens = request.getPasswordsList();
final List<String> tokens = request.getPasswordsList().stream().distinct().toList();
final List<ExternalServiceCredentialsSelector.CredentialInfo> credentials = ExternalServiceCredentialsSelector.check(
tokens,
new HashSet<>(tokens),
svrCredentialsGenerator,
MAX_SVR_PASSWORD_AGE_SECONDS);
// the username associated with the provided number
final Optional<String> maybeUsername = accountsManager.getByE164(request.getNumber())
.map(Account::getUuid)
.map(Account::getAccountIdentifier)
.map(svrCredentialsGenerator::generateForUuid)
.map(ExternalServiceCredentials::username);
@@ -15,6 +15,7 @@ import io.grpc.StatusRuntimeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.logging.ImpossibleEvents;
import java.io.IOException;
import java.io.UncheckedIOException;
@@ -59,6 +60,10 @@ public class ErrorMappingInterceptor implements ServerInterceptor {
log.warn("RPC {} encountered IOException", call.getMethodDescriptor().getFullMethodName(), e);
yield GrpcExceptions.unavailable();
}
case IllegalStateException e -> {
ImpossibleEvents.logImpossible(log, e.getMessage(), e);
yield GrpcExceptions.unavailable(e.getMessage());
}
case null -> {
log.error("RPC {} finished with status UNKNOWN: {}",
call.getMethodDescriptor().getFullMethodName(), status.getDescription());
@@ -232,8 +232,8 @@ public class MessageDispatcher {
messageMetrics.measureMessageStreamDisplaced(MessageMetrics.GRPC_CHANNEL, userAgent, false);
sink.error(GrpcExceptions.invalidCredentials("reauthentication required"));
};
disconnectionRequestManager.addListener(account.getUuid(), device.getId(), listener);
sink.onDispose(() -> disconnectionRequestManager.removeListener(account.getUuid(), device.getId(), listener));
disconnectionRequestManager.addListener(account.getAccountIdentifier(), device.getId(), listener);
sink.onDispose(() -> disconnectionRequestManager.removeListener(account.getAccountIdentifier(), device.getId(), listener));
});
}
@@ -142,7 +142,7 @@ public class MessagesGrpcService extends SimpleMessagesGrpc.MessagesImplBase {
}
final Account destination = maybeDestination.get();
rateLimiters.getMessagesLimiter().validate(authenticatedDevice.accountIdentifier(), destination.getUuid());
rateLimiters.getMessagesLimiter().validate(authenticatedDevice.accountIdentifier(), destination.getAccountIdentifier());
return sendMessage(destination,
destinationServiceIdentifier,
@@ -1,110 +1,42 @@
package org.whispersystems.textsecuregcm.grpc;
import com.google.protobuf.ByteString;
import com.google.protobuf.CodedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import org.signal.chat.purchase.AmountList;
import org.signal.chat.purchase.BackupConfiguration;
import org.signal.chat.purchase.BackupLevelConfiguration;
import org.signal.chat.purchase.Configuration;
import org.signal.chat.purchase.CurrencyConfiguration;
import org.signal.chat.purchase.GetConfigurationRequest;
import org.signal.chat.purchase.GetConfigurationResponse;
import org.signal.chat.purchase.LevelConfiguration;
import org.signal.chat.purchase.SimpleProductConfigurationGrpc;
import org.signal.chat.purchase.TaggedConfiguration;
import org.whispersystems.textsecuregcm.badges.BadgeTranslator;
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
import org.whispersystems.textsecuregcm.configuration.SubscriptionConfiguration;
import org.whispersystems.textsecuregcm.entities.PurchasableBadge;
import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionPaymentProcessor;
import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod;
public class ProductConfigurationGrpcService extends SimpleProductConfigurationGrpc.ProductConfigurationImplBase {
private final SubscriptionConfiguration subscriptionConfiguration;
private final OneTimeDonationConfiguration oneTimeDonationConfiguration;
private final BadgeTranslator badgeTranslator;
// These portions of the configuration are identical on every request
private final Map<String, CurrencyConfiguration> currencyConfigurations;
private final BackupConfiguration backupConfiguration;
// The configuration varies based on the provided Accept-Language header. Here we cache the eTag for the resolved
// language, so if the caller provides a matching etag we don't have to build the full configuration match.
private final ConcurrentHashMap<Locale, ByteString> localeToEtag = new ConcurrentHashMap<>();
private final GetConfigurationResponse configurationResponse;
public ProductConfigurationGrpcService(
final SubscriptionConfiguration subscriptionConfiguration,
final OneTimeDonationConfiguration oneTimeDonationConfiguration,
List<CustomerAwareSubscriptionPaymentProcessor> paymentProcessors,
final BadgeTranslator badgeTranslator,
final long backupMediaStorageAllowanceBytes) {
this.subscriptionConfiguration = subscriptionConfiguration;
this.oneTimeDonationConfiguration = oneTimeDonationConfiguration;
this.badgeTranslator = badgeTranslator;
this.backupConfiguration = buildBackupConfiguration(subscriptionConfiguration, backupMediaStorageAllowanceBytes);
this.currencyConfigurations =
buildCurrencyConfigurations(subscriptionConfiguration, oneTimeDonationConfiguration, paymentProcessors);
this.configurationResponse = GetConfigurationResponse.newBuilder()
.setBackup(buildBackupConfiguration(subscriptionConfiguration, backupMediaStorageAllowanceBytes))
.setSepaMaximumEuros(oneTimeDonationConfiguration.sepaMaximumEuros().toString())
.putAllCurrencies(buildCurrencyConfigurations(subscriptionConfiguration, oneTimeDonationConfiguration, paymentProcessors))
.putAllBadgeLevels(buildLevelConfigurations(subscriptionConfiguration, oneTimeDonationConfiguration))
.build();
}
@Override
public GetConfigurationResponse getConfiguration(final GetConfigurationRequest request) {
final Locale locale = badgeTranslator.resolveLocale(RequestAttributesUtil.getAvailableAcceptedLocales());
final ByteString etag = localeToEtag.get(locale);
if (etag != null && etag.equals(request.getEtag())) {
return GetConfigurationResponse.newBuilder().setEtagMatched(true).build();
}
final Map<Long, LevelConfiguration> levelConfigurations = SubscriptionsUtil
.buildDonationLevelsConfiguration(subscriptionConfiguration, oneTimeDonationConfiguration, badgeTranslator,
RequestAttributesUtil.getAvailableAcceptedLocales())
.entrySet().stream().collect(Collectors.toMap(
Map.Entry::getKey,
entry -> toProtoLevelConfiguration(entry.getValue())));
final Configuration configuration = Configuration.newBuilder()
.putAllCurrencies(currencyConfigurations)
.putAllBadgeLevels(levelConfigurations)
.setBackup(backupConfiguration)
.setSepaMaximumEuros(oneTimeDonationConfiguration.sepaMaximumEuros().toString()).build();
final TaggedConfiguration taggedConfiguration = calculateEtag(configuration);
// This could race and multiple threads could decide to build-and-cache. That's fine, they should all calculate
// the same etag.
localeToEtag.put(locale, taggedConfiguration.getEtag());
return GetConfigurationResponse.newBuilder().setTaggedConfiguration(taggedConfiguration).build();
}
private static TaggedConfiguration calculateEtag(final Configuration configuration) {
final ByteArrayOutputStream baos = new ByteArrayOutputStream(configuration.getSerializedSize());
final CodedOutputStream cos = CodedOutputStream.newInstance(baos);
cos.useDeterministicSerialization();
try {
configuration.writeTo(cos);
cos.flush();
final byte[] configurationBytes = baos.toByteArray();
byte[] hash = MessageDigest.getInstance("SHA-256").digest(configurationBytes);
return TaggedConfiguration.newBuilder()
.setConfiguration(configuration)
.setEtag(ByteString.copyFrom(hash))
.build();
} catch (IOException e) {
throw new UncheckedIOException(e);
} catch (NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
return this.configurationResponse;
}
private static Map<String, CurrencyConfiguration> buildCurrencyConfigurations(
@@ -119,6 +51,24 @@ public class ProductConfigurationGrpcService extends SimpleProductConfigurationG
e -> toProtoCurrencyConfiguration(e.getKey(), e.getValue())));
}
private static Map<Long, LevelConfiguration> buildLevelConfigurations(
final SubscriptionConfiguration subscriptionConfiguration,
final OneTimeDonationConfiguration oneTimeDonationConfiguration) {
final Map<Long, LevelConfiguration> donationLevels = new HashMap<>();
subscriptionConfiguration.getDonationLevels().forEach((levelId, levelConfig) -> {
donationLevels.put(levelId, LevelConfiguration.newBuilder().setBadgeId(levelConfig.badge()).build());
});
donationLevels.put(oneTimeDonationConfiguration.boost().level(),
LevelConfiguration.newBuilder()
.setBadgeId(oneTimeDonationConfiguration.boost().badge())
.setBadgeDurationSeconds(oneTimeDonationConfiguration.boost().expiration().toSeconds()).build());
donationLevels.put(oneTimeDonationConfiguration.gift().level(),
LevelConfiguration.newBuilder()
.setBadgeId(oneTimeDonationConfiguration.gift().badge())
.setBadgeDurationSeconds(oneTimeDonationConfiguration.gift().expiration().toSeconds()).build());
return donationLevels;
}
private static BackupConfiguration buildBackupConfiguration(final SubscriptionConfiguration subscriptionConfiguration,
final long backupMediaStorageAllowanceBytes) {
final Map<Long, BackupLevelConfiguration> backupLevels =
@@ -153,15 +103,4 @@ public class ProductConfigurationGrpcService extends SimpleProductConfigurationG
.forEach((levelId, amount) -> builder.putBackupSubscription(levelId, amount.toString()));
return builder.build();
}
private static LevelConfiguration toProtoLevelConfiguration(
final org.whispersystems.textsecuregcm.subscriptions.LevelConfiguration levelConfiguration) {
final LevelConfiguration.Builder builder = LevelConfiguration.newBuilder();
if (levelConfiguration.badge() instanceof final PurchasableBadge purchasableBadge) {
builder.setBadgeDurationSeconds(purchasableBadge.getDuration().toSeconds());
}
return builder
.setBadge(BadgeGrpcHelper.toGrpcBadge(levelConfiguration.badge()))
.build();
}
}
@@ -13,7 +13,6 @@ import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.util.Arrays;
import java.util.HexFormat;
import java.util.List;
import java.util.Optional;
import org.bouncycastle.crypto.digests.TupleHash;
import org.signal.chat.common.S3UploadForm;
@@ -54,7 +53,7 @@ public class ProfileGrpcHelper {
final ProfileBadgeConverter profileBadgeConverter,
final byte[] requestVersion) {
final Optional<VersionedProfileV1> maybeV1Profile =
profilesManager.getV1(account.getUuid(), HexFormat.of().formatHex(requestVersion));
profilesManager.getV1(account.getAccountIdentifier(), HexFormat.of().formatHex(requestVersion));
if (maybeV1Profile.isEmpty()) {
return Optional.empty();
}
@@ -86,7 +85,7 @@ public class ProfileGrpcHelper {
final byte[] requestVersion) {
final Optional<VersionedProfile> maybeProfile = account.hasCapability(DeviceCapability.PROFILES_V2)
? profilesManager.get(account.getUuid(), requestVersion)
? profilesManager.get(account.getAccountIdentifier(), requestVersion)
: Optional.empty();
if (maybeProfile.isEmpty()) {
return Optional.empty();
@@ -131,13 +130,13 @@ public class ProfileGrpcHelper {
final Optional<VersionedProfile> versionedProfile;
if (account.hasCapability(DeviceCapability.PROFILES_V2)) {
versionedProfile = profilesManager.get(account.getUuid(), version);
versionedProfile = profilesManager.get(account.getAccountIdentifier(), version);
} else {
versionedProfile = Optional.empty();
}
return versionedProfile.map(VersionedProfile::commitment)
.or(() -> profilesManager.getV1(account.getUuid(), HexFormat.of().formatHex(version))
.or(() -> profilesManager.getV1(account.getAccountIdentifier(), HexFormat.of().formatHex(version))
.map(VersionedProfileV1::commitment))
.map(commitment -> {
@@ -145,7 +144,7 @@ public class ProfileGrpcHelper {
try {
profileKeyCredentialResponse = ProfileHelper.getExpiringProfileKeyCredential(
new ProfileKeyCredentialRequest(encodedCredentialRequest),
new ProfileKeyCommitment(commitment), new ServiceId.Aci(account.getUuid()), zkProfileOperations);
new ProfileKeyCommitment(commitment), new ServiceId.Aci(account.getAccountIdentifier()), zkProfileOperations);
} catch (VerificationFailedException | InvalidInputException e) {
throw GrpcExceptions.invalidArguments("invalid credential request");
}
@@ -0,0 +1,121 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc;
import com.google.protobuf.ByteString;
import com.google.protobuf.CodedOutputStream;
import com.google.protobuf.Message;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.signal.chat.common.Badge;
import org.signal.chat.remoteconfiguration.Badges;
import org.signal.chat.remoteconfiguration.Configuration;
import org.signal.chat.remoteconfiguration.GetBadgesRequest;
import org.signal.chat.remoteconfiguration.GetBadgesResponse;
import org.signal.chat.remoteconfiguration.GetConfigurationRequest;
import org.signal.chat.remoteconfiguration.GetConfigurationResponse;
import org.signal.chat.remoteconfiguration.SimpleRemoteConfigurationGrpc;
import org.signal.chat.remoteconfiguration.TaggedBadges;
import org.signal.chat.remoteconfiguration.TaggedConfiguration;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
import org.whispersystems.textsecuregcm.badges.BadgeTranslator;
import org.whispersystems.textsecuregcm.storage.RemoteConfigsManager;
public class RemoteConfigurationGrpcService extends SimpleRemoteConfigurationGrpc.RemoteConfigurationImplBase {
private static final GetConfigurationResponse CONFIGURATION_ETAG_MATCHED =
GetConfigurationResponse.newBuilder().setEtagMatched(true).build();
private static final GetBadgesResponse BADGES_ETAG_MATCHED =
GetBadgesResponse.newBuilder().setEtagMatched(true).build();
private final RemoteConfigsManager remoteConfigsManager;
private final BadgeTranslator badgeTranslator;
private final List<String> badgeIds;
// Badge information varies based on the provided Accept-Language header. Here we cache the etag for the resolved
// language, so if the caller provides a matching etag we don't have to build the full badge response.
private final ConcurrentHashMap<Locale, ByteString> localeToBadgesEtag = new ConcurrentHashMap<>();
public RemoteConfigurationGrpcService(
final RemoteConfigsManager remoteConfigsManager,
final BadgeTranslator badgeTranslator,
final List<String> badgeIds) {
this.remoteConfigsManager = remoteConfigsManager;
this.badgeTranslator = badgeTranslator;
this.badgeIds = badgeIds;
}
@Override
public GetConfigurationResponse getConfiguration(final GetConfigurationRequest request) {
final UUID accountIdentifier = AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier();
final String userAgent = RequestAttributesUtil.getUserAgent().orElse(null);
final Map<String, String> configForAccount = remoteConfigsManager.getConfigForAccount(accountIdentifier, userAgent);
final Configuration configuration = Configuration.newBuilder()
.putAllConfiguration(configForAccount)
.build();
final ByteString etagByteString = etag(configuration);
if (etagByteString.equals(request.getEtag())) {
return CONFIGURATION_ETAG_MATCHED;
}
return GetConfigurationResponse.newBuilder()
.setTaggedConfiguration(TaggedConfiguration.newBuilder()
.setEtag(etagByteString)
.setConfiguration(configuration))
.build();
}
@Override
public GetBadgesResponse getBadges(final GetBadgesRequest request) {
final List<Locale> acceptableLanguages = RequestAttributesUtil.getAvailableAcceptedLocales();
final Locale locale = badgeTranslator.resolveLocale(acceptableLanguages);
final ByteString cachedEtag = localeToBadgesEtag.get(locale);
if (cachedEtag != null && cachedEtag.equals(request.getEtag())) {
return BADGES_ETAG_MATCHED;
}
final Map<String, Badge> badgesById = badgeIds.stream().collect(Collectors.toMap(
Function.identity(),
badgeId -> BadgeGrpcHelper.toGrpcBadge(badgeTranslator.translate(acceptableLanguages, badgeId))));
final Badges badges = Badges.newBuilder().putAllBadges(badgesById).build();
final TaggedBadges taggedBadges = TaggedBadges.newBuilder()
.setBadges(badges)
.setEtag(etag(badges))
.build();
// This could race and multiple threads could decide to build-and-cache. That's fine, they should all calculate
// the same etag.
localeToBadgesEtag.put(locale, taggedBadges.getEtag());
return GetBadgesResponse.newBuilder().setTaggedBadges(taggedBadges).build();
}
private static ByteString etag(final Message message) {
final ByteArrayOutputStream baos = new ByteArrayOutputStream(message.getSerializedSize());
final CodedOutputStream cos = CodedOutputStream.newInstance(baos);
cos.useDeterministicSerialization();
try {
message.writeTo(cos);
cos.flush();
return ByteString.copyFrom(MessageDigest.getInstance("SHA-256").digest(baos.toByteArray()));
} catch (final IOException e) {
throw new UncheckedIOException(e);
} catch (final NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
}
}
@@ -53,7 +53,7 @@ public class PushChallengeManager {
final boolean sent;
final String platform;
if (pushChallengeDynamoDb.add(account.getUuid(), token, CHALLENGE_TTL)) {
if (pushChallengeDynamoDb.add(account.getAccountIdentifier(), token, CHALLENGE_TTL)) {
pushNotificationManager.sendRateLimitChallengeNotification(account, HexFormat.of().formatHex(token));
sent = true;
@@ -82,7 +82,7 @@ public class PushChallengeManager {
boolean success = false;
try {
success = pushChallengeDynamoDb.remove(account.getUuid(), HexFormat.of().parseHex(challengeTokenHex));
success = pushChallengeDynamoDb.remove(account.getAccountIdentifier(), HexFormat.of().parseHex(challengeTokenHex));
} catch (final IllegalArgumentException ignored) {
}
@@ -55,12 +55,12 @@ public class RateLimitChallengeManager {
}
public boolean answerPushChallenge(final Account account, final String challenge) throws RateLimitExceededException {
rateLimiters.getPushChallengeAttemptLimiter().validate(account.getUuid());
rateLimiters.getPushChallengeAttemptLimiter().validate(account.getAccountIdentifier());
final boolean challengeSuccess = pushChallengeManager.answerChallenge(account, challenge);
if (challengeSuccess) {
rateLimiters.getPushChallengeSuccessLimiter().validate(account.getUuid());
rateLimiters.getPushChallengeSuccessLimiter().validate(account.getAccountIdentifier());
resetRateLimits(account, ChallengeType.PUSH);
}
return challengeSuccess;
@@ -73,10 +73,10 @@ public class RateLimitChallengeManager {
final Optional<Float> scoreThreshold)
throws RateLimitExceededException, IOException, InvalidCaptchaArgumentException {
rateLimiters.getCaptchaChallengeAttemptLimiter().validate(account.getUuid());
rateLimiters.getCaptchaChallengeAttemptLimiter().validate(account.getAccountIdentifier());
final AssessmentResult assessmentResult =
captchaChecker.verify(Optional.of(account.getUuid()), Action.CHALLENGE, captcha, mostRecentProxyIp, userAgent);
captchaChecker.verify(Optional.of(account.getAccountIdentifier()), Action.CHALLENGE, captcha, mostRecentProxyIp, userAgent);
final boolean challengeSuccess = assessmentResult.isValid(scoreThreshold);
@@ -96,7 +96,7 @@ public class RateLimitChallengeManager {
"sendMessage");
if (challengeSuccess) {
rateLimiters.getCaptchaChallengeSuccessLimiter().validate(account.getUuid());
rateLimiters.getCaptchaChallengeSuccessLimiter().validate(account.getAccountIdentifier());
resetRateLimits(account, ChallengeType.CAPTCHA);
}
return challengeSuccess;
@@ -104,7 +104,7 @@ public class RateLimitChallengeManager {
private void resetRateLimits(final Account account, final ChallengeType type) throws RateLimitExceededException {
try {
rateLimiters.getRateLimitResetLimiter().validate(account.getUuid());
rateLimiters.getRateLimitResetLimiter().validate(account.getAccountIdentifier());
} catch (final RateLimitExceededException e) {
Metrics.counter(RESET_RATE_LIMIT_EXCEEDED_COUNTER_NAME,
SOURCE_COUNTRY_TAG_NAME, Util.getCountryCode(account.getNumber())).increment();
@@ -20,14 +20,14 @@ public class RateLimitChallengeOptionManager {
public List<RateLimitChallengeOption> getChallengeOptions(final Account account) {
final List<RateLimitChallengeOption> options = new ArrayList<>(2);
if (rateLimiters.getCaptchaChallengeAttemptLimiter().hasAvailablePermits(account.getUuid(), 1) &&
rateLimiters.getCaptchaChallengeSuccessLimiter().hasAvailablePermits(account.getUuid(), 1)) {
if (rateLimiters.getCaptchaChallengeAttemptLimiter().hasAvailablePermits(account.getAccountIdentifier(), 1) &&
rateLimiters.getCaptchaChallengeSuccessLimiter().hasAvailablePermits(account.getAccountIdentifier(), 1)) {
options.add(RateLimitChallengeOption.CAPTCHA);
}
if (rateLimiters.getPushChallengeAttemptLimiter().hasAvailablePermits(account.getUuid(), 1) &&
rateLimiters.getPushChallengeSuccessLimiter().hasAvailablePermits(account.getUuid(), 1)) {
if (rateLimiters.getPushChallengeAttemptLimiter().hasAvailablePermits(account.getAccountIdentifier(), 1) &&
rateLimiters.getPushChallengeSuccessLimiter().hasAvailablePermits(account.getAccountIdentifier(), 1)) {
options.add(RateLimitChallengeOption.PUSH_CHALLENGE);
}
@@ -0,0 +1,31 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.mappers;
import io.dropwizard.jersey.errors.ErrorMessage;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.ext.ExceptionMapper;
import jakarta.ws.rs.ext.Provider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.util.logging.ImpossibleEvents;
@Provider
public class IllegalStateExceptionMapper implements ExceptionMapper<IllegalStateException> {
private static final Logger logger = LoggerFactory.getLogger(IllegalStateExceptionMapper.class);
@Override
public Response toResponse(final IllegalStateException exception) {
ImpossibleEvents.logImpossible(logger, exception.getMessage(), exception);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(new ErrorMessage(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
"There was an internal server error processing your request"))
.type(MediaType.APPLICATION_JSON_TYPE)
.build();
}
}
@@ -12,8 +12,6 @@ import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tags;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.function.BiConsumer;
@@ -164,8 +162,8 @@ public class PushNotificationManager {
result.unregisteredTimestamp());
}
} else {
logger.debug("Failed to deliver {} push notification to {} ({})",
pushNotification.notificationType(), pushNotification.deviceToken(), pushNotification.tokenType(),
logger.debug("Failed to deliver {} push notification to token of type {}",
pushNotification.notificationType(), pushNotification.tokenType(),
throwable);
Metrics.counter(FAILED_NOTIFICATION_COUNTER_NAME, "cause", throwable.getClass().getSimpleName()).increment();
@@ -217,7 +215,7 @@ public class PushNotificationManager {
// Reread the account to avoid marking the caller's account as stale. The consumers of this class tend to
// promise not to modify accounts. There's no need to force the caller to be considered mutable just for
// updating an uninstalled feedback timestamp though.
accountsManager.getByAccountIdentifier(account.getUuid()).ifPresent(rereadAccount ->
accountsManager.getByAccountIdentifier(account.getAccountIdentifier()).ifPresent(rereadAccount ->
rereadAccount.getDevice(device.getId()).ifPresent(rereadDevice ->
accountsManager.updateDevice(rereadAccount.getIdentifier(IdentityType.ACI), device.getId(), d -> {
// Don't clear the token if it's already changed
@@ -350,7 +350,7 @@ public class PushNotificationScheduler implements Managed {
// the original device's id, the new device might get the old device's scheduled push, or the new device might
// delay its own push because the old device had a recent push. An extra or delayed background push is harmless,
// so this is okay.
return account.getUuid() + ":" + device.getId();
return account.getAccountIdentifier() + ":" + device.getId();
}
static Pair<UUID, Byte> decodeAciAndDeviceId(final String encoded) {
@@ -24,6 +24,7 @@ import java.util.Base64;
import java.util.Collections;
import java.util.HexFormat;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
@@ -52,9 +53,11 @@ public class Account {
private UUID uuid;
@JsonProperty("pni")
@Nullable
private UUID phoneNumberIdentifier;
@JsonProperty
@Nullable
private String number;
@JsonProperty
@@ -148,37 +151,72 @@ public class Account {
public record BackupVoucher(@JsonProperty("rl") long receiptLevel, @JsonProperty("e") Instant expiration) {}
/// Returns an identifier for the given identity type for this account with the assumption that all accounts have
/// identifiers for all identity types.
///
/// @param identityType the identity type for which to retrieve an account identifier
///
/// @return the identifier for the given identity type
///
/// @throws NoSuchElementException if the account does not have an identifier for the given identity type
///
/// @deprecated Different identity types have significantly differing presence and staleness requirements/guarantees
/// for their respective account identifiers. Please use [#getAccountIdentifier()] or
/// [#getPhoneNumberIdentifierOptional()] instead.
@Deprecated
public UUID getIdentifier(final IdentityType identityType) {
return switch (identityType) {
case ACI -> getUuid();
case ACI -> getAccountIdentifier();
case PNI -> getPhoneNumberIdentifier();
};
}
public UUID getUuid() {
/// Returns the core account identifier (ACI) for this account. An account's core identifier never changes.
///
/// @return the core account identifier for this account
public UUID getAccountIdentifier() {
// this is the one method that may be called on a stale account
return uuid;
}
public void setUuid(final UUID uuid) {
public void setAccountIdentifier(final UUID accountIdentifier) {
requireNotStale();
this.uuid = uuid;
this.uuid = accountIdentifier;
}
/// Returns the phone number identifier for this account.
///
/// @throws NoSuchElementException if this account does not have a phone number identifier
///
/// @return the phone number identifier for this account
///
/// @deprecated Please use [#getPhoneNumberIdentifierOptional()] (which has clearer presence semantics) instead.
@Deprecated
public UUID getPhoneNumberIdentifier() {
requireNotStale();
if (phoneNumberIdentifier == null) {
throw new NoSuchElementException();
}
return phoneNumberIdentifier;
}
/**
* Tests whether this account's account identifier or phone number identifier (depending on the given service
* identifier's identity type) matches the given service identifier.
*
* @param serviceIdentifier the identifier to test
* @return {@code true} if this account's identifier or phone number identifier matches
*/
/// Returns the phone number identifier for this account or empty if this account does not have a phone number.
///
/// @return the phone number identifier for this account or empty if this account does not have a phone number
public Optional<UUID> getPhoneNumberIdentifierOptional() {
requireNotStale();
return Optional.ofNullable(phoneNumberIdentifier);
}
/// Tests whether this account's account identifier or phone number identifier (depending on the given service
/// identifier's identity type) matches the given service identifier.
///
/// @param serviceIdentifier the identifier to test
/// @return `true` if this account's identifier or phone number identifier matches
public boolean isIdentifiedBy(final ServiceIdentifier serviceIdentifier) {
return switch (serviceIdentifier.identityType()) {
case ACI -> serviceIdentifier.uuid().equals(uuid);
@@ -186,12 +224,31 @@ public class Account {
};
}
/// Returns the E.164-formatted phone number for this account.
///
/// @return the E.164-formatted phone number for this account
///
/// @throws NoSuchElementException if this account does not have a phone number
@Deprecated
public String getNumber() {
requireNotStale();
if (number == null) {
throw new NoSuchElementException();
}
return number;
}
/// Returns the phone number for this account or empty if this account does not have a phone number.
///
/// @return the phone number for this account or empty if this account does not have a phone number
public Optional<String> getNumberOptional() {
requireNotStale();
return Optional.ofNullable(number);
}
public void setNumber(final String number, final UUID phoneNumberIdentifier) {
requireNotStale();
@@ -528,26 +585,22 @@ public class Account {
this.backupVoucher = backupVoucher;
}
/**
* Have all this account's devices been manually locked?
*
* @see Device#hasLockedCredentials
*
* @return true if all the account's devices were locked, false otherwise.
*/
/// Have all this account's devices been manually locked?
///
/// @see Device#hasLockedCredentials
///
/// @return true if all the account's devices were locked, false otherwise.
public boolean hasLockedCredentials() {
return devices.stream().allMatch(Device::hasLockedCredentials);
}
/**
* Lock account by invalidating authentication tokens.
*
* We only want to do this in cases where there is a potential conflict between the
* phone number holder and the registration lock holder. In that case, locking the
* account will ensure that either the registration lock holder proves ownership
* of the phone number, or after 7 days the phone number holder can register a new
* account.
*/
/// Lock account by invalidating authentication tokens.
///
/// We only want to do this in cases where there is a potential conflict between the
/// phone number holder and the registration lock holder. In that case, locking the
/// account will ensure that either the registration lock holder proves ownership
/// of the phone number, or after 7 days the phone number holder can register a new
/// account.
public void lockAuthTokenHash() {
devices.forEach(Device::lockAuthTokenHash);
}
@@ -218,7 +218,7 @@ public class Accounts {
final Timer.Sample sample = Timer.start();
try {
final AttributeValue uuidAttr = AttributeValues.fromUUID(account.getUuid());
final AttributeValue uuidAttr = AttributeValues.fromUUID(account.getAccountIdentifier());
final AttributeValue numberAttr = AttributeValues.fromString(account.getNumber());
final AttributeValue pniUuidAttr = AttributeValues.fromUUID(account.getPhoneNumberIdentifier());
@@ -303,12 +303,12 @@ public class Accounts {
final Account accountToCreate,
final Collection<TransactWriteItem> additionalWriteItems) {
if (!existingAccount.getUuid().equals(accountToCreate.getUuid()) ||
if (!existingAccount.getAccountIdentifier().equals(accountToCreate.getAccountIdentifier()) ||
!existingAccount.getPhoneNumberIdentifier().equals(accountToCreate.getPhoneNumberIdentifier())) {
log.error("Reclaimed accounts must match. Old account {}:{}:{}, New account {}:{}:{}",
existingAccount.getUuid(), redactPhoneNumber(existingAccount.getNumber()), existingAccount.getPhoneNumberIdentifier(),
accountToCreate.getUuid(), redactPhoneNumber(accountToCreate.getNumber()), accountToCreate.getPhoneNumberIdentifier());
existingAccount.getAccountIdentifier(), redactPhoneNumber(existingAccount.getNumber()), existingAccount.getPhoneNumberIdentifier(),
accountToCreate.getAccountIdentifier(), redactPhoneNumber(accountToCreate.getNumber()), accountToCreate.getPhoneNumberIdentifier());
throw new IllegalArgumentException("reclaimed accounts must match");
}
@@ -360,7 +360,7 @@ public class Accounts {
.tableName(usernamesConstraintTableName)
.item(Map.of(
UsernameTable.KEY_USERNAME_HASH, AttributeValues.fromByteArray(usernameHash),
UsernameTable.ATTR_ACCOUNT_UUID, AttributeValues.fromUUID(accountToCreate.getUuid()),
UsernameTable.ATTR_ACCOUNT_UUID, AttributeValues.fromUUID(accountToCreate.getAccountIdentifier()),
UsernameTable.ATTR_TTL, AttributeValues.fromLong(expirationTime),
UsernameTable.ATTR_CONFIRMED, AttributeValues.fromBool(false),
UsernameTable.ATTR_RECLAIMABLE, AttributeValues.fromBool(true)))
@@ -371,7 +371,7 @@ public class Accounts {
"#uuid", UsernameTable.ATTR_ACCOUNT_UUID))
.expressionAttributeValues(Map.of(
":now", AttributeValues.fromLong(clock.instant().getEpochSecond()),
":uuid", AttributeValues.fromUUID(accountToCreate.getUuid())))
":uuid", AttributeValues.fromUUID(accountToCreate.getAccountIdentifier())))
.returnValuesOnConditionCheckFailure(ReturnValuesOnConditionCheckFailure.ALL_OLD)
.build())
.build());
@@ -381,7 +381,7 @@ public class Accounts {
// to reclaim the account.
if (!existingAccount.getNumber().equals(accountToCreate.getNumber())) {
if (getAlternateForms(existingAccount.getNumber()).contains(accountToCreate.getNumber())) {
final AttributeValue uuidAttr = AttributeValues.fromUUID(existingAccount.getUuid());
final AttributeValue uuidAttr = AttributeValues.fromUUID(existingAccount.getAccountIdentifier());
final AttributeValue numberAttr = AttributeValues.fromString(accountToCreate.getNumber());
final TransactWriteItem phoneNumberConstraintPut = buildConstraintTablePutIfAbsent(
phoneNumberConstraintTableName, uuidAttr, ATTR_ACCOUNT_E164, numberAttr);
@@ -389,10 +389,9 @@ public class Accounts {
writeItems.add(buildDelete(phoneNumberConstraintTableName, ATTR_ACCOUNT_E164, existingAccount.getNumber()));
writeItems.add(phoneNumberConstraintPut);
} else {
log.error("Reclaiming account with a non-equivalent phone number. Old account {}:{}:{}, new account {}:{}:{}",
existingAccount.getUuid(), existingAccount.getNumber(), existingAccount.getPhoneNumberIdentifier(),
accountToCreate.getUuid(), accountToCreate.getNumber(), accountToCreate.getPhoneNumberIdentifier());
throw new IllegalArgumentException("reclaimed accounts must have equivalent phone numbers");
throw new IllegalStateException(String.format("Reclaiming account with a non-equivalent phone number. Old account %s:%s:%s, new account %s:%s:%s",
existingAccount.getAccountIdentifier(), redactPhoneNumber(existingAccount.getNumber()), existingAccount.getPhoneNumberIdentifier(),
accountToCreate.getAccountIdentifier(), redactPhoneNumber(accountToCreate.getNumber()), accountToCreate.getPhoneNumberIdentifier()));
}
}
@@ -413,7 +412,7 @@ public class Accounts {
final String existingNumber = AttributeValues.getString(item, Accounts.ATTR_ACCOUNT_E164, null);
if (!existingAccount.getNumber().equals(existingNumber)) {
log.error("Failed to update account due to unexpected existing phone number. Account {}. Expected {}, got {}",
existingAccount.getUuid(), existingAccount.getNumber(), existingNumber);
existingAccount.getAccountIdentifier(), existingAccount.getNumber(), existingNumber);
throw new UnexpectedExistingPhoneNumberException();
}
}
@@ -458,7 +457,7 @@ public class Accounts {
int accountUpdateIndex = -1;
try {
final List<TransactWriteItem> writeItems = new ArrayList<>();
final AttributeValue uuidAttr = AttributeValues.fromUUID(account.getUuid());
final AttributeValue uuidAttr = AttributeValues.fromUUID(account.getAccountIdentifier());
final AttributeValue numberAttr = AttributeValues.fromString(number);
final AttributeValue pniAttr = AttributeValues.fromUUID(phoneNumberIdentifier);
@@ -600,7 +599,7 @@ public class Accounts {
final long expirationTimeSeconds) throws ContestedOptimisticLockException, TtlConflictException, UsernameHashNotAvailableException {
// Use account UUID as a "reservation token" - by providing this, the client proves ownership of the hash
final UUID uuid = updatedAccount.getUuid();
final UUID uuid = updatedAccount.getAccountIdentifier();
final List<TransactWriteItem> writeItems = new ArrayList<>();
@@ -787,7 +786,7 @@ public class Accounts {
writeItems.add(TransactWriteItem.builder().put(Put.builder()
.tableName(usernamesConstraintTableName)
.item(Map.of(
UsernameTable.ATTR_ACCOUNT_UUID, AttributeValues.fromUUID(updatedAccount.getUuid()),
UsernameTable.ATTR_ACCOUNT_UUID, AttributeValues.fromUUID(updatedAccount.getAccountIdentifier()),
UsernameTable.KEY_USERNAME_HASH, AttributeValues.fromByteArray(usernameHash),
UsernameTable.ATTR_CONFIRMED, AttributeValues.fromBool(true)))
// it's not in the constraint table OR it's expired OR it was reserved by us
@@ -799,7 +798,7 @@ public class Accounts {
"#confirmed", UsernameTable.ATTR_CONFIRMED))
.expressionAttributeValues(Map.of(
":now", AttributeValues.fromLong(clock.instant().getEpochSecond()),
":aci", AttributeValues.fromUUID(updatedAccount.getUuid()),
":aci", AttributeValues.fromUUID(updatedAccount.getAccountIdentifier()),
":confirmed", AttributeValues.fromBool(false)))
.returnValuesOnConditionCheckFailure(ReturnValuesOnConditionCheckFailure.ALL_OLD)
.build())
@@ -810,11 +809,11 @@ public class Accounts {
// 2?: Add a temporary hold for the old username to stop others from claiming it
maybeOriginalUsernameHash.ifPresent(originalUsernameHash ->
writeItems.add(holdUsernameTransactItem(updatedAccount.getUuid(), originalUsernameHash, now)));
writeItems.add(holdUsernameTransactItem(updatedAccount.getAccountIdentifier(), originalUsernameHash, now)));
// 3?: Adding that hold may have caused our account to exceed our maximum holds. Release an old hold
holdToRemove.ifPresent(oldHold ->
writeItems.add(releaseHoldIfAllowedTransactItem(updatedAccount.getUuid(), oldHold, now)));
writeItems.add(releaseHoldIfAllowedTransactItem(updatedAccount.getAccountIdentifier(), oldHold, now)));
try {
dynamoDbClient.transactWriteItems(TransactWriteItemsRequest.builder().transactItems(writeItems).build());
@@ -895,10 +894,10 @@ public class Accounts {
items.add(UpdateAccountSpec.forAccount(accountsTableName, updatedAccount).transactItem());
// 1: Un-confirm our username, adding a temporary hold for the old username to stop others from claiming it
items.add(holdUsernameTransactItem(updatedAccount.getUuid(), usernameHash, now));
items.add(holdUsernameTransactItem(updatedAccount.getAccountIdentifier(), usernameHash, now));
// 2?: Adding that hold may have caused our account to exceed our maximum holds. Release an old hold
holdToRemove.ifPresent(oldHold -> items.add(releaseHoldIfAllowedTransactItem(updatedAccount.getUuid(), oldHold, now)));
holdToRemove.ifPresent(oldHold -> items.add(releaseHoldIfAllowedTransactItem(updatedAccount.getAccountIdentifier(), oldHold, now)));
try {
dynamoDbClient.transactWriteItems(TransactWriteItemsRequest.builder().transactItems(items).build());
@@ -1081,7 +1080,7 @@ public class Accounts {
return new UpdateAccountSpec(
accountTableName,
Map.of(KEY_ACCOUNT_UUID, AttributeValues.fromUUID(account.getUuid())),
Map.of(KEY_ACCOUNT_UUID, AttributeValues.fromUUID(account.getAccountIdentifier())),
attrNames,
attrValues,
new UpdateExpression(setClauses, addClauses, removeClauses),
@@ -1103,7 +1102,7 @@ public class Accounts {
} catch (final ConditionalCheckFailedException e) {
// the exception doesn't give details about which condition failed,
// but we can infer it was an optimistic locking failure if the UUID is known
if (getByAccountIdentifier(account.getUuid()).isPresent()) {
if (getByAccountIdentifier(account.getAccountIdentifier()).isPresent()) {
throw new ContestedOptimisticLockException();
} else {
throw e;
@@ -1242,7 +1241,7 @@ public class Accounts {
return TransactWriteItem.builder()
.delete(Delete.builder()
.tableName(accountsTableName)
.key(Map.of(KEY_ACCOUNT_UUID, AttributeValues.fromUUID(account.getUuid())))
.key(Map.of(KEY_ACCOUNT_UUID, AttributeValues.fromUUID(account.getAccountIdentifier())))
.conditionExpression("#version = :version")
.expressionAttributeNames(Map.of("#version", ATTR_VERSION))
.expressionAttributeValues(Map.of(":version", AttributeValues.fromInt(account.getVersion())))
@@ -1681,7 +1680,7 @@ public class Accounts {
}
account.setNumber(attributeNumber, phoneNumberIdentifierFromAttribute);
account.setUuid(accountIdentifier);
account.setAccountIdentifier(accountIdentifier);
account.setUsernameHash(AttributeValues.getByteArray(item, ATTR_USERNAME_HASH, null));
account.setUsernameLinkHandle(AttributeValues.getUUID(item, ATTR_USERNAME_LINK_UUID, null));
account.setVersion(Integer.parseInt(item.get(ATTR_VERSION).n()));
@@ -87,6 +87,7 @@ import org.whispersystems.textsecuregcm.util.ResilienceUtil;
import org.whispersystems.textsecuregcm.util.SystemMapper;
import org.whispersystems.textsecuregcm.util.ThrowingConsumer;
import org.whispersystems.textsecuregcm.util.Util;
import org.whispersystems.textsecuregcm.util.logging.ImpossibleEvents;
import reactor.core.publisher.Flux;
import reactor.core.scheduler.Scheduler;
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
@@ -321,7 +322,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
// Reuse the ACI from any recently-deleted account with this number to cover cases where somebody is
// re-registering.
account.setUuid(maybeRecentlyDeletedAccountIdentifier.orElseGet(UUID::randomUUID));
account.setAccountIdentifier(maybeRecentlyDeletedAccountIdentifier.orElseGet(UUID::randomUUID));
account.setNumber(number, pni);
account.setIdentityKey(aciIdentityKey);
account.setPhoneNumberIdentityKey(pniIdentityKey);
@@ -366,7 +367,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
}
final UUID aci = e.getExistingAccount().getIdentifier(IdentityType.ACI);
account.setUuid(aci);
account.setAccountIdentifier(aci);
final List<TransactWriteItem> additionalWriteItems = Stream.concat(
keysManager.buildWriteItemsForNewDevice(account.getIdentifier(IdentityType.ACI),
@@ -416,7 +417,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
.store(account.getIdentifier(IdentityType.PNI), registrationRecoveryPassword))
.orElse(false);
changeNumberWaitingPeriodManager.handleAccountCreated(account.getUuid(), clock.instant());
changeNumberWaitingPeriodManager.handleAccountCreated(account.getAccountIdentifier(), clock.instant());
Tags tags = Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of("type", accountCreationType),
@@ -456,9 +457,9 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
final byte nextDeviceId = account.getNextDeviceId();
CompletableFuture.allOf(
keysManager.deleteSingleUsePreKeys(account.getUuid(), nextDeviceId),
keysManager.deleteSingleUsePreKeys(account.getAccountIdentifier(), nextDeviceId),
keysManager.deleteSingleUsePreKeys(account.getPhoneNumberIdentifier(), nextDeviceId),
messagesManager.clear(account.getUuid(), nextDeviceId))
messagesManager.clear(account.getAccountIdentifier(), nextDeviceId))
.join();
account.addDevice(deviceSpec.toDevice(nextDeviceId, clock, account.getIdentityKey(IdentityType.ACI)));
@@ -649,8 +650,8 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
.orElseThrow(ContestedOptimisticLockException::new);
CompletableFuture.allOf(
keysManager.deleteSingleUsePreKeys(account.getUuid(), deviceId),
messagesManager.clear(account.getUuid(), deviceId))
keysManager.deleteSingleUsePreKeys(account.getAccountIdentifier(), deviceId),
messagesManager.clear(account.getAccountIdentifier(), deviceId))
.join();
account.removeDevice(deviceId);
@@ -668,8 +669,8 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
// Ensure any messages/single-use pre-keys that came in while we were working are also removed
CompletableFuture.allOf(
keysManager.deleteSingleUsePreKeys(account.getUuid(), deviceId),
messagesManager.clear(account.getUuid(), deviceId))
keysManager.deleteSingleUsePreKeys(account.getAccountIdentifier(), deviceId),
messagesManager.clear(account.getAccountIdentifier(), deviceId))
.join();
disconnectionRequestManager.requestDisconnection(accountIdentifier, List.of(deviceId));
@@ -742,13 +743,13 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
maybeDisplacedUuid = Optional.empty();
} else {
delete(maybeExistingAccount.get());
maybeDisplacedUuid = maybeExistingAccount.map(Account::getUuid);
maybeDisplacedUuid = maybeExistingAccount.map(Account::getAccountIdentifier);
}
} else {
maybeDisplacedUuid = recentlyDeletedAci;
}
final UUID uuid = account.getUuid();
final UUID uuid = account.getAccountIdentifier();
CompletableFuture.allOf(
keysManager.deleteSingleUsePreKeys(targetPhoneNumberIdentifier),
@@ -867,7 +868,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
_ -> true,
a -> reservedUsernameHash.set(
checkAndReserveNextUsernameHash(a, new ArrayDeque<>(requestedUsernameHashes))),
() -> accounts.getByAccountIdentifier(account.getUuid()).orElseThrow(),
() -> accounts.getByAccountIdentifier(account.getAccountIdentifier()).orElseThrow(),
AccountChangeValidator.USERNAME_CHANGE_VALIDATOR);
redisDelete(updatedAccount);
@@ -926,7 +927,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
final Account updatedAccount = updateWithRetries(
_ -> true,
a -> accounts.confirmUsernameHash(a, reservedUsernameHash, encryptedUsername),
() -> accounts.getByAccountIdentifier(account.getUuid()).orElseThrow(),
() -> accounts.getByAccountIdentifier(account.getAccountIdentifier()).orElseThrow(),
AccountChangeValidator.USERNAME_CHANGE_VALIDATOR);
redisDelete(updatedAccount);
@@ -1208,17 +1209,17 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
.toList();
CompletableFuture.allOf(
secureStorageClient.deleteStoredData(account.getUuid()),
secureValueRecovery2Client.removeData(account.getUuid()),
keysManager.deleteSingleUsePreKeys(account.getUuid()),
secureStorageClient.deleteStoredData(account.getAccountIdentifier()),
secureValueRecovery2Client.removeData(account.getAccountIdentifier()),
keysManager.deleteSingleUsePreKeys(account.getAccountIdentifier()),
keysManager.deleteSingleUsePreKeys(account.getPhoneNumberIdentifier()),
messagesManager.clear(account.getUuid()),
profilesManager.deleteAll(account.getUuid(), true))
messagesManager.clear(account.getAccountIdentifier()),
profilesManager.deleteAll(account.getAccountIdentifier(), true))
.join();
registrationRecoveryPasswordsManager.remove(account.getIdentifier(IdentityType.PNI));
accounts.delete(account.getUuid(), additionalWriteItems);
accounts.delete(account.getAccountIdentifier(), additionalWriteItems);
redisDelete(account);
disconnectionRequestManager.requestDisconnection(account);
@@ -1241,8 +1242,8 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
final RedisAdvancedClusterCommands<String, String> commands = connection.sync();
commands.setex(getAccountMapKey(account.getPhoneNumberIdentifier().toString()), CACHE_TTL_SECONDS,
account.getUuid().toString());
commands.setex(getAccountEntityKey(account.getUuid()), CACHE_TTL_SECONDS, accountJson);
account.getAccountIdentifier().toString());
commands.setex(getAccountEntityKey(account.getAccountIdentifier()), CACHE_TTL_SECONDS, accountJson);
});
} catch (JsonProcessingException e) {
throw new IllegalStateException(e);
@@ -1262,9 +1263,9 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
return cacheCluster.withCluster(connection -> CompletableFuture.allOf(
connection.async().setex(
getAccountMapKey(account.getPhoneNumberIdentifier().toString()), CACHE_TTL_SECONDS,
account.getUuid().toString())
account.getAccountIdentifier().toString())
.toCompletableFuture(),
connection.async().setex(getAccountEntityKey(account.getUuid()), CACHE_TTL_SECONDS, accountJson)
connection.async().setex(getAccountEntityKey(account.getAccountIdentifier()), CACHE_TTL_SECONDS, accountJson)
.toCompletableFuture()));
}
@@ -1371,7 +1372,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
try {
if (StringUtils.isNotBlank(accountJson)) {
Account account = SystemMapper.jsonMapper().readValue(accountJson, Account.class);
account.setUuid(uuid);
account.setAccountIdentifier(uuid);
if (account.getPhoneNumberIdentifier() == null) {
logger.warn("Account {} loaded from Redis is missing a PNI", uuid);
@@ -1397,7 +1398,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
redisDeleteTimer.record(() ->
cacheCluster.useCluster(connection ->
connection.sync().del(getAccountMapKey(account.getPhoneNumberIdentifier().toString()),
getAccountEntityKey(account.getUuid())))));
getAccountEntityKey(account.getAccountIdentifier())))));
}
public CompletableFuture<Optional<DeviceInfo>> waitForNewLinkedDevice(
@@ -1634,7 +1635,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
channel.substring(TRANSFER_ARCHIVE_KEYSPACE_PATTERN.length() - 1).split(":", 4);
if (deviceIdentifierComponents.length != 4) {
logger.error("Could not parse device identifier; unexpected component count: {}",
ImpossibleEvents.logImpossible(logger, "Could not parse device identifier; unexpected component count: {}",
deviceIdentifierComponents.length);
return;
}
@@ -44,6 +44,7 @@ import org.whispersystems.textsecuregcm.push.MessageSender;
import org.whispersystems.textsecuregcm.push.MessageTooLargeException;
import org.whispersystems.textsecuregcm.util.Pair;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import org.whispersystems.textsecuregcm.util.logging.ImpossibleEvents;
public class ChangeNumberManager {
@@ -104,7 +105,7 @@ public class ChangeNumberManager {
// Only verify and check reglock if there's a data change to be made...
if (!account.getNumber().equals(number)) {
final Optional<Duration> waitingPeriodRemaining = changeNumberWaitingPeriodManager.getWaitingPeriodRemaining(account.getUuid());
final Optional<Duration> waitingPeriodRemaining = changeNumberWaitingPeriodManager.getWaitingPeriodRemaining(account.getAccountIdentifier());
if (waitingPeriodRemaining.isPresent()) {
Metrics.counter(POST_REGISTRATION_WAITING_PERIOD_NOT_MET_COUNTER_NAME).increment();
throw new RateLimitExceededException(waitingPeriodRemaining.get());
@@ -174,6 +175,11 @@ public class ChangeNumberManager {
registrationIdsByDeviceId,
Optional.of(Device.PRIMARY_ID),
userAgent);
} catch (MismatchedDevicesException | MessageTooLargeException e) {
ImpossibleEvents.logImpossible(logger,
"Changed number but could not send device messages after preliminary validation succeeded {}",
account.getIdentifier(IdentityType.ACI), e);
throw e;
} catch (final RuntimeException e) {
logger.warn("Changed number but could not send all device messages for {}",
account.getIdentifier(IdentityType.ACI), e);
@@ -270,7 +270,7 @@ public class MessagePersister implements Managed {
@VisibleForTesting
Mono<Void> persistQueue(final Account account, final Device device, final Tags baseTags) {
final UUID accountUuid = account.getUuid();
final UUID accountUuid = account.getAccountIdentifier();
final byte deviceId = device.getId();
final Tag platformTag = Tag.of("platform", DevicePlatformUtil.getDevicePlatform(device)
@@ -305,7 +305,7 @@ public class MessagePersister implements Managed {
// may throw, in which case we'll retry later by the usual mechanism
if (isPrimary) {
logger.warn("Failed to persist queue {}::{} due to overfull queue; will trim oldest messages",
account.getUuid(), deviceId);
account.getAccountIdentifier(), deviceId);
return trimQueue(account, device)
.then(Mono.error(new MessagePersistenceException("Could not persist due to an overfull queue. Trimmed primary queue, a subsequent retry may succeed")));
@@ -6,12 +6,12 @@ package org.whispersystems.textsecuregcm.storage;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.apple.foundationdb.FDBException;
import com.google.common.annotations.VisibleForTesting;
import com.google.protobuf.ByteString;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Metrics;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.Collections;
import java.util.List;
@@ -24,6 +24,7 @@ import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.UnaryOperator;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.reactivestreams.Publisher;
@@ -61,8 +62,7 @@ public class MessagesManager {
private static final String PRESENCE_MATCH_COUNTER_NAME =
MetricsUtil.name(MessagesManager.class, "presenceMatch");
private static final Counter INSERT_TIMEOUT_COUNTER =
Metrics.counter(name(MessagesManager.class, "insertTimeout"));
private static final String INSERT_FDB_EXCEPTIONS_COUNTER_NAME = name(MessagesManager.class, "insertExceptions");
@VisibleForTesting
static final String MIRROR_INSERTS_EXPERIMENT_NAME = "foundationDbMirrorInserts";
@@ -73,8 +73,6 @@ public class MessagesManager {
@VisibleForTesting
static final String MIRROR_READS_EXPERIMENT_NAME = "foundationDbMirrorReads";
private static final long FOUNDATIONDB_INSERT_TIMEOUT_MILLIS = Duration.ofSeconds(2).toMillis();
private final MessagesDynamoDb messagesDynamoDb;
private final MessagesCache messagesCache;
private final FoundationDbMessageStore foundationDbMessageStore;
@@ -133,10 +131,10 @@ public class MessagesManager {
foundationDbInsertFuture =
foundationDbMessageStore.insert(new AciServiceIdentifier(accountIdentifier), minimizedMessagesByDeviceId)
.orTimeout(FOUNDATIONDB_INSERT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
.exceptionally(e -> {
if (e instanceof TimeoutException) {
INSERT_TIMEOUT_COUNTER.increment();
if (e instanceof FDBException fdbException) {
Metrics.counter(INSERT_FDB_EXCEPTIONS_COUNTER_NAME, "code", String.valueOf(fdbException.getCode()))
.increment();
} else {
logger.warn("Failed to insert {} message(s) for {} into FoundationDB",
minimizedMessagesByDeviceId.size(),
@@ -422,4 +420,24 @@ public class MessagesManager {
public void deleteFoundationDbMessagesBefore(final Map<AciServiceIdentifier, List<Byte>> accountDeviceIdentifiers, final Instant cutoffTime) {
foundationDbMessageStore.deleteMessagesBefore(accountDeviceIdentifiers, cutoffTime);
}
/// Trim the provided message queue if needed.
///
/// @param aci The ACI of the message queue to trim
/// @param device The device of the message queue to trim
/// @param maxQueueSizeBytes The threshold size beyond which the message queue will be trimmed
/// @param targetQueueSizeBytes The target size to trim to
/// @param rangeSplitChunkSizeBytes The approximate chunk size in bytes used to split the range covered by the message queue
/// @param dryRun Whether to actually trim the provided queue
public Mono<Void> trimQueue(
final AciServiceIdentifier aci,
final Device device,
final long maxQueueSizeBytes,
final long targetQueueSizeBytes,
final long rangeSplitChunkSizeBytes,
final boolean dryRun) {
// All trims will be considered successful during a dry run
final UnaryOperator<Mono<Boolean>> deleteModifier = dryRun ? _ -> Mono.just(true) : UnaryOperator.identity();
return foundationDbMessageStore.trimQueue(aci, device, maxQueueSizeBytes, targetQueueSizeBytes, rangeSplitChunkSizeBytes, deleteModifier);
}
}
@@ -8,11 +8,14 @@ package org.whispersystems.textsecuregcm.storage;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Flow;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Metrics;
import org.reactivestreams.Subscription;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStream;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import reactor.adapter.JdkFlowAdapter;
@@ -28,6 +31,9 @@ public class MirroringMessageStream implements MessageStream {
private final AciServiceIdentifier accountIdentifier;
private final byte deviceId;
private static final Counter CONFLICTING_CONSUMER_COUNTER =
Metrics.counter(MetricsUtil.name(MirroringMessageStream.class, "conflictingConsumer"));
private static final Logger logger = LoggerFactory.getLogger(MirroringMessageStream.class);
private static class FoundationDbSubscriber extends BaseSubscriber<MessageStreamEntry> {
@@ -50,6 +56,14 @@ public class MirroringMessageStream implements MessageStream {
// The base `hookOnSubscribe` requests `Long.MAX_VALUE` elements, and that is something we're explicitly trying
// to avoid with this subscriber
}
@Override
protected void hookOnError(final Throwable throwable) {
switch (throwable) {
case ConflictingMessageConsumerException _ -> CONFLICTING_CONSUMER_COUNTER.increment();
default -> super.hookOnError(throwable);
}
}
}
public MirroringMessageStream(final RedisDynamoDbMessageStream redisDynamoDbMessageStream,
@@ -30,6 +30,7 @@ import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
import org.whispersystems.textsecuregcm.util.AttributeValues;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import org.whispersystems.textsecuregcm.util.Util;
import org.whispersystems.textsecuregcm.util.logging.ImpossibleEvents;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import software.amazon.awssdk.core.async.AsyncRequestBody;
@@ -245,7 +246,7 @@ public class PagedSingleUseKEMPreKeyStore {
final int numKeys = AttributeValues.getInt(getResponse.item(), ATTR_PAGE_NUM_KEYS, -1);
final int index = AttributeValues.getInt(getResponse.item(), ATTR_PAGE_IDX, -1);
if (numKeys < 0 || index < 0 || index > numKeys) {
log.error("unexpected index/length in page descriptor: {}", getResponse.item());
ImpossibleEvents.logImpossible(log, "unexpected index/length in page descriptor: {}", getResponse.item());
return 0;
}
@@ -355,7 +356,7 @@ public class PagedSingleUseKEMPreKeyStore {
final byte deviceId = (byte) AttributeValues.getInt(item, KEY_DEVICE_ID, -1);
final UUID pageId = AttributeValues.getUUID(item, ATTR_PAGE_ID, null);
if (aci == null || deviceId < 0 || pageId == null) {
log.error("can't delete page from unexpected page descriptor {}", item);
ImpossibleEvents.logImpossible(log, "can't delete page from unexpected page descriptor {}", item);
}
return Mono.fromFuture(deleteBundleFromS3(aci, deviceId, pageId))
.thenReturn(Map.of(
@@ -429,7 +430,7 @@ public class PagedSingleUseKEMPreKeyStore {
.thenApply(bytes -> {
final ByteBuffer serialized = bytes.asByteBuffer();
if (serialized.remaining() != keyLocation.length()) {
log.error("Unexpected ranged read response, requested {} got {} for offset {} in page {}",
ImpossibleEvents.logImpossible(log, "Unexpected ranged read response, requested {} got {} for offset {} in page {}",
keyLocation.length(), serialized.remaining(), keyLocation, s3Key(identifier, deviceId, pageId));
throw new CompletionException(new IOException("Invalid response to ranged read"));
}
@@ -5,22 +5,111 @@
package org.whispersystems.textsecuregcm.storage;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Suppliers;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.apache.commons.lang3.tuple.Pair;
import org.whispersystems.textsecuregcm.util.Conversions;
import org.whispersystems.textsecuregcm.util.Util;
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
public class RemoteConfigsManager {
private final Supplier<List<RemoteConfig>> remoteConfigSupplier;
private final Map<String, String> globalConfig;
public RemoteConfigsManager(RemoteConfigs remoteConfigs) {
remoteConfigSupplier =
private static final String GLOBAL_CONFIG_PREFIX = "global.";
private static final Set<String> PLATFORM_PREFIXES = Arrays.stream(ClientPlatform.values())
.map(p -> p.name().toLowerCase())
.collect(Collectors.toSet());
public RemoteConfigsManager(final RemoteConfigs remoteConfigs, final Map<String, String> globalConfig) {
this.remoteConfigSupplier =
Suppliers.memoizeWithExpiration(remoteConfigs::getAll, 10, TimeUnit.SECONDS);
this.globalConfig = globalConfig;
}
public List<RemoteConfig> getAll() {
return remoteConfigSupplier.get();
/**
* Returns all remote configuration (per-platform and global) for the specified account and client.
*
* @param accountIdentifier the identifier of the authenticated account
* @param userAgent the requester's user agent, used to select the client platform
* @return a map of namespaced configuration keys to their resolved values
*/
public Map<String, String> getConfigForAccount(final UUID accountIdentifier, @Nullable final String userAgent) {
final String platformPrefix = platformPrefix(userAgent);
final MessageDigest digest;
try {
digest = MessageDigest.getInstance("SHA-256");
} catch (final NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
final List<RemoteConfig> perPlatformConfig = remoteConfigSupplier.get();
return Stream.concat(
perPlatformConfig.stream()
.filter(config -> {
final String firstNameComponent = config.getName().split("\\.", 2)[0];
return firstNameComponent.equals(platformPrefix) || !PLATFORM_PREFIXES.contains(firstNameComponent);
})
.map(config -> {
final byte[] hashKey = config.getHashKey() != null
? config.getHashKey().getBytes(StandardCharsets.UTF_8)
: config.getName().getBytes(StandardCharsets.UTF_8);
boolean inBucket = isInBucket(digest, accountIdentifier, hashKey, config.getPercentage(),
config.getUuids());
final String value = inBucket ? config.getValue() : config.getDefaultValue();
return Pair.of(config.getName(), value == null ? String.valueOf(inBucket) : value);
}),
globalConfig.entrySet().stream()
.map(e -> Pair.of(GLOBAL_CONFIG_PREFIX + e.getKey(), e.getValue())))
.collect(Collectors.toMap(Pair::getLeft, Pair::getRight));
}
@Nullable
private static String platformPrefix(@Nullable final String userAgent) {
try {
return UserAgentUtil.parseUserAgentString(userAgent).platform().name().toLowerCase();
} catch (UnrecognizedUserAgentException e) {
return null;
}
}
@VisibleForTesting
static boolean isInBucket(MessageDigest digest, UUID uid, byte[] hashKey, int configPercentage,
Set<UUID> uuidsInBucket) {
if (uuidsInBucket.contains(uid)) {
return true;
}
ByteBuffer bb = ByteBuffer.allocate(16);
bb.putLong(uid.getMostSignificantBits());
bb.putLong(uid.getLeastSignificantBits());
digest.update(bb.array());
byte[] hash = digest.digest(hashKey);
int bucket = (int) (Util.ensureNonNegativeLong(Conversions.byteArrayToLong(hash)) % 100);
return bucket < configPercentage;
}
}
@@ -118,7 +118,7 @@ public class ReportMessageManager {
connection ->
Math.max(
connection.sync().pfcount(getReportedSenderPniKey(account.getPhoneNumberIdentifier())).intValue(),
connection.sync().pfcount(getReportedSenderAciKey(account.getUuid())).intValue()));
connection.sync().pfcount(getReportedSenderAciKey(account.getAccountIdentifier())).intValue()));
} catch (final RedisException e) {
return 0;
}
@@ -115,7 +115,7 @@ public class AppleDeviceCheckManager {
throw new TooManyKeysException();
}
final String redisChallengeKey = challengeKey(ChallengeType.ATTEST, account.getUuid());
final String redisChallengeKey = challengeKey(ChallengeType.ATTEST, account.getAccountIdentifier());
@Nullable final String challenge = ResilienceUtil.getGeneralRedisRetry(RETRY_NAME)
.executeSupplier(() -> redisClient.withCluster(cluster -> cluster.sync().get(redisChallengeKey)));
@@ -175,7 +175,7 @@ public class AppleDeviceCheckManager {
final byte[] assertion)
throws ChallengeNotFoundException, DeviceCheckVerificationFailedException, DeviceCheckKeyIdNotFoundException, RequestReuseException {
final String redisChallengeKey = challengeKey(challengeType, account.getUuid());
final String redisChallengeKey = challengeKey(challengeType, account.getAccountIdentifier());
@Nullable final String storedChallenge = ResilienceUtil.getGeneralRedisRetry(RETRY_NAME)
.executeSupplier(() -> redisClient.withCluster(cluster -> cluster.sync().get(redisChallengeKey)));
@@ -220,7 +220,7 @@ public class AppleDeviceCheckManager {
* @return The challenge to be included as part of an attestation or assertion
*/
public String createChallenge(final ChallengeType challengeType, final Account account) {
final UUID accountIdentifier = account.getUuid();
final UUID accountIdentifier = account.getAccountIdentifier();
final String challengeKey = challengeKey(challengeType, accountIdentifier);
return ResilienceUtil.getGeneralRedisRetry(RETRY_NAME)
@@ -94,7 +94,7 @@ public class AppleDeviceChecks {
.tableName(deviceCheckTableName)
.keyConditionExpression("#aci = :aci")
.expressionAttributeNames(Map.of("#aci", KEY_ACCOUNT_UUID, "#kid", KEY_PUBLIC_KEY_ID))
.expressionAttributeValues(Map.of(":aci", AttributeValues.fromUUID(account.getUuid())))
.expressionAttributeValues(Map.of(":aci", AttributeValues.fromUUID(account.getAccountIdentifier())))
.projectionExpression("#kid")
.build())
.items()
@@ -136,12 +136,12 @@ public class AppleDeviceChecks {
.tableName(publicKeyConstraintTableName)
.item(Map.of(
KEY_PUBLIC_KEY, AttributeValues.fromByteArray(extractPublicKey(appleDevice).getEncoded()),
KEY_ACCOUNT_UUID, AttributeValues.fromUUID(account.getUuid())
KEY_ACCOUNT_UUID, AttributeValues.fromUUID(account.getAccountIdentifier())
))
// Enforces public key uniqueness, as described in https://developer.apple.com/documentation/devicecheck/validating-apps-that-connect-to-your-server#Store-the-public-key-and-receipt
.conditionExpression("attribute_not_exists(#pk) or #aci = :aci")
.expressionAttributeNames(Map.of("#aci", KEY_ACCOUNT_UUID, "#pk", KEY_PUBLIC_KEY))
.expressionAttributeValues(Map.of(":aci", AttributeValues.fromUUID(account.getUuid())))
.expressionAttributeValues(Map.of(":aci", AttributeValues.fromUUID(account.getAccountIdentifier())))
.build()).build()).build());
return true;
@@ -170,7 +170,7 @@ public class AppleDeviceChecks {
final GetItemResponse item = dynamoDbClient.getItem(GetItemRequest.builder()
.tableName(deviceCheckTableName)
.key(Map.of(
KEY_ACCOUNT_UUID, AttributeValues.fromUUID(account.getUuid()),
KEY_ACCOUNT_UUID, AttributeValues.fromUUID(account.getAccountIdentifier()),
KEY_PUBLIC_KEY_ID, AttributeValues.fromByteArray(keyId))).build());
return item.hasItem() ? Optional.of(fromItem(item.item())) : Optional.empty();
}
@@ -189,7 +189,7 @@ public class AppleDeviceChecks {
dynamoDbClient.updateItem(UpdateItemRequest.builder()
.tableName(deviceCheckTableName)
.key(Map.of(
KEY_ACCOUNT_UUID, AttributeValues.fromUUID(account.getUuid()),
KEY_ACCOUNT_UUID, AttributeValues.fromUUID(account.getAccountIdentifier()),
KEY_PUBLIC_KEY_ID, AttributeValues.fromByteArray(keyId)))
.expressionAttributeNames(Map.of("#counter", ATTR_COUNTER))
.expressionAttributeValues(Map.of(":counter", AttributeValues.n(newCounter)))
@@ -217,7 +217,7 @@ public class AppleDeviceChecks {
.writeValueAsBytes(appleDevice.getAuthenticatorExtensions());
return Map.of(
KEY_ACCOUNT_UUID, AttributeValues.fromUUID(account.getUuid()),
KEY_ACCOUNT_UUID, AttributeValues.fromUUID(account.getAccountIdentifier()),
KEY_PUBLIC_KEY_ID, AttributeValues.fromByteArray(keyId),
ATTR_CRED_DATA, AttributeValues.fromByteArray(attestedCredentialData),
ATTR_STATEMENT, AttributeValues.fromByteArray(attestationStatement),
@@ -7,6 +7,7 @@ import com.apple.foundationdb.Transaction;
import com.apple.foundationdb.tuple.Versionstamp;
import com.google.common.annotations.VisibleForTesting;
import com.google.protobuf.InvalidProtocolBufferException;
import io.micrometer.core.instrument.Metrics;
import java.io.UncheckedIOException;
import java.time.Clock;
import java.util.Arrays;
@@ -14,16 +15,18 @@ import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.BiConsumer;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.storage.ConflictingMessageConsumerException;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
import reactor.core.publisher.Flux;
import reactor.core.publisher.FluxSink;
import reactor.core.publisher.Mono;
@@ -40,15 +43,12 @@ class FoundationDbMessagePublisher {
/// time the publisher was created. For an infinite publisher, this is the end of subspace range.
private final KeySelector endKeyExclusive;
/// The maximum number of messages we will fetch per range query operation to avoid excessive memory consumption
private final int maxMessagesPerScan;
/// The key that stores the server ID/timestamp indicating when/where the connected client was last known to be
/// present. Active publishers refresh this key at regular intervals (see [#renewPresenceFuture]).
@Nullable private final byte[] presenceKey;
// An ID for this specific stream for use when checking "ownership" of a presence value.
private final int streamId = NEXT_STREAM_ID.getAndIncrement();
private final int streamId;
/// The key that is updated whenever new messages are available in the queue. If null, it is inferred that the publisher
/// is finite and will terminate when the end-of-queue at time of publisher creation is reached. Otherwise, the publisher
@@ -78,16 +78,21 @@ class FoundationDbMessagePublisher {
/// A future that represents the next pending presence renewal.
@Nullable private CompletableFuture<?> renewPresenceFuture;
private final AtomicLong totalRequested = new AtomicLong(0);
private final AtomicLong totalEmitted = new AtomicLong(0);
private static final AtomicInteger NEXT_STREAM_ID = new AtomicInteger();
private long totalRequested;
private long totalEmitted;
private static final long RENEWAL_INTERVAL_MILLIS =
FoundationDbMessageStore.PRESENCE_STALE_THRESHOLD.multipliedBy(4).dividedBy(5).toMillis();
private static final int MAX_MESSAGES_PER_PAGE = 1024;
private static final int STREAM_ID_UNASSIGNED = -1;
private static final Logger LOGGER = LoggerFactory.getLogger(FoundationDbMessagePublisher.class);
private static final String WATCHES_COUNTER = MetricsUtil.name(FoundationDbMessagePublisher.class, "watches");
private static final String ACTION_TAG = "action";
enum State {
/// Messages are likely available in the queue. Initial state.
MESSAGES_AVAILABLE,
@@ -127,7 +132,7 @@ class FoundationDbMessagePublisher {
final Clock clock,
final KeySelector beginKeyInclusive,
final KeySelector endKeyExclusive,
final int maxMessagesPerScan,
final int streamId,
@Nullable final byte[] presenceKey,
@Nullable final ScheduledExecutorService presenceRenewalExecutorService,
@Nullable final byte[] messagesAvailableWatchKey,
@@ -137,7 +142,7 @@ class FoundationDbMessagePublisher {
this.clock = clock;
this.beginKeyCursor = beginKeyInclusive;
this.endKeyExclusive = endKeyExclusive;
this.maxMessagesPerScan = maxMessagesPerScan;
this.streamId = streamId;
this.presenceKey = presenceKey;
this.presenceRenewalExecutorService = presenceRenewalExecutorService;
this.messagesAvailableWatchKey = messagesAvailableWatchKey;
@@ -160,12 +165,7 @@ class FoundationDbMessagePublisher {
this.messagePublisher = establishPresence
.thenMany(Flux.create(emitter -> {
this.emitter = emitter;
emitter.onRequest(n -> {
final long totalRequestedCount = totalRequested.addAndGet(n);
if (totalRequestedCount > totalEmitted.get()) {
transitionStateOnEvent(Event.DEMAND_REQUESTED);
}
});
emitter.onRequest(this::addDemand);
emitter.onDispose(this::onDispose);
}));
}
@@ -178,14 +178,13 @@ class FoundationDbMessagePublisher {
final Database database,
final Clock clock,
final KeySelector beginKeyInclusive,
final KeySelector endKeyExclusive,
final int maxMessagesPerScan) {
final KeySelector endKeyExclusive) {
return new FoundationDbMessagePublisher(database,
clock,
beginKeyInclusive,
endKeyExclusive,
maxMessagesPerScan,
STREAM_ID_UNASSIGNED,
null,
null,
null,
@@ -200,7 +199,7 @@ class FoundationDbMessagePublisher {
final Clock clock,
final KeySelector beginKeyInclusive,
final KeySelector endKeyExclusive,
final int maxMessagesPerScan,
final int streamId,
final byte[] presenceKey,
final ScheduledExecutorService presenceRenewalExecutorService,
final byte[] messagesAvailableWatchKey) {
@@ -209,7 +208,7 @@ class FoundationDbMessagePublisher {
clock,
beginKeyInclusive,
endKeyExclusive,
maxMessagesPerScan,
streamId,
presenceKey,
presenceRenewalExecutorService,
messagesAvailableWatchKey,
@@ -300,24 +299,49 @@ class FoundationDbMessagePublisher {
}
}
/// Fetch messages using a range query limiting batch size to [#maxMessagesPerScan]. If the query returns fewer than
/// [#maxMessagesPerScan], emit [Event#FETCHED_ALL_AVAILABLE_MESSAGES]. In the case of an infinite publisher, also set
/// Fetch messages using a range query limiting batch size to `maxMessages`. If the query returns fewer than
/// `maxMessages`, emit [Event#FETCHED_ALL_AVAILABLE_MESSAGES]. In the case of an infinite publisher, also set
/// a watch for new messages. Additionally, the cursor is updated so that we begin fetching from the right key on
/// subsequent scans.
///
/// @return a future of a list of [FoundationDbMessageStreamEntry.Message] with a max size of [#maxMessagesPerScan]
private CompletableFuture<List<FoundationDbMessageStreamEntry.Message>> getMessagesBatch() {
return database.runAsync(transaction ->
transaction.getRange(beginKeyCursor, endKeyExclusive, maxMessagesPerScan, false, StreamingMode.EXACT).asList()
.thenApply(keyValues -> {
if (keyValues.size() < maxMessagesPerScan && !terminateOnQueueEmpty) {
setWatch(transaction);
}
/// @param maxMessages the maximum number of messages to retrieve
///
/// @return a future of a list of [FoundationDbMessageStreamEntry.Message] with a max size of `maxMessages`
private CompletableFuture<List<FoundationDbMessageStreamEntry.Message>> getMessagesBatch(final int maxMessages) {
if (maxMessages <= 0) {
throw new IllegalArgumentException("Max messages must be positive");
}
return keyValues;
}))
return FoundationDbUtil.safeRunAsync(database, transaction -> {
final CompletableFuture<Void> checkPresenceFuture;
if (!terminateOnQueueEmpty) {
// This is an unbounded publisher and we've established presence, so we should check for conflicts
checkPresenceFuture = transaction.get(presenceKey)
.thenAccept(presenceValue -> {
if (isPresenceContested(presenceValue)) {
throw new CompletionException(new ConflictingMessageConsumerException());
}
});
} else {
// This is a bounded publisher and we have not established presence, so we don't need to check for conflicts
checkPresenceFuture = CompletableFuture.completedFuture(null);
}
return checkPresenceFuture
.thenCombine(
transaction.getRange(beginKeyCursor, endKeyExclusive, maxMessages, false, StreamingMode.EXACT).asList(),
(_, keyValues) -> keyValues)
.thenApply(keyValues -> {
if (keyValues.size() < maxMessages && !terminateOnQueueEmpty) {
setWatch(transaction);
}
return keyValues;
});
})
.thenApply(keyValues -> {
if (keyValues.size() < maxMessagesPerScan) {
if (keyValues.size() < maxMessages) {
transitionStateOnEvent(Event.FETCHED_ALL_AVAILABLE_MESSAGES);
}
@@ -342,23 +366,44 @@ class FoundationDbMessagePublisher {
});
}
/// Fetch and publish messages. Messages are fetched in batches of [#maxMessagesPerScan] to avoid excessive memory
/// consumption. After each fetch operation, [#beginKeyCursor] is updated to the next key we need to start reading
/// from. If the fetch operation returns fewer items than the batch size, we infer that we have fetched all available
/// messages and [Event#FETCHED_ALL_AVAILABLE_MESSAGES] is sent to the state machine. See [#getMessagesBatch()]
/// for details. Additionally, after we successfully publish the batch of messages, {@link Event#PUBLISHED_MESSAGES}
/// is emitted. If there's an error while fetching or publishing, [Event#FETCH_OR_PUBLISH_ERROR_OCCURRED] is emitted
/// instead.
private synchronized void addDemand(final long n) {
totalRequested += n;
assert totalRequested > totalEmitted;
transitionStateOnEvent(Event.DEMAND_REQUESTED);
}
private synchronized void handleEntriesEmitted(final long n) {
totalEmitted += n;
}
/// Returns the unmet demand requested by subscribers. Values larger than [Integer#MAX_VALUE] are clamped to
/// [Integer#MAX_VALUE].
///
/// @return the unmet demand requested by publishers as an `int`
private synchronized int getOutstandingDemand() {
return (int) Math.min(totalRequested - totalEmitted, Integer.MAX_VALUE);
}
/// Fetch and publish messages. Messages are fetched in batches to avoid excessive memory consumption. After each
/// fetch operation, [#beginKeyCursor] is updated to the next key we need to start reading from. If the fetch
/// operation returns fewer items than the batch size, we infer that we have fetched all available messages and
/// [Event#FETCHED_ALL_AVAILABLE_MESSAGES] is sent to the state machine. See [#getMessagesBatch(int)] for details.
/// Additionally, after we successfully publish the batch of messages, {@link Event#PUBLISHED_MESSAGES} is emitted. If
/// there's an error while fetching or publishing, [Event#FETCH_OR_PUBLISH_ERROR_OCCURRED] is emitted instead.
private void emitMessages() {
getMessagesBatch()
final int maxMessages = Math.min(getOutstandingDemand(), MAX_MESSAGES_PER_PAGE);
getMessagesBatch(maxMessages)
.thenAccept(messageStreamEntries -> {
messageStreamEntries.forEach(emitter::next);
totalEmitted.addAndGet(messageStreamEntries.size());
handleEntriesEmitted(messageStreamEntries.size());
transitionStateOnEvent(Event.PUBLISHED_MESSAGES);
})
.exceptionally(t -> {
transitionStateOnEvent(Event.FETCH_OR_PUBLISH_ERROR_OCCURRED);
emitter.error(t);
emitter.error(ExceptionUtils.unwrap(t));
return null;
});
}
@@ -372,18 +417,29 @@ class FoundationDbMessagePublisher {
private synchronized void setWatch(final Transaction transaction) {
assert messagesAvailableWatchKey != null;
if (state == State.TERMINATED || state == State.ERROR) {
// If we're already in a terminal state, we don't want to set a watch that would leak
return;
}
// Set a watch that will be triggered when new messages arrive. When it is triggered, we attempt to fetch messages
// again (if there is demand). When we run out of messages, this method will be called again, setting another watch,
// and so on, thus achieving a "watch for new messages -> read -> publish" loop.
watchFuture = transaction.watch(messagesAvailableWatchKey);
watchFuture.thenRun(() -> transitionStateOnEvent(Event.MESSAGE_AVAILABLE_WATCH_TRIGGERED));
Metrics.counter(WATCHES_COUNTER, ACTION_TAG, "set").increment();
watchFuture.thenRun(() -> {
Metrics.counter(WATCHES_COUNTER, ACTION_TAG, "triggered").increment();
transitionStateOnEvent(Event.MESSAGE_AVAILABLE_WATCH_TRIGGERED);
});
}
/// Cancel the watch (if any). Although inactive watches are automatically timed-out, we explicitly cancel when the
/// subscription is disposed to clean up associated resources and to avoid having too many watches open at once.
private synchronized void cancelWatch() {
if (watchFuture != null) {
watchFuture.cancel(true);
if (watchFuture.cancel(true)) {
Metrics.counter(WATCHES_COUNTER, ACTION_TAG, "cancelled").increment();
}
watchFuture = null;
}
}
@@ -433,7 +489,7 @@ class FoundationDbMessagePublisher {
return CompletableFuture.failedFuture(new IllegalStateException("Publisher already terminated"));
}
return database.runAsync(transaction -> {
return FoundationDbUtil.safeRunAsync(database, transaction -> {
transaction.set(presenceKey, FoundationDbMessageStore.getPresenceValue(clock.instant(), streamId));
return CompletableFuture.completedFuture(null);
});
@@ -445,15 +501,8 @@ class FoundationDbMessagePublisher {
renewPresenceFuture.cancel(true);
renewPresenceFuture.whenComplete((_, _) ->
database.runAsync(transaction -> transaction.get(presenceKey).thenAccept(presenceValue -> {
if (presenceValue == null) {
return;
}
final byte[] presenceServerId = FoundationDbMessageStore.getPresenceServerId(presenceValue);
final int presenceStreamId = FoundationDbMessageStore.getPresenceStreamId(presenceValue);
if (Arrays.equals(presenceServerId, FoundationDbMessageStore.getServerId()) && streamId == presenceStreamId) {
FoundationDbUtil.safeRunAsync(database, transaction -> transaction.get(presenceKey).thenAccept(presenceValue -> {
if (!isPresenceContested(presenceValue)) {
transaction.clear(presenceKey);
}
}))
@@ -465,6 +514,16 @@ class FoundationDbMessagePublisher {
}
}
private boolean isPresenceContested(final byte[] presenceValue) {
if (presenceValue == null) {
// Some other process has cleared our presence key, so we must assume a conflict somewhere
return true;
}
return streamId != FoundationDbMessageStore.getPresenceStreamId(presenceValue) ||
!Arrays.equals(FoundationDbMessageStore.getPresenceServerId(presenceValue), FoundationDbMessageStore.getServerId());
}
@VisibleForTesting
synchronized void terminateWithError(final Throwable throwable) {
if (state != State.TERMINATED && state != State.ERROR) {
@@ -1,6 +1,9 @@
package org.whispersystems.textsecuregcm.storage.foundationdb;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.apple.foundationdb.Database;
import com.apple.foundationdb.KeyArrayResult;
import com.apple.foundationdb.MutationType;
import com.apple.foundationdb.Range;
import com.apple.foundationdb.Transaction;
@@ -11,7 +14,10 @@ import com.google.common.annotations.VisibleForTesting;
import com.google.common.hash.Hashing;
import io.dropwizard.util.DataSize;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.DistributionSummary;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import io.micrometer.core.instrument.Timer;
import java.nio.ByteBuffer;
import java.time.Clock;
@@ -22,21 +28,34 @@ import java.util.Arrays;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.UnaryOperator;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.metrics.DevicePlatformUtil;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.util.Pair;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import org.whispersystems.textsecuregcm.util.Util;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.util.function.Tuple3;
import reactor.util.function.Tuples;
/// An implementation of a message store backed by FoundationDB.
///
@@ -59,6 +78,10 @@ public class FoundationDbMessageStore {
private final ScheduledExecutorService presenceRenewalExecutorService;
private final Clock clock;
// Per-attempt timeout and retry limit for batch priority transacitons, e.g. expired-message trim.
private final Duration batchPriorityTransactionTimeout;
private final long batchPriorityTransactionRetryLimit;
private static final byte[] SERVER_ID = UUIDUtil.toBytes(UUID.randomUUID());
private static final int PRESENCE_VALUE_LENGTH = 28;
@@ -78,6 +101,8 @@ public class FoundationDbMessageStore {
public static final int MAX_EPOCHS = 4;
public static final int MAX_SHARDS = 64;
private static final String QUEUE_SIZE_DISTRIBUTION_SUMMARY_NAME = name(FoundationDbMessageStore.class, "queueSize");
private static final Counter INSERT_MESSAGE_COUNTER =
Metrics.counter(MetricsUtil.name(FoundationDbMessageStore.class, "insertMessage"));
@@ -90,6 +115,10 @@ public class FoundationDbMessageStore {
private static final Timer DELETE_MESSAGE_TIMER =
Metrics.timer(MetricsUtil.name(FoundationDbMessageStore.class, "deleteMessageTimer"));
private static final Counter ESTIMATED_TRIMMED_BYTES_COUNTER = Metrics.counter(MetricsUtil.name(FoundationDbMessageStore.class, "estimatedTrimmedBytes"));
private static final String TRIM_QUEUE_COUNTER_NAME = MetricsUtil.name(FoundationDbMessageStore.class, "trimQueue");
private static final Logger LOGGER = LoggerFactory.getLogger(FoundationDbMessageStore.class);
/// Result of inserting a message for a particular device
///
/// @param versionstamp the versionstamp of the transaction in which this device's message was inserted, empty
@@ -105,7 +134,9 @@ public class FoundationDbMessageStore {
final int activeEpoch,
final VersionstampUUIDCipher versionstampUUIDCipher,
final ScheduledExecutorService presenceRenewalExecutorService,
final Clock clock) {
final Clock clock,
final Duration batchPriorityTransactionTimeout,
final long batchPriorityTransactionRetryLimit) {
final Database[][] databasesByEpochArray = new Database[MAX_EPOCHS][];
@@ -127,6 +158,8 @@ public class FoundationDbMessageStore {
},
IdentityHashMap::new));
this.clock = clock;
this.batchPriorityTransactionTimeout = batchPriorityTransactionTimeout;
this.batchPriorityTransactionRetryLimit = batchPriorityTransactionRetryLimit;
}
/// Convenience method for inserting a single recipient message bundle. See [#insert(Map)] for details.
@@ -391,15 +424,10 @@ public class FoundationDbMessageStore {
}
public FoundationDbMessageStream getMessages(final AciServiceIdentifier aci, final byte deviceId) {
return getMessages(aci, deviceId, FoundationDbMessageStream.DEFAULT_MAX_MESSAGES_PER_SCAN, Util.NOOP);
return getMessages(aci, deviceId, Util.NOOP);
}
@VisibleForTesting
FoundationDbMessageStream getMessages(final AciServiceIdentifier aci,
final byte deviceId,
final int maxMessagesPerScan,
final Runnable doAfterCleanup) {
Database[] getDatabasesByEpochForAci(final AciServiceIdentifier aci) {
// For each configured database epoch, which database held (or holds) the messages for this ACI/device pair?
final Database[] databasesForQueueByEpoch = new Database[databasesByEpoch.length];
@@ -407,12 +435,21 @@ public class FoundationDbMessageStore {
databasesForQueueByEpoch[epoch] = getShardForAci(aci, epoch);
}
return databasesForQueueByEpoch;
}
@VisibleForTesting
FoundationDbMessageStream getMessages(final AciServiceIdentifier aci,
final byte deviceId,
final Runnable doAfterCleanup) {
final Database[] databasesForQueueByEpoch = getDatabasesByEpochForAci(aci);
return new FoundationDbMessageStream(this,
aci,
deviceId,
databasesForQueueByEpoch,
new MessageGuidCodec(aci.uuid(), deviceId, versionstampUUIDCipher),
maxMessagesPerScan,
doAfterCleanup,
presenceRenewalExecutorService,
clock);
@@ -466,17 +503,19 @@ public class FoundationDbMessageStore {
queueSubspacesToTrimByDatabase.forEach((database, queueSubspaces) -> {
// It's OK that this puts reading the versionstamp in a separate transaction from the deletes; versionstamp clock
// entries are effectively immutable and we're looking for one that was written presumably very far in the past,
// entries are effectively immutable, and we're looking for one that was written presumably very far in the past,
// so there's no conflict to avoid
versionstampClocks.get(database).getVersionstamp(cutoffTime).ifPresent(cutoffVersionstamp -> {
database.run(transaction -> {
transaction.options().setPriorityBatch();
for (final Subspace queueSubspace : queueSubspaces) {
transaction.clear(new Range(queueSubspace.getKey(), queueSubspace.pack(Tuple.from(cutoffVersionstamp))));
}
return null;
});
});
versionstampClocks.get(database).getVersionstamp(cutoffTime).ifPresent(cutoffVersionstamp ->
database.run(transaction -> {
transaction.options().setPriorityBatch();
transaction.options().setTimeout(batchPriorityTransactionTimeout.toMillis());
transaction.options().setRetryLimit(batchPriorityTransactionRetryLimit);
for (final Subspace queueSubspace : queueSubspaces) {
transaction.clear(
new Range(queueSubspace.getKey(), queueSubspace.pack(Tuple.from(cutoffVersionstamp))));
}
return null;
}));
});
}
@@ -527,7 +566,6 @@ public class FoundationDbMessageStore {
return versionstamp.getUserVersion() & 0x3f;
}
@VisibleForTesting
static Subspace getDeviceQueueSubspace(final AciServiceIdentifier aci, final byte deviceId) {
return getDeviceSubspace(aci, deviceId).get("Q");
}
@@ -536,6 +574,149 @@ public class FoundationDbMessageStore {
return getAccountSubspace(aci).get(deviceId);
}
@VisibleForTesting
record QueueSizeAndRangeSplitPoints(long estimatedQueueSize, Map<Database, List<byte[]>> splitPointsByDatabase) {}
private Flux<Database> getDistinctDatabasesForAci(final AciServiceIdentifier aci) {
return Flux.fromStream(Arrays.stream(getDatabasesByEpochForAci(aci)).filter(Objects::nonNull).distinct());
}
/// Estimates the size of the provided queue in bytes.
///
/// @param aci The ACI of the message queue to estimate the size of
/// @param deviceId The device ID of the message queue to estimate the size of
@VisibleForTesting
Mono<Long> estimateQueueSize(final AciServiceIdentifier aci, final byte deviceId) {
final Range deviceQueueRange = getDeviceQueueSubspace(aci, deviceId).range();
return getDistinctDatabasesForAci(aci)
.flatMap(database -> Mono.fromFuture(() -> FoundationDbUtil.safeRunAsync(database, transaction -> transaction.getEstimatedRangeSizeBytes(deviceQueueRange))))
.reduce(0L, Long::sum);
}
/// Estimates the size of the provided queue in bytes and computes a set of keys per database that split the range
/// covered by the queue in that database into roughly equally sized chunks.
///
/// @param aci The ACI of the message queue to estimate the size of
/// @param deviceId The device ID of the message queue to estimate the size of
/// @param rangeSplitChunkSize The approximate chunk size in bytes used to split the range covered by the message queue
@VisibleForTesting
Mono<QueueSizeAndRangeSplitPoints> estimateQueueSizeAndSplitPoints(
final AciServiceIdentifier aci,
final byte deviceId,
final long rangeSplitChunkSize) {
return getDistinctDatabasesForAci(aci)
.flatMap(database -> Mono.fromFuture(() -> estimateQueueSizeAndRangeSplitsForDatabase(database, aci, deviceId, rangeSplitChunkSize))
.map(pair -> Tuples.of(pair.first(), database, pair.second().getKeys())))
.collect(Collectors.teeing(
Collectors.summingLong(Tuple3::getT1),
Collectors.toMap(Tuple3::getT2, Tuple3::getT3),
QueueSizeAndRangeSplitPoints::new));
}
private CompletableFuture<Pair<Long, KeyArrayResult>> estimateQueueSizeAndRangeSplitsForDatabase(
final Database database,
final AciServiceIdentifier aci,
final byte deviceId,
final long rangeSplitChunkSize) {
return FoundationDbUtil.safeRunAsync(database, transaction -> {
final Range deviceQueueRange = getDeviceQueueSubspace(aci, deviceId).range();
final CompletableFuture<Long> estimatedQueueSizeFuture = transaction.getEstimatedRangeSizeBytes(deviceQueueRange);
final CompletableFuture<KeyArrayResult> rangeSplitPointsFuture = transaction.getRangeSplitPoints(deviceQueueRange, rangeSplitChunkSize);
return estimatedQueueSizeFuture.thenCombine(rangeSplitPointsFuture, Pair::new);
});
}
public Mono<Void> trimQueue(final AciServiceIdentifier aci,
final Device device,
final long maxQueueSizeBytes,
final long targetQueueSizeBytes,
final long rangeSplitChunkSizeBytes,
final UnaryOperator<Mono<Boolean>> deleteModifier) {
final Tag platformTag = Tag.of("platform", DevicePlatformUtil.getDevicePlatform(device)
.map(platform -> platform.name().toLowerCase(Locale.ROOT))
.orElse("unknown"));
return estimateQueueSizeAndSplitPoints(aci, device.getId(), rangeSplitChunkSizeBytes)
.doOnNext(queueSizeAndRangeSplitPoints ->
DistributionSummary.builder(QUEUE_SIZE_DISTRIBUTION_SUMMARY_NAME)
.tags(Tags.of(platformTag))
.register(Metrics.globalRegistry)
.record(queueSizeAndRangeSplitPoints.estimatedQueueSize()))
.flatMap(queueSizeAndRangeSplits -> {
if (queueSizeAndRangeSplits.estimatedQueueSize() < maxQueueSizeBytes) {
Metrics.counter(TRIM_QUEUE_COUNTER_NAME, "needed", "false").increment();
return Mono.empty();
}
final List<Database> orderedDatabases;
{
// Trim messages from the database(s) in the inactive epoch(s) before trimming from the database in the active epoch
final List<Integer> orderedEpochsToTrim = new ArrayList<>(Arrays.stream(liveEpochs)
.filter(i -> i != activeEpoch)
.boxed()
.toList());
orderedEpochsToTrim.add(activeEpoch);
orderedDatabases = orderedEpochsToTrim.stream().map(e -> getShardForAci(aci, e)).distinct().toList();
}
final Subspace deviceQueueSubspace = getDeviceQueueSubspace(aci, device.getId());
final AtomicLong remainingBytesToDelete = new AtomicLong(queueSizeAndRangeSplits.estimatedQueueSize() - targetQueueSizeBytes);
return Flux.fromIterable(orderedDatabases)
.concatMap(database -> {
if (remainingBytesToDelete.get() <= 0) {
return Mono.just(true);
}
// We used the same set of databases to compute the split points, so an entry must exist.
final List<byte[]> splitPoints = queueSizeAndRangeSplits.splitPointsByDatabase().get(database);
assert splitPoints.size() >= 2;
final int chunksToDelete = Math.min(Math.toIntExact(Math.ceilDiv(remainingBytesToDelete.get(), rangeSplitChunkSizeBytes)), splitPoints.size() - 1);
final byte[] endKeyExclusive = splitPoints.get(chunksToDelete);
// Trim the oldest messages in the queue.
final Range range = new Range(deviceQueueSubspace.range().begin, endKeyExclusive);
final Mono<Boolean> deleteMono = Mono.fromFuture(() -> trimQueue(database, range))
.doOnSuccess(_ -> {
final long estimatedDeletedBytes = chunksToDelete * rangeSplitChunkSizeBytes;
remainingBytesToDelete.addAndGet(-estimatedDeletedBytes);
ESTIMATED_TRIMMED_BYTES_COUNTER.increment(estimatedDeletedBytes);
})
.flatMap(_ -> Mono.just(true));
return deleteModifier.apply(deleteMono)
.onErrorResume(throwable -> {
LOGGER.warn("Failed to trim message queue for {}:{}", aci, device.getId(), throwable);
return Mono.just(false);
});
})
.reduce(true, (a, b) -> a && b)
.doOnSuccess(trimSucceeded -> Metrics.counter(TRIM_QUEUE_COUNTER_NAME, "needed", "true", "success", String.valueOf(trimSucceeded)).increment())
.then();
})
.onErrorResume(throwable -> {
// If we error out on estimating queue size, we don't know if this queue needed trimming
Metrics.counter(TRIM_QUEUE_COUNTER_NAME, "success", "false").increment();
LOGGER.warn("Failed to estimate queue size for {}:{}", aci, device.getId(), throwable);
return Mono.empty();
});
}
private CompletableFuture<Void> trimQueue(final Database database, final Range range) {
return FoundationDbUtil.safeRunAsync(database, transaction -> {
transaction.options().setPriorityBatch();
transaction.options().setTimeout(batchPriorityTransactionTimeout.toMillis());
transaction.options().setRetryLimit(batchPriorityTransactionRetryLimit);
transaction.clear(range);
return CompletableFuture.completedFuture(null);
});
}
private static Subspace getAccountSubspace(final AciServiceIdentifier aci) {
return MESSAGES_SUBSPACE.get(aci.uuid());
}
@@ -18,6 +18,7 @@ import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Flow;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicInteger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
@@ -44,12 +45,13 @@ public class FoundationDbMessageStream implements MessageStream {
private final Database[] databasesByEpoch;
private final MessageGuidCodec messageGuidCodec;
/// The maximum number of messages we will fetch per range query operation to avoid excessive memory consumption
private final int maxMessagesPerScan;
private final Flow.Publisher<MessageStreamEntry> messageStreamPublisher;
private final Runnable doAfterCleanup;
private final ScheduledExecutorService presenceRenewalExecutorService;
private final Clock clock;
private static final AtomicInteger NEXT_STREAM_ID = new AtomicInteger();
private final Counter messageReadCounter =
Metrics.counter(name(FoundationDbMessageStream.class, "messagesRead"));
@@ -59,11 +61,11 @@ public class FoundationDbMessageStream implements MessageStream {
private final Counter staleEphemeralMessagesCounter =
Metrics.counter(name(FoundationDbMessageStream.class, "staleEphemeralMessages"));
static final int DEFAULT_MAX_MESSAGES_PER_SCAN = 100;
private static final Comparator<FoundationDbMessageStreamEntry.Message> STREAM_ENTRY_TIMESTAMP_COMPARATOR =
Comparator.comparingLong(streamEntry -> streamEntry.partialEnvelope().getServerTimestamp());
private static final int PREFETCH = 128;
private static final Logger logger = LoggerFactory.getLogger(FoundationDbMessageStream.class);
FoundationDbMessageStream(final FoundationDbMessageStore foundationDbMessageStore,
@@ -71,7 +73,6 @@ public class FoundationDbMessageStream implements MessageStream {
final byte deviceId,
final Database[] databasesByEpoch,
final MessageGuidCodec messageGuidCodec,
final int maxMessagesPerScan,
final Runnable doAfterCleanup,
final ScheduledExecutorService presenceRenewalExecutorService,
final Clock clock) {
@@ -83,7 +84,6 @@ public class FoundationDbMessageStream implements MessageStream {
this.messagesAvailableWatchKey = FoundationDbMessageStore.getMessagesAvailableWatchKey(aciServiceIdentifier);
this.databasesByEpoch = databasesByEpoch;
this.messageGuidCodec = messageGuidCodec;
this.maxMessagesPerScan = maxMessagesPerScan;
this.messageStreamPublisher = JdkFlowAdapter.publisherToFlowPublisher(createMessagePublisher());
this.doAfterCleanup = doAfterCleanup;
this.presenceRenewalExecutorService = presenceRenewalExecutorService;
@@ -129,7 +129,7 @@ public class FoundationDbMessageStream implements MessageStream {
final List<Database> databases = Arrays.stream(databasesByEpoch).filter(Objects::nonNull).distinct().toList();
return Flux.fromIterable(databases)
.flatMap(database -> Mono.fromFuture(getEndOfQueueKeyExclusive(database))
.flatMap(database -> Mono.fromFuture(() -> getEndOfQueueKeyExclusive(database))
.map(maybeEndOfQueueKeyExclusive -> Tuples.of(database, maybeEndOfQueueKeyExclusive)))
.collectMap(Tuple2::getT1, Tuple2::getT2)
.flatMapMany(endOfQueueKeysByDatabase -> {
@@ -144,8 +144,7 @@ public class FoundationDbMessageStream implements MessageStream {
database,
clock,
KeySelector.firstGreaterOrEqual(deviceQueueSubspace.range().begin),
endOfQueueKeyExclusive,
maxMessagesPerScan)
endOfQueueKeyExclusive)
.getMessages())
.orElseGet(Flux::empty)
.handle((fdbMessageStreamEntry, sink) -> {
@@ -177,7 +176,7 @@ public class FoundationDbMessageStream implements MessageStream {
clock,
infinitePublisherBeginKey,
KeySelector.firstGreaterThan(deviceQueueSubspace.range().end),
maxMessagesPerScan,
NEXT_STREAM_ID.getAndIncrement(),
presenceKey,
presenceRenewalExecutorService,
messagesAvailableWatchKey).getMessages();
@@ -185,7 +184,7 @@ public class FoundationDbMessageStream implements MessageStream {
.toArray(Flux[]::new);
return Flux.concat(
Flux.mergeComparing(maxMessagesPerScan, STREAM_ENTRY_TIMESTAMP_COMPARATOR, finitePublishers),
Flux.mergeComparing(PREFETCH, STREAM_ENTRY_TIMESTAMP_COMPARATOR, finitePublishers),
Mono.just(new FoundationDbMessageStreamEntry.QueueEmpty()),
// Note that we use `mergePriority` instead of `mergeComparing` for the "live"/non-terminating publishers
@@ -196,7 +195,7 @@ public class FoundationDbMessageStream implements MessageStream {
// where messages arrive at different servers while somebody is connected and a migration is in progress,
// but that should be (again) exceedingly rare and also minimally-disruptive (i.e. it would self-correct
// so quickly that end users would likely never even notice).
Flux.mergePriority(maxMessagesPerScan, STREAM_ENTRY_TIMESTAMP_COMPARATOR, infinitePublishers));
Flux.mergePriority(PREFETCH, STREAM_ENTRY_TIMESTAMP_COMPARATOR, infinitePublishers));
});
}
@@ -206,7 +205,7 @@ public class FoundationDbMessageStream implements MessageStream {
///
/// @return a [KeySelector] for the first key greater than the current greatest key in the device queue.
private CompletableFuture<Optional<KeySelector>> getEndOfQueueKeyExclusive(final Database database) {
return database.runAsync(transaction ->
return FoundationDbUtil.safeRunAsync(database, transaction ->
transaction.getRange(deviceQueueSubspace.range(), 1, true, StreamingMode.EXACT).asList())
.<Optional<KeySelector>>thenApply(items -> {
if (items.isEmpty()) {
@@ -0,0 +1,24 @@
package org.whispersystems.textsecuregcm.storage.foundationdb;
import com.apple.foundationdb.Database;
import com.apple.foundationdb.Transaction;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
public class FoundationDbUtil {
/// Returns a cancellation-safe version of the result from [Database#runAsync(Function)]. Since the final stage
/// of the result from [Database#runAsync(Function)] is a cleanup stage that closes the transaction, the
/// transaction leaks if the future gets cancelled and the cleanup stage is skipped. So, we add another dummy stage
/// that serves as the cancellation target and the cleanup can proceed as normal.
///
/// @param database the FoundationDB database instance
/// @param retryable the block of transaction logic to execute
/// @param <T> the return type of retryable
/// @return a cancellation-safe version of the future returned from [Database#runAsync(Function)]
public static <T> CompletableFuture<T> safeRunAsync(final Database database,
final Function<? super Transaction, ? extends CompletableFuture<T>> retryable) {
return database.runAsync(retryable)
.thenApply(Function.identity());
}
}
@@ -285,7 +285,6 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor {
.orElse(AcknowledgementState.UNSPECIFIED);
if (acknowledgementState != AcknowledgementState.ACKNOWLEDGED) {
// We should only ever generate receipts for a stored and acknowledged token.
logger.error("Tried to fetch receipt for purchaseToken {} that was never acknowledged", purchaseToken);
throw new IllegalStateException("Tried to fetch receipt for purchaseToken that was never acknowledged");
}
@@ -95,7 +95,9 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
final byte[] idempotencyKeyGenerator,
final String boostDescription,
final Map<PaymentMethod, Set<String>> supportedCurrenciesByPaymentMethod) {
Stripe.setAppInfo("Signal-Server", WhisperServerVersion.getServerVersion());
Stripe.enableTelemetry = false;
this.stripeClient = Objects.requireNonNull(stripeClient);
this.executor = Objects.requireNonNull(executor);
@@ -6,6 +6,7 @@ package org.whispersystems.textsecuregcm.subscriptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.util.logging.ImpossibleEvents;
public enum SubscriptionStatus {
/**
@@ -55,7 +56,7 @@ public enum SubscriptionStatus {
case "trialing" -> {
final Logger logger = LoggerFactory.getLogger(CustomerAwareSubscriptionPaymentProcessor.class);
logger.error("Subscription has status that should never happen: {}", status);
ImpossibleEvents.logImpossible(logger, "Subscription has status that should never happen: {}", status);
yield UNKNOWN;
}
@@ -13,6 +13,7 @@ import java.util.concurrent.atomic.AtomicInteger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.util.logging.ImpossibleEvents;
/**
* A thread factory that creates virtual threads but limits the total number of virtual threads created.
@@ -87,7 +88,7 @@ public class BoundedVirtualThreadFactory implements ThreadFactory {
private void release() {
int updated = runningThreads.decrementAndGet();
if (updated < 0) {
logger.error("Released a thread and count was {}, which should never happen", updated);
ImpossibleEvents.logImpossible(logger, "Released a thread and count was {}, which should never happen", updated);
}
completed.increment();
}
@@ -109,8 +109,9 @@ public final class HeaderUtils {
Tag.of("path", containerRequestContext.getUriInfo().getPath())))
.increment();
logger.debug("Could not get acceptable languages; Accept-Language: {}; User-Agent: {}",
containerRequestContext.getHeaderString(HttpHeaders.ACCEPT_LANGUAGE),
userAgent,
// Strip any control codes to avoid any weird formatting with console loggers
containerRequestContext.getHeaderString(HttpHeaders.ACCEPT_LANGUAGE).replaceAll("\\p{Cntrl}", ""),
userAgent.replaceAll("\\p{Cntrl}", ""),
e);
return List.of();
@@ -0,0 +1,30 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.util.logging;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Metrics;
import net.logstash.logback.marker.Markers;
import org.slf4j.Logger;
import org.slf4j.Marker;
/// Log errors that represent a programming logic error
public final class ImpossibleEvents {
private static final Marker IMPOSSIBLE = Markers.append("impossible", true);
private static final Counter COUNTER = Metrics.counter(name(ImpossibleEvents.class, "count"));
private ImpossibleEvents() {
}
/// Log that an event should never happen.
public static void logImpossible(final Logger logger, final String message, final Object... args) {
COUNTER.increment();
logger.error(IMPOSSIBLE, message, args);
}
}
@@ -57,7 +57,8 @@ public class LoggingUnhandledExceptionMapper extends LoggingExceptionMapper<Thro
super.formatLogMessage(id, exception),
requestMethod,
requestPath,
userAgent) ;
// Strip any control codes to avoid any weird formatting with console loggers
userAgent.replaceAll("\\p{Cntrl}", ""));
}
}
@@ -155,6 +155,10 @@ public record CommandDependencies(
try {
final Database database = entry.getValue().build(fdb);
database.options().setMaxWatches(configuration.getFoundationDbMessagesConfiguration().maxWatchesPerClient());
database.options().setTransactionTimeout(
configuration.getFoundationDbMessagesConfiguration().transactionTimeout().toMillis());
database.options().setTransactionRetryLimit(
configuration.getFoundationDbMessagesConfiguration().transactionRetryLimit());
return database;
} catch (final IOException e) {
@@ -319,7 +323,9 @@ public record CommandDependencies(
new VersionstampUUIDCipher(configuration.getFoundationDbMessagesConfiguration().currentVersionstampCipherKey(),
configuration.getFoundationDbMessagesConfiguration().versionstampCipherKeys().get(configuration.getFoundationDbMessagesConfiguration().currentVersionstampCipherKey()).value()),
presenceRenewalExecutor,
Clock.systemUTC());
Clock.systemUTC(),
configuration.getFoundationDbMessagesConfiguration().batchPriorityTransactionTimeout(),
configuration.getFoundationDbMessagesConfiguration().batchPriorityTransactionRetryLimit());
ProfilesManager profilesManager = new ProfilesManager(profilesV1, profiles, profileAvatars, cacheCluster, retryExecutor, asyncCdnS3Client,
configuration.getCdnConfiguration().bucket());
ReportMessageDynamoDb reportMessageDynamoDb = new ReportMessageDynamoDb(dynamoDbClient, dynamoDbAsyncClient,
@@ -76,7 +76,7 @@ public class RemoveExpiredAccountsCommand extends AbstractSinglePassCrawlAccount
.doOnSuccess(ignored -> deletedAccountCounter.increment())
.retryWhen(Retry.backoff(8, Duration.ofSeconds(1)).maxBackoff(Duration.ofSeconds(4)))
.onErrorResume(throwable -> {
log.warn("Failed to delete account {}", expiredAccount.getUuid(), throwable);
log.warn("Failed to delete account {}", expiredAccount.getAccountIdentifier(), throwable);
return Mono.empty();
});
}, MAX_CONCURRENCY)
@@ -116,7 +116,7 @@ public class RemoveExpiredLinkedDevicesCommand extends AbstractSinglePassCrawlAc
return accountUpdate
.doOnNext(successCounter::increment)
.onErrorResume(t -> {
logger.warn("Failed to remove expired linked devices for {}", account.getUuid(), t);
logger.warn("Failed to remove expired linked devices for {}", account.getAccountIdentifier(), t);
return Mono.empty();
});
}, maxConcurrency)
@@ -136,7 +136,7 @@ public class RemoveExpiredLinkedDevicesCommand extends AbstractSinglePassCrawlAc
.doAfterRetry(ignored -> retryCounter.increment())
.onRetryExhaustedThrow((spec, rs) -> rs.failure()))
.onErrorResume(t -> {
logger.info("Failed to remove expired linked device {}.{}", account.getUuid(), deviceId, t);
logger.info("Failed to remove expired linked device {}.{}", account.getAccountIdentifier(), deviceId, t);
errorCounter.increment();
return Mono.empty();
}),
@@ -97,7 +97,7 @@ public class RemoveExpiredUsernameHoldsCommand extends AbstractSinglePassCrawlAc
.retryWhen(Retry.backoff(3, Duration.ofSeconds(1)))
.doOnSuccess(ignored -> deletedHoldsCounter.increment(holdsToRemove))
.onErrorResume(throwable -> {
log.warn("Failed to purge {} expired holds on account {}", holdsToRemove, account.getUuid());
log.warn("Failed to purge {} expired holds on account {}", holdsToRemove, account.getAccountIdentifier());
return Mono.empty();
});
}, maxConcurrency)
@@ -0,0 +1,139 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.workers;
import com.google.common.annotations.VisibleForTesting;
import io.dropwizard.util.DataSize;
import io.micrometer.core.instrument.Metrics;
import net.sourceforge.argparse4j.inf.Subparser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.MessagesManager;
import org.whispersystems.textsecuregcm.util.Pair;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
public class TrimOversizedFoundationDbMessageQueuesCommand extends AbstractSinglePassCrawlAccountsCommand {
@VisibleForTesting
static final String DRY_RUN_ARGUMENT = "dry-run";
@VisibleForTesting
static final String MAX_CONCURRENCY_ARGUMENT = "max-concurrency";
@VisibleForTesting
static final String MAX_QUEUE_SIZE_BYTES_ARGUMENT = "max-queue-size-bytes";
@VisibleForTesting
static final String TARGET_QUEUE_SIZE_BYTES_ARGUMENT = "target-queue-size-bytes";
@VisibleForTesting
static final String RANGE_SPLIT_CHUNK_SIZE_BYTES_ARGUMENT = "range-split-chunk-size-bytes";
@VisibleForTesting
static final long DEFAULT_MAX_QUEUE_SIZE_BYTES = DataSize.gigabytes(10).toBytes();
@VisibleForTesting
static final long DEFAULT_TARGET_QUEUE_SIZE_BYTES = DataSize.gigabytes(9).toBytes();
@VisibleForTesting
static final long DEFAULT_RANGE_SPLIT_CHUNK_SIZE_BYTES = DataSize.gigabytes(1).toBytes();
private static final String QUEUES_INSPECTED_COUNTER_NAME = MetricsUtil.name(
TrimOversizedFoundationDbMessageQueuesCommand.class, "inspectedQueues");
private static final int DEFAULT_MAX_CONCURRENCY = 16;
private static final Logger LOGGER = LoggerFactory.getLogger(TrimOversizedFoundationDbMessageQueuesCommand.class);
public TrimOversizedFoundationDbMessageQueuesCommand() {
super("trim-oversized-fdb-message-queues", "Trims oversized message queues in FoundationDB");
}
@Override
public void configure(final Subparser subparser) {
super.configure(subparser);
subparser.addArgument("--dry-run")
.type(Boolean.class)
.dest(DRY_RUN_ARGUMENT)
.required(false)
.setDefault(true)
.help("If true, don't actually trim any message queues.");
subparser.addArgument("--max-concurrency")
.type(Integer.class)
.dest(MAX_CONCURRENCY_ARGUMENT)
.required(false)
.setDefault(DEFAULT_MAX_CONCURRENCY)
.help("Max concurrency for FoundationDB operations");
subparser.addArgument("--max-queue-size-bytes")
.type(Long.class)
.dest(MAX_QUEUE_SIZE_BYTES_ARGUMENT)
.required(false)
.setDefault(DEFAULT_MAX_QUEUE_SIZE_BYTES)
.help("If a message queue size exceeds this limit, trim it down.");
subparser.addArgument("--target-queue-size-bytes")
.type(Long.class)
.dest(TARGET_QUEUE_SIZE_BYTES_ARGUMENT)
.required(false)
.setDefault(DEFAULT_TARGET_QUEUE_SIZE_BYTES)
.help("If trimming a message queue, the queue size to target.");
subparser.addArgument("--range-split-chunk-size-bytes")
.type(Long.class)
.dest(RANGE_SPLIT_CHUNK_SIZE_BYTES_ARGUMENT)
.required(false)
.setDefault(DEFAULT_RANGE_SPLIT_CHUNK_SIZE_BYTES)
.help("""
The chunk size to use when determining split points for the range of keys covered by a message queue.
FoundationDB does not provide any documentation on this parameter, but observationally,
setting this value greater than 1 MB should be okay.
""");
}
@Override
protected void crawlAccounts(final Flux<Account> accounts) {
final long maxQueueSizeBytes = getNamespace().getLong(MAX_QUEUE_SIZE_BYTES_ARGUMENT);
final long targetQueueSizeBytes = getNamespace().getLong(TARGET_QUEUE_SIZE_BYTES_ARGUMENT);
final long rangeSplitChunkSizeBytes = getNamespace().getLong(RANGE_SPLIT_CHUNK_SIZE_BYTES_ARGUMENT);
if (targetQueueSizeBytes <= 0) {
throw new IllegalArgumentException("target-queue-size-bytes must be positive");
}
if (targetQueueSizeBytes >= maxQueueSizeBytes) {
throw new IllegalArgumentException("target-queue-size-bytes must be less than max-queue-size-bytes");
}
if (rangeSplitChunkSizeBytes <= 0) {
throw new IllegalArgumentException("range-split-chunk-size-bytes must be positive");
}
final boolean dryRun = getNamespace().getBoolean(DRY_RUN_ARGUMENT);
final int maxConcurrency = getNamespace().getInt(MAX_CONCURRENCY_ARGUMENT);
final MessagesManager messagesManager = getCommandDependencies().messagesManager();
accounts
.flatMapIterable(account ->
account.getDevices().stream().map(
device -> new Pair<>(new AciServiceIdentifier(account.getIdentifier(IdentityType.ACI)), device)).toList())
.doOnNext(_ -> Metrics.counter(QUEUES_INSPECTED_COUNTER_NAME, "dryRun", String.valueOf(dryRun)).increment())
.flatMap(accountAndDevice ->
messagesManager.trimQueue(accountAndDevice.first(), accountAndDevice.second(), maxQueueSizeBytes, targetQueueSizeBytes, rangeSplitChunkSizeBytes, dryRun),
maxConcurrency)
.onErrorResume(e -> {
LOGGER.error("Failed to trim queue", e);
return Mono.empty();
})
.then()
.block();
}
}
@@ -4,6 +4,8 @@ option java_multiple_files = true;
package org.signal.chat.account;
import "google/protobuf/empty.proto";
import "org/signal/chat/common.proto";
import "org/signal/chat/errors.proto";
import "org/signal/chat/messages.proto";
@@ -101,7 +103,7 @@ message GetAccountIdentityRequest {
}
message GetAccountIdentityResponse {
// A set of account identifiers for the authenticated account.
// The identifiers for the authenticated account.
common.AccountIdentifiers account_identifiers = 1;
}
@@ -112,7 +114,7 @@ message GetEntitlementsResponse {
message BadgeEntitlement {
// The id of the badge the account is entitled. Metadata to display for
// badges may be obtained by cross-referencing badge ids with
// ProductConfiguration.GetConfiguration.
// RemoteConfiguration.GetBadges.
string badge_id = 1;
// When the badge expires, in number of seconds since epoch
uint64 expiration_epoch_seconds = 2;
@@ -187,8 +189,7 @@ message ConfirmUsernameHashRequest {
message ConfirmUsernameHashResponse {
message ConfirmedUsernameHash {
// The newly-confirmed username hash.
bytes username_hash = 1;
reserved 1; // username_hash
// The server-generated username link handle for the newly-confirmed username.
bytes username_link_handle = 2;
@@ -242,16 +243,20 @@ message DeleteUsernameLinkResponse {
}
message ConfigureUnidentifiedAccessRequest {
// The key that other users must provide to interact with this account
// anonymously (i.e. to retrieve keys or profiles or to send messages) unless
// unrestricted unidentified access is permitted. Must be present if
// unrestricted unidentified access is not allowed.
bytes unidentified_access_key = 1 [(require.exactlySize) = 0, (require.exactlySize) = 16];
oneof configuration {
// The key that other users must provide to interact with this account
// anonymously (i.e. to retrieve keys or profiles or to send messages) unless
// unrestricted unidentified access is permitted. Must be present if
// unrestricted unidentified access is not allowed.
bytes unidentified_access_key = 1 [(require.exactlySize) = 16];
// If `true`, any user may interact with this account anonymously without
// providing an unidentified access key. Otherwise, users must provide the
// given unidentified access key to interact with this account anonymously.
bool allow_unrestricted_unidentified_access = 2;
// If set, any user may interact with this account anonymously without
// providing an unidentified access key. Otherwise, users must provide the
// given unidentified access key to interact with this account anonymously.
// Setting unrestricted unidentified access will clear any existing
// unidentified_access_key
google.protobuf.Empty allow_unrestricted_unidentified_access = 2;
}
}
message ConfigureUnidentifiedAccessResponse {
@@ -25,8 +25,10 @@ message ServiceIdentifier {
bytes uuid = 2 [(require.exactlySize) = 16];
}
// All identifiers associated with an account.
message AccountIdentifiers {
// A list of service identifiers for the identified account.
// A list of service identifiers for the identified account. Always includes
// exactly one ACI service identifier and one PNI service identifier.
repeated ServiceIdentifier service_identifiers = 1;
// The phone number associated with the identified account.
@@ -9,39 +9,30 @@ option java_multiple_files = true;
package org.signal.chat.purchase;
import "org/signal/chat/common.proto";
import "org/signal/chat/require.proto";
import "org/signal/chat/tag.proto";
import "org/signal/chat/subscriptions.proto";
// Retrieve product metadata for one-time donations, subscriptions, and backups
service ProductConfiguration {
option (require.auth) = AUTH_ONLY_AUTHENTICATED;
option (require.auth) = AUTH_ONLY_ANONYMOUS;
// Returns all configuration for badges, donation subscriptions, backup subscriptions, and one-time donation (
// "boost" and "gift") minimum and suggested amounts.
//
// Product descriptions may contain localized strings. Callers should set
// their language preferences via an "Accept-Language" header on the request
// https://datatracker.ietf.org/doc/html/rfc3282#section-3
// Returns configuration for donation subscriptions, backup subscriptions, and one-time donation (
// "boost" and "gift") minimum and suggested amounts. Badges are referenced by ID only; resolve those
// IDs to full badge details via RemoteConfiguration.GetBadges.
rpc GetConfiguration(GetConfigurationRequest) returns (GetConfigurationResponse) {}
}
message GetConfigurationRequest {
// If present, the etag from a prior GetConfigurationResponse. If the
// provided etag matches the current configuration etag, the server may elide
// the configuration response.
bytes etag = 1;
}
message GetConfigurationRequest {}
message GetConfigurationResponse {
oneof response {
// The full configuration and corresponding ETag.
TaggedConfiguration tagged_configuration = 1;
// The etag in the request matched the current configuration ETag
bool etag_matched = 2 [(tag.reason) = "etag_match"];
}
// Map of lower-cased ISO 3 currency codes to currency-specific configuration
map<string, CurrencyConfiguration> currencies = 1;
// Map of numeric donation level IDs to level-specific badge configuration
map<uint64, LevelConfiguration> badge_levels = 2;
// Configuration for backup subscription options
BackupConfiguration backup = 3;
// Maximum value of a one-time SEPA donation
string sepa_maximum_euros = 4;
}
message AmountList {
@@ -65,7 +56,9 @@ message CurrencyConfiguration {
}
message LevelConfiguration {
common.Badge badge = 1;
// The ID of the badge awarded at this level. Resolve to full badge details
// via RemoteConfiguration.GetBadges.
string badge_id = 1;
// The duration for which a badge is valid. Present only for
// one-time (boost, gift) badges
@@ -88,22 +81,3 @@ message BackupConfiguration {
// The number of days of media a free tier backup user gets
uint64 free_tier_media_days = 2;
}
message Configuration {
// Map of lower-cased ISO 3 currency codes to currency-specific configuration
map<string, CurrencyConfiguration> currencies = 1;
// Map of numeric donation level IDs to level-specific badge configuration
map<uint64, LevelConfiguration> badge_levels = 2;
// Configuration for backup subscription options
BackupConfiguration backup = 3;
// Maximum value of a one-time SEPA donation
string sepa_maximum_euros = 4;
}
message TaggedConfiguration {
Configuration configuration = 1;
// An entity tag for `configuration`. This may be used in subsequent
// requests for the configuration version to optimize bandwidth.
bytes etag = 2;
}
@@ -208,7 +208,7 @@ message AccountInfo {
// A list of the badges ids associated with the account. Metadata to display
// badges may be obtained by cross-referencing badge ids with
// ProductConfiguration.GetConfiguration.
// RemoteConfiguration.GetBadges.
repeated string badge_ids = 4;
}
@@ -0,0 +1,96 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
syntax = "proto3";
option java_multiple_files = true;
package org.signal.chat.remoteconfiguration;
import "org/signal/chat/common.proto";
import "org/signal/chat/require.proto";
import "org/signal/chat/tag.proto";
// Provides remote configuration applicable to the authenticated user
service RemoteConfiguration {
option (require.auth) = AUTH_ONLY_AUTHENTICATED;
// Fetches the configuration for the authenticated user. Returned
// values are based on the authenticated account and caller's client platform,
// which is derived from the "User-Agent" header.
rpc GetConfiguration(GetConfigurationRequest) returns (GetConfigurationResponse) {}
// Returns detailed information for all configured badges, keyed by badge ID.
//
// Badge descriptions may contain localized strings. Callers should set their
// language preferences via an "Accept-Language" header on the request
// https://datatracker.ietf.org/doc/html/rfc3282#section-3
//
// Callers may cache a badges result for up to 1 day before checking (via
// etag) if there are any new updates.
rpc GetBadges(GetBadgesRequest) returns (GetBadgesResponse) {}
}
message GetConfigurationRequest {
// If present, the etag from a prior GetConfigurationResponse. If the
// provided etag matches the current configuration etag, the server may elide
// the configuration response.
bytes etag = 1;
}
message GetConfigurationResponse {
oneof response {
// The full configuration and corresponding etag.
TaggedConfiguration tagged_configuration = 1;
// The etag in the request matched the current configuration etag.
bool etag_matched = 2 [(tag.reason) = "etag_match"];
}
}
message Configuration {
// A map of namespaced configuration keys to their resolved values. All
// configuration values are represented as strings. boolean values are
// represented as the strings "true" or "false".
map<string, string> configuration = 1;
}
message TaggedConfiguration {
Configuration configuration = 1;
// An entity tag for `configuration`. This may be supplied in a
// subsequent request to optimize bandwidth when the configuration has not
// changed.
bytes etag = 2;
}
message GetBadgesRequest {
// If present, the etag from a prior GetBadgesResponse. If the provided etag
// matches the current badge etag, the server may elide the badge response.
bytes etag = 1;
}
message GetBadgesResponse {
oneof response {
// The full set of badges and corresponding etag.
TaggedBadges tagged_badges = 1;
// The etag in the request matched the current badge etag.
bool etag_matched = 2 [(tag.reason) = "etag_match"];
}
}
message Badges {
// A map of badge ID to the detailed information for that badge.
map<string, common.Badge> badges = 1;
}
message TaggedBadges {
Badges badges = 1;
// An entity tag for `badges`. This may be supplied in a subsequent request
// to optimize bandwidth when the set of badges has not changed.
bytes etag = 2;
}
@@ -29,6 +29,7 @@ import org.eclipse.jetty.websocket.api.StatusCode;
import org.eclipse.jetty.websocket.client.WebSocketClient;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
@@ -78,6 +79,7 @@ public class GracefulShutdownIntegrationTest {
return new DropwizardTestSupport<>(TestApplication.class, configuration);
}
@Disabled("flaky: Sometimes (rarely) we do not see a close from jetty during shutdown. Requires investigation")
@ParameterizedTest
@ValueSource(booleans = {true, false})
void jettyClosesOpenWebsocketSessions(final boolean useH2) throws Exception {
@@ -153,7 +153,7 @@ class AccountAuthenticatorTest {
clock.unpin();
when(accountsManager.getByAccountIdentifier(uuid)).thenReturn(Optional.of(account));
when(account.getUuid()).thenReturn(uuid);
when(account.getAccountIdentifier()).thenReturn(uuid);
when(account.getIdentifier(IdentityType.ACI)).thenReturn(uuid);
when(account.getDevice(deviceId)).thenReturn(Optional.of(device));
when(account.getPrimaryDevice()).thenReturn(device);
@@ -181,7 +181,7 @@ class AccountAuthenticatorTest {
clock.unpin();
when(accountsManager.getByAccountIdentifier(uuid)).thenReturn(Optional.of(account));
when(account.getUuid()).thenReturn(uuid);
when(account.getAccountIdentifier()).thenReturn(uuid);
when(account.getIdentifier(IdentityType.ACI)).thenReturn(uuid);
when(account.getDevice(deviceId)).thenReturn(Optional.of(device));
when(account.getPrimaryDevice()).thenReturn(device);
@@ -210,7 +210,7 @@ class AccountAuthenticatorTest {
clock.unpin();
when(accountsManager.getByAccountIdentifier(uuid)).thenReturn(Optional.of(account));
when(account.getUuid()).thenReturn(uuid);
when(account.getAccountIdentifier()).thenReturn(uuid);
when(account.getIdentifier(IdentityType.ACI)).thenReturn(uuid);
when(account.getDevice(deviceId)).thenReturn(Optional.of(authenticatedDevice));
when(account.getPrimaryDevice()).thenReturn(authenticatedDevice);
@@ -250,7 +250,7 @@ class AccountAuthenticatorTest {
clock.unpin();
when(accountsManager.getByAccountIdentifier(uuid)).thenReturn(Optional.of(account));
when(account.getUuid()).thenReturn(uuid);
when(account.getAccountIdentifier()).thenReturn(uuid);
when(account.getIdentifier(IdentityType.ACI)).thenReturn(uuid);
when(account.getDevice(deviceId)).thenReturn(Optional.of(device));
when(account.getPrimaryDevice()).thenReturn(device);
@@ -277,7 +277,7 @@ class AccountAuthenticatorTest {
clock.unpin();
when(accountsManager.getByAccountIdentifier(uuid)).thenReturn(Optional.of(account));
when(account.getUuid()).thenReturn(uuid);
when(account.getAccountIdentifier()).thenReturn(uuid);
when(account.getIdentifier(IdentityType.ACI)).thenReturn(uuid);
when(account.getDevice(deviceId)).thenReturn(Optional.of(device));
when(account.getPrimaryDevice()).thenReturn(device);
@@ -59,7 +59,7 @@ class CertificateGeneratorTest {
SIGNING_CERTIFICATE_DATA, SIGNING_KEY, 1, embedSigner);
when(account.getIdentityKey(IdentityType.ACI)).thenReturn(IDENTITY_KEY);
when(account.getUuid()).thenReturn(ACI);
when(account.getAccountIdentifier()).thenReturn(ACI);
when(account.getNumber()).thenReturn(E164);
final byte[] contents = certificateGenerator.createFor(account, deviceId, includeE164);
@@ -9,8 +9,10 @@ import static org.assertj.core.api.Assertions.assertThat;
import java.time.Instant;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
@@ -44,11 +46,11 @@ public class ExternalServiceCredentialsSelectorTest {
private static ExternalServiceCredentials atTime(
final ExternalServiceCredentialsGenerator gen,
final long deltaMillis,
final long deltaSeconds,
final UUID identity) {
final Instant old = CLOCK.instant();
try {
CLOCK.incrementMillis(deltaMillis);
CLOCK.incrementMillis(deltaSeconds * 1000);
return gen.generateForUuid(identity);
} finally {
CLOCK.setTimeInstant(old);
@@ -63,7 +65,7 @@ public class ExternalServiceCredentialsSelectorTest {
void single() {
final ExternalServiceCredentials cred = GEN1.generateForUuid(UUID1);
var result = ExternalServiceCredentialsSelector.check(
List.of(token(cred)), GEN1, TimeUnit.MINUTES.toSeconds(1));
Set.of(token(cred)), GEN1, TimeUnit.MINUTES.toSeconds(1));
assertThat(result).singleElement()
.matches(CredentialInfo::valid)
.matches(info -> info.credentials().equals(cred));
@@ -77,9 +79,9 @@ public class ExternalServiceCredentialsSelectorTest {
final ExternalServiceCredentials cred2New = GEN1.generateForUuid(UUID2);
final ExternalServiceCredentials cred2Old = atTime(GEN1, -1, UUID2);
final List<String> tokens = Stream.of(cred1New, cred1Old, cred2New, cred2Old)
final Set<String> tokens = Stream.of(cred1New, cred1Old, cred2New, cred2Old)
.map(ExternalServiceCredentialsSelectorTest::token)
.toList();
.collect(Collectors.toSet());
final List<CredentialInfo> result = ExternalServiceCredentialsSelector.check(tokens, GEN1,
TimeUnit.MINUTES.toSeconds(1));
@@ -99,7 +101,7 @@ public class ExternalServiceCredentialsSelectorTest {
final ExternalServiceCredentials gen2Cred = GEN2.generateForUuid(UUID1);
final List<CredentialInfo> result = ExternalServiceCredentialsSelector.check(
List.of(token(gen1Cred), token(gen2Cred)),
Set.of(token(gen1Cred), token(gen2Cred)),
GEN2,
TimeUnit.MINUTES.toSeconds(1));
@@ -120,7 +122,7 @@ public class ExternalServiceCredentialsSelectorTest {
void invalidCredentials(final String invalidCredential) {
final ExternalServiceCredentials validCredential = GEN1.generateForUuid(UUID1);
var result = ExternalServiceCredentialsSelector.check(
List.of(invalidCredential, token(validCredential)), GEN1, TimeUnit.MINUTES.toSeconds(1));
Set.of(invalidCredential, token(validCredential)), GEN1, TimeUnit.MINUTES.toSeconds(1));
assertThat(result).hasSize(2);
assertThat(result).filteredOn(CredentialInfo::valid).singleElement()
.matches(info -> info.credentials().equals(validCredential));
@@ -74,7 +74,7 @@ class RegistrationLockVerificationManagerTest {
account = mock(Account.class);
final UUID accountIdentifier = UUID.randomUUID();
when(account.getUuid()).thenReturn(accountIdentifier);
when(account.getAccountIdentifier()).thenReturn(accountIdentifier);
when(account.getIdentifier(IdentityType.ACI)).thenReturn(accountIdentifier);
when(account.getNumber()).thenReturn("+18005551212");
when(account.getDevices()).thenReturn(List.of(device));
@@ -106,7 +106,7 @@ class RegistrationLockVerificationManagerTest {
} else {
verify(registrationRecoveryPasswordsManager, never()).remove(any());
}
verify(disconnectionRequestManager).requestDisconnection(account.getUuid(), List.of(Device.PRIMARY_ID));
verify(disconnectionRequestManager).requestDisconnection(account.getAccountIdentifier(), List.of(Device.PRIMARY_ID));
try {
verify(pushNotificationManager).sendAttemptLoginNotification(any(), eq("failedRegistrationLock"));
} catch (final NotPushRegisteredException ignored) {
@@ -111,7 +111,7 @@ public class BackupAuthManagerTest {
final BackupAuthManager authManager = create();
final Account account = mock(Account.class);
when(account.getUuid()).thenReturn(aci);
when(account.getAccountIdentifier()).thenReturn(aci);
when(account.getIdentifier(IdentityType.ACI)).thenReturn(aci);
AccountsHelper.setupMockGet(accountsManager, account);
@@ -556,7 +556,7 @@ public class BackupAuthManagerTest {
private final Account account = mock(Account.class);
MockAccountBuilder() {
when(account.getUuid()).thenReturn(aci);
when(account.getAccountIdentifier()).thenReturn(aci);
}
MockAccountBuilder backupLevel(BackupLevel backupLevel) {
@@ -70,7 +70,7 @@ public class BackupAuthTestUtil {
final BackupAuthManager issuer = new BackupAuthManager(
mock(ExperimentEnrollmentManager.class), null, null, null, null, params, clock);
Account account = mock(Account.class);
when(account.getUuid()).thenReturn(aci);
when(account.getAccountIdentifier()).thenReturn(aci);
when(account.getBackupCredentialRequest(any())).thenReturn(Optional.of(request.serialize()));
when(account.getBackupVoucher()).thenReturn(switch (backupLevel) {
case FREE -> null;
@@ -57,6 +57,7 @@ public class Cdn3RemoteStorageManagerTest {
Map.of(2, "gcs", 3, "r2"),
2,
null,
null,
null));
}
@@ -5,14 +5,14 @@
package org.whispersystems.textsecuregcm.configuration;
import org.junit.jupiter.api.Test;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretBytes;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretBytes;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
class FoundationDbMessagesConfigurationTest {
@@ -24,7 +24,11 @@ class FoundationDbMessagesConfigurationTest {
0,
Map.of(0, new SecretBytes(TestRandomUtil.nextBytes(16))),
0,
FoundationDbMessagesConfiguration.DEFAULT_MAX_WATCHES_PER_CLIENT
FoundationDbMessagesConfiguration.DEFAULT_MAX_WATCHES_PER_CLIENT,
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_TIMEOUT,
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT,
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_TIMEOUT.multipliedBy(2),
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT * 2
).isEveryEpochClusterConfigured());
assertFalse(new FoundationDbMessagesConfiguration(
@@ -33,7 +37,11 @@ class FoundationDbMessagesConfigurationTest {
0,
Map.of(0, new SecretBytes(TestRandomUtil.nextBytes(16))),
0,
FoundationDbMessagesConfiguration.DEFAULT_MAX_WATCHES_PER_CLIENT
FoundationDbMessagesConfiguration.DEFAULT_MAX_WATCHES_PER_CLIENT,
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_TIMEOUT,
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT,
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_TIMEOUT.multipliedBy(2),
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT * 2
).isEveryEpochClusterConfigured());
}
@@ -45,7 +53,11 @@ class FoundationDbMessagesConfigurationTest {
0,
Map.of(0, new SecretBytes(TestRandomUtil.nextBytes(16))),
0,
FoundationDbMessagesConfiguration.DEFAULT_MAX_WATCHES_PER_CLIENT
FoundationDbMessagesConfiguration.DEFAULT_MAX_WATCHES_PER_CLIENT,
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_TIMEOUT,
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT,
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_TIMEOUT.multipliedBy(2),
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT * 2
).isEveryEpochFreeOfDuplicates());
assertFalse(new FoundationDbMessagesConfiguration(
@@ -54,7 +66,11 @@ class FoundationDbMessagesConfigurationTest {
0,
Map.of(0, new SecretBytes(TestRandomUtil.nextBytes(16))),
0,
FoundationDbMessagesConfiguration.DEFAULT_MAX_WATCHES_PER_CLIENT
FoundationDbMessagesConfiguration.DEFAULT_MAX_WATCHES_PER_CLIENT,
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_TIMEOUT,
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT,
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_TIMEOUT.multipliedBy(2),
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT * 2
).isEveryEpochFreeOfDuplicates());
}
@@ -66,7 +82,11 @@ class FoundationDbMessagesConfigurationTest {
0,
Map.of(0, new SecretBytes(TestRandomUtil.nextBytes(16))),
0,
FoundationDbMessagesConfiguration.DEFAULT_MAX_WATCHES_PER_CLIENT
FoundationDbMessagesConfiguration.DEFAULT_MAX_WATCHES_PER_CLIENT,
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_TIMEOUT,
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT,
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_TIMEOUT.multipliedBy(2),
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT * 2
).isActiveEpochConfigured());
assertFalse(new FoundationDbMessagesConfiguration(
@@ -75,7 +95,11 @@ class FoundationDbMessagesConfigurationTest {
1,
Map.of(0, new SecretBytes(TestRandomUtil.nextBytes(16))),
0,
FoundationDbMessagesConfiguration.DEFAULT_MAX_WATCHES_PER_CLIENT
FoundationDbMessagesConfiguration.DEFAULT_MAX_WATCHES_PER_CLIENT,
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_TIMEOUT,
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT,
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_TIMEOUT.multipliedBy(2),
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT * 2
).isActiveEpochConfigured());
}
@@ -87,7 +111,11 @@ class FoundationDbMessagesConfigurationTest {
0,
Map.of(0, new SecretBytes(TestRandomUtil.nextBytes(16))),
0,
FoundationDbMessagesConfiguration.DEFAULT_MAX_WATCHES_PER_CLIENT
FoundationDbMessagesConfiguration.DEFAULT_MAX_WATCHES_PER_CLIENT,
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_TIMEOUT,
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT,
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_TIMEOUT.multipliedBy(2),
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT * 2
).isCurrentVersionstampCipherKeyConfigured());
assertFalse(new FoundationDbMessagesConfiguration(
@@ -96,7 +124,11 @@ class FoundationDbMessagesConfigurationTest {
0,
Map.of(0, new SecretBytes(TestRandomUtil.nextBytes(16))),
1,
FoundationDbMessagesConfiguration.DEFAULT_MAX_WATCHES_PER_CLIENT
FoundationDbMessagesConfiguration.DEFAULT_MAX_WATCHES_PER_CLIENT,
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_TIMEOUT,
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT,
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_TIMEOUT.multipliedBy(2),
FoundationDbMessagesConfiguration.DEFAULT_TRANSACTION_RETRY_LIMIT * 2
).isCurrentVersionstampCipherKeyConfigured());
}
}
@@ -185,7 +185,7 @@ class AccountControllerTest {
when(senderPinAccount.getRegistrationLock()).thenReturn(
new StoredRegistrationLock(Optional.empty(), Optional.empty(), Instant.ofEpochMilli(System.currentTimeMillis())));
when(senderHasStorage.getUuid()).thenReturn(UUID.randomUUID());
when(senderHasStorage.getAccountIdentifier()).thenReturn(UUID.randomUUID());
when(senderHasStorage.hasCapability(DeviceCapability.STORAGE)).thenReturn(true);
when(senderHasStorage.getRegistrationLock()).thenReturn(
new StoredRegistrationLock(Optional.empty(), Optional.empty(), Instant.ofEpochMilli(System.currentTimeMillis())));
@@ -194,12 +194,12 @@ class AccountControllerTest {
new StoredRegistrationLock(Optional.of(registrationLockCredentials.hash()),
Optional.of(registrationLockCredentials.salt()), Instant.ofEpochMilli(System.currentTimeMillis())));
when(senderRegLockAccount.getLastSeen()).thenReturn(System.currentTimeMillis());
when(senderRegLockAccount.getUuid()).thenReturn(SENDER_REG_LOCK_UUID);
when(senderRegLockAccount.getAccountIdentifier()).thenReturn(SENDER_REG_LOCK_UUID);
when(senderRegLockAccount.getNumber()).thenReturn(SENDER_REG_LOCK);
when(senderTransfer.getRegistrationLock()).thenReturn(
new StoredRegistrationLock(Optional.empty(), Optional.empty(), Instant.ofEpochMilli(System.currentTimeMillis())));
when(senderTransfer.getUuid()).thenReturn(SENDER_TRANSFER_UUID);
when(senderTransfer.getAccountIdentifier()).thenReturn(SENDER_TRANSFER_UUID);
when(senderTransfer.getNumber()).thenReturn(SENDER_TRANSFER);
when(accountsManager.getByE164(eq(SENDER_PIN))).thenReturn(Optional.of(senderPinAccount));
@@ -975,7 +975,7 @@ class AccountControllerTest {
void testLookupUsername() {
final Account account = mock(Account.class);
final UUID uuid = UUID.randomUUID();
when(account.getUuid()).thenReturn(uuid);
when(account.getAccountIdentifier()).thenReturn(uuid);
when(accountsManager.getByUsernameHash(any())).thenReturn(CompletableFuture.completedFuture(Optional.of(account)));
Response response = resources.getJerseyTest()
@@ -126,7 +126,7 @@ class AccountControllerV2Test {
final List<Device> devices = account.getDevices();
final Account updatedAccount = mock(Account.class);
when(updatedAccount.getUuid()).thenReturn(uuid);
when(updatedAccount.getAccountIdentifier()).thenReturn(uuid);
when(updatedAccount.getNumber()).thenReturn(number);
when(updatedAccount.getIdentityKey(IdentityType.PNI)).thenReturn(pniIdentityKey);
if (number.equals(account.getNumber())) {
@@ -469,13 +469,13 @@ class AccountControllerV2Test {
@ParameterizedTest
@ArgumentsSource(AccountsTestHelper.AccountsDataReportArgumentProvider.class)
void testGetAccountDataReport(final Account account, final String expectedTextAfterHeader) throws Exception {
when(AuthHelper.ACCOUNTS_MANAGER.getByAccountIdentifier(account.getUuid())).thenReturn(Optional.of(account));
when(accountsManager.getByAccountIdentifier(account.getUuid())).thenReturn(Optional.of(account));
when(AuthHelper.ACCOUNTS_MANAGER.getByAccountIdentifier(account.getAccountIdentifier())).thenReturn(Optional.of(account));
when(accountsManager.getByAccountIdentifier(account.getAccountIdentifier())).thenReturn(Optional.of(account));
final Response response = resources.getJerseyTest()
.target("/v2/accounts/data_report")
.request()
.header("Authorization", AuthHelper.getAuthHeader(account.getUuid(), "password"))
.header("Authorization", AuthHelper.getAuthHeader(account.getAccountIdentifier(), "password"))
.get();
assertEquals(200, response.getStatus());
@@ -138,7 +138,7 @@ class DeviceControllerTest {
when(account.getNextDeviceId()).thenReturn(NEXT_DEVICE_ID);
when(account.getNumber()).thenReturn(AuthHelper.VALID_NUMBER);
when(account.getUuid()).thenReturn(AuthHelper.VALID_UUID);
when(account.getAccountIdentifier()).thenReturn(AuthHelper.VALID_UUID);
when(account.getIdentifier(IdentityType.ACI)).thenReturn(AuthHelper.VALID_UUID);
when(account.getPhoneNumberIdentifier()).thenReturn(AuthHelper.VALID_PNI);
when(account.getIdentifier(IdentityType.PNI)).thenReturn(AuthHelper.VALID_PNI);
@@ -211,7 +211,7 @@ class KeysControllerTest {
when(KEYS.takeDevicePreKeys(eq(SAMPLE_DEVICE_ID), eq(EXISTS_PNI_SERVICE_ID), any()))
.thenReturn(CompletableFuture.completedFuture(Optional.of(pniKeys)));
when(existsAccount.getUuid()).thenReturn(EXISTS_UUID);
when(existsAccount.getAccountIdentifier()).thenReturn(EXISTS_UUID);
when(existsAccount.isIdentifiedBy(new AciServiceIdentifier(EXISTS_UUID))).thenReturn(true);
when(existsAccount.getPhoneNumberIdentifier()).thenReturn(EXISTS_PNI);
when(existsAccount.isIdentifiedBy(new PniServiceIdentifier(EXISTS_PNI))).thenReturn(true);
@@ -722,7 +722,7 @@ class MessageControllerTest {
UUID messageGuid = UUID.randomUUID();
final Account account = mock(Account.class);
when(account.getUuid()).thenReturn(senderAci);
when(account.getAccountIdentifier()).thenReturn(senderAci);
when(account.getNumber()).thenReturn(senderNumber);
when(account.getPhoneNumberIdentifier()).thenReturn(senderPni);
@@ -754,7 +754,7 @@ class MessageControllerTest {
UUID messageGuid = UUID.randomUUID();
final Account account = mock(Account.class);
when(account.getUuid()).thenReturn(senderAci);
when(account.getAccountIdentifier()).thenReturn(senderAci);
when(account.getNumber()).thenReturn(senderNumber);
when(account.getPhoneNumberIdentifier()).thenReturn(senderPni);
@@ -786,7 +786,7 @@ class MessageControllerTest {
UUID messageGuid = UUID.randomUUID();
final Account account = mock(Account.class);
when(account.getUuid()).thenReturn(senderAci);
when(account.getAccountIdentifier()).thenReturn(senderAci);
when(account.getNumber()).thenReturn(senderNumber);
when(account.getPhoneNumberIdentifier()).thenReturn(senderPni);
@@ -819,7 +819,7 @@ class MessageControllerTest {
final UUID messageGuid = UUID.randomUUID();
final Account account = mock(Account.class);
when(account.getUuid()).thenReturn(senderAci);
when(account.getAccountIdentifier()).thenReturn(senderAci);
when(account.getNumber()).thenReturn(senderNumber);
when(account.getPhoneNumberIdentifier()).thenReturn(senderPni);
@@ -851,7 +851,7 @@ class MessageControllerTest {
UUID messageGuid = UUID.randomUUID();
final Account account = mock(Account.class);
when(account.getUuid()).thenReturn(senderAci);
when(account.getAccountIdentifier()).thenReturn(senderAci);
when(account.getNumber()).thenReturn(senderNumber);
when(account.getPhoneNumberIdentifier()).thenReturn(senderPni);
@@ -914,7 +914,7 @@ class MessageControllerTest {
UUID messageGuid = UUID.randomUUID();
final Account account = mock(Account.class);
when(account.getUuid()).thenReturn(senderAci);
when(account.getAccountIdentifier()).thenReturn(senderAci);
when(account.getNumber()).thenReturn(senderNumber);
when(account.getPhoneNumberIdentifier()).thenReturn(senderPni);
@@ -211,7 +211,7 @@ class ProfileControllerTest {
when(profileAccount.getIdentityKey(IdentityType.ACI)).thenReturn(ACCOUNT_TWO_IDENTITY_KEY);
when(profileAccount.getIdentityKey(IdentityType.PNI)).thenReturn(ACCOUNT_TWO_PHONE_NUMBER_IDENTITY_KEY);
when(profileAccount.getUuid()).thenReturn(AuthHelper.VALID_UUID_TWO);
when(profileAccount.getAccountIdentifier()).thenReturn(AuthHelper.VALID_UUID_TWO);
when(profileAccount.getIdentifier(IdentityType.ACI)).thenReturn(AuthHelper.VALID_UUID_TWO);
when(profileAccount.getPhoneNumberIdentifier()).thenReturn(AuthHelper.VALID_PNI_TWO);
when(profileAccount.getCurrentProfileVersion()).thenReturn(Optional.empty());
@@ -222,7 +222,7 @@ class ProfileControllerTest {
capabilitiesAccount = mock(Account.class);
when(capabilitiesAccount.getUuid()).thenReturn(AuthHelper.VALID_UUID);
when(capabilitiesAccount.getAccountIdentifier()).thenReturn(AuthHelper.VALID_UUID);
when(capabilitiesAccount.getIdentifier(IdentityType.ACI)).thenReturn(AuthHelper.VALID_UUID);
when(capabilitiesAccount.getIdentityKey(IdentityType.ACI)).thenReturn(ACCOUNT_IDENTITY_KEY);
when(capabilitiesAccount.getIdentityKey(IdentityType.PNI)).thenReturn(ACCOUNT_PHONE_NUMBER_IDENTITY_KEY);
@@ -1037,7 +1037,7 @@ class ProfileControllerTest {
@Test
void testGetProfileWithExpiringProfileKeyCredentialVersionNotFound() throws VerificationFailedException {
final Account account = mock(Account.class);
when(account.getUuid()).thenReturn(AuthHelper.VALID_UUID);
when(account.getAccountIdentifier()).thenReturn(AuthHelper.VALID_UUID);
when(account.getIdentifier(IdentityType.ACI)).thenReturn(AuthHelper.VALID_UUID);
when(account.getCurrentProfileVersion()).thenReturn(Optional.of(version("version")));
@@ -1249,7 +1249,7 @@ class ProfileControllerTest {
final ProfileKeyCredentialRequest credentialRequest = profileKeyCredentialRequestContext.getRequest();
final Account account = mock(Account.class);
when(account.getUuid()).thenReturn(AuthHelper.VALID_UUID);
when(account.getAccountIdentifier()).thenReturn(AuthHelper.VALID_UUID);
when(account.getIdentifier(IdentityType.ACI)).thenReturn(AuthHelper.VALID_UUID);
when(account.getCurrentProfileVersion()).thenReturn(Optional.of(version));
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(UNIDENTIFIED_ACCESS_KEY));
@@ -1318,7 +1318,7 @@ class ProfileControllerTest {
final ProfileKeyCredentialRequest credentialRequest = profileKeyCredentialRequestContext.getRequest();
final Account account = mock(Account.class);
when(account.getUuid()).thenReturn(AuthHelper.VALID_UUID);
when(account.getAccountIdentifier()).thenReturn(AuthHelper.VALID_UUID);
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(UNIDENTIFIED_ACCESS_KEY));
when(account.isIdentifiedBy(new AciServiceIdentifier(AuthHelper.VALID_UUID))).thenReturn(true);
when(account.getCurrentProfileVersion()).thenReturn(Optional.of(version));
@@ -1366,7 +1366,7 @@ class ProfileControllerTest {
final ProfileKeyCredentialRequest credentialRequest = profileKeyCredentialRequestContext.getRequest();
final Account account = mock(Account.class);
when(account.getUuid()).thenReturn(AuthHelper.VALID_UUID);
when(account.getAccountIdentifier()).thenReturn(AuthHelper.VALID_UUID);
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(UNIDENTIFIED_ACCESS_KEY));
when(account.isIdentifiedBy(new AciServiceIdentifier(AuthHelper.VALID_UUID))).thenReturn(true);
when(account.getCurrentProfileVersion()).thenReturn(Optional.of(version("the-current-version")));
@@ -619,7 +619,7 @@ class RegistrationControllerTest {
final Device device = mock(Device.class);
final Account account = MockUtils.buildMock(Account.class, a -> {
when(a.getUuid()).thenReturn(accountIdentifier);
when(a.getAccountIdentifier()).thenReturn(accountIdentifier);
when(a.getPhoneNumberIdentifier()).thenReturn(phoneNumberIdentifier);
when(a.getPrimaryDevice()).thenReturn(device);
});
@@ -6,11 +6,8 @@
package org.whispersystems.textsecuregcm.controllers;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
@@ -19,32 +16,23 @@ import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
import io.dropwizard.testing.junit5.ResourceExtension;
import jakarta.ws.rs.core.EntityTag;
import jakarta.ws.rs.core.Response;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import org.assertj.core.data.Offset;
import java.util.TreeMap;
import java.util.stream.Collectors;
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.EnumSource;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.junitpioneer.jupiter.params.IntRangeSource;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.entities.RemoteConfigurationResponse;
import org.whispersystems.textsecuregcm.mappers.DeviceLimitExceededExceptionMapper;
import org.whispersystems.textsecuregcm.storage.RemoteConfig;
import org.whispersystems.textsecuregcm.storage.RemoteConfigsManager;
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
@ExtendWith(DropwizardExtensionsSupport.class)
class RemoteConfigControllerTest {
@@ -56,122 +44,14 @@ class RemoteConfigControllerTest {
.addProvider(new AuthValueFactoryProvider.Binder<>(AuthenticatedDevice.class))
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
.addProvider(new DeviceLimitExceededExceptionMapper())
.addResource(new RemoteConfigController(remoteConfigsManager, Map.of("maxGroupSize", "42")))
.addResource(new RemoteConfigController(remoteConfigsManager))
.build();
@BeforeEach
void setup() throws Exception {
when(remoteConfigsManager.getAll()).thenReturn(
List.of(
new RemoteConfig("android.stickers", 100, Set.of(), null, null, null),
new RemoteConfig("ios.stickers", 100, Set.of(), null, null, null),
new RemoteConfig("desktop.stickers", 100, Set.of(), null, null, null),
new RemoteConfig("always.true", 100, Set.of(), null, null, null),
new RemoteConfig("only.special", 0, Set.of(AuthHelper.VALID_UUID), null, null, null),
new RemoteConfig("value.always.true", 100, Set.of(), "foo", "bar", null),
new RemoteConfig("value.only.special", 0, Set.of(AuthHelper.VALID_UUID), "abc", "xyz", null),
new RemoteConfig("value.always.false", 0, Set.of(), "red", "green", null),
new RemoteConfig("linked.config.0", 50, Set.of(), null, null, null),
new RemoteConfig("linked.config.1", 50, Set.of(), null, null, "linked.config.0"),
new RemoteConfig("unlinked.config", 50, Set.of(), null, null, null)));
}
@AfterEach
void teardown() {
void setUp() {
reset(remoteConfigsManager);
}
@ParameterizedTest
@EnumSource
void testRetrieveConfig(ClientPlatform platform) {
RemoteConfigurationResponse configuration = resources.getJerseyTest()
.target("/v2/config/")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.header("User-Agent", String.format("Signal-%s/7.6.2", platform.name()))
.get(RemoteConfigurationResponse.class);
verify(remoteConfigsManager, times(1)).getAll();
assertThat(configuration.config()).hasSize(10);
assertThat(configuration.config()).containsKeys(platform.name().toLowerCase() + ".stickers", "linked.config.0", "linked.config.1", "unlinked.config");
assertThat(configuration.config()).contains(
entry("always.true", "true"),
entry("only.special", "true"),
entry("value.always.true", "bar"),
entry("value.only.special", "xyz"),
entry("value.always.false", "red"),
entry("global.maxGroupSize", "42"));
}
@ParameterizedTest
@EnumSource
void testRetrieveConfigNotSpecial(ClientPlatform platform) {
RemoteConfigurationResponse configuration = resources.getJerseyTest()
.target("/v2/config/")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID_TWO, AuthHelper.VALID_PASSWORD_TWO))
.header("User-Agent", String.format("Signal-%s/7.6.2", platform.name()))
.get(RemoteConfigurationResponse.class);
verify(remoteConfigsManager, times(1)).getAll();
assertThat(configuration.config()).hasSize(10);
assertThat(configuration.config()).containsKeys(platform.name().toLowerCase() + ".stickers", "linked.config.0", "linked.config.1", "unlinked.config");
assertThat(configuration.config()).contains(
entry("always.true", "true"),
entry("only.special", "false"),
entry("value.always.true", "bar"),
entry("value.only.special", "abc"),
entry("value.always.false", "red"),
entry("global.maxGroupSize", "42"));
}
@Test
void testRetrieveConfigUnrecognizedPlatform() {
RemoteConfigurationResponse configuration = resources.getJerseyTest()
.target("/v2/config/")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID_TWO, AuthHelper.VALID_PASSWORD_TWO))
.header("User-Agent", "Third-Party-Signal-Client/1.0.0")
.get(RemoteConfigurationResponse.class);
verify(remoteConfigsManager, times(1)).getAll();
assertThat(configuration.config()).hasSize(9);
assertThat(configuration.config()).containsKeys("linked.config.0", "linked.config.1", "unlinked.config");
assertThat(configuration.config()).contains(
entry("always.true", "true"),
entry("only.special", "false"),
entry("value.always.true", "bar"),
entry("value.only.special", "abc"),
entry("value.always.false", "red"),
entry("global.maxGroupSize", "42"));
}
@Test
void testHashKeyLinkedConfigs() {
boolean allUnlinkedConfigsMatched = true;
for (AuthHelper.TestAccount testAccount : AuthHelper.TEST_ACCOUNTS) {
RemoteConfigurationResponse configuration = resources.getJerseyTest()
.target("/v2/config/")
.request()
.header("Authorization", testAccount.getAuthHeader())
.get(RemoteConfigurationResponse.class);
assertThat(configuration.config().get("linked.config.0")).isEqualTo(configuration.config().get("linked.config.1"));
allUnlinkedConfigsMatched &= (configuration.config().get("linked.config.0").equals(configuration.config().get("unlinked.config")));
}
// with 20 test accounts, 1 in 2^20 chance that this fails when it shouldn't, but
// AuthHelper#generateTestAccounts uses a constant random seed that doesn't fail as of the time
// of this writing; if this starts failing for no apparent reason, it's likely that we've
// changed the order of the sequence of random numbers used during test initialization in such
// a way that we've accidentally picked an unlucky set of accounts here
assertThat(allUnlinkedConfigsMatched).isFalse();
}
@Test
void testRetrieveConfigUnauthorized() {
Response response = resources.getJerseyTest()
@@ -187,11 +67,15 @@ class RemoteConfigControllerTest {
@Test
void testRetrieveConfigUnchanged() {
final String userAgent = "user-agent";
when(remoteConfigsManager.getConfigForAccount(AuthHelper.VALID_UUID, userAgent))
.thenReturn(Map.of("test.test", "bar", "global.test", "false"));
Response response = resources.getJerseyTest()
.target("/v2/config/")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.header("User-Agent", "Signal-Android/7.6.2 Android/34 libsignal/0.46.0")
.header("User-Agent", userAgent)
.get();
assertThat(response.getStatus()).isEqualTo(200);
@@ -203,7 +87,7 @@ class RemoteConfigControllerTest {
.target("/v2/config/")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.header("User-Agent", "Signal-Android/7.6.2 Android/34 libsignal/0.46.0")
.header("User-Agent", userAgent)
.header("If-None-Match", etag)
.get();
@@ -213,6 +97,15 @@ class RemoteConfigControllerTest {
@Test
void testRetrieveConfigChanged() {
final String userAgent = "Signal-Android/7.6.2 Android/34 libsignal/0.46.0";
final Map<String, String> config1 = Map.of(
"android.stickers", "foo",
"test.test", "bar",
"global.test", "false");
when(remoteConfigsManager.getConfigForAccount(AuthHelper.VALID_UUID, userAgent)).thenReturn(config1);
Response response = resources.getJerseyTest()
.target("/v2/config/")
.request()
@@ -225,9 +118,10 @@ class RemoteConfigControllerTest {
final EntityTag etag = response.getEntityTag();
assertThat(etag).isNotNull();
final List<RemoteConfig> configs = new ArrayList<>(remoteConfigsManager.getAll());
configs.add(new RemoteConfig("android.new.config", 100, Set.of(), null, null, null));
when(remoteConfigsManager.getAll()).thenReturn(configs);
final Map<String, String> config2 = new HashMap<>(config1);
config2.put("android.new.config", "true");
when(remoteConfigsManager.getConfigForAccount(AuthHelper.VALID_UUID, userAgent)).thenReturn(config2);
response = resources.getJerseyTest()
.target("/v2/config/")
@@ -243,16 +137,18 @@ class RemoteConfigControllerTest {
@ParameterizedTest
@MethodSource
void testEtag(boolean expect304, String userAgent1, String authHeader1, String userAgent2, String authHeader2) {
// Use a deterministic config; account 1 is special, 2 and 3 are identical
List<RemoteConfig> configs = remoteConfigsManager.getAll().stream().filter(config -> config.getPercentage() == 0 || config.getPercentage() == 100).toList();
when(remoteConfigsManager.getAll()).thenReturn(configs);
void testEtag(boolean expect304, final Map<String, String> config1, Map<String, String> config2) {
final String ua1 = "user-agent-1";
final String ua2 = "user-agent-2";
when(remoteConfigsManager.getConfigForAccount(AuthHelper.VALID_UUID, ua1)).thenReturn(config1);
when(remoteConfigsManager.getConfigForAccount(AuthHelper.VALID_UUID_TWO, ua2)).thenReturn(config2);
Response response = resources.getJerseyTest()
.target("/v2/config/")
.request()
.header("Authorization", authHeader1)
.header("User-Agent", userAgent1)
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.header("User-Agent", ua1)
.get();
assertThat(response.getStatus()).isEqualTo(200);
@@ -263,8 +159,8 @@ class RemoteConfigControllerTest {
response = resources.getJerseyTest()
.target("/v2/config/")
.request()
.header("Authorization", authHeader2)
.header("User-Agent", userAgent2)
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID_TWO, AuthHelper.VALID_PASSWORD_TWO))
.header("User-Agent", ua2)
.header("If-None-Match", etag)
.get();
@@ -278,63 +174,23 @@ class RemoteConfigControllerTest {
}
static List<Arguments> testEtag() {
final String uuid1AuthHeader = AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD);
final String uuid2AuthHeader = AuthHelper.getAuthHeader(AuthHelper.VALID_UUID_TWO, AuthHelper.VALID_PASSWORD_TWO);
final String uuid3AuthHeader = AuthHelper.getAuthHeader(AuthHelper.VALID_UUID_3, AuthHelper.VALID_PASSWORD_3_PRIMARY);
final Map<String, String> config1 = Map.of(
"android.stickers", "foo",
"test.test", "bar",
"global.test", "false");
final Map<String, String> config2 = Map.of(
"android.stickers", "foo",
"test.test", "bar",
"global.test", "true");
final String ios762 = "Signal-iOS/7.6.2 iOS/18.5 libsignal/0.46.0";
final String android762 = "Signal-Android/7.6.2 Android/34 libsignal/0.46.0";
final String android763 = "Signal-Android/7.6.3 Android/34 libsignal/0.46.0";
// boolean is expect304
return List.of(
Arguments.argumentSet("User change", false, android762, uuid1AuthHeader, android762, uuid2AuthHeader),
Arguments.argumentSet("Irrelevant user change", true, android762, uuid2AuthHeader, android762, uuid3AuthHeader),
Arguments.argumentSet("User agent change", false, android762, uuid1AuthHeader, ios762, uuid1AuthHeader),
Arguments.argumentSet("Irrelevant user agent change", true, android762, uuid1AuthHeader, android763, uuid1AuthHeader)
Arguments.argumentSet("same", true, config1, config1),
Arguments.argumentSet("change", false, config1, config2),
Arguments.argumentSet("different sort", true,
new TreeMap<>(config1),
config1.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a,_) -> a, () -> new TreeMap<String, String>(Comparator.reverseOrder()))))
);
}
@ParameterizedTest
@IntRangeSource(from = 1, to = 99)
void testMath(int percentage) throws NoSuchAlgorithmException {
final MessageDigest digest = MessageDigest.getInstance("SHA-256");
final Random random = new Random(9424242L); // the seed value doesn't matter so much as it's constant to make the test not flaky
final int iterations = 10000;
int enabledCount = 0;
for (int i = 0; i < iterations; i++) {
if (RemoteConfigController.isInBucket(digest, AuthHelper.getRandomUUID(random), "test".getBytes(), percentage, Set.of())) {
enabledCount++;
}
}
// https://en.wikipedia.org/wiki/Binomial_distribution#Expected_value_and_variance
final double expectedCount = iterations * percentage / 100.0;
final double stdev = Math.sqrt(expectedCount * (1 - percentage / 100.0));
// 3 standard deviations = 99.73% chance of success for one bucket, 23.5%
// chance of any failure in 99 buckets; if this starts failing after a
// change, run it again with a few different random seeds to make sure it
// fails only about on about one seed in four
assertThat((double) enabledCount).isCloseTo(expectedCount, Offset.offset(3 * stdev));
}
@ParameterizedTest
@ValueSource(ints = {0, 100})
void testMathExactForZeroOrOneHundred(int percentage) throws NoSuchAlgorithmException {
final MessageDigest digest = MessageDigest.getInstance("SHA-256");
final Random random = new Random();
final int iterations = 10000;
int enabledCount = 0;
for (int i = 0; i < iterations; i++) {
if (RemoteConfigController.isInBucket(digest, AuthHelper.getRandomUUID(random), "test".getBytes(), percentage, Set.of())) {
enabledCount++;
}
}
assertThat(enabledCount).isEqualTo(iterations * percentage / 100);
}
}
@@ -211,6 +211,25 @@ public class SecureValueRecovery2ControllerTest {
}
}
@Test
public void testDuplicateTokens() {
CLOCK.setTimeMillis(dayToMillis(2));
// There's no good reason to do it, but the endpoint should handle a duplicated token in the request
final String duplicatedToken = token(USER_1, dayToMillis(1));
final AuthCheckRequest in = new AuthCheckRequest(E164_VALID, List.of(duplicatedToken, duplicatedToken));
final Response response = RESOURCES.getJerseyTest()
.target(pathPrefix + "/auth/check")
.request()
.post(Entity.entity(in, MediaType.APPLICATION_JSON));
try (response) {
assertEquals(200, response.getStatus());
assertEquals(Map.of(duplicatedToken, CheckStatus.MATCH), parseCheckResponse(response));
}
}
@Test
public void testHttpResponseCodeWhenInvalidNumber() {
final AuthCheckRequest in = new AuthCheckRequest(E164_INVALID, Collections.singletonList("1"));
@@ -366,7 +385,7 @@ public class SecureValueRecovery2ControllerTest {
private static Account account(final UUID uuid) {
final Account a = new Account();
a.setUuid(uuid);
a.setAccountIdentifier(uuid);
return a;
}
}
@@ -81,25 +81,25 @@ class ExperimentEnrollmentManagerTest {
.thenReturn(Optional.of(e164ExperimentEnrollmentConfiguration));
account = mock(Account.class);
when(account.getUuid()).thenReturn(ACCOUNT_UUID);
when(account.getAccountIdentifier()).thenReturn(ACCOUNT_UUID);
}
@Test
void testIsEnrolled_UuidExperiment() {
assertFalse(experimentEnrollmentManager.isEnrolled(account.getUuid(), UUID_EXPERIMENT_NAME));
assertFalse(experimentEnrollmentManager.isEnrolled(account.getAccountIdentifier(), UUID_EXPERIMENT_NAME));
assertFalse(
experimentEnrollmentManager.isEnrolled(account.getUuid(), UUID_EXPERIMENT_NAME + "-unrelated-experiment"));
experimentEnrollmentManager.isEnrolled(account.getAccountIdentifier(), UUID_EXPERIMENT_NAME + "-unrelated-experiment"));
when(uuidSelector.getUuids()).thenReturn(Set.of(ACCOUNT_UUID));
assertTrue(experimentEnrollmentManager.isEnrolled(account.getUuid(), UUID_EXPERIMENT_NAME));
assertTrue(experimentEnrollmentManager.isEnrolled(account.getAccountIdentifier(), UUID_EXPERIMENT_NAME));
when(uuidSelector.getUuids()).thenReturn(Collections.emptySet());
when(experimentEnrollmentConfiguration.getEnrollmentPercentage()).thenReturn(0);
assertFalse(experimentEnrollmentManager.isEnrolled(account.getUuid(), UUID_EXPERIMENT_NAME));
assertFalse(experimentEnrollmentManager.isEnrolled(account.getAccountIdentifier(), UUID_EXPERIMENT_NAME));
when(experimentEnrollmentConfiguration.getEnrollmentPercentage()).thenReturn(100);
assertTrue(experimentEnrollmentManager.isEnrolled(account.getUuid(), UUID_EXPERIMENT_NAME));
assertTrue(experimentEnrollmentManager.isEnrolled(account.getAccountIdentifier(), UUID_EXPERIMENT_NAME));
when(experimentEnrollmentConfiguration.getExcludedUuids()).thenReturn(Set.of(EXCLUDED_UUID));
when(experimentEnrollmentConfiguration.getEnrollmentPercentage()).thenReturn(100);
@@ -112,14 +112,14 @@ class ExperimentEnrollmentManagerTest {
void testIsEnrolled_UuidExperimentPercentage() {
when(uuidSelector.getUuids()).thenReturn(Set.of(ACCOUNT_UUID));
when(uuidSelector.getUuidEnrollmentPercentage()).thenReturn(0);
assertFalse(experimentEnrollmentManager.isEnrolled(account.getUuid(), UUID_EXPERIMENT_NAME));
assertFalse(experimentEnrollmentManager.isEnrolled(account.getAccountIdentifier(), UUID_EXPERIMENT_NAME));
when(uuidSelector.getUuidEnrollmentPercentage()).thenReturn(100);
assertTrue(experimentEnrollmentManager.isEnrolled(account.getUuid(), UUID_EXPERIMENT_NAME));
assertTrue(experimentEnrollmentManager.isEnrolled(account.getAccountIdentifier(), UUID_EXPERIMENT_NAME));
when(uuidSelector.getUuidEnrollmentPercentage()).thenReturn(75);
final Map<Boolean, Long> counts = IntStream.range(0, 100).mapToObj(i -> {
when(random.nextInt(100)).thenReturn(i);
return experimentEnrollmentManager.isEnrolled(account.getUuid(), UUID_EXPERIMENT_NAME);
return experimentEnrollmentManager.isEnrolled(account.getAccountIdentifier(), UUID_EXPERIMENT_NAME);
})
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
assertEquals(25, counts.get(false));
@@ -137,24 +137,24 @@ class ExperimentEnrollmentManagerTest {
// test UUID enrollment is prioritized
when(uuidSelector.getUuids()).thenReturn(Set.of(ACCOUNT_UUID));
when(uuidSelector.getUuidEnrollmentPercentage()).thenReturn(100);
assertTrue(experimentEnrollmentManager.isEnrolled(NOT_ENROLLED_164, account.getUuid(), E164_AND_UUID_EXPERIMENT_NAME));
assertTrue(experimentEnrollmentManager.isEnrolled(NOT_ENROLLED_164, account.getAccountIdentifier(), E164_AND_UUID_EXPERIMENT_NAME));
when(uuidSelector.getUuidEnrollmentPercentage()).thenReturn(0);
assertFalse(experimentEnrollmentManager.isEnrolled(NOT_ENROLLED_164, account.getUuid(), E164_AND_UUID_EXPERIMENT_NAME));
assertFalse(experimentEnrollmentManager.isEnrolled(ENROLLED_164, account.getUuid(), E164_AND_UUID_EXPERIMENT_NAME));
assertFalse(experimentEnrollmentManager.isEnrolled(NOT_ENROLLED_164, account.getAccountIdentifier(), E164_AND_UUID_EXPERIMENT_NAME));
assertFalse(experimentEnrollmentManager.isEnrolled(ENROLLED_164, account.getAccountIdentifier(), E164_AND_UUID_EXPERIMENT_NAME));
// test fallback from UUID enrollment to general enrollment percentage
when(uuidSelector.getUuids()).thenReturn(Collections.emptySet());
when(experimentEnrollmentConfiguration.getEnrollmentPercentage()).thenReturn(100);
assertTrue(experimentEnrollmentManager.isEnrolled(NOT_ENROLLED_164, account.getUuid(), E164_AND_UUID_EXPERIMENT_NAME));
assertTrue(experimentEnrollmentManager.isEnrolled(ENROLLED_164, account.getUuid(), E164_AND_UUID_EXPERIMENT_NAME));
assertTrue(experimentEnrollmentManager.isEnrolled(NOT_ENROLLED_164, account.getAccountIdentifier(), E164_AND_UUID_EXPERIMENT_NAME));
assertTrue(experimentEnrollmentManager.isEnrolled(ENROLLED_164, account.getAccountIdentifier(), E164_AND_UUID_EXPERIMENT_NAME));
// test fallback from UUID/general enrollment to e164 enrollment
when(experimentEnrollmentConfiguration.getEnrollmentPercentage()).thenReturn(0);
assertTrue(experimentEnrollmentManager.isEnrolled(ENROLLED_164, account.getUuid(), E164_AND_UUID_EXPERIMENT_NAME));
assertFalse(experimentEnrollmentManager.isEnrolled(NOT_ENROLLED_164, account.getUuid(), E164_AND_UUID_EXPERIMENT_NAME));
assertTrue(experimentEnrollmentManager.isEnrolled(ENROLLED_164, account.getAccountIdentifier(), E164_AND_UUID_EXPERIMENT_NAME));
assertFalse(experimentEnrollmentManager.isEnrolled(NOT_ENROLLED_164, account.getAccountIdentifier(), E164_AND_UUID_EXPERIMENT_NAME));
when(e164ExperimentEnrollmentConfiguration.getEnrollmentPercentage()).thenReturn(100);
assertTrue(experimentEnrollmentManager.isEnrolled(ENROLLED_164, account.getUuid(), E164_AND_UUID_EXPERIMENT_NAME));
assertTrue(experimentEnrollmentManager.isEnrolled(NOT_ENROLLED_164, account.getUuid(), E164_AND_UUID_EXPERIMENT_NAME));
assertTrue(experimentEnrollmentManager.isEnrolled(ENROLLED_164, account.getAccountIdentifier(), E164_AND_UUID_EXPERIMENT_NAME));
assertTrue(experimentEnrollmentManager.isEnrolled(NOT_ENROLLED_164, account.getAccountIdentifier(), E164_AND_UUID_EXPERIMENT_NAME));
}
@ParameterizedTest
@@ -112,7 +112,6 @@ class AccountsAnonymousGrpcServiceTest extends
@ParameterizedTest
@MethodSource
void checkAccountExistenceIllegalRequest(final CheckAccountExistenceRequest request) {
//noinspection ResultOfMethodCallIgnored
GrpcTestUtils.assertStatusException(Status.INVALID_ARGUMENT,
() -> unauthenticatedServiceStub().checkAccountExistence(request));
}
@@ -154,7 +153,7 @@ class AccountsAnonymousGrpcServiceTest extends
final byte[] usernameHash = TestRandomUtil.nextBytes(AccountController.USERNAME_HASH_LENGTH);
final Account account = mock(Account.class);
when(account.getUuid()).thenReturn(accountIdentifier);
when(account.getAccountIdentifier()).thenReturn(accountIdentifier);
when(accountsManager.getByUsernameHash(usernameHash))
.thenReturn(CompletableFuture.completedFuture(Optional.of(account)));
@@ -174,7 +173,6 @@ class AccountsAnonymousGrpcServiceTest extends
@ParameterizedTest
@MethodSource
void lookupUsernameHashIllegalHash(final LookupUsernameHashRequest request) {
//noinspection ResultOfMethodCallIgnored
GrpcTestUtils.assertStatusException(Status.INVALID_ARGUMENT,
() -> unauthenticatedServiceStub().lookupUsernameHash(request));
}
@@ -248,7 +246,6 @@ class AccountsAnonymousGrpcServiceTest extends
@ParameterizedTest
@MethodSource
void lookupUsernameLinkIllegalHandle(final LookupUsernameLinkRequest request) {
//noinspection ResultOfMethodCallIgnored
GrpcTestUtils.assertStatusException(Status.INVALID_ARGUMENT,
() -> unauthenticatedServiceStub().lookupUsernameLink(request));
}
@@ -20,6 +20,7 @@ import static org.mockito.Mockito.when;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.protobuf.ByteString;
import com.google.protobuf.Empty;
import io.grpc.Status;
import java.io.IOException;
import java.time.Duration;
@@ -169,7 +170,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
final UUID usernameLinkHandle = UUID.randomUUID();
final Account account = mock(Account.class);
when(account.getUuid()).thenReturn(AUTHENTICATED_ACI);
when(account.getAccountIdentifier()).thenReturn(AUTHENTICATED_ACI);
when(account.getPhoneNumberIdentifier()).thenReturn(phoneNumberIdentifier);
when(account.getNumber()).thenReturn(e164);
when(account.getUsernameHash()).thenReturn(Optional.of(usernameHash));
@@ -204,15 +205,17 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
void deleteAccountLinkedDevice() {
getMockAuthenticationInterceptor().setAuthenticatedDevice(AUTHENTICATED_ACI, (byte) (Device.PRIMARY_ID + 1));
//noinspection ResultOfMethodCallIgnored
GrpcTestUtils.assertStatusException(Status.INVALID_ARGUMENT, "BAD_AUTHENTICATION",
() -> authenticatedServiceStub().deleteAccount(DeleteAccountRequest.newBuilder().build()));
final DeleteAccountResponse ignored =
authenticatedServiceStub().deleteAccount(DeleteAccountRequest.newBuilder().build());
verify(accountsManager, never()).delete(any(), any());
verify(accountsManager).delete(AUTHENTICATED_ACI, AccountsManager.DeletionReason.USER_REQUEST);
}
@Test
void setRegistrationLock() {
@ParameterizedTest
@ValueSource(bytes = { Device.PRIMARY_ID, Device.PRIMARY_ID + 1 })
void setRegistrationLock(final byte deviceId) {
getMockAuthenticationInterceptor().setAuthenticatedDevice(AUTHENTICATED_ACI, (byte) (deviceId));
final Account account = mock(Account.class);
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI))
@@ -236,7 +239,6 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
@Test
void setRegistrationLockEmptySecret() {
//noinspection ResultOfMethodCallIgnored
GrpcTestUtils.assertStatusException(Status.INVALID_ARGUMENT,
() -> authenticatedServiceStub().setRegistrationLock(SetRegistrationLockRequest.newBuilder()
.build()));
@@ -244,21 +246,11 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
verify(accountsManager, never()).update(any(UUID.class), any());
}
@Test
void setRegistrationLockLinkedDevice() {
@ParameterizedTest
@ValueSource(bytes = { Device.PRIMARY_ID, Device.PRIMARY_ID + 1 })
void clearRegistrationLock(final byte deviceId) {
getMockAuthenticationInterceptor().setAuthenticatedDevice(AUTHENTICATED_ACI, (byte) (Device.PRIMARY_ID + 1));
//noinspection ResultOfMethodCallIgnored
GrpcTestUtils.assertStatusException(Status.INVALID_ARGUMENT, "BAD_AUTHENTICATION",
() -> authenticatedServiceStub().setRegistrationLock(SetRegistrationLockRequest.newBuilder()
.setRegistrationLock(ByteString.copyFrom(TestRandomUtil.nextBytes(32)))
.build()));
verify(accountsManager, never()).update(any(UUID.class), any());
}
@Test
void clearRegistrationLock() {
final Account account = mock(Account.class);
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI))
@@ -270,17 +262,6 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
verify(account).setRegistrationLock(null, null);
}
@Test
void clearRegistrationLockLinkedDevice() {
getMockAuthenticationInterceptor().setAuthenticatedDevice(AUTHENTICATED_ACI, (byte) (Device.PRIMARY_ID + 1));
//noinspection ResultOfMethodCallIgnored
GrpcTestUtils.assertStatusException(Status.INVALID_ARGUMENT,
() -> authenticatedServiceStub().clearRegistrationLock(ClearRegistrationLockRequest.newBuilder().build()));
verify(accountsManager, never()).update(any(UUID.class), any());
}
@Test
void reserveUsernameHash() throws UsernameHashNotAvailableException {
final Account account = mock(Account.class);
@@ -332,7 +313,6 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
@Test
void reserveUsernameHashNoHashes() {
//noinspection ResultOfMethodCallIgnored
GrpcTestUtils.assertStatusException(Status.INVALID_ARGUMENT,
() -> authenticatedServiceStub().reserveUsernameHash(ReserveUsernameHashRequest.newBuilder().build()));
}
@@ -346,7 +326,6 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
requestBuilder.addUsernameHashes(ByteString.copyFrom(usernameHash));
}
//noinspection ResultOfMethodCallIgnored
GrpcTestUtils.assertStatusException(Status.INVALID_ARGUMENT,
() -> authenticatedServiceStub().reserveUsernameHash(requestBuilder.build()));
}
@@ -360,7 +339,6 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
final byte[] usernameHash = TestRandomUtil.nextBytes(AccountController.USERNAME_HASH_LENGTH + 1);
//noinspection ResultOfMethodCallIgnored
GrpcTestUtils.assertStatusException(Status.INVALID_ARGUMENT,
() -> authenticatedServiceStub().reserveUsernameHash(ReserveUsernameHashRequest.newBuilder()
.addUsernameHashes(ByteString.copyFrom(usernameHash))
@@ -411,7 +389,6 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
final ConfirmUsernameHashResponse expectedResponse = ConfirmUsernameHashResponse.newBuilder()
.setConfirmedUsernameHash(ConfirmUsernameHashResponse.ConfirmedUsernameHash.newBuilder()
.setUsernameHash(ByteString.copyFrom(usernameHash))
.setUsernameLinkHandle(UUIDUtil.toByteString(linkHandle))
.build())
.build();
@@ -480,7 +457,6 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
doThrow(BaseUsernameException.class).when(usernameHashZkProofVerifier).verifyProof(any(), any());
//noinspection ResultOfMethodCallIgnored
GrpcTestUtils.assertStatusException(Status.INVALID_ARGUMENT,
() -> authenticatedServiceStub().confirmUsernameHash(ConfirmUsernameHashRequest.newBuilder()
.setUsernameHash(ByteString.copyFrom(usernameHash))
@@ -492,7 +468,6 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
@ParameterizedTest
@MethodSource
void confirmUsernameHashInvalidArgument(final ConfirmUsernameHashRequest request) {
//noinspection ResultOfMethodCallIgnored
GrpcTestUtils.assertStatusException(Status.INVALID_ARGUMENT,
() -> authenticatedServiceStub().confirmUsernameHash(request));
}
@@ -600,7 +575,6 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
@ParameterizedTest
@MethodSource
void setUsernameLinkIllegalCiphertext(final SetUsernameLinkRequest request) {
//noinspection ResultOfMethodCallIgnored
GrpcTestUtils.assertStatusException(Status.INVALID_ARGUMENT,
() -> authenticatedServiceStub().setUsernameLink(request));
}
@@ -661,39 +635,30 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
}
@ParameterizedTest
@MethodSource
void configureUnidentifiedAccess(final boolean unrestrictedUnidentifiedAccess,
final byte[] unidentifiedAccessKey,
final byte[] expectedUnidentifiedAccessKey) {
@ValueSource(booleans = {true, false})
void configureUnidentifiedAccess(final boolean unrestrictedUnidentifiedAccess) {
final Account account = mock(Account.class);
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI))
.thenReturn(Optional.of(account));
final byte[] uak = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
final ConfigureUnidentifiedAccessRequest.Builder builder = ConfigureUnidentifiedAccessRequest.newBuilder();
if (unrestrictedUnidentifiedAccess) {
builder.setAllowUnrestrictedUnidentifiedAccess(Empty.getDefaultInstance());
} else {
builder.setUnidentifiedAccessKey(ByteString.copyFrom(uak));
}
assertDoesNotThrow(() -> authenticatedServiceStub().configureUnidentifiedAccess(ConfigureUnidentifiedAccessRequest.newBuilder()
.setAllowUnrestrictedUnidentifiedAccess(unrestrictedUnidentifiedAccess)
.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey))
.build()));
assertDoesNotThrow(() -> authenticatedServiceStub().configureUnidentifiedAccess(builder.build()));
verify(account).setUnrestrictedUnidentifiedAccess(unrestrictedUnidentifiedAccess);
verify(account).setUnidentifiedAccessKey(expectedUnidentifiedAccessKey);
}
private static Stream<Arguments> configureUnidentifiedAccess() {
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
return Stream.of(
Arguments.of(true, new byte[0], null),
Arguments.of(true, unidentifiedAccessKey, null),
Arguments.of(false, unidentifiedAccessKey, unidentifiedAccessKey)
);
verify(account).setUnidentifiedAccessKey(unrestrictedUnidentifiedAccess ? null : uak);
}
@ParameterizedTest
@MethodSource
void configureUnidentifiedAccessIllegalArguments(final ConfigureUnidentifiedAccessRequest request) {
//noinspection ResultOfMethodCallIgnored
GrpcTestUtils.assertStatusException(Status.INVALID_ARGUMENT,
() -> authenticatedServiceStub().configureUnidentifiedAccess(request));
}
@@ -705,7 +670,6 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
// Key with incorrect length
ConfigureUnidentifiedAccessRequest.newBuilder()
.setAllowUnrestrictedUnidentifiedAccess(false)
.setUnidentifiedAccessKey(ByteString.copyFrom(new byte[15]))
.build()
);
@@ -749,7 +713,6 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
@Test
void setRegistrationRecoveryPasswordMissingPassword() {
//noinspection ResultOfMethodCallIgnored
GrpcTestUtils.assertStatusException(Status.INVALID_ARGUMENT,
() -> authenticatedServiceStub().setRegistrationRecoveryPassword(
SetRegistrationRecoveryPasswordRequest.newBuilder().build()));
@@ -796,7 +759,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
final Duration retryDuration = Duration.ofDays(1);
final Account account = mock(Account.class);
when(account.getUuid()).thenReturn(AUTHENTICATED_ACI);
when(account.getAccountIdentifier()).thenReturn(AUTHENTICATED_ACI);
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI))
.thenReturn(Optional.of(account));
@@ -824,7 +787,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
when(account.getBackupVoucher()).thenReturn(new Account.BackupVoucher(100, expiration));
when(account.getBadges()).thenReturn(List.of(badge1, badge2));
when(account.getUuid()).thenReturn(AUTHENTICATED_ACI);
when(account.getAccountIdentifier()).thenReturn(AUTHENTICATED_ACI);
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI)).thenReturn(Optional.of(account));
final GetEntitlementsResponse entitlements = authenticatedServiceStub()
@@ -864,7 +827,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
final UUID updatedPni = UUID.randomUUID();
final Account updatedAccount = mock(Account.class);
when(updatedAccount.getUuid()).thenReturn(AUTHENTICATED_ACI);
when(updatedAccount.getAccountIdentifier()).thenReturn(AUTHENTICATED_ACI);
when(updatedAccount.getNumber()).thenReturn(newNumber);
when(updatedAccount.getPhoneNumberIdentifier()).thenReturn(updatedPni);
when(updatedAccount.getUsernameHash()).thenReturn(Optional.empty());
@@ -942,7 +905,6 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
when(changeNumberManager.changeNumber(any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any()))
.thenThrow(exceptionToThrow);
//noinspection ResultOfMethodCallIgnored
GrpcTestUtils.assertStatusException(Status.UNAVAILABLE,
() -> authenticatedServiceStub().changeNumber(createChangeNumberRequest()));
}
@@ -1034,8 +996,8 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
@ParameterizedTest
@ArgumentsSource(AccountsTestHelper.AccountsDataReportArgumentProvider.class)
void getAccountDataReport(final Account account, final String expectedTextAfterHeader) {
getMockAuthenticationInterceptor().setAuthenticatedDevice(account.getUuid(), Device.PRIMARY_ID);
when(accountsManager.getByAccountIdentifier(account.getUuid())).thenReturn(Optional.of(account));
getMockAuthenticationInterceptor().setAuthenticatedDevice(account.getAccountIdentifier(), Device.PRIMARY_ID);
when(accountsManager.getByAccountIdentifier(account.getAccountIdentifier())).thenReturn(Optional.of(account));
final GetAccountDataReportResponse response =
authenticatedServiceStub().getAccountDataReport(GetAccountDataReportRequest.newBuilder().build());
@@ -1047,12 +1009,12 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
@Test
void getCapabilities() {
final Account account = mock(Account.class);
when(account.getUuid()).thenReturn(AUTHENTICATED_ACI);
when(account.getAccountIdentifier()).thenReturn(AUTHENTICATED_ACI);
// public-visible and self-visible capabilities should be returned on the authenticated RPC
when(account.hasCapability(DeviceCapability.SPARSE_POST_QUANTUM_RATCHET)).thenReturn(true);
when(account.hasCapability(DeviceCapability.USERNAME_CHANGE_SYNC_MESSAGE)).thenReturn(true);
when(account.getUuid()).thenReturn(AUTHENTICATED_ACI);
when(account.getAccountIdentifier()).thenReturn(AUTHENTICATED_ACI);
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI)).thenReturn(Optional.of(account));
@@ -70,6 +70,7 @@ import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.metrics.BackupMetrics;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
import reactor.core.publisher.Flux;
import reactor.core.scheduler.Schedulers;
class BackupsAnonymousGrpcServiceTest extends
SimpleBaseGrpcTest<BackupsAnonymousGrpcService, BackupsAnonymousGrpc.BackupsAnonymousBlockingStub> {
@@ -146,10 +147,11 @@ class BackupsAnonymousGrpcServiceTest extends
@Test
void putMediaBatchSuccess() {
final byte[][] mediaIds = {TestRandomUtil.nextBytes(15), TestRandomUtil.nextBytes(15)};
when(backupManager.copyToBackup(any()))
.thenReturn(Flux.just(
when(backupManager.copyToBackup(any())).thenReturn(Flux.just(
new CopyResult(CopyResult.Outcome.SUCCESS, mediaIds[0], 1),
new CopyResult(CopyResult.Outcome.SUCCESS, mediaIds[1], 1)));
new CopyResult(CopyResult.Outcome.SUCCESS, mediaIds[1], 1))
// helps catch any issues with streaming concurrency (especially context propagation)
.publishOn(Schedulers.parallel()));
final CopyMediaRequest request = CopyMediaRequest.newBuilder()
.setSignedPresentation(signedPresentation(presentation))
Loaded 100 of 154 files, more files were not shown because too many files have changed in this diff. Show more