mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-01 09:56:47 +00:00
Compare commits
81
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3447345d02 | ||
|
|
ab0235a574 | ||
|
|
38c5a292fb | ||
|
|
35663956b5 | ||
|
|
d5a0c63de8 | ||
|
|
2f0a081d2e | ||
|
|
adfab44ed6 | ||
|
|
24cea1926a | ||
|
|
242a5f6a78 | ||
|
|
45dab47ea8 | ||
|
|
0587a08017 | ||
|
|
02d6138848 | ||
|
|
07444bffb4 | ||
|
|
4f8ca893f0 | ||
|
|
7bb94bc99e | ||
|
|
f6ca5e55a5 | ||
|
|
4e2bca886e | ||
|
|
088037b412 | ||
|
|
548c688df2 | ||
|
|
8b103030ed | ||
|
|
6a8bf7f78e | ||
|
|
98ba337787 | ||
|
|
4410da5fb2 | ||
|
|
607c839dda | ||
|
|
bb3ad8d116 | ||
|
|
2dcd43318e | ||
|
|
b255c37978 | ||
|
|
ea411e2f1e | ||
|
|
70f83326ef | ||
|
|
90a5ad589b | ||
|
|
749d9c4f92 | ||
|
|
3d45706a35 | ||
|
|
ed90c1c15c | ||
|
|
5147fe57f2 | ||
|
|
1d366c98a9 | ||
|
|
8c19171284 | ||
|
|
47a461ef1f | ||
|
|
a959656c96 | ||
|
|
ab08a3a0e4 | ||
|
|
688d3a2212 | ||
|
|
25fdc95843 | ||
|
|
d3c93dd1a2 | ||
|
|
54ea7a288c | ||
|
|
e2cb484743 | ||
|
|
45f176d5a8 | ||
|
|
450945a9cc | ||
|
|
253671c206 | ||
|
|
cdd461b8f4 | ||
|
|
d9a54a0d42 | ||
|
|
3f3aa89b0f | ||
|
|
55fa60dd4e | ||
|
|
b539df8e48 | ||
|
|
0cd0716eb5 | ||
|
|
6386aada73 | ||
|
|
5c44398bb5 | ||
|
|
54736bb117 | ||
|
|
aed8e60789 | ||
|
|
5fa50e8ad7 | ||
|
|
fdaba751bd | ||
|
|
0eebb58956 | ||
|
|
6bb85d77a7 | ||
|
|
9e3844ee5a | ||
|
|
7ee8e349e2 | ||
|
|
4d9e252697 | ||
|
|
222e5a033b | ||
|
|
8c6fbbfa65 | ||
|
|
b0b2122d8c | ||
|
|
d7711e235b | ||
|
|
5174550ef3 | ||
|
|
d0fcb9ab54 | ||
|
|
375150a8c3 | ||
|
|
cb28614721 | ||
|
|
f02caf78cd | ||
|
|
8fd72549fb | ||
|
|
1e4774820f | ||
|
|
48cdad7e57 | ||
|
|
392bab5b60 | ||
|
|
6b67604fe7 | ||
|
|
67a03f81b9 | ||
|
|
90b75cbf22 | ||
|
|
4dede4acad |
No files matched your search
@@ -11,8 +11,8 @@ jobs:
|
||||
contents: write
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
|
||||
- uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5.2.0
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
- uses: actions/setup-java@1bcf9fb12cf4aa7d266a90ae39939e61372fe520 # v5.4.0
|
||||
with:
|
||||
distribution: 'temurin'
|
||||
java-version-file: .java-version
|
||||
|
||||
@@ -17,14 +17,15 @@ jobs:
|
||||
permissions:
|
||||
id-token: write
|
||||
contents: read
|
||||
issues: write
|
||||
steps:
|
||||
- uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
|
||||
- uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5.2.0
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
- uses: actions/setup-java@1bcf9fb12cf4aa7d266a90ae39939e61372fe520 # v5.4.0
|
||||
with:
|
||||
distribution: 'temurin'
|
||||
java-version-file: .java-version
|
||||
cache: 'maven'
|
||||
- uses: aws-actions/configure-aws-credentials@e7f100cf4c008499ea8adda475de1042d6975c7b # v6.2.0
|
||||
- uses: aws-actions/configure-aws-credentials@254c19bd240aabef8777f48595e9d2d7b972184b # v6.2.1
|
||||
name: Configure AWS credentials from Test account
|
||||
with:
|
||||
role-to-assume: ${{ vars.AWS_ROLE }}
|
||||
@@ -35,3 +36,11 @@ jobs:
|
||||
echo "${INTEGRATION_TEST_CONFIG}" > integration-tests/src/main/resources/config.yml
|
||||
- name: Run and verify integration tests
|
||||
run: ./mvnw clean compile test-compile failsafe:integration-test failsafe:verify -P aws-sso
|
||||
- name: Open an issue on failure
|
||||
if: ${{ failure() && github.event_name == 'schedule' }}
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
gh issue create \
|
||||
--title "Failed server integration tests ($(date +'%Y-%m-%d'))" \
|
||||
--body "Workflow **${{ github.workflow }}** failed. See the run: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}"
|
||||
+17
-12
@@ -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:
|
||||
@@ -25,23 +28,15 @@ jobs:
|
||||
options: --name foundationdb1
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
|
||||
- name: Set up JDK
|
||||
uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5.2.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
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
- 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
|
||||
|
||||
Vendored
BIN
Binary file not shown.
+4
-3
@@ -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
|
||||
@@ -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 "$@"
|
||||
@@ -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"
|
||||
@@ -67,7 +67,7 @@
|
||||
<junit-pioneer.version>2.3.0</junit-pioneer.version>
|
||||
<jsr305.version>3.0.2</jsr305.version>
|
||||
<kotlin.version>2.3.20</kotlin.version>
|
||||
<logback.version>1.5.32</logback.version>
|
||||
<logback.version>1.5.38</logback.version>
|
||||
<logback-access-common.version>2.0.12</logback-access-common.version>
|
||||
<lettuce.version>7.5.1.RELEASE</lettuce.version>
|
||||
<libphonenumber.version>9.0.21</libphonenumber.version>
|
||||
@@ -85,18 +85,17 @@
|
||||
<semver4j.version>3.1.0</semver4j.version>
|
||||
<simple-grpc.version>0.2.0</simple-grpc.version>
|
||||
<slf4j.version>2.0.17</slf4j.version>
|
||||
<stripe.version>31.2.0</stripe.version>
|
||||
<stripe.version>33.1.0</stripe.version>
|
||||
<swagger.version>2.2.46</swagger.version>
|
||||
<testcontainers.version>2.0.4</testcontainers.version>
|
||||
|
||||
<!-- 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>
|
||||
|
||||
@@ -79,10 +79,8 @@ storageService.userAuthenticationTokenSharedSecret: AAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
||||
|
||||
zkConfig-libsignal-0.42.serverSecret: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdef
|
||||
|
||||
genericZkConfig.serverSecret: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzAA==
|
||||
callingZkConfig.serverSecret: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzAA==
|
||||
backupsZkConfig.serverSecret: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzAA==
|
||||
profileAvatarsZkConfig.serverSecret: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzAA==
|
||||
chatZkConfig.serverSecret: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzAA==
|
||||
|
||||
paymentsService.userAuthenticationTokenSharedSecret: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= # base64-encoded 32-byte secret shared with MobileCoin services used to generate auth tokens for Signal users
|
||||
paymentsService.fixerApiKey: unset
|
||||
|
||||
@@ -318,18 +318,15 @@ storageService:
|
||||
AAAAAAAAAAAAAAAAAAAA
|
||||
-----END CERTIFICATE-----
|
||||
|
||||
zkConfig:
|
||||
serverPublic: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzAB==
|
||||
serverSecret: secret://zkConfig-libsignal-0.42.serverSecret
|
||||
|
||||
callingZkConfig:
|
||||
serverSecret: secret://callingZkConfig.serverSecret
|
||||
|
||||
backupsZkConfig:
|
||||
serverSecret: secret://backupsZkConfig.serverSecret
|
||||
chatZkConfig:
|
||||
serverSecret: secret://chatZkConfig.serverSecret
|
||||
|
||||
profileAvatarsZkConfig:
|
||||
serverSecret: secret://profileAvatarsZkConfig.serverSecret
|
||||
groupsZkConfig:
|
||||
serverPublic: ABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/0123456789+abcdefghijklmnopqrstuvwxyzAB==
|
||||
serverSecret: secret://zkConfig-libsignal-0.42.serverSecret
|
||||
|
||||
dynamicConfig:
|
||||
s3Region: a-region
|
||||
@@ -368,8 +365,6 @@ badges:
|
||||
svgs:
|
||||
- light: example-light.svg
|
||||
dark: example-dark.svg
|
||||
badgeIdsEnabledForAll:
|
||||
- TEST
|
||||
receiptLevels:
|
||||
'1': TEST
|
||||
|
||||
@@ -549,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
@@ -572,6 +572,12 @@
|
||||
<artifactId>google-auth-library-oauth2-http</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.bouncycastle</groupId>
|
||||
<artifactId>bcprov-jdk18on</artifactId>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.stripe</groupId>
|
||||
<artifactId>stripe-java</artifactId>
|
||||
@@ -720,7 +726,7 @@
|
||||
</executions>
|
||||
<configuration>
|
||||
<from>
|
||||
<image>eclipse-temurin@sha256:${docker.image.sha256}</image>
|
||||
<image>${docker.image}</image>
|
||||
<platforms>
|
||||
<platform>
|
||||
<architecture>amd64</architecture>
|
||||
|
||||
+20
-16
@@ -17,6 +17,7 @@ import org.whispersystems.textsecuregcm.configuration.AppleAppStoreConfiguration
|
||||
import org.whispersystems.textsecuregcm.configuration.AppleDeviceCheckConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.AttachmentsConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.AwsCredentialsProviderFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.BackupConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.BadgesConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.BraintreeConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.CallQualitySurveyConfiguration;
|
||||
@@ -67,7 +68,7 @@ import org.whispersystems.textsecuregcm.configuration.VirtualThreadConfiguration
|
||||
import org.whispersystems.textsecuregcm.configuration.ZkConfig;
|
||||
import org.whispersystems.websocket.configuration.WebSocketConfiguration;
|
||||
|
||||
/** @noinspection MismatchedQueryAndUpdateOfCollection, WeakerAccess */
|
||||
// @noinspection MismatchedQueryAndUpdateOfCollection, WeakerAccess
|
||||
public class WhisperServerConfiguration extends Configuration {
|
||||
|
||||
@NotNull
|
||||
@@ -130,6 +131,11 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@JsonProperty
|
||||
private GcpAttachmentsConfiguration gcpAttachments;
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@JsonProperty
|
||||
private BackupConfiguration backup = new BackupConfiguration();
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@JsonProperty
|
||||
@@ -220,11 +226,6 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@JsonProperty
|
||||
private PaymentsServiceConfiguration paymentsService;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
private ZkConfig zkConfig;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
@@ -233,12 +234,12 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
private GenericZkConfig backupsZkConfig;
|
||||
private GenericZkConfig chatZkConfig;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@JsonProperty
|
||||
private GenericZkConfig profileAvatarsZkConfig;
|
||||
private ZkConfig groupsZkConfig;
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
@@ -428,6 +429,10 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
return gcpAttachments;
|
||||
}
|
||||
|
||||
public BackupConfiguration getBackupConfiguration() {
|
||||
return backup;
|
||||
}
|
||||
|
||||
public FaultTolerantRedisClusterFactory getCacheClusterConfiguration() {
|
||||
return cacheCluster;
|
||||
}
|
||||
@@ -492,20 +497,19 @@ public class WhisperServerConfiguration extends Configuration {
|
||||
return paymentsService;
|
||||
}
|
||||
|
||||
public ZkConfig getZkConfig() {
|
||||
return zkConfig;
|
||||
/// ZK secret limited to Chat Service
|
||||
public GenericZkConfig getChatZkConfig() {
|
||||
return chatZkConfig;
|
||||
}
|
||||
|
||||
/// ZK secret shared with Calling Service
|
||||
public GenericZkConfig getCallingZkConfig() {
|
||||
return callingZkConfig;
|
||||
}
|
||||
|
||||
public GenericZkConfig getBackupsZkConfig() {
|
||||
return backupsZkConfig;
|
||||
}
|
||||
|
||||
public GenericZkConfig getProfileAvatarsZkConfig() {
|
||||
return profileAvatarsZkConfig;
|
||||
/// ZK secret shared with Groups Service
|
||||
public ZkConfig getGroupsZkConfig() {
|
||||
return groupsZkConfig;
|
||||
}
|
||||
|
||||
public RemoteConfigConfiguration getRemoteConfigConfiguration() {
|
||||
|
||||
@@ -178,6 +178,7 @@ import org.whispersystems.textsecuregcm.grpc.MessagesGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.MetricServerInterceptor;
|
||||
import org.whispersystems.textsecuregcm.grpc.OneTimeDonationsGrpcService;
|
||||
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.RequestAttributesInterceptor;
|
||||
@@ -203,12 +204,14 @@ 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;
|
||||
import org.whispersystems.textsecuregcm.mappers.NonNormalizedPhoneNumberExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.ObsoletePhoneNumberFormatExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.RegistrationLockFailureExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.RegistrationServiceSenderExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.ServerRejectedExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.SubscriptionExceptionMapper;
|
||||
@@ -316,6 +319,7 @@ import org.whispersystems.textsecuregcm.workers.BackupMetricsCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.BackupUsageRecalculationCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.CertificateCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.CheckDynamicConfigurationCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.ClearExpiredFoundationDbMessagesCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.ClearIssuedReceiptRedemptionsCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.CopyToS3Command;
|
||||
import org.whispersystems.textsecuregcm.workers.DeleteUserCommand;
|
||||
@@ -333,6 +337,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;
|
||||
@@ -391,6 +396,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
bootstrap.addCommand(new NotifyIdleDevicesCommand());
|
||||
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",
|
||||
@@ -492,6 +499,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) {
|
||||
@@ -754,7 +765,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(),
|
||||
@@ -914,18 +927,18 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getCdnConfiguration().credentials().accessKeyId().value(),
|
||||
config.getCdnConfiguration().credentials().secretAccessKey().value());
|
||||
|
||||
ServerSecretParams zkSecretParams = new ServerSecretParams(config.getZkConfig().serverSecret().value());
|
||||
ServerSecretParams groupZkSecretParams = new ServerSecretParams(config.getGroupsZkConfig().serverSecret().value());
|
||||
GenericServerSecretParams callingGenericZkSecretParams = new GenericServerSecretParams(config.getCallingZkConfig().serverSecret().value());
|
||||
GenericServerSecretParams backupsGenericZkSecretParams = new GenericServerSecretParams(config.getBackupsZkConfig().serverSecret().value());
|
||||
GenericServerSecretParams profileAvatarsGenericZkSecretParams = new GenericServerSecretParams(config.getProfileAvatarsZkConfig().serverSecret().value());
|
||||
ServerZkProfileOperations zkProfileOperations = new ServerZkProfileOperations(zkSecretParams);
|
||||
ServerZkAuthOperations zkAuthOperations = new ServerZkAuthOperations(zkSecretParams);
|
||||
ServerZkReceiptOperations zkReceiptOperations = new ServerZkReceiptOperations(zkSecretParams);
|
||||
GenericServerSecretParams chatGenericZkSecretParams = new GenericServerSecretParams(config.getChatZkConfig().serverSecret().value());
|
||||
ServerZkProfileOperations zkProfileOperations = new ServerZkProfileOperations(groupZkSecretParams);
|
||||
ServerZkAuthOperations zkAuthOperations = new ServerZkAuthOperations(groupZkSecretParams);
|
||||
// ZK receipts are not actually shared with ZK groups, but use the same extensible parameters object for legacy reasons
|
||||
ServerZkReceiptOperations zkReceiptOperations = new ServerZkReceiptOperations(groupZkSecretParams);
|
||||
|
||||
TusAttachmentGenerator tusAttachmentGenerator = new TusAttachmentGenerator(config.getTus());
|
||||
Cdn3BackupCredentialGenerator cdn3BackupCredentialGenerator = new Cdn3BackupCredentialGenerator(config.getTus());
|
||||
BackupAuthManager backupAuthManager = new BackupAuthManager(experimentEnrollmentManager, rateLimiters,
|
||||
accountsManager, zkReceiptOperations, redeemedReceiptsManager, backupsGenericZkSecretParams, clock);
|
||||
accountsManager, zkReceiptOperations, redeemedReceiptsManager, chatGenericZkSecretParams, clock);
|
||||
BackupsDb backupsDb = new BackupsDb(
|
||||
dynamoDbAsyncClient,
|
||||
config.getDynamoDbTables().getBackups().getTableName(),
|
||||
@@ -936,7 +949,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getCdn3StorageManagerConfiguration());
|
||||
BackupManager backupManager = new BackupManager(
|
||||
backupsDb,
|
||||
backupsGenericZkSecretParams,
|
||||
chatGenericZkSecretParams,
|
||||
rateLimiters,
|
||||
tusAttachmentGenerator,
|
||||
cdn3BackupCredentialGenerator,
|
||||
@@ -944,7 +957,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
svrbCredentialsGenerator,
|
||||
secureValueRecoveryBClient,
|
||||
clock,
|
||||
dynamicConfigurationManager);
|
||||
config.getBackupConfiguration());
|
||||
final BackupMetrics backupMetrics = new BackupMetrics();
|
||||
|
||||
final AppleDeviceChecks appleDeviceChecks = new AppleDeviceChecks(
|
||||
@@ -961,7 +974,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getAppleDeviceCheck().teamId(),
|
||||
config.getAppleDeviceCheck().bundleId());
|
||||
|
||||
final DonationPermitsManager donationPermitsManager = new DonationPermitsManager(donationPermits, zkSecretParams,
|
||||
final DonationPermitsManager donationPermitsManager = new DonationPermitsManager(donationPermits, groupZkSecretParams,
|
||||
clock);
|
||||
|
||||
final SubscriptionManager subscriptionManager = new SubscriptionManager(subscriptions,
|
||||
@@ -1054,7 +1067,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getExternalRequestFilterConfiguration().grpcMethods());
|
||||
final RequireAuthenticationInterceptor requireAuthenticationInterceptor = new RequireAuthenticationInterceptor(accountAuthenticator);
|
||||
final ProhibitAuthenticationInterceptor prohibitAuthenticationInterceptor = new ProhibitAuthenticationInterceptor();
|
||||
final GroupSendTokenUtil groupSendTokenUtil = new GroupSendTokenUtil(zkSecretParams, Clock.systemUTC());
|
||||
final GroupSendTokenUtil groupSendTokenUtil = new GroupSendTokenUtil(groupZkSecretParams, Clock.systemUTC());
|
||||
final MessageMetrics messageMetrics = new MessageMetrics();
|
||||
final MessageDispatcher messageDispatcher = new MessageDispatcher(receiptSender, messagesManager, messageMetrics,
|
||||
pushNotificationManager, pushNotificationScheduler, messageDeliveryLoopMonitor, disconnectionRequestManager,
|
||||
@@ -1066,12 +1079,19 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getDeliveryCertificate().expiresDays(),
|
||||
config.getDeliveryCertificate().embedSigner());
|
||||
|
||||
final PhoneVerificationTokenManager phoneVerificationTokenManager = new PhoneVerificationTokenManager(
|
||||
phoneNumberIdentifiers, registrationServiceClient, registrationRecoveryPasswordsManager, registrationRecoveryChecker);
|
||||
|
||||
final ChangeNumberManager changeNumberManager = new ChangeNumberManager(messageSender, accountsManager,
|
||||
phoneVerificationTokenManager, registrationLockVerificationManager, rateLimiters,
|
||||
changeNumberWaitingPeriodManager, Clock.systemUTC());
|
||||
|
||||
final List<ServerServiceDefinition> authenticatedServices = Stream.of(
|
||||
new AccountsGrpcService(accountsManager, rateLimiters, usernameHashZkProofVerifier, registrationRecoveryPasswordsManager),
|
||||
new AccountsGrpcService(accountsManager, rateLimiters, usernameHashZkProofVerifier, registrationRecoveryPasswordsManager, Clock.systemUTC(), changeNumberManager),
|
||||
new CallingGrpcService(cloudflareTurnCredentialsManager, rateLimiters),
|
||||
new CredentialsGrpcService(accountsManager, certificateGenerator, zkAuthOperations, callingGenericZkSecretParams, rateLimiters, Clock.systemUTC(), ExternalServiceDefinitions.createExternalServiceList(config, Clock.systemUTC())),
|
||||
new KeysGrpcService(accountsManager, keysManager, rateLimiters),
|
||||
new ProfileGrpcService(clock, accountsManager, profilesManager, dynamicConfigurationManager, config.getBadges(), profileCdnPolicyGenerator, profileAvatarsGenericZkSecretParams, profileBadgeConverter, rateLimiters),
|
||||
new ProfileGrpcService(clock, accountsManager, profilesManager, dynamicConfigurationManager, config.getBadges(), profileCdnPolicyGenerator, chatGenericZkSecretParams, profileBadgeConverter, rateLimiters),
|
||||
new MessagesGrpcService(accountsManager, rateLimiters, messageSender, messageByteLimitCardinalityEstimator, spamChecker, messageDispatcher, Clock.systemUTC()),
|
||||
new BackupsGrpcService(accountsManager, backupAuthManager, backupMetrics),
|
||||
new DevicesGrpcService(accountsManager),
|
||||
@@ -1080,7 +1100,10 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getAttachments().maxAttachmentUploadSizeInBytes(), Clock.systemUTC()),
|
||||
new PaymentsGrpcService(currencyManager),
|
||||
new ChallengeGrpcService(accountsManager, rateLimitChallengeManager, challengeConstraintChecker),
|
||||
new DonationsGrpcService(clock, zkReceiptOperations, redeemedReceiptsManager, accountsManager, config.getBadges(), ReceiptCredentialPresentation::new, donationPermitsManager, rateLimiters))
|
||||
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()))
|
||||
.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!
|
||||
@@ -1094,16 +1117,15 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
requireAuthenticationInterceptor))
|
||||
.toList();
|
||||
final List<ServerServiceDefinition> unauthenticatedServices = Stream.of(
|
||||
new AccountsAnonymousGrpcService(accountsManager, rateLimiters),
|
||||
new AccountsAnonymousGrpcService(accountsManager, rateLimiters, groupSendTokenUtil),
|
||||
new CallQualitySurveyGrpcService(callQualitySurveyManager, rateLimiters),
|
||||
new KeysAnonymousGrpcService(accountsManager, keysManager, zkSecretParams, Clock.systemUTC()),
|
||||
new ProfileAnonymousGrpcService(accountsManager, profilesManager, profileBadgeConverter, profileCdnPolicyGenerator, profileAvatarsGenericZkSecretParams, zkSecretParams, rateLimiters, clock),
|
||||
new KeysAnonymousGrpcService(accountsManager, keysManager, groupZkSecretParams, Clock.systemUTC()),
|
||||
new ProfileAnonymousGrpcService(accountsManager, profilesManager, profileBadgeConverter, profileCdnPolicyGenerator, chatGenericZkSecretParams, groupZkSecretParams, rateLimiters, clock),
|
||||
new MessagesAnonymousGrpcService(accountsManager, rateLimiters, messageSender, groupSendTokenUtil, messageByteLimitCardinalityEstimator, spamChecker, Clock.systemUTC()),
|
||||
new BackupsAnonymousGrpcService(backupManager, backupMetrics, config.getAttachments().maxAttachmentUploadSizeInBytes(), config.getAttachments().maxMessageBackupUploadSizeInBytes()),
|
||||
new CredentialsAnonymousGrpcService(accountsManager, ExternalServiceDefinitions.SVR.generatorFactory().apply(config, Clock.systemUTC())),
|
||||
new SubscriptionsGrpcService(clock, config.getSubscription(), config.getOneTimeDonations(), subscriptionManager,
|
||||
donationPermitsManager, stripeManager, braintreeManager, googlePlayBillingManager, appleAppStoreManager,
|
||||
profileBadgeConverter, bankMandateTranslator, dynamicConfigurationManager),
|
||||
new SubscriptionsGrpcService(clock, config.getSubscription(), subscriptionManager, donationPermitsManager,
|
||||
stripeManager, braintreeManager, googlePlayBillingManager, appleAppStoreManager, bankMandateTranslator),
|
||||
new OneTimeDonationsGrpcService(config.getOneTimeDonations(), stripeManager, braintreeManager,
|
||||
payPalDonationsTranslator, oneTimeDonationsManager, issuedReceiptsManager,
|
||||
zkReceiptOperations, clock, rateLimiters, donationPermitsManager))
|
||||
@@ -1212,13 +1234,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
|
||||
final PersistentTimer persistentTimer = new PersistentTimer(rateLimitersCluster, clock);
|
||||
|
||||
final PhoneVerificationTokenManager phoneVerificationTokenManager = new PhoneVerificationTokenManager(
|
||||
phoneNumberIdentifiers, registrationServiceClient, registrationRecoveryPasswordsManager, registrationRecoveryChecker);
|
||||
|
||||
final ChangeNumberManager changeNumberManager = new ChangeNumberManager(messageSender, accountsManager,
|
||||
phoneVerificationTokenManager, registrationLockVerificationManager, rateLimiters,
|
||||
changeNumberWaitingPeriodManager, Clock.systemUTC());
|
||||
|
||||
final List<Object> commonControllers = Lists.newArrayList(
|
||||
new AccountController(accountsManager, rateLimiters, registrationRecoveryPasswordsManager,
|
||||
usernameHashZkProofVerifier),
|
||||
@@ -1238,14 +1253,14 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new DirectoryV2Controller(directoryV2CredentialsGenerator),
|
||||
new DonationController(clock, zkReceiptOperations, redeemedReceiptsManager, accountsManager, config.getBadges(),
|
||||
ReceiptCredentialPresentation::new, donationPermitsManager, rateLimiters),
|
||||
new KeysController(rateLimiters, keysManager, accountsManager, zkSecretParams, Clock.systemUTC()),
|
||||
new KeysController(rateLimiters, keysManager, accountsManager, groupZkSecretParams, Clock.systemUTC()),
|
||||
new KeyTransparencyController(keyTransparencyServiceClient),
|
||||
new MessageController(rateLimiters, messageByteLimitCardinalityEstimator, messageSender, accountsManager,
|
||||
phoneNumberIdentifiers, reportMessageManager, zkSecretParams, spamChecker, Clock.systemUTC()),
|
||||
phoneNumberIdentifiers, reportMessageManager, groupZkSecretParams, spamChecker, Clock.systemUTC()),
|
||||
new PaymentsController(currencyManager, paymentsCredentialsGenerator),
|
||||
new ProfileController(clock, rateLimiters, accountsManager, profilesManager, dynamicConfigurationManager,
|
||||
profileBadgeConverter, config.getBadges(), profileCdnPolicyGenerator,
|
||||
zkSecretParams, zkProfileOperations, batchIdentityCheckExecutor),
|
||||
groupZkSecretParams, zkProfileOperations, batchIdentityCheckExecutor),
|
||||
new ProvisioningController(rateLimiters, provisioningManager),
|
||||
new RegistrationController(accountsManager, phoneVerificationTokenManager, registrationLockVerificationManager,
|
||||
rateLimiters, registrationFraudChecker),
|
||||
@@ -1259,7 +1274,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
dynamicConfigurationManager, experimentEnrollmentManager, clock),
|
||||
new SubscriptionController(clock, config.getSubscription(), config.getOneTimeDonations(),
|
||||
subscriptionManager, stripeManager, braintreeManager, googlePlayBillingManager, appleAppStoreManager,
|
||||
profileBadgeConverter, bankMandateTranslator, donationPermitsManager, dynamicConfigurationManager),
|
||||
profileBadgeConverter, bankMandateTranslator, donationPermitsManager,
|
||||
config.getBackupConfiguration().maxTotalMediaSize()),
|
||||
new OneTimeDonationController(clock, config.getOneTimeDonations(), stripeManager, braintreeManager,
|
||||
payPalDonationsTranslator, zkReceiptOperations, issuedReceiptsManager, oneTimeDonationsManager,
|
||||
donationPermitsManager)
|
||||
@@ -1328,13 +1344,15 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new InvalidWebsocketAddressExceptionMapper(),
|
||||
new DeviceLimitExceededExceptionMapper(),
|
||||
new ServerRejectedExceptionMapper(),
|
||||
new IllegalStateExceptionMapper(),
|
||||
new ImpossiblePhoneNumberExceptionMapper(),
|
||||
new NonNormalizedPhoneNumberExceptionMapper(),
|
||||
new ObsoletePhoneNumberFormatExceptionMapper(),
|
||||
new RegistrationServiceSenderExceptionMapper(),
|
||||
new SubscriptionExceptionMapper(),
|
||||
new BackupExceptionMapper(),
|
||||
new JsonMappingExceptionMapper()
|
||||
new JsonMappingExceptionMapper(),
|
||||
new RegistrationLockFailureExceptionMapper()
|
||||
).forEach(exceptionMapper -> {
|
||||
environment.jersey().register(exceptionMapper);
|
||||
webSocketEnvironment.jersey().register(exceptionMapper);
|
||||
|
||||
+5
-3
@@ -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) {
|
||||
|
||||
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import org.whispersystems.textsecuregcm.util.NoStackTraceException;
|
||||
|
||||
public class InvalidRegistrationSessionException extends NoStackTraceException {
|
||||
|
||||
public InvalidRegistrationSessionException(final String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
+29
-25
@@ -7,12 +7,7 @@ package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import io.grpc.Status;
|
||||
import io.grpc.StatusRuntimeException;
|
||||
import jakarta.ws.rs.BadRequestException;
|
||||
import jakarta.ws.rs.ForbiddenException;
|
||||
import jakarta.ws.rs.NotAuthorizedException;
|
||||
import jakarta.ws.rs.ServerErrorException;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.io.IOException;
|
||||
import java.security.MessageDigest;
|
||||
import java.time.Duration;
|
||||
import java.util.UUID;
|
||||
@@ -55,23 +50,27 @@ public class PhoneVerificationTokenManager {
|
||||
* Checks if a {@link PhoneVerificationRequest} has a token that verifies the caller has confirmed access to the e164
|
||||
* number
|
||||
*
|
||||
* @param requestContext the container request context
|
||||
* @param number the e164 presented for verification
|
||||
* @param sessionId a verification session ID; exactly one of {@code sessionId} or {@code recoveryPassword} must be
|
||||
* non-null
|
||||
* @param recoveryPassword a registration recovery password; exactly one of {@code sessionId} or
|
||||
* {@code recoveryPassword} must be non-null
|
||||
* @return if verification was successful, returns the verification type
|
||||
* @throws BadRequestException if the number does not match the sessionId’s number, or the remote service rejects
|
||||
* @throws InvalidRegistrationSessionException if the number does not match the sessionId’s number, or the remote service rejects
|
||||
* the session ID as invalid
|
||||
* @throws NotAuthorizedException if the session is not verified
|
||||
* @throws ForbiddenException if the recovery password is not valid
|
||||
* @throws UnverifiedRegistrationSessionException if the session is not verified
|
||||
* @throws RecoveryPasswordVerificationFailedException if the recovery password is not valid
|
||||
* @throws InterruptedException if verification did not complete before a timeout
|
||||
* @throws IOException if there was an error talking to registration service
|
||||
*/
|
||||
public PhoneVerificationRequest.VerificationType verify(final ContainerRequestContext requestContext,
|
||||
public PhoneVerificationRequest.VerificationType verify(
|
||||
final String number,
|
||||
@Nullable final String userAgent,
|
||||
@Nullable final String acceptLanguage,
|
||||
@Nullable final String mostRecentProxy,
|
||||
@Nullable final byte[] sessionId,
|
||||
@Nullable final byte[] recoveryPassword) throws InterruptedException {
|
||||
@Nullable final byte[] recoveryPassword)
|
||||
throws InterruptedException, UnverifiedRegistrationSessionException, InvalidRegistrationSessionException, IOException, RecoveryPasswordVerificationFailedException {
|
||||
|
||||
if ((sessionId == null) == (recoveryPassword == null)) {
|
||||
throw new IllegalArgumentException("Exactly one of session ID or recovery password must non-null");
|
||||
@@ -83,40 +82,45 @@ public class PhoneVerificationTokenManager {
|
||||
|
||||
switch (verificationType) {
|
||||
case SESSION -> verifyBySessionId(number, sessionId);
|
||||
case RECOVERY_PASSWORD -> verifyByRecoveryPassword(requestContext, number, recoveryPassword);
|
||||
case RECOVERY_PASSWORD -> verifyByRecoveryPassword(number, userAgent, acceptLanguage, mostRecentProxy, recoveryPassword);
|
||||
}
|
||||
|
||||
return verificationType;
|
||||
}
|
||||
|
||||
private void verifyBySessionId(final String number, final byte[] sessionId) {
|
||||
private void verifyBySessionId(final String number, final byte[] sessionId)
|
||||
throws UnverifiedRegistrationSessionException, InvalidRegistrationSessionException, IOException {
|
||||
try {
|
||||
final RegistrationServiceSession session = registrationServiceClient
|
||||
.getSession(sessionId, REGISTRATION_RPC_TIMEOUT)
|
||||
.orElseThrow(() -> new NotAuthorizedException("session not verified"));
|
||||
.orElseThrow(UnverifiedRegistrationSessionException::new);
|
||||
|
||||
if (!MessageDigest.isEqual(number.getBytes(), session.number().getBytes())) {
|
||||
throw new BadRequestException("number does not match session");
|
||||
throw new InvalidRegistrationSessionException("number does not match session");
|
||||
}
|
||||
if (!session.verified()) {
|
||||
throw new NotAuthorizedException("session not verified");
|
||||
throw new UnverifiedRegistrationSessionException();
|
||||
}
|
||||
} catch (final StatusRuntimeException e) {
|
||||
if (e.getStatus().getCode() == Status.Code.INVALID_ARGUMENT) {
|
||||
throw new BadRequestException();
|
||||
throw new InvalidRegistrationSessionException(e.getMessage());
|
||||
}
|
||||
|
||||
logger.error("Registration service failure", e);
|
||||
throw new ServerErrorException(Response.Status.SERVICE_UNAVAILABLE);
|
||||
throw new IOException("Registration service failure", e);
|
||||
}
|
||||
}
|
||||
|
||||
private void verifyByRecoveryPassword(final ContainerRequestContext requestContext,
|
||||
private void verifyByRecoveryPassword(
|
||||
final String number,
|
||||
final byte[] recoveryPassword) throws InterruptedException {
|
||||
@Nullable final String userAgent,
|
||||
@Nullable final String acceptLanguage,
|
||||
@Nullable final String mostRecentProxy,
|
||||
final byte[] recoveryPassword)
|
||||
throws InterruptedException, IOException, RecoveryPasswordVerificationFailedException {
|
||||
|
||||
if (!registrationRecoveryChecker.checkRegistrationRecoveryAttempt(requestContext, number)) {
|
||||
throw new ForbiddenException("recoveryPassword couldn't be verified");
|
||||
if (!registrationRecoveryChecker.checkRegistrationRecoveryAttempt(number, userAgent, acceptLanguage, mostRecentProxy)) {
|
||||
throw new RecoveryPasswordVerificationFailedException();
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -126,10 +130,10 @@ public class PhoneVerificationTokenManager {
|
||||
final boolean verified = registrationRecoveryPasswordsManager.verify(phoneNumberIdentifier, recoveryPassword);
|
||||
|
||||
if (!verified) {
|
||||
throw new ForbiddenException("recoveryPassword couldn't be verified");
|
||||
throw new RecoveryPasswordVerificationFailedException();
|
||||
}
|
||||
} catch (final ExecutionException | TimeoutException e) {
|
||||
throw new ServerErrorException(Response.Status.SERVICE_UNAVAILABLE);
|
||||
throw new IOException("registration service unavailable", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import org.whispersystems.textsecuregcm.util.NoStackTraceException;
|
||||
|
||||
public class RecoveryPasswordVerificationFailedException extends NoStackTraceException {
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import org.whispersystems.textsecuregcm.entities.RegistrationLockFailure;
|
||||
import org.whispersystems.textsecuregcm.util.NoStackTraceException;
|
||||
|
||||
public class RegistrationLockFailureException extends NoStackTraceException {
|
||||
|
||||
private final RegistrationLockFailure failure;
|
||||
|
||||
public RegistrationLockFailureException(final RegistrationLockFailure failure) {
|
||||
super();
|
||||
this.failure = failure;
|
||||
}
|
||||
|
||||
public RegistrationLockFailure getFailure() {
|
||||
return failure;
|
||||
}
|
||||
}
|
||||
+6
-9
@@ -12,8 +12,6 @@ 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 jakarta.ws.rs.WebApplicationException;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
@@ -80,13 +78,13 @@ public class RegistrationLockVerificationManager {
|
||||
* @param account
|
||||
* @param clientRegistrationLock
|
||||
* @throws RateLimitExceededException
|
||||
* @throws WebApplicationException
|
||||
* @throws RegistrationLockFailureException
|
||||
*/
|
||||
public void verifyRegistrationLock(final Account account, @Nullable final String clientRegistrationLock,
|
||||
final String userAgent,
|
||||
@Nullable final String userAgent,
|
||||
final Flow flow,
|
||||
final PhoneVerificationRequest.VerificationType phoneVerificationType
|
||||
) throws RateLimitExceededException, WebApplicationException {
|
||||
) throws RateLimitExceededException, RegistrationLockFailureException {
|
||||
|
||||
final Tags expiredTags = Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
Tag.of(REGISTRATION_LOCK_VERIFICATION_FLOW_TAG_NAME, flow.name()),
|
||||
@@ -165,11 +163,10 @@ public class RegistrationLockVerificationManager {
|
||||
Metrics.counter(CHALLENGED_DEVICE_NOT_PUSH_REGISTERED_COUNTER_NAME).increment();
|
||||
}
|
||||
|
||||
throw new WebApplicationException(Response.status(FAILURE_HTTP_STATUS)
|
||||
.entity(new RegistrationLockFailure(
|
||||
throw new RegistrationLockFailureException(
|
||||
new RegistrationLockFailure(
|
||||
existingRegistrationLock.getTimeRemaining().toMillis(),
|
||||
svr2FailureCredentials(existingRegistrationLock, updatedAccount)))
|
||||
.build());
|
||||
svr2FailureCredentials(existingRegistrationLock, updatedAccount)));
|
||||
}
|
||||
|
||||
rateLimiters.getPinLimiter().clear(phoneNumber);
|
||||
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import org.whispersystems.textsecuregcm.util.NoStackTraceException;
|
||||
|
||||
public class UnverifiedRegistrationSessionException extends NoStackTraceException {
|
||||
}
|
||||
@@ -23,6 +23,7 @@ import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import java.util.function.Function;
|
||||
import javax.annotation.Nullable;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.signal.libsignal.protocol.ecc.ECKeyPair;
|
||||
import org.signal.libsignal.protocol.ecc.ECPublicKey;
|
||||
@@ -34,19 +35,17 @@ import org.signal.libsignal.zkgroup.backups.BackupLevel;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.attachments.AttachmentGenerator;
|
||||
import org.whispersystems.textsecuregcm.attachments.AttachmentUtil;
|
||||
import org.whispersystems.textsecuregcm.attachments.TusAttachmentGenerator;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedBackupUser;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials;
|
||||
import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicBackupConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.BackupConfiguration;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecoveryClient;
|
||||
import org.whispersystems.textsecuregcm.attachments.AttachmentUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
|
||||
@@ -55,7 +54,6 @@ import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
public class BackupManager {
|
||||
|
||||
@@ -89,7 +87,7 @@ public class BackupManager {
|
||||
private final ExternalServiceCredentialsGenerator secureValueRecoveryBCredentialsGenerator;
|
||||
private final SecureValueRecoveryClient secureValueRecoveryBClient;
|
||||
private final Clock clock;
|
||||
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
private final BackupConfiguration backupConfiguration;
|
||||
|
||||
public BackupManager(
|
||||
final BackupsDb backupsDb,
|
||||
@@ -101,7 +99,7 @@ public class BackupManager {
|
||||
final ExternalServiceCredentialsGenerator secureValueRecoveryBCredentialsGenerator,
|
||||
final SecureValueRecoveryClient secureValueRecoveryBClient,
|
||||
final Clock clock,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
|
||||
final BackupConfiguration backupConfiguration) {
|
||||
this.backupsDb = backupsDb;
|
||||
this.serverSecretParams = serverSecretParams;
|
||||
this.rateLimiters = rateLimiters;
|
||||
@@ -111,7 +109,7 @@ public class BackupManager {
|
||||
this.secureValueRecoveryBClient = secureValueRecoveryBClient;
|
||||
this.clock = clock;
|
||||
this.secureValueRecoveryBCredentialsGenerator = secureValueRecoveryBCredentialsGenerator;
|
||||
this.dynamicConfigurationManager = dynamicConfigurationManager;
|
||||
this.backupConfiguration = backupConfiguration;
|
||||
}
|
||||
|
||||
|
||||
@@ -196,8 +194,7 @@ public class BackupManager {
|
||||
// update message backup TTL
|
||||
final StoredBackupAttributes storedBackupAttributes = backupsDb.ttlRefresh(backupUser).join();
|
||||
if (backupUser.credentialType() == BackupCredentialType.MEDIA) {
|
||||
final long maxTotalMediaSize =
|
||||
dynamicConfigurationManager.getConfiguration().getBackupConfiguration().maxTotalMediaSize();
|
||||
final long maxTotalMediaSize = backupConfiguration.maxTotalMediaSize();
|
||||
|
||||
// Report that the backup is out of quota if it is within 100MiB of the limit
|
||||
final boolean quotaExhausted = storedBackupAttributes.bytesUsed() >=
|
||||
@@ -258,8 +255,6 @@ public class BackupManager {
|
||||
*/
|
||||
public Flux<CopyResult> copyToBackup(final CopyQuota copyQuota) {
|
||||
final AuthenticatedBackupUser backupUser = copyQuota.backupUser();
|
||||
final DynamicBackupConfiguration backupConfiguration =
|
||||
dynamicConfigurationManager.getConfiguration().getBackupConfiguration();
|
||||
|
||||
return Flux.concat(
|
||||
|
||||
@@ -347,8 +342,6 @@ public class BackupManager {
|
||||
}
|
||||
final long totalBytesAdded = toCopy.stream().mapToLong(CopyParameters::destinationObjectSize).sum();
|
||||
|
||||
final DynamicBackupConfiguration backupConfiguration =
|
||||
dynamicConfigurationManager.getConfiguration().getBackupConfiguration();
|
||||
final Duration maxQuotaStaleness = backupConfiguration.maxQuotaStaleness();
|
||||
final long maxTotalMediaSize = backupConfiguration.maxTotalMediaSize();
|
||||
|
||||
@@ -491,8 +484,7 @@ public class BackupManager {
|
||||
public void deleteEntireBackup(final AuthenticatedBackupUser backupUser) throws BackupPermissionException {
|
||||
checkBackupLevel(backupUser, BackupLevel.FREE);
|
||||
|
||||
final int deletionConcurrency =
|
||||
dynamicConfigurationManager.getConfiguration().getBackupConfiguration().deletionConcurrency();
|
||||
final int deletionConcurrency = backupConfiguration.deletionConcurrency();
|
||||
|
||||
// Clients only include SVRB data with their messages backup-id
|
||||
if (backupUser.credentialType() == BackupCredentialType.MESSAGES) {
|
||||
@@ -523,8 +515,6 @@ public class BackupManager {
|
||||
if (storageDescriptors.stream().anyMatch(sd -> sd.cdn() != remoteStorageManager.cdnNumber())) {
|
||||
return Flux.error(new BackupInvalidArgumentException("unsupported media cdn provided"));
|
||||
}
|
||||
final DynamicBackupConfiguration backupConfiguration =
|
||||
dynamicConfigurationManager.getConfiguration().getBackupConfiguration();
|
||||
|
||||
return Flux.usingWhen(
|
||||
|
||||
|
||||
+3
@@ -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 -> {
|
||||
|
||||
@@ -10,5 +10,8 @@ import java.util.Locale;
|
||||
import org.whispersystems.textsecuregcm.entities.Badge;
|
||||
|
||||
public interface BadgeTranslator {
|
||||
|
||||
Locale resolveLocale(List<Locale> acceptableLanguages);
|
||||
|
||||
Badge translate(List<Locale> acceptableLanguages, String badgeId);
|
||||
}
|
||||
+21
-18
@@ -7,7 +7,6 @@ package org.whispersystems.textsecuregcm.badges;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
@@ -31,7 +30,6 @@ public class ConfiguredProfileBadgeConverter implements ProfileBadgeConverter, B
|
||||
|
||||
private final Clock clock;
|
||||
private final Map<String, BadgeConfiguration> knownBadges;
|
||||
private final List<String> badgeIdsEnabledForAll;
|
||||
private final HeaderControlledResourceBundleLookup headerControlledResourceBundleLookup;
|
||||
|
||||
public ConfiguredProfileBadgeConverter(
|
||||
@@ -41,10 +39,14 @@ public class ConfiguredProfileBadgeConverter implements ProfileBadgeConverter, B
|
||||
this.clock = clock;
|
||||
this.knownBadges = badgesConfiguration.getBadges().stream()
|
||||
.collect(Collectors.toMap(BadgeConfiguration::getId, Function.identity()));
|
||||
this.badgeIdsEnabledForAll = badgesConfiguration.getBadgeIdsEnabledForAll();
|
||||
this.headerControlledResourceBundleLookup = headerControlledResourceBundleLookup;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Locale resolveLocale(final List<Locale> acceptableLanguages) {
|
||||
return headerControlledResourceBundleLookup.getResourceBundle(BASE_NAME, acceptableLanguages).getLocale();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Badge translate(final List<Locale> acceptableLanguages, final String badgeId) {
|
||||
final ResourceBundle resourceBundle = headerControlledResourceBundleLookup.getResourceBundle(BASE_NAME,
|
||||
@@ -63,12 +65,27 @@ public class ConfiguredProfileBadgeConverter implements ProfileBadgeConverter, B
|
||||
false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> visibleBadgeIds(final List<AccountBadge> accountBadges) {
|
||||
if (accountBadges.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
final Instant now = clock.instant();
|
||||
return accountBadges.stream()
|
||||
.filter(accountBadge -> accountBadge.visible()
|
||||
&& now.isBefore(accountBadge.expiration())
|
||||
&& knownBadges.containsKey(accountBadge.id()))
|
||||
.map(AccountBadge::id)
|
||||
.toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Badge> convert(
|
||||
final List<Locale> acceptableLanguages,
|
||||
final List<AccountBadge> accountBadges,
|
||||
final boolean isSelf) {
|
||||
if (accountBadges.isEmpty() && badgeIdsEnabledForAll.isEmpty()) {
|
||||
if (accountBadges.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
@@ -94,20 +111,6 @@ public class ConfiguredProfileBadgeConverter implements ProfileBadgeConverter, B
|
||||
accountBadge.visible());
|
||||
})
|
||||
.collect(Collectors.toCollection(ArrayList::new));
|
||||
badges.addAll(badgeIdsEnabledForAll.stream().filter(knownBadges::containsKey).map(id -> {
|
||||
BadgeConfiguration configuration = knownBadges.get(id);
|
||||
return newBadge(
|
||||
isSelf,
|
||||
id,
|
||||
configuration.getCategory(),
|
||||
resourceBundle.getString(id + "_name"),
|
||||
resourceBundle.getString(id + "_description"),
|
||||
configuration.getSprites(),
|
||||
configuration.getSvg(),
|
||||
configuration.getSvgs(),
|
||||
now.plus(Duration.ofDays(1)),
|
||||
true);
|
||||
}).collect(Collectors.toList()));
|
||||
return badges;
|
||||
}
|
||||
|
||||
|
||||
+6
@@ -12,6 +12,12 @@ import org.whispersystems.textsecuregcm.storage.AccountBadge;
|
||||
|
||||
public interface ProfileBadgeConverter {
|
||||
|
||||
/// Determine displayable badge ids for an account's badges
|
||||
///
|
||||
/// @param badges The full list of badges on an account
|
||||
/// @return The list of badge-ids that should appear on this account's profile to other users
|
||||
List<String> visibleBadgeIds(final List<AccountBadge> badges);
|
||||
|
||||
/**
|
||||
* Converts the {@link AccountBadge}s for an account into the objects
|
||||
* that can be returned on a profile fetch.
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
|
||||
+4
-4
@@ -3,7 +3,7 @@
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.configuration.dynamic;
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import io.dropwizard.util.DataSize;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
@@ -17,14 +17,14 @@ import java.time.Duration;
|
||||
* @param maxQuotaStaleness The maximum age of a quota estimate that can be used to enforce a quota limit
|
||||
* @param maxTotalMediaSize The number of media bytes a paid-tier user may store
|
||||
*/
|
||||
public record DynamicBackupConfiguration(
|
||||
public record BackupConfiguration(
|
||||
@NotNull Integer deletionConcurrency,
|
||||
@NotNull Integer copyConcurrency,
|
||||
@NotNull Integer usageCheckpointCount,
|
||||
@NotNull Duration maxQuotaStaleness,
|
||||
@NotNull Long maxTotalMediaSize) {
|
||||
|
||||
public DynamicBackupConfiguration {
|
||||
public BackupConfiguration {
|
||||
if (deletionConcurrency == null) {
|
||||
deletionConcurrency = 10;
|
||||
}
|
||||
@@ -42,7 +42,7 @@ public record DynamicBackupConfiguration(
|
||||
}
|
||||
}
|
||||
|
||||
public DynamicBackupConfiguration() {
|
||||
public BackupConfiguration() {
|
||||
this(null, null, null, null, null);
|
||||
}
|
||||
}
|
||||
-9
@@ -21,16 +21,13 @@ import java.util.stream.Collectors;
|
||||
|
||||
public class BadgesConfiguration {
|
||||
private final List<BadgeConfiguration> badges;
|
||||
private final List<String> badgeIdsEnabledForAll;
|
||||
private final Map<Long, String> receiptLevels;
|
||||
|
||||
@JsonCreator
|
||||
public BadgesConfiguration(
|
||||
@JsonProperty("badges") @JsonSetter(nulls = Nulls.AS_EMPTY) final List<BadgeConfiguration> badges,
|
||||
@JsonProperty("badgeIdsEnabledForAll") @JsonSetter(nulls = Nulls.AS_EMPTY) final List<String> badgeIdsEnabledForAll,
|
||||
@JsonProperty("receiptLevels") @JsonSetter(nulls = Nulls.AS_EMPTY) final Map<Long, String> receiptLevels) {
|
||||
this.badges = Objects.requireNonNull(badges);
|
||||
this.badgeIdsEnabledForAll = Objects.requireNonNull(badgeIdsEnabledForAll);
|
||||
this.receiptLevels = Objects.requireNonNull(receiptLevels);
|
||||
}
|
||||
|
||||
@@ -40,12 +37,6 @@ public class BadgesConfiguration {
|
||||
return badges;
|
||||
}
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
public List<String> getBadgeIdsEnabledForAll() {
|
||||
return badgeIdsEnabledForAll;
|
||||
}
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
public Map<Long, String> getReceiptLevels() {
|
||||
|
||||
+8
-1
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+14
-1
@@ -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() {
|
||||
|
||||
-8
@@ -69,10 +69,6 @@ public class DynamicConfiguration {
|
||||
@Valid
|
||||
DynamicRestDeprecationConfiguration restDeprecation = new DynamicRestDeprecationConfiguration(Map.of());
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
private DynamicBackupConfiguration backup = new DynamicBackupConfiguration();
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
private DynamicCarrierDataLookupConfiguration carrierDataLookup = new DynamicCarrierDataLookupConfiguration();
|
||||
@@ -143,10 +139,6 @@ public class DynamicConfiguration {
|
||||
return restDeprecation;
|
||||
}
|
||||
|
||||
public DynamicBackupConfiguration getBackupConfiguration() {
|
||||
return backup;
|
||||
}
|
||||
|
||||
public DynamicCarrierDataLookupConfiguration getCarrierDataLookupConfiguration() {
|
||||
return carrierDataLookup;
|
||||
}
|
||||
|
||||
+20
-2
@@ -19,6 +19,7 @@ import jakarta.ws.rs.Consumes;
|
||||
import jakarta.ws.rs.ForbiddenException;
|
||||
import jakarta.ws.rs.GET;
|
||||
import jakarta.ws.rs.HeaderParam;
|
||||
import jakarta.ws.rs.NotAuthorizedException;
|
||||
import jakarta.ws.rs.PUT;
|
||||
import jakarta.ws.rs.Path;
|
||||
import jakarta.ws.rs.Produces;
|
||||
@@ -28,11 +29,16 @@ import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.core.Context;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.io.IOException;
|
||||
import java.time.Instant;
|
||||
import java.util.UUID;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.ChangesPhoneNumber;
|
||||
import org.whispersystems.textsecuregcm.auth.InvalidRegistrationSessionException;
|
||||
import org.whispersystems.textsecuregcm.auth.RecoveryPasswordVerificationFailedException;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockFailureException;
|
||||
import org.whispersystems.textsecuregcm.auth.UnverifiedRegistrationSessionException;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountDataReportResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.ChangeNumberRequest;
|
||||
@@ -40,6 +46,7 @@ import org.whispersystems.textsecuregcm.entities.MismatchedDevicesResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.PhoneNumberDiscoverabilityRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.RegistrationLockFailure;
|
||||
import org.whispersystems.textsecuregcm.entities.StaleDevicesResponse;
|
||||
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
|
||||
import org.whispersystems.textsecuregcm.push.MessageTooLargeException;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
@@ -80,7 +87,8 @@ public class AccountControllerV2 {
|
||||
public AccountIdentityResponse changeNumber(@Auth final AuthenticatedDevice authenticatedDevice,
|
||||
@NotNull @Valid final ChangeNumberRequest request,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgentString,
|
||||
@Context final ContainerRequestContext requestContext) throws RateLimitExceededException, InterruptedException {
|
||||
@Context final ContainerRequestContext requestContext)
|
||||
throws RateLimitExceededException, InterruptedException, RegistrationLockFailureException {
|
||||
|
||||
if (authenticatedDevice.deviceId() != Device.PRIMARY_ID) {
|
||||
throw new ForbiddenException();
|
||||
@@ -102,7 +110,9 @@ public class AccountControllerV2 {
|
||||
request.devicePniPqLastResortPrekeys(),
|
||||
request.deviceMessages(),
|
||||
request.pniRegistrationIds(),
|
||||
requestContext);
|
||||
userAgentString,
|
||||
requestContext.getHeaderString(HttpHeaders.ACCEPT_LANGUAGE),
|
||||
(String) requestContext.getProperty(RemoteAddressFilter.REMOTE_ADDRESS_ATTRIBUTE_NAME));
|
||||
|
||||
return AccountIdentityResponseBuilder.fromAccount(updatedAccount);
|
||||
} catch (final MismatchedDevicesException e) {
|
||||
@@ -124,6 +134,14 @@ public class AccountControllerV2 {
|
||||
throw new WebApplicationException(Response.Status.REQUEST_ENTITY_TOO_LARGE);
|
||||
} catch (final MessageDeliveryNotAllowedException e) {
|
||||
throw new ServiceUnavailableException();
|
||||
} catch (final UnverifiedRegistrationSessionException e) {
|
||||
throw new NotAuthorizedException("registration session is unverified");
|
||||
} catch (final InvalidRegistrationSessionException e) {
|
||||
throw new BadRequestException(e.getMessage());
|
||||
} catch (final IOException e) {
|
||||
throw new ServiceUnavailableException(e.getMessage());
|
||||
} catch (final RecoveryPasswordVerificationFailedException e) {
|
||||
throw new ForbiddenException("recovery password could not be verified");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
-1
@@ -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 {
|
||||
|
||||
+3
-3
@@ -75,7 +75,7 @@ public class KeyTransparencyController {
|
||||
"""
|
||||
)
|
||||
@ApiResponse(responseCode = "200", description = "The ACI was found and its mapped value matched the provided ACI identity key", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "400", description = "Invalid request. See response for any available details.")
|
||||
@ApiResponse(responseCode = "400", description = "Request was authenticated but endpoint requires unauthenticated access.")
|
||||
@ApiResponse(responseCode = "403", description = """
|
||||
The ACI was found but its mapped value did not match the provided ACI identity key
|
||||
or the ACI was not found in the log.
|
||||
@@ -135,7 +135,7 @@ public class KeyTransparencyController {
|
||||
"""
|
||||
)
|
||||
@ApiResponse(responseCode = "200", description = "All identifiers exist in the log", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "400", description = "Invalid request. See response for any available details.")
|
||||
@ApiResponse(responseCode = "400", description = "Request was authenticated but endpoint requires unauthenticated access.")
|
||||
@ApiResponse(responseCode = "403", description = "One or more of the provided commitment indexes did not match")
|
||||
@ApiResponse(responseCode = "404", description = "At least one identifier was not found")
|
||||
@ApiResponse(responseCode = "429", description = "Rate-limited")
|
||||
@@ -205,7 +205,7 @@ public class KeyTransparencyController {
|
||||
"""
|
||||
)
|
||||
@ApiResponse(responseCode = "200", description = "The `distinguished` search key exists in the log", useReturnTypeSchema = true)
|
||||
@ApiResponse(responseCode = "400", description = "Invalid request. See response for any available details.")
|
||||
@ApiResponse(responseCode = "400", description = "Request was authenticated but endpoint requires unauthenticated access.")
|
||||
@ApiResponse(responseCode = "422", description = "Invalid request format")
|
||||
@ApiResponse(responseCode = "429", description = "Rate-limited")
|
||||
@GET
|
||||
|
||||
+97
-98
@@ -8,6 +8,7 @@ import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.getClientP
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import com.stripe.model.PaymentIntent;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
@@ -34,9 +35,9 @@ import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.core.Context;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.io.IOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.Collections;
|
||||
@@ -45,7 +46,7 @@ import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import org.glassfish.jersey.server.ManagedAsync;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialRequest;
|
||||
@@ -74,6 +75,8 @@ import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentStatus;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.StripeManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidAmountException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorException;
|
||||
import org.whispersystems.textsecuregcm.util.ExactlySize;
|
||||
import org.whispersystems.textsecuregcm.util.HeaderUtils;
|
||||
|
||||
@@ -168,14 +171,15 @@ public class OneTimeDonationController {
|
||||
})))
|
||||
@ApiResponse(responseCode = "401", description = "Donation permit was invalid or already spent")
|
||||
@RateLimitedByIp(RateLimiters.For.ONE_TIME_DONATION)
|
||||
public CompletableFuture<Response> createBoostPaymentIntent(
|
||||
@ManagedAsync
|
||||
public CreateBoostResponse createBoostPaymentIntent(
|
||||
@Auth final Optional<AuthenticatedDevice> authenticatedAccount,
|
||||
|
||||
@Parameter(description = "A base64-encoded donation permit retrieved from POST /v1/donation/permit")
|
||||
@HeaderParam(HeaderUtils.DONATION_PERMIT) final Optional<DonationPermitHeader> donationPermitHeader,
|
||||
|
||||
@NotNull @Valid final CreateBoostRequest request,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent) {
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent) throws SubscriptionInvalidAmountException {
|
||||
|
||||
if (authenticatedAccount.isPresent()) {
|
||||
throw new ForbiddenException("must not use authenticated connection for one-time donation operations");
|
||||
@@ -190,16 +194,16 @@ public class OneTimeDonationController {
|
||||
return false;
|
||||
}
|
||||
})
|
||||
.orElse(true);
|
||||
.orElse(false);
|
||||
if (!spendSuccessful) {
|
||||
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
|
||||
}
|
||||
|
||||
return CompletableFuture.runAsync(() ->
|
||||
validateRequestCurrencyAmount(request, BigDecimal.valueOf(request.amount), stripeManager))
|
||||
.thenCompose(_ -> stripeManager.createPaymentIntent(request.currency, request.amount, request.level,
|
||||
getClientPlatform(userAgent)))
|
||||
.thenApply(paymentIntent -> Response.ok(new CreateBoostResponse(paymentIntent.getClientSecret())).build());
|
||||
validateRequestCurrencyAmount(request, BigDecimal.valueOf(request.amount), stripeManager);
|
||||
final PaymentIntent paymentIntent = stripeManager.createPaymentIntent(request.currency, request.amount,
|
||||
request.level,
|
||||
getClientPlatform(userAgent));
|
||||
return new CreateBoostResponse(paymentIntent.getClientSecret());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -245,34 +249,32 @@ public class OneTimeDonationController {
|
||||
}
|
||||
}
|
||||
|
||||
record CreatePayPalBoostResponse(String approvalUrl, String paymentId) {}
|
||||
public record CreatePayPalBoostResponse(String approvalUrl, String paymentId) {}
|
||||
|
||||
@POST
|
||||
@Path("/paypal/create")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public CompletableFuture<Response> createPayPalBoost(
|
||||
@ManagedAsync
|
||||
public CreatePayPalBoostResponse createPayPalBoost(
|
||||
@Auth final Optional<AuthenticatedDevice> authenticatedAccount,
|
||||
@NotNull @Valid final CreatePayPalBoostRequest request,
|
||||
@Context final ContainerRequestContext containerRequestContext) {
|
||||
@Context final ContainerRequestContext containerRequestContext) throws IOException {
|
||||
|
||||
if (authenticatedAccount.isPresent()) {
|
||||
throw new ForbiddenException("must not use authenticated connection for one-time donation operations");
|
||||
}
|
||||
|
||||
return CompletableFuture.runAsync(() ->
|
||||
validateRequestCurrencyAmount(request, BigDecimal.valueOf(request.amount), braintreeManager))
|
||||
.thenCompose(_ -> {
|
||||
final List<Locale> acceptableLanguages =
|
||||
HeaderUtils.getAcceptableLanguagesForRequest(containerRequestContext);
|
||||
final OneTimeDonationUtil.LocalizedPayPalDonationLineItem localizedLineItem = OneTimeDonationUtil.localizePayPalDonationLineItem(
|
||||
payPalDonationsTranslator, acceptableLanguages);
|
||||
return braintreeManager.createOneTimePayment(request.currency.toUpperCase(Locale.ROOT), request.amount,
|
||||
localizedLineItem.locale().toLanguageTag(),
|
||||
request.returnUrl, request.cancelUrl, localizedLineItem.itemName());
|
||||
})
|
||||
.thenApply(approvalDetails -> Response.ok(
|
||||
new CreatePayPalBoostResponse(approvalDetails.approvalUrl(), approvalDetails.paymentId())).build());
|
||||
validateRequestCurrencyAmount(request, BigDecimal.valueOf(request.amount), braintreeManager);
|
||||
final List<Locale> acceptableLanguages =
|
||||
HeaderUtils.getAcceptableLanguagesForRequest(containerRequestContext);
|
||||
final OneTimeDonationUtil.LocalizedPayPalDonationLineItem localizedLineItem = OneTimeDonationUtil.localizePayPalDonationLineItem(
|
||||
payPalDonationsTranslator, acceptableLanguages);
|
||||
final BraintreeManager.PayPalOneTimePaymentApprovalDetails approvalDetails =
|
||||
braintreeManager.createOneTimePayment(request.currency.toUpperCase(Locale.ROOT), request.amount,
|
||||
localizedLineItem.locale().toLanguageTag(),
|
||||
request.returnUrl, request.cancelUrl, localizedLineItem.itemName());
|
||||
return new CreatePayPalBoostResponse(approvalDetails.approvalUrl(), approvalDetails.paymentId());
|
||||
}
|
||||
|
||||
public static class ConfirmPayPalBoostRequest extends CreateBoostRequest {
|
||||
@@ -289,30 +291,28 @@ public class OneTimeDonationController {
|
||||
}
|
||||
}
|
||||
|
||||
record ConfirmPayPalBoostResponse(String paymentId) {}
|
||||
public record ConfirmPayPalBoostResponse(String paymentId) {}
|
||||
|
||||
@POST
|
||||
@Path("/paypal/confirm")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public CompletableFuture<Response> confirmPayPalBoost(
|
||||
@ManagedAsync
|
||||
public ConfirmPayPalBoostResponse confirmPayPalBoost(
|
||||
@Auth final Optional<AuthenticatedDevice> authenticatedAccount,
|
||||
@NotNull @Valid final ConfirmPayPalBoostRequest request,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent) {
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent) throws SubscriptionProcessorException, IOException {
|
||||
|
||||
if (authenticatedAccount.isPresent()) {
|
||||
throw new ForbiddenException("must not use authenticated connection for one-time donation operations");
|
||||
}
|
||||
|
||||
return CompletableFuture.runAsync(() ->
|
||||
validateRequestCurrencyAmount(request, BigDecimal.valueOf(request.amount), braintreeManager))
|
||||
.thenCompose(_ -> braintreeManager.captureOneTimePayment(request.payerId, request.paymentId,
|
||||
request.paymentToken, request.currency, request.amount, request.level, getClientPlatform(userAgent)))
|
||||
.thenApply(chargeSuccessDetails -> {
|
||||
oneTimeDonationsManager.putPaidAt(chargeSuccessDetails.paymentId(), Instant.now());
|
||||
return Response.ok(
|
||||
new ConfirmPayPalBoostResponse(chargeSuccessDetails.paymentId())).build();
|
||||
});
|
||||
validateRequestCurrencyAmount(request, BigDecimal.valueOf(request.amount), braintreeManager);
|
||||
final BraintreeManager.PayPalChargeSuccessDetails chargeSuccessDetails = braintreeManager.captureOneTimePayment(
|
||||
request.payerId, request.paymentId,
|
||||
request.paymentToken, request.currency, request.amount, request.level, getClientPlatform(userAgent));
|
||||
oneTimeDonationsManager.putPaidAt(chargeSuccessDetails.paymentId(), Instant.now());
|
||||
return new ConfirmPayPalBoostResponse(chargeSuccessDetails.paymentId());
|
||||
}
|
||||
|
||||
public static class CreateBoostReceiptCredentialsRequest {
|
||||
@@ -339,77 +339,76 @@ public class OneTimeDonationController {
|
||||
@Path("/receipt_credentials")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public CompletableFuture<Response> createBoostReceiptCredentials(
|
||||
@ManagedAsync
|
||||
public Response createBoostReceiptCredentials(
|
||||
@Auth final Optional<AuthenticatedDevice> authenticatedAccount,
|
||||
@NotNull @Valid final CreateBoostReceiptCredentialsRequest request,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent) {
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent) throws IOException {
|
||||
|
||||
if (authenticatedAccount.isPresent()) {
|
||||
throw new ForbiddenException("must not use authenticated connection for one-time donation operations");
|
||||
}
|
||||
|
||||
final CompletableFuture<Optional<PaymentDetails>> paymentDetailsFut = switch (request.processor) {
|
||||
final Optional<PaymentDetails> maybePaymentDetails = (switch (request.processor) {
|
||||
case STRIPE -> stripeManager.getPaymentDetails(request.paymentIntentId);
|
||||
case BRAINTREE -> braintreeManager.getPaymentDetails(request.paymentIntentId);
|
||||
case GOOGLE_PLAY_BILLING -> throw new BadRequestException("cannot use play billing for one-time donations");
|
||||
case APPLE_APP_STORE -> throw new BadRequestException("cannot use app store purchases for one-time donations");
|
||||
};
|
||||
|
||||
return paymentDetailsFut.thenApply(maybePaymentDetails -> {
|
||||
if (maybePaymentDetails.isEmpty()) {
|
||||
throw new WebApplicationException(Response.Status.NOT_FOUND);
|
||||
}
|
||||
final PaymentDetails paymentDetails = maybePaymentDetails.get();
|
||||
if (paymentDetails.status() == PaymentStatus.PROCESSING) {
|
||||
return Response.noContent().build();
|
||||
}
|
||||
if (paymentDetails.status() != PaymentStatus.SUCCEEDED) {
|
||||
throw new WebApplicationException(Response.status(Response.Status.PAYMENT_REQUIRED)
|
||||
.entity(new CreateBoostReceiptCredentialsErrorResponse(paymentDetails.chargeFailure())).build());
|
||||
}
|
||||
|
||||
// The payment was successful, try to issue the receipt credential
|
||||
|
||||
final OneTimeDonationUtil.DonationLevelDetails levelDetails;
|
||||
try {
|
||||
levelDetails = OneTimeDonationUtil.getLevelDetails(paymentDetails, oneTimeDonationConfiguration);
|
||||
} catch (OneTimeDonationUtil.InvalidLevelException _) {
|
||||
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
|
||||
final ReceiptCredentialRequest receiptCredentialRequest;
|
||||
try {
|
||||
receiptCredentialRequest = new ReceiptCredentialRequest(request.receiptCredentialRequest);
|
||||
} catch (final InvalidInputException e) {
|
||||
throw new BadRequestException("invalid receipt credential request", e);
|
||||
}
|
||||
try {
|
||||
issuedReceiptsManager.recordIssuance(paymentDetails.id(), request.processor,
|
||||
receiptCredentialRequest, clock.instant());
|
||||
} catch (WriteConflictException _) {
|
||||
throw new WebApplicationException(Response.Status.CONFLICT);
|
||||
}
|
||||
final Instant paidAt = oneTimeDonationsManager.getPaidAt(paymentDetails.id(), paymentDetails.created());
|
||||
final Instant expiration = paidAt
|
||||
.plus(levelDetails.levelExpiration())
|
||||
.truncatedTo(ChronoUnit.DAYS)
|
||||
.plus(1, ChronoUnit.DAYS);
|
||||
final ReceiptCredentialResponse receiptCredentialResponse;
|
||||
try {
|
||||
receiptCredentialResponse = zkReceiptOperations.issueReceiptCredential(
|
||||
receiptCredentialRequest, expiration.getEpochSecond(), levelDetails.level());
|
||||
} catch (final VerificationFailedException e) {
|
||||
throw new BadRequestException("receipt credential request failed verification", e);
|
||||
}
|
||||
Metrics.counter(SubscriptionController.RECEIPT_ISSUED_COUNTER_NAME,
|
||||
Tags.of(
|
||||
Tag.of(SubscriptionController.PROCESSOR_TAG_NAME, request.processor.toString()),
|
||||
Tag.of(SubscriptionController.TYPE_TAG_NAME, "boost"),
|
||||
UserAgentTagUtil.getPlatformTag(userAgent)))
|
||||
.increment();
|
||||
return Response.ok(
|
||||
new CreateBoostReceiptCredentialsSuccessResponse(receiptCredentialResponse.serialize()))
|
||||
.build();
|
||||
});
|
||||
|
||||
if (maybePaymentDetails.isEmpty()) {
|
||||
throw new WebApplicationException(Response.Status.NOT_FOUND);
|
||||
}
|
||||
final PaymentDetails paymentDetails = maybePaymentDetails.get();
|
||||
if (paymentDetails.status() == PaymentStatus.PROCESSING) {
|
||||
return Response.noContent().build();
|
||||
}
|
||||
if (paymentDetails.status() != PaymentStatus.SUCCEEDED) {
|
||||
throw new WebApplicationException(Response.status(Response.Status.PAYMENT_REQUIRED)
|
||||
.entity(new CreateBoostReceiptCredentialsErrorResponse(paymentDetails.chargeFailure())).build());
|
||||
}
|
||||
|
||||
// The payment was successful, try to issue the receipt credential
|
||||
|
||||
final OneTimeDonationUtil.DonationLevelDetails levelDetails;
|
||||
try {
|
||||
levelDetails = OneTimeDonationUtil.getLevelDetails(paymentDetails, oneTimeDonationConfiguration);
|
||||
} catch (OneTimeDonationUtil.InvalidLevelException _) {
|
||||
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
|
||||
final ReceiptCredentialRequest receiptCredentialRequest;
|
||||
try {
|
||||
receiptCredentialRequest = new ReceiptCredentialRequest(request.receiptCredentialRequest);
|
||||
} catch (final InvalidInputException e) {
|
||||
throw new BadRequestException("invalid receipt credential request", e);
|
||||
}
|
||||
try {
|
||||
issuedReceiptsManager.recordIssuance(paymentDetails.id(), request.processor,
|
||||
receiptCredentialRequest, clock.instant());
|
||||
} catch (WriteConflictException _) {
|
||||
throw new WebApplicationException(Response.Status.CONFLICT);
|
||||
}
|
||||
final Instant paidAt = oneTimeDonationsManager.getPaidAt(paymentDetails.id(), paymentDetails.created());
|
||||
final Instant expiration = paidAt
|
||||
.plus(levelDetails.levelExpiration())
|
||||
.truncatedTo(ChronoUnit.DAYS)
|
||||
.plus(1, ChronoUnit.DAYS);
|
||||
final ReceiptCredentialResponse receiptCredentialResponse;
|
||||
try {
|
||||
receiptCredentialResponse = zkReceiptOperations.issueReceiptCredential(
|
||||
receiptCredentialRequest, expiration.getEpochSecond(), levelDetails.level());
|
||||
} catch (final VerificationFailedException e) {
|
||||
throw new BadRequestException("receipt credential request failed verification", e);
|
||||
}
|
||||
Metrics.counter(SubscriptionController.RECEIPT_ISSUED_COUNTER_NAME,
|
||||
Tags.of(
|
||||
Tag.of(SubscriptionController.PROCESSOR_TAG_NAME, request.processor.toString()),
|
||||
Tag.of(SubscriptionController.TYPE_TAG_NAME, "boost"),
|
||||
UserAgentTagUtil.getPlatformTag(userAgent)))
|
||||
.increment();
|
||||
return Response.ok(
|
||||
new CreateBoostReceiptCredentialsSuccessResponse(receiptCredentialResponse.serialize()))
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -559,7 +559,7 @@ public class ProfileController {
|
||||
|
||||
private static Map<String, Boolean> getAccountCapabilities(final Account account) {
|
||||
return Arrays.stream(DeviceCapability.values())
|
||||
.filter(DeviceCapability::includeInProfile)
|
||||
.filter(DeviceCapability::includeInLegacyProfile)
|
||||
.collect(Collectors.toMap(DeviceCapability::getName, account::hasCapability));
|
||||
}
|
||||
}
|
||||
+30
-6
@@ -19,16 +19,21 @@ import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.ws.rs.BadRequestException;
|
||||
import jakarta.ws.rs.Consumes;
|
||||
import jakarta.ws.rs.ForbiddenException;
|
||||
import jakarta.ws.rs.HeaderParam;
|
||||
import jakarta.ws.rs.NotAuthorizedException;
|
||||
import jakarta.ws.rs.POST;
|
||||
import jakarta.ws.rs.Path;
|
||||
import jakarta.ws.rs.Produces;
|
||||
import jakarta.ws.rs.ServiceUnavailableException;
|
||||
import jakarta.ws.rs.WebApplicationException;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.core.Context;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.io.IOException;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
@@ -38,13 +43,18 @@ import org.apache.commons.lang3.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.BasicAuthorizationHeader;
|
||||
import org.whispersystems.textsecuregcm.auth.InvalidRegistrationSessionException;
|
||||
import org.whispersystems.textsecuregcm.auth.PhoneVerificationTokenManager;
|
||||
import org.whispersystems.textsecuregcm.auth.RecoveryPasswordVerificationFailedException;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockFailureException;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager;
|
||||
import org.whispersystems.textsecuregcm.auth.UnverifiedRegistrationSessionException;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountCreationResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.PhoneVerificationRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.RegistrationLockFailure;
|
||||
import org.whispersystems.textsecuregcm.entities.RegistrationRequest;
|
||||
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.spam.RegistrationFraudChecker;
|
||||
@@ -116,7 +126,8 @@ public class RegistrationController {
|
||||
@HeaderParam(HeaderUtils.X_SIGNAL_AGENT) final String signalAgent,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
|
||||
@NotNull @Valid final RegistrationRequest registrationRequest,
|
||||
@Context final ContainerRequestContext requestContext) throws RateLimitExceededException, InterruptedException {
|
||||
@Context final ContainerRequestContext requestContext)
|
||||
throws RateLimitExceededException, InterruptedException, RegistrationLockFailureException {
|
||||
|
||||
final String number = authorizationHeader.getUsername();
|
||||
final String password = authorizationHeader.getPassword();
|
||||
@@ -134,11 +145,24 @@ public class RegistrationController {
|
||||
|
||||
rateLimiters.getRegistrationLimiter().validate(number);
|
||||
|
||||
final PhoneVerificationRequest.VerificationType verificationType =
|
||||
phoneVerificationTokenManager.verify(requestContext,
|
||||
number,
|
||||
StringUtils.isNotBlank(registrationRequest.sessionId()) ? registrationRequest.decodeSessionId() : null,
|
||||
registrationRequest.recoveryPassword());
|
||||
final PhoneVerificationRequest.VerificationType verificationType;
|
||||
try {
|
||||
verificationType = phoneVerificationTokenManager.verify(
|
||||
number,
|
||||
requestContext.getHeaderString(HttpHeaders.USER_AGENT),
|
||||
requestContext.getHeaderString(HttpHeaders.ACCEPT_LANGUAGE),
|
||||
(String) requestContext.getProperty(RemoteAddressFilter.REMOTE_ADDRESS_ATTRIBUTE_NAME),
|
||||
StringUtils.isNotBlank(registrationRequest.sessionId()) ? registrationRequest.decodeSessionId() : null,
|
||||
registrationRequest.recoveryPassword());
|
||||
} catch (final UnverifiedRegistrationSessionException e) {
|
||||
throw new NotAuthorizedException("registration session is unverified");
|
||||
} catch (final InvalidRegistrationSessionException e) {
|
||||
throw new BadRequestException(e.getMessage());
|
||||
} catch (final IOException e) {
|
||||
throw new ServiceUnavailableException(e.getMessage());
|
||||
} catch (final RecoveryPasswordVerificationFailedException e) {
|
||||
throw new ForbiddenException("recovery password could not be verified");
|
||||
}
|
||||
|
||||
// There can be at most one existing account for a set of numbers in the same equivalence class, so it's sufficient
|
||||
// to find the first one.
|
||||
|
||||
+2
-1
@@ -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,7 +119,7 @@ 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());
|
||||
|
||||
|
||||
+27
-20
@@ -48,6 +48,8 @@ import jakarta.ws.rs.core.Context;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import jakarta.ws.rs.core.Response.Status;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
@@ -67,7 +69,6 @@ import org.whispersystems.textsecuregcm.badges.BadgeTranslator;
|
||||
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.SubscriptionConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.SubscriptionLevelConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimitedByIp;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
@@ -75,7 +76,6 @@ import org.whispersystems.textsecuregcm.mappers.SubscriptionExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.DonationPermitsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriberCredentials;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriptionManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Subscriptions;
|
||||
@@ -114,7 +114,7 @@ public class SubscriptionController {
|
||||
private final BadgeTranslator badgeTranslator;
|
||||
private final BankMandateTranslator bankMandateTranslator;
|
||||
private final DonationPermitsManager donationPermitsManager;
|
||||
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
private final long backupMediaStorageAllowanceBytes;
|
||||
static final String RECEIPT_ISSUED_COUNTER_NAME = MetricsUtil.name(SubscriptionController.class, "receiptIssued");
|
||||
static final String PROCESSOR_TAG_NAME = "processor";
|
||||
static final String TYPE_TAG_NAME = "type";
|
||||
@@ -132,7 +132,7 @@ public class SubscriptionController {
|
||||
BadgeTranslator badgeTranslator,
|
||||
BankMandateTranslator bankMandateTranslator,
|
||||
DonationPermitsManager donationPermitsManager,
|
||||
DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
|
||||
long backupMediaStorageAllowanceBytes) {
|
||||
this.subscriptionManager = subscriptionManager;
|
||||
this.clock = Objects.requireNonNull(clock);
|
||||
this.subscriptionConfiguration = Objects.requireNonNull(subscriptionConfiguration);
|
||||
@@ -144,7 +144,7 @@ public class SubscriptionController {
|
||||
this.badgeTranslator = Objects.requireNonNull(badgeTranslator);
|
||||
this.bankMandateTranslator = Objects.requireNonNull(bankMandateTranslator);
|
||||
this.donationPermitsManager = donationPermitsManager;
|
||||
this.dynamicConfigurationManager = Objects.requireNonNull(dynamicConfigurationManager);
|
||||
this.backupMediaStorageAllowanceBytes = backupMediaStorageAllowanceBytes;
|
||||
}
|
||||
|
||||
|
||||
@@ -152,14 +152,12 @@ public class SubscriptionController {
|
||||
GetSubscriptionConfigurationResponse buildGetSubscriptionConfigurationResponse(
|
||||
final List<Locale> acceptableLanguages) {
|
||||
|
||||
final long maxTotalBackupMediaBytes =
|
||||
dynamicConfigurationManager.getConfiguration().getBackupConfiguration().maxTotalMediaSize();
|
||||
final Map<String, BackupLevelConfiguration> backupLevels = subscriptionConfiguration.getBackupLevels()
|
||||
.entrySet().stream()
|
||||
.collect(Collectors.toMap(
|
||||
e -> String.valueOf(e.getKey()),
|
||||
e -> new BackupLevelConfiguration(
|
||||
maxTotalBackupMediaBytes,
|
||||
backupMediaStorageAllowanceBytes,
|
||||
e.getValue().playProductId(),
|
||||
e.getValue().mediaTtl().toDays())));
|
||||
|
||||
@@ -236,7 +234,7 @@ public class SubscriptionController {
|
||||
return false;
|
||||
}
|
||||
})
|
||||
.orElse(true);
|
||||
.orElse(false);
|
||||
|
||||
subscriptionManager.updateSubscriber(subscriberCredentials, creationPermitted);
|
||||
return Response.ok().build();
|
||||
@@ -250,6 +248,16 @@ public class SubscriptionController {
|
||||
@Path("/{subscriberId}/create_payment_method")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Operation(summary = "Create a payment method", description = """
|
||||
Creates a payment method setup token with the payment processor and returns a client secret that can be used to
|
||||
complete the payment method setup.
|
||||
""")
|
||||
@ApiResponse(responseCode = "200", description = "The payment method was created", content = @Content(schema = @Schema(implementation = CreatePaymentMethodResponse.class)))
|
||||
@ApiResponse(responseCode = "400", description = "The requested payment method type is not supported by this endpoint")
|
||||
@ApiResponse(responseCode = "401", description = "Donation permit was invalid or already spent")
|
||||
@ApiResponse(responseCode = "403", description = "subscriberId authentication failure OR account authentication is present")
|
||||
@ApiResponse(responseCode = "404", description = "subscriberId is malformed OR the subscriber does not exist")
|
||||
@ApiResponse(responseCode = "409", description = "The subscriber is already associated with a different payment processor")
|
||||
@ManagedAsync
|
||||
@RateLimitedByIp(RateLimiters.For.ADD_SUBSCRIPTION_PAYMENT_METHOD)
|
||||
public CreatePaymentMethodResponse createPaymentMethod(
|
||||
@@ -285,7 +293,7 @@ public class SubscriptionController {
|
||||
return false;
|
||||
}
|
||||
})
|
||||
.orElse(true);
|
||||
.orElse(false);
|
||||
|
||||
if (!spendSuccessful) {
|
||||
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
|
||||
@@ -315,7 +323,8 @@ public class SubscriptionController {
|
||||
@PathParam("subscriberId") String subscriberId,
|
||||
@NotNull @Valid CreatePayPalBillingAgreementRequest request,
|
||||
@Context ContainerRequestContext containerRequestContext,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) @Nullable final String userAgentString) throws SubscriptionException {
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) @Nullable final String userAgentString)
|
||||
throws SubscriptionException, IOException {
|
||||
|
||||
final SubscriberCredentials subscriberCredentials =
|
||||
SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
|
||||
@@ -325,10 +334,8 @@ public class SubscriptionController {
|
||||
subscriberCredentials,
|
||||
braintreeManager,
|
||||
getClientPlatform(userAgentString),
|
||||
(mgr, customerId) ->
|
||||
mgr.createPayPalBillingAgreement(request.returnUrl, request.cancelUrl, locale.toLanguageTag()))
|
||||
.join();
|
||||
return new CreatePayPalBillingAgreementResponse(
|
||||
(mgr, _) -> mgr.createPayPalBillingAgreement(request.returnUrl, request.cancelUrl, locale.toLanguageTag()));
|
||||
return new CreatePayPalBillingAgreementResponse(
|
||||
billingAgreementApprovalDetails.approvalUrl(),
|
||||
billingAgreementApprovalDetails.billingAgreementToken());
|
||||
}
|
||||
@@ -350,7 +357,7 @@ public class SubscriptionController {
|
||||
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
|
||||
@PathParam("subscriberId") String subscriberId,
|
||||
@PathParam("processor") PaymentProvider processor,
|
||||
@PathParam("paymentMethodToken") @NotEmpty String paymentMethodToken) throws SubscriptionException {
|
||||
@PathParam("paymentMethodToken") @NotEmpty String paymentMethodToken) throws SubscriptionException, IOException {
|
||||
SubscriberCredentials subscriberCredentials =
|
||||
SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
|
||||
|
||||
@@ -754,18 +761,18 @@ public class SubscriptionController {
|
||||
public Response setDefaultPaymentMethodForIdeal(
|
||||
@Auth Optional<AuthenticatedDevice> authenticatedAccount,
|
||||
@PathParam("subscriberId") String subscriberId,
|
||||
@PathParam("setupIntentId") @NotEmpty String setupIntentId) throws SubscriptionException {
|
||||
@PathParam("setupIntentId") @NotEmpty String setupIntentId) throws SubscriptionException, IOException {
|
||||
SubscriberCredentials subscriberCredentials =
|
||||
SubscriberCredentials.process(authenticatedAccount, subscriberId, clock);
|
||||
|
||||
final String generatedSepaId = stripeManager.getGeneratedSepaIdFromSetupIntent(setupIntentId).join();
|
||||
final String generatedSepaId = stripeManager.getGeneratedSepaIdFromSetupIntent(setupIntentId);
|
||||
setDefaultPaymentMethod(stripeManager, generatedSepaId, subscriberCredentials);
|
||||
return Response.ok().build();
|
||||
}
|
||||
|
||||
private void setDefaultPaymentMethod(final CustomerAwareSubscriptionPaymentProcessor manager,
|
||||
final String paymentMethodId,
|
||||
final SubscriberCredentials requestData) throws SubscriptionException {
|
||||
final SubscriberCredentials requestData) throws SubscriptionException, IOException {
|
||||
try {
|
||||
final Subscriptions.Record record = subscriptionManager.getSubscriber(requestData);
|
||||
|
||||
@@ -776,7 +783,7 @@ public class SubscriptionController {
|
||||
|
||||
manager
|
||||
.setDefaultPaymentMethodForCustomer(processorCustomer.customerId(), paymentMethodId, record.subscriptionId);
|
||||
} catch (SubscriptionInvalidArgumentsException e) {
|
||||
} catch (final SubscriptionInvalidArgumentsException e) {
|
||||
// Here, invalid arguments must mean that the client has made requests out of order, and needs to finish
|
||||
// setting up the paymentMethod first
|
||||
throw new ClientErrorException(Status.CONFLICT);
|
||||
|
||||
+1
-1
@@ -28,7 +28,7 @@ public record AccountDataReportResponse(UUID reportId,
|
||||
|
||||
@JsonProperty
|
||||
@Schema(description = "A plaintext representation of the data report")
|
||||
String text() {
|
||||
public String text() {
|
||||
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
|
||||
|
||||
+1
-1
@@ -11,7 +11,7 @@ import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import org.whispersystems.textsecuregcm.registration.VerificationSession;
|
||||
|
||||
public record VerificationSessionResponse(
|
||||
@Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "A URL-safe ID for the session")
|
||||
@Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "A URL-safe base64-encoded ID for the session")
|
||||
String id,
|
||||
|
||||
@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = "Duration in seconds after which next SMS can be requested for this session")
|
||||
|
||||
+2
-1
@@ -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;
|
||||
}
|
||||
|
||||
+2
-1
@@ -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);
|
||||
|
||||
+49
-1
@@ -6,31 +6,43 @@
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import org.signal.chat.account.Capabilities;
|
||||
import org.signal.chat.account.CheckAccountExistenceRequest;
|
||||
import org.signal.chat.account.CheckAccountExistenceResponse;
|
||||
import org.signal.chat.account.GetCapabilitiesAnonymousRequest;
|
||||
import org.signal.chat.account.GetCapabilitiesAnonymousResponse;
|
||||
import org.signal.chat.account.LookupUsernameHashRequest;
|
||||
import org.signal.chat.account.LookupUsernameHashResponse;
|
||||
import org.signal.chat.account.LookupUsernameLinkRequest;
|
||||
import org.signal.chat.account.LookupUsernameLinkResponse;
|
||||
import org.signal.chat.account.SimpleAccountsAnonymousGrpc;
|
||||
import org.signal.chat.errors.FailedUnidentifiedAuthorization;
|
||||
import org.signal.chat.errors.NotFound;
|
||||
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
|
||||
public class AccountsAnonymousGrpcService extends SimpleAccountsAnonymousGrpc.AccountsAnonymousImplBase {
|
||||
|
||||
private final AccountsManager accountsManager;
|
||||
private final RateLimiters rateLimiters;
|
||||
private final GroupSendTokenUtil groupSendTokenUtil;
|
||||
|
||||
public AccountsAnonymousGrpcService(final AccountsManager accountsManager, final RateLimiters rateLimiters) {
|
||||
public AccountsAnonymousGrpcService(
|
||||
final AccountsManager accountsManager,
|
||||
final RateLimiters rateLimiters,
|
||||
final GroupSendTokenUtil groupSendTokenUtil) {
|
||||
this.accountsManager = accountsManager;
|
||||
this.rateLimiters = rateLimiters;
|
||||
this.groupSendTokenUtil = groupSendTokenUtil;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -80,4 +92,40 @@ public class AccountsAnonymousGrpcService extends SimpleAccountsAnonymousGrpc.Ac
|
||||
.build())
|
||||
.orElseGet(() -> LookupUsernameLinkResponse.newBuilder().setNotFound(NotFound.getDefaultInstance()).build());
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public GetCapabilitiesAnonymousResponse getCapabilities(GetCapabilitiesAnonymousRequest request) {
|
||||
final ServiceIdentifier targetIdentifier =
|
||||
GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getAccountIdentifier());
|
||||
final Optional<Account> targetAccount = accountsManager.getByServiceIdentifier(targetIdentifier);
|
||||
|
||||
final boolean authorized = switch (request.getAuthenticationCase()) {
|
||||
case GROUP_SEND_TOKEN -> groupSendTokenUtil.checkGroupSendToken(request.getGroupSendToken(), targetIdentifier);
|
||||
case UNIDENTIFIED_ACCESS_KEY -> targetAccount
|
||||
.map(a -> UnidentifiedAccessUtil.checkUnidentifiedAccess(a, request.getUnidentifiedAccessKey().toByteArray()))
|
||||
.orElse(false);
|
||||
default -> throw GrpcExceptions.invalidArguments("invalid authentication");
|
||||
};
|
||||
|
||||
if (!authorized) {
|
||||
return GetCapabilitiesAnonymousResponse.newBuilder()
|
||||
.setFailedUnidentifiedAuthorization(FailedUnidentifiedAuthorization.getDefaultInstance())
|
||||
.build();
|
||||
}
|
||||
|
||||
return targetAccount.map(target -> {
|
||||
final Capabilities.Builder builder = Capabilities.newBuilder();
|
||||
for (DeviceCapability capability : DeviceCapability.PUBLIC_VISIBLE_CAPABILITIES) {
|
||||
if (target.hasCapability(capability)) {
|
||||
builder.addCapabilities(DeviceCapabilityUtil.toGrpcDeviceCapability(capability));
|
||||
}
|
||||
}
|
||||
return GetCapabilitiesAnonymousResponse.newBuilder().setCapabilities(builder.build()).build();
|
||||
})
|
||||
.orElseGet(() -> GetCapabilitiesAnonymousResponse.newBuilder()
|
||||
.setNotFound(NotFound.getDefaultInstance())
|
||||
.build());
|
||||
}
|
||||
|
||||
}
|
||||
+289
-25
@@ -6,12 +6,23 @@
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import io.grpc.StatusRuntimeException;
|
||||
import java.io.IOException;
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
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;
|
||||
import org.signal.chat.account.Capabilities;
|
||||
import org.signal.chat.account.ChangeNumberRequest;
|
||||
import org.signal.chat.account.ChangeNumberResponse;
|
||||
import org.signal.chat.account.ClearRegistrationLockRequest;
|
||||
import org.signal.chat.account.ClearRegistrationLockResponse;
|
||||
import org.signal.chat.account.ConfigureUnidentifiedAccessRequest;
|
||||
@@ -24,8 +35,16 @@ import org.signal.chat.account.DeleteUsernameHashRequest;
|
||||
import org.signal.chat.account.DeleteUsernameHashResponse;
|
||||
import org.signal.chat.account.DeleteUsernameLinkRequest;
|
||||
import org.signal.chat.account.DeleteUsernameLinkResponse;
|
||||
import org.signal.chat.account.ExternalServiceCredentials;
|
||||
import org.signal.chat.account.GetAccountDataReportRequest;
|
||||
import org.signal.chat.account.GetAccountDataReportResponse;
|
||||
import org.signal.chat.account.GetAccountIdentityRequest;
|
||||
import org.signal.chat.account.GetAccountIdentityResponse;
|
||||
import org.signal.chat.account.GetCapabilitiesRequest;
|
||||
import org.signal.chat.account.GetCapabilitiesResponse;
|
||||
import org.signal.chat.account.GetEntitlementsRequest;
|
||||
import org.signal.chat.account.GetEntitlementsResponse;
|
||||
import org.signal.chat.account.RegistrationLockFailure;
|
||||
import org.signal.chat.account.ReserveUsernameHashRequest;
|
||||
import org.signal.chat.account.ReserveUsernameHashResponse;
|
||||
import org.signal.chat.account.SetDiscoverableByPhoneNumberRequest;
|
||||
@@ -39,26 +58,47 @@ import org.signal.chat.account.SetUsernameLinkResponse;
|
||||
import org.signal.chat.account.SetZkCredentialKeyRequest;
|
||||
import org.signal.chat.account.SetZkCredentialKeyResponse;
|
||||
import org.signal.chat.account.SimpleAccountsGrpc;
|
||||
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;
|
||||
import org.signal.libsignal.usernames.BaseUsernameException;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.ZkCredentialPublicKey;
|
||||
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;
|
||||
import org.whispersystems.textsecuregcm.controllers.MessageDeliveryNotAllowedException;
|
||||
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountDataReportResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.IncomingMessage;
|
||||
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.push.MessageTooLargeException;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ChangeNumberManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.UsernameHashNotAvailableException;
|
||||
import org.whispersystems.textsecuregcm.storage.UsernameReservationNotFoundException;
|
||||
import org.whispersystems.textsecuregcm.util.RegistrationIdValidator;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import org.whispersystems.textsecuregcm.util.UsernameHashZkProofVerifier;
|
||||
|
||||
@@ -70,38 +110,60 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
private final RateLimiters rateLimiters;
|
||||
private final UsernameHashZkProofVerifier usernameHashZkProofVerifier;
|
||||
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
|
||||
private final Clock clock;
|
||||
private final ChangeNumberManager changeNumberManager;
|
||||
|
||||
public AccountsGrpcService(final AccountsManager accountsManager,
|
||||
final RateLimiters rateLimiters,
|
||||
final UsernameHashZkProofVerifier usernameHashZkProofVerifier,
|
||||
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager) {
|
||||
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
|
||||
final Clock clock,
|
||||
final ChangeNumberManager changeNumberManager) {
|
||||
|
||||
this.accountsManager = accountsManager;
|
||||
this.rateLimiters = rateLimiters;
|
||||
this.usernameHashZkProofVerifier = usernameHashZkProofVerifier;
|
||||
this.registrationRecoveryPasswordsManager = registrationRecoveryPasswordsManager;
|
||||
this.clock = clock;
|
||||
this.changeNumberManager = changeNumberManager;
|
||||
}
|
||||
|
||||
@Override
|
||||
public GetAccountIdentityResponse getAccountIdentity(final GetAccountIdentityRequest request) {
|
||||
final Account account = getAuthenticatedAccount();
|
||||
|
||||
final AccountIdentifiers.Builder accountIdentifiersBuilder = AccountIdentifiers.newBuilder()
|
||||
.addServiceIdentifiers(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new AciServiceIdentifier(account.getUuid())))
|
||||
.addServiceIdentifiers(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new PniServiceIdentifier(account.getPhoneNumberIdentifier())))
|
||||
.setE164(account.getNumber());
|
||||
|
||||
account.getUsernameHash().ifPresent(usernameHash ->
|
||||
accountIdentifiersBuilder.setUsernameHash(ByteString.copyFrom(usernameHash)));
|
||||
|
||||
return GetAccountIdentityResponse.newBuilder()
|
||||
.setAccountIdentifiers(accountIdentifiersBuilder)
|
||||
.setAccountIdentifiers(buildAccountIdentifiers(getAuthenticatedAccount()))
|
||||
.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public GetEntitlementsResponse getEntitlements(final GetEntitlementsRequest request) {
|
||||
final Account account = getAuthenticatedAccount();
|
||||
final GetEntitlementsResponse.Builder builder = GetEntitlementsResponse.newBuilder();
|
||||
|
||||
final Instant now = clock.instant();
|
||||
|
||||
final Account.BackupVoucher backupVoucher = account.getBackupVoucher();
|
||||
if (backupVoucher != null && backupVoucher.expiration().isAfter(now)) {
|
||||
builder.setBackup(GetEntitlementsResponse.BackupEntitlement.newBuilder()
|
||||
.setExpirationEpochSeconds(backupVoucher.expiration().getEpochSecond())
|
||||
.setLevel(backupVoucher.receiptLevel()));
|
||||
}
|
||||
|
||||
builder.addAllBadges(account.getBadges().stream()
|
||||
.filter(badge -> badge.expiration().isAfter(now))
|
||||
.map(badge -> GetEntitlementsResponse.BadgeEntitlement.newBuilder()
|
||||
.setBadgeId(badge.id())
|
||||
.setExpirationEpochSeconds(badge.expiration().getEpochSecond())
|
||||
.setVisible(badge.visible())
|
||||
.build())
|
||||
.toList());
|
||||
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public DeleteAccountResponse deleteAccount(final DeleteAccountRequest request) {
|
||||
accountsManager.delete(AuthenticationUtil.requireAuthenticatedPrimaryDevice().accountIdentifier(),
|
||||
accountsManager.delete(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier(),
|
||||
AccountsManager.DeletionReason.USER_REQUEST);
|
||||
|
||||
return DeleteAccountResponse.getDefaultInstance();
|
||||
@@ -109,12 +171,10 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
|
||||
@Override
|
||||
public SetRegistrationLockResponse setRegistrationLock(final SetRegistrationLockRequest request) {
|
||||
// In the previous REST-based API, clients would send hex strings directly. For backward compatibility, we
|
||||
// convert the registration lock secret to a lowercase hex string before turning it into a salted hash.
|
||||
final SaltedTokenHash credentials =
|
||||
SaltedTokenHash.generateFor(HexFormat.of().withLowerCase().formatHex(request.getRegistrationLock().toByteArray()));
|
||||
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();
|
||||
@@ -122,7 +182,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();
|
||||
@@ -175,7 +235,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) {
|
||||
@@ -237,15 +296,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();
|
||||
@@ -300,6 +359,190 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ChangeNumberResponse changeNumber(final ChangeNumberRequest request)
|
||||
throws RateLimitExceededException, InterruptedException {
|
||||
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedPrimaryDevice();
|
||||
|
||||
final IdentityKey pniIdentityKey;
|
||||
try {
|
||||
pniIdentityKey = new IdentityKey(request.getPniIdentityKey().toByteArray());
|
||||
} catch (final InvalidKeyException e) {
|
||||
throw GrpcExceptions.fieldViolation("pni_identity_key", "invalid identity key");
|
||||
}
|
||||
|
||||
final Map<Byte, ECSignedPreKey> devicePniSignedPreKeys = transformDeviceMap(request.getDevicePniSignedPreKeysMap(),
|
||||
key -> KeysGrpcHelper.checkEcSignedPreKey(key, pniIdentityKey,
|
||||
invalidPublicKeyException("device_pni_signed_pre_keys"),
|
||||
invalidSignatureException("device_pni_signed_pre_keys")));
|
||||
|
||||
final Map<Byte, KEMSignedPreKey> devicePniPqLastResortPreKeys = transformDeviceMap(request.getDevicePniPqLastResortPreKeysMap(),
|
||||
key -> KeysGrpcHelper.checkKemSignedPreKey(key, pniIdentityKey,
|
||||
invalidPublicKeyException("device_pni_pq_last_resort_pre_keys"),
|
||||
invalidSignatureException("device_pni_pq_last_resort_pre_keys")));
|
||||
|
||||
final Map<Byte, Integer> pniRegistrationIds = transformDeviceMap(request.getPniRegistrationIdsMap(), Function.identity());
|
||||
|
||||
if (!pniRegistrationIds.values().stream().allMatch(RegistrationIdValidator::validRegistrationId)) {
|
||||
throw GrpcExceptions.fieldViolation("pni_registration_ids", "invalid registration id");
|
||||
}
|
||||
|
||||
final List<IncomingMessage> deviceMessages = request.getDeviceMessages().getMessagesMap()
|
||||
.entrySet()
|
||||
.stream()
|
||||
.map(entry -> new IncomingMessage(
|
||||
getEnvelopeType(entry.getValue().getType()).getNumber(),
|
||||
(byte) (int) entry.getKey(),
|
||||
entry.getValue().getRegistrationId(),
|
||||
entry.getValue().getPayload().toByteArray()))
|
||||
.toList();
|
||||
|
||||
final byte[] sessionId = request.getVerificationCase() == ChangeNumberRequest.VerificationCase.SESSION_ID
|
||||
? request.getSessionId().toByteArray()
|
||||
: null;
|
||||
|
||||
final byte[] recoveryPassword =
|
||||
request.getVerificationCase() == ChangeNumberRequest.VerificationCase.RECOVERY_PASSWORD
|
||||
? request.getRecoveryPassword().toByteArray()
|
||||
: null;
|
||||
|
||||
final String registrationLock = request.getRegistrationLock().isEmpty() ? null :
|
||||
formatRegistrationLock(request.getRegistrationLock().toByteArray());
|
||||
|
||||
try {
|
||||
final Account updatedAccount = changeNumberManager.changeNumber(
|
||||
authenticatedDevice.accountIdentifier(),
|
||||
sessionId,
|
||||
recoveryPassword,
|
||||
registrationLock,
|
||||
request.getNumber(),
|
||||
pniIdentityKey,
|
||||
devicePniSignedPreKeys,
|
||||
devicePniPqLastResortPreKeys,
|
||||
deviceMessages,
|
||||
pniRegistrationIds,
|
||||
RequestAttributesUtil.getUserAgent().orElse(null),
|
||||
RequestAttributesUtil.getAcceptLanguageRaw(),
|
||||
RequestAttributesUtil.getRemoteAddress().getHostAddress());
|
||||
|
||||
return ChangeNumberResponse.newBuilder()
|
||||
.setAccountIdentifiers(buildAccountIdentifiers(updatedAccount))
|
||||
.build();
|
||||
} catch (final MismatchedDevicesException e) {
|
||||
if (!e.getMismatchedDevices().staleDeviceIds().isEmpty()) {
|
||||
return ChangeNumberResponse.newBuilder()
|
||||
.setStaleDevices(StaleDevices.newBuilder()
|
||||
.addAllStaleDevices(e.getMismatchedDevices().staleDeviceIds().stream().map(Byte::intValue).toList()))
|
||||
.build();
|
||||
}
|
||||
|
||||
return ChangeNumberResponse.newBuilder()
|
||||
.setMismatchedDevices(MessagesGrpcHelper.buildMismatchedDevices(
|
||||
new AciServiceIdentifier(authenticatedDevice.accountIdentifier()), e.getMismatchedDevices()))
|
||||
.build();
|
||||
} catch (final MessageTooLargeException e) {
|
||||
return ChangeNumberResponse.newBuilder()
|
||||
.setMessageTooLarge(FailedPrecondition.newBuilder()
|
||||
.setDescription("one or more device messages was too large"))
|
||||
.build();
|
||||
} catch (final MessageDeliveryNotAllowedException e) {
|
||||
throw GrpcExceptions.unavailable();
|
||||
} catch (final IllegalArgumentException e) {
|
||||
throw GrpcExceptions.invalidArguments(e.getMessage());
|
||||
} catch (final RegistrationLockFailureException e) {
|
||||
final RegistrationLockFailure.Builder failureBuilder = RegistrationLockFailure.newBuilder()
|
||||
.setTimeRemainingMillis(e.getFailure().timeRemaining());
|
||||
|
||||
if (e.getFailure().svr2Credentials() != null) {
|
||||
failureBuilder.setSvr2Credentials(ExternalServiceCredentials.newBuilder()
|
||||
.setUsername(e.getFailure().svr2Credentials().username())
|
||||
.setPassword(e.getFailure().svr2Credentials().password()));
|
||||
}
|
||||
|
||||
return ChangeNumberResponse.newBuilder()
|
||||
.setRegistrationLockFailure(failureBuilder)
|
||||
.build();
|
||||
} catch (final UnverifiedRegistrationSessionException e) {
|
||||
return ChangeNumberResponse.newBuilder()
|
||||
.setUnverifiedRegistrationSession(FailedPrecondition.getDefaultInstance())
|
||||
.build();
|
||||
} catch (final InvalidRegistrationSessionException e) {
|
||||
return ChangeNumberResponse.newBuilder()
|
||||
.setInvalidRegistrationSession(FailedPrecondition.newBuilder().setDescription(e.getMessage()))
|
||||
.build();
|
||||
} catch (final IOException e) {
|
||||
throw GrpcExceptions.unavailable(e.getMessage());
|
||||
} catch (final RecoveryPasswordVerificationFailedException e) {
|
||||
return ChangeNumberResponse.newBuilder()
|
||||
.setRecoveryPasswordVerificationFailed(FailedPrecondition.getDefaultInstance())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public GetAccountDataReportResponse getAccountDataReport(final GetAccountDataReportRequest request)
|
||||
throws IOException {
|
||||
final Account account = getAuthenticatedAccount();
|
||||
|
||||
final AccountDataReportResponse report = new AccountDataReportResponse(UUID.randomUUID(), clock.instant(),
|
||||
new AccountDataReportResponse.AccountAndDevicesDataReport(
|
||||
new AccountDataReportResponse.AccountDataReport(
|
||||
account.getNumber(),
|
||||
account.getBadges().stream().map(AccountDataReportResponse.BadgeDataReport::new).toList(),
|
||||
account.isUnrestrictedUnidentifiedAccess(),
|
||||
account.isDiscoverableByPhoneNumber()),
|
||||
account.getDevices().stream().map(device ->
|
||||
new AccountDataReportResponse.DeviceDataReport(
|
||||
device.getId(),
|
||||
Instant.ofEpochMilli(device.getLastSeen()),
|
||||
Instant.ofEpochMilli(device.getCreated()),
|
||||
device.getUserAgent())).toList()));
|
||||
|
||||
return GetAccountDataReportResponse.newBuilder()
|
||||
.setJson(SystemMapper.jsonMapper().writeValueAsString(report))
|
||||
.setText(report.text())
|
||||
.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public GetCapabilitiesResponse getCapabilities(GetCapabilitiesRequest request) {
|
||||
final Account account = getAuthenticatedAccount();
|
||||
final Capabilities.Builder builder = Capabilities.newBuilder();
|
||||
for (DeviceCapability capability : DeviceCapability.SELF_VISIBLE_CAPABILITIES) {
|
||||
if (account.hasCapability(capability)) {
|
||||
builder.addCapabilities(DeviceCapabilityUtil.toGrpcDeviceCapability(capability));
|
||||
}
|
||||
}
|
||||
return GetCapabilitiesResponse.newBuilder().setCapabilities(builder.build()).build();
|
||||
}
|
||||
|
||||
private static AccountIdentifiers buildAccountIdentifiers(final Account account) {
|
||||
final AccountIdentifiers.Builder accountIdentifiersBuilder = AccountIdentifiers.newBuilder()
|
||||
.addServiceIdentifiers(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new AciServiceIdentifier(account.getUuid())))
|
||||
.addServiceIdentifiers(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new PniServiceIdentifier(account.getPhoneNumberIdentifier())))
|
||||
.setE164(account.getNumber());
|
||||
|
||||
account.getUsernameHash().ifPresent(usernameHash ->
|
||||
accountIdentifiersBuilder.setUsernameHash(ByteString.copyFrom(usernameHash)));
|
||||
|
||||
if (account.getUsernameLinkHandle() != null) {
|
||||
accountIdentifiersBuilder.setUsernameLinkHandle(UUIDUtil.toByteString(account.getUsernameLinkHandle()));
|
||||
}
|
||||
|
||||
return accountIdentifiersBuilder.build();
|
||||
}
|
||||
|
||||
private static MessageProtos.Envelope.Type getEnvelopeType(final SendMessageType type) {
|
||||
return switch (type) {
|
||||
case DOUBLE_RATCHET -> MessageProtos.Envelope.Type.CIPHERTEXT;
|
||||
case PREKEY_MESSAGE -> MessageProtos.Envelope.Type.PREKEY_BUNDLE;
|
||||
case PLAINTEXT_CONTENT -> MessageProtos.Envelope.Type.PLAINTEXT_CONTENT;
|
||||
case UNIDENTIFIED_SENDER -> throw GrpcExceptions.invalidArguments("illegal envelope type for change-number sync messages");
|
||||
case UNSPECIFIED, UNRECOGNIZED -> throw GrpcExceptions.invalidArguments("unrecognized envelope type");
|
||||
};
|
||||
}
|
||||
|
||||
private Account getAuthenticatedAccount() {
|
||||
return getAuthenticatedAccount(AuthenticationUtil.requireAuthenticatedDevice());
|
||||
}
|
||||
@@ -308,4 +551,25 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
return accountsManager.getByAccountIdentifier(authenticatedDevice.accountIdentifier())
|
||||
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
|
||||
}
|
||||
|
||||
private static String formatRegistrationLock(final byte[] registrationLock) {
|
||||
// In the previous REST-based API, clients would send hex strings directly. For backward compatibility, we
|
||||
// convert the registration lock secret to a lowercase hex string before turning it into a salted hash.
|
||||
return HexFormat.of().withLowerCase().formatHex(registrationLock);
|
||||
}
|
||||
|
||||
private static StatusRuntimeException invalidPublicKeyException(final String fieldName) {
|
||||
return GrpcExceptions.fieldViolation(fieldName, "invalid public key");
|
||||
}
|
||||
|
||||
private static StatusRuntimeException invalidSignatureException(final String fieldName) {
|
||||
return GrpcExceptions.fieldViolation(fieldName, "pre-key signature did not match PNI identity key");
|
||||
}
|
||||
|
||||
private static <T, U> Map<Byte, U> transformDeviceMap(final Map<Integer, T> byDeviceId, final Function<T, U> f) {
|
||||
return byDeviceId.entrySet()
|
||||
.stream()
|
||||
.collect(Collectors.<Map.Entry<Integer, T>, Byte, U>toMap(entry -> entry.getKey().byteValue(),
|
||||
entry -> f.apply(entry.getValue())));
|
||||
}
|
||||
}
|
||||
+4
-3
@@ -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()
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import org.signal.chat.common.Badge;
|
||||
import org.signal.chat.common.BadgeSvg;
|
||||
|
||||
public class BadgeGrpcHelper {
|
||||
|
||||
public static Badge toGrpcBadge(final org.whispersystems.textsecuregcm.entities.Badge badge) {
|
||||
final Badge.Builder builder = Badge.newBuilder()
|
||||
.setId(badge.getId())
|
||||
.setCategory(badge.getCategory())
|
||||
.setName(badge.getName())
|
||||
.setDescription(badge.getDescription())
|
||||
.addAllSprites6(badge.getSprites6())
|
||||
.setSvg(badge.getSvg());
|
||||
|
||||
badge.getSvgs().stream()
|
||||
.map(badgeSvg -> BadgeSvg.newBuilder()
|
||||
.setDark(badgeSvg.getDark())
|
||||
.setLight(badgeSvg.getLight())
|
||||
.build())
|
||||
.forEach(builder::addSvgs);
|
||||
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
}
|
||||
+3
-2
@@ -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,9 +35,9 @@ 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);
|
||||
|
||||
|
||||
@@ -138,7 +138,9 @@ public class DevicesGrpcService extends SimpleDevicesGrpc.DevicesImplBase {
|
||||
final Device device = account.getDevice(authenticatedDevice.deviceId())
|
||||
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
|
||||
|
||||
if (!Objects.equals(device.getApnId(), apnsToken) || !Objects.equals(device.getGcmId(), fcmToken)) {
|
||||
// Unlike FCM tokens, we need current "last updated" timestamps for APNs tokens and so update device records
|
||||
// unconditionally if it's an APNS request
|
||||
if (request.hasApnsTokenRequest() || !Objects.equals(device.getGcmId(), fcmToken)) {
|
||||
accountsManager.updateDevice(account.getIdentifier(IdentityType.ACI), authenticatedDevice.deviceId(), d -> {
|
||||
d.setApnId(apnsToken);
|
||||
d.setGcmId(fcmToken);
|
||||
|
||||
+5
@@ -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());
|
||||
|
||||
@@ -6,19 +6,31 @@
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import java.util.Arrays;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
import io.grpc.StatusRuntimeException;
|
||||
import org.signal.chat.common.EcPreKey;
|
||||
import org.signal.chat.common.EcSignedPreKey;
|
||||
import org.signal.chat.common.KemSignedPreKey;
|
||||
import org.signal.chat.keys.AccountPreKeyBundles;
|
||||
import org.signal.chat.keys.DevicePreKeyBundle;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.signal.libsignal.protocol.InvalidKeyException;
|
||||
import org.signal.libsignal.protocol.ecc.ECPublicKey;
|
||||
import org.signal.libsignal.protocol.kem.KEMPublicKey;
|
||||
import org.whispersystems.textsecuregcm.entities.ECPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessChecksum;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
import org.whispersystems.textsecuregcm.storage.KeyIdUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.KeysManager;
|
||||
|
||||
@@ -63,7 +75,16 @@ class KeysGrpcHelper {
|
||||
}
|
||||
|
||||
final AccountPreKeyBundles.Builder preKeyBundlesBuilder = AccountPreKeyBundles.newBuilder()
|
||||
.setIdentityKey(ByteString.copyFrom(targetAccount.getIdentityKey(targetServiceIdentifier.identityType()).serialize()));
|
||||
.setIdentityKey(ByteString.copyFrom(targetAccount.getIdentityKey(targetServiceIdentifier.identityType()).serialize()))
|
||||
.setUnrestrictedUnidentifiedAccess(targetServiceIdentifier.identityType() == IdentityType.ACI && targetAccount.isUnrestrictedUnidentifiedAccess());
|
||||
|
||||
// Set the UAK hash if the account has a UAK and we're targeting an ACI. PNIs don't allow unidentified access.
|
||||
targetAccount
|
||||
.getUnidentifiedAccessKey()
|
||||
.filter(_ -> targetServiceIdentifier.identityType() == IdentityType.ACI)
|
||||
.map(UnidentifiedAccessChecksum::generateFor)
|
||||
.map(ByteString::copyFrom)
|
||||
.ifPresent(preKeyBundlesBuilder::setUnidentifiedAccessKeyFingerprint);
|
||||
|
||||
preKeysByDeviceId.forEach((deviceId, devicePreKeys) -> {
|
||||
final Device device = targetAccount.getDevice(deviceId).orElseThrow();
|
||||
@@ -89,4 +110,46 @@ class KeysGrpcHelper {
|
||||
|
||||
return Optional.of(preKeyBundlesBuilder.build());
|
||||
}
|
||||
|
||||
public static ECPreKey checkEcPreKey(final EcPreKey preKey, final StatusRuntimeException invalidPublicKeyException) {
|
||||
try {
|
||||
return new ECPreKey(preKey.getKeyId(), new ECPublicKey(preKey.getPublicKey().toByteArray()));
|
||||
} catch (final InvalidKeyException e) {
|
||||
throw invalidPublicKeyException;
|
||||
}
|
||||
}
|
||||
|
||||
public static ECSignedPreKey checkEcSignedPreKey(final EcSignedPreKey preKey, final IdentityKey identityKey,
|
||||
final StatusRuntimeException invalidPublicKeyException, final StatusRuntimeException invalidSignatureException) {
|
||||
try {
|
||||
final ECSignedPreKey ecSignedPreKey = new ECSignedPreKey(preKey.getKeyId(),
|
||||
new ECPublicKey(preKey.getPublicKey().toByteArray()),
|
||||
preKey.getSignature().toByteArray());
|
||||
|
||||
if (ecSignedPreKey.signatureValid(identityKey)) {
|
||||
return ecSignedPreKey;
|
||||
} else {
|
||||
throw invalidSignatureException;
|
||||
}
|
||||
} catch (final InvalidKeyException e) {
|
||||
throw invalidPublicKeyException;
|
||||
}
|
||||
}
|
||||
|
||||
public static KEMSignedPreKey checkKemSignedPreKey(final KemSignedPreKey preKey, final IdentityKey identityKey,
|
||||
final StatusRuntimeException invalidPublicKeyException, final StatusRuntimeException invalidSignatureException) {
|
||||
try {
|
||||
final KEMSignedPreKey kemSignedPreKey = new KEMSignedPreKey(preKey.getKeyId(),
|
||||
new KEMPublicKey(preKey.getPublicKey().toByteArray()),
|
||||
preKey.getSignature().toByteArray());
|
||||
|
||||
if (kemSignedPreKey.signatureValid(identityKey)) {
|
||||
return kemSignedPreKey;
|
||||
} else {
|
||||
throw invalidSignatureException;
|
||||
}
|
||||
} catch (final InvalidKeyException e) {
|
||||
throw invalidPublicKeyException;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,9 +11,6 @@ import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.BiFunction;
|
||||
import org.signal.chat.common.EcPreKey;
|
||||
import org.signal.chat.common.EcSignedPreKey;
|
||||
import org.signal.chat.common.KemSignedPreKey;
|
||||
import org.signal.chat.errors.NotFound;
|
||||
import org.signal.chat.keys.GetPreKeyCountRequest;
|
||||
import org.signal.chat.keys.GetPreKeyCountResponse;
|
||||
@@ -26,16 +23,10 @@ import org.signal.chat.keys.SetOneTimeKemSignedPreKeysRequest;
|
||||
import org.signal.chat.keys.SetPreKeyResponse;
|
||||
import org.signal.chat.keys.SimpleKeysGrpc;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.signal.libsignal.protocol.InvalidKeyException;
|
||||
import org.signal.libsignal.protocol.ecc.ECPublicKey;
|
||||
import org.signal.libsignal.protocol.kem.KEMPublicKey;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitKeys;
|
||||
import org.whispersystems.textsecuregcm.entities.ECPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
@@ -136,7 +127,7 @@ public class KeysGrpcService extends SimpleKeysGrpc.KeysImplBase {
|
||||
storeOneTimePreKeys(authenticatedDevice.accountIdentifier(),
|
||||
request.getPreKeysList(),
|
||||
IdentityTypeUtil.fromGrpcIdentityType(request.getIdentityType()),
|
||||
(requestPreKey, _) -> checkEcPreKey(requestPreKey),
|
||||
(requestPreKey, _) -> KeysGrpcHelper.checkEcPreKey(requestPreKey, INVALID_PUBLIC_KEY_EXCEPTION),
|
||||
(identifier, preKeys) -> keysManager.storeEcOneTimePreKeys(identifier, authenticatedDevice.deviceId(), preKeys));
|
||||
|
||||
return SetPreKeyResponse.getDefaultInstance();
|
||||
@@ -149,7 +140,7 @@ public class KeysGrpcService extends SimpleKeysGrpc.KeysImplBase {
|
||||
storeOneTimePreKeys(authenticatedDevice.accountIdentifier(),
|
||||
request.getPreKeysList(),
|
||||
IdentityTypeUtil.fromGrpcIdentityType(request.getIdentityType()),
|
||||
KeysGrpcService::checkKemSignedPreKey,
|
||||
(preKey, identityKey) -> KeysGrpcHelper.checkKemSignedPreKey(preKey, identityKey, INVALID_PUBLIC_KEY_EXCEPTION, INVALID_SIGNATURE_EXCEPTION),
|
||||
(identifier, preKeys) -> keysManager.storeKemOneTimePreKeys(identifier, authenticatedDevice.deviceId(), preKeys));
|
||||
|
||||
return SetPreKeyResponse.getDefaultInstance();
|
||||
@@ -177,7 +168,7 @@ public class KeysGrpcService extends SimpleKeysGrpc.KeysImplBase {
|
||||
storeRepeatedUseKey(authenticatedDevice.accountIdentifier(),
|
||||
request.getIdentityType(),
|
||||
request.getSignedPreKey(),
|
||||
KeysGrpcService::checkEcSignedPreKey,
|
||||
(preKey, identityKey) -> KeysGrpcHelper.checkEcSignedPreKey(preKey, identityKey, INVALID_PUBLIC_KEY_EXCEPTION, INVALID_SIGNATURE_EXCEPTION),
|
||||
(account, signedPreKey) -> {
|
||||
final IdentityType identityType = IdentityTypeUtil.fromGrpcIdentityType(request.getIdentityType());
|
||||
final UUID identifier = account.getIdentifier(identityType);
|
||||
@@ -195,7 +186,7 @@ public class KeysGrpcService extends SimpleKeysGrpc.KeysImplBase {
|
||||
storeRepeatedUseKey(authenticatedDevice.accountIdentifier(),
|
||||
request.getIdentityType(),
|
||||
request.getSignedPreKey(),
|
||||
KeysGrpcService::checkKemSignedPreKey,
|
||||
(preKey, identityKey) -> KeysGrpcHelper.checkKemSignedPreKey(preKey, identityKey, INVALID_PUBLIC_KEY_EXCEPTION, INVALID_SIGNATURE_EXCEPTION),
|
||||
(account, lastResortKey) -> {
|
||||
final UUID identifier =
|
||||
account.getIdentifier(IdentityTypeUtil.fromGrpcIdentityType(request.getIdentityType()));
|
||||
@@ -220,45 +211,6 @@ public class KeysGrpcService extends SimpleKeysGrpc.KeysImplBase {
|
||||
storeKeyFunction.apply(account, key).join();
|
||||
}
|
||||
|
||||
private static ECPreKey checkEcPreKey(final EcPreKey preKey) {
|
||||
try {
|
||||
return new ECPreKey(preKey.getKeyId(), new ECPublicKey(preKey.getPublicKey().toByteArray()));
|
||||
} catch (final InvalidKeyException e) {
|
||||
throw INVALID_PUBLIC_KEY_EXCEPTION;
|
||||
}
|
||||
}
|
||||
|
||||
private static ECSignedPreKey checkEcSignedPreKey(final EcSignedPreKey preKey, final IdentityKey identityKey) {
|
||||
try {
|
||||
final ECSignedPreKey ecSignedPreKey = new ECSignedPreKey(preKey.getKeyId(),
|
||||
new ECPublicKey(preKey.getPublicKey().toByteArray()),
|
||||
preKey.getSignature().toByteArray());
|
||||
|
||||
if (ecSignedPreKey.signatureValid(identityKey)) {
|
||||
return ecSignedPreKey;
|
||||
} else {
|
||||
throw INVALID_SIGNATURE_EXCEPTION;
|
||||
}
|
||||
} catch (final InvalidKeyException e) {
|
||||
throw INVALID_PUBLIC_KEY_EXCEPTION;
|
||||
}
|
||||
}
|
||||
|
||||
private static KEMSignedPreKey checkKemSignedPreKey(final KemSignedPreKey preKey, final IdentityKey identityKey) {
|
||||
try {
|
||||
final KEMSignedPreKey kemSignedPreKey = new KEMSignedPreKey(preKey.getKeyId(),
|
||||
new KEMPublicKey(preKey.getPublicKey().toByteArray()),
|
||||
preKey.getSignature().toByteArray());
|
||||
|
||||
if (kemSignedPreKey.signatureValid(identityKey)) {
|
||||
return kemSignedPreKey;
|
||||
} else {
|
||||
throw INVALID_SIGNATURE_EXCEPTION;
|
||||
}
|
||||
} catch (final InvalidKeyException e) {
|
||||
throw INVALID_PUBLIC_KEY_EXCEPTION;
|
||||
}
|
||||
}
|
||||
|
||||
private Account getAuthenticatedAccount(final UUID authenticatedAccountId) {
|
||||
return accountsManager.getByAccountIdentifier(authenticatedAccountId)
|
||||
|
||||
+12
@@ -30,6 +30,7 @@ import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.atomic.LongAdder;
|
||||
import javax.annotation.Nullable;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@@ -65,12 +66,19 @@ public class MetricServerInterceptor implements ServerInterceptor {
|
||||
@VisibleForTesting
|
||||
static final String DURATION_TIMER_NAME = MetricsUtil.name(MetricServerInterceptor.class, "processingDuration");
|
||||
|
||||
private static final String ACTIVE_REQUESTS_GAUGE_NAME =
|
||||
MetricsUtil.name(MetricServerInterceptor.class, "activeRequests");
|
||||
|
||||
private final MeterRegistry meterRegistry;
|
||||
private final ClientReleaseManager clientReleaseManager;
|
||||
|
||||
private final LongAdder activeRequests;
|
||||
|
||||
public MetricServerInterceptor(final MeterRegistry meterRegistry, final ClientReleaseManager clientReleaseManager) {
|
||||
this.meterRegistry = meterRegistry;
|
||||
this.clientReleaseManager = clientReleaseManager;
|
||||
|
||||
this.activeRequests = meterRegistry.gauge(ACTIVE_REQUESTS_GAUGE_NAME, new LongAdder());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -194,6 +202,8 @@ public class MetricServerInterceptor implements ServerInterceptor {
|
||||
this.requestBytesCounter = meterRegistry.counter(REQUEST_BYTES_COUNTER_NAME, tags);
|
||||
this.responseTimer = meterRegistry.timer(DURATION_TIMER_NAME, tags);
|
||||
this.sample = Timer.start(meterRegistry);
|
||||
|
||||
activeRequests.increment();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -210,12 +220,14 @@ public class MetricServerInterceptor implements ServerInterceptor {
|
||||
@Override
|
||||
public void onComplete() {
|
||||
this.sample.stop(responseTimer);
|
||||
activeRequests.decrement();
|
||||
super.onComplete();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCancel() {
|
||||
this.sample.stop(responseTimer);
|
||||
activeRequests.decrement();
|
||||
super.onCancel();
|
||||
}
|
||||
}
|
||||
|
||||
+45
-28
@@ -8,6 +8,7 @@ import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.getClientP
|
||||
import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.toChargeFailure;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import java.io.IOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
@@ -21,18 +22,18 @@ import io.micrometer.core.instrument.Tags;
|
||||
import org.signal.chat.errors.FailedPrecondition;
|
||||
import org.signal.chat.errors.FailedZkAuthentication;
|
||||
import org.signal.chat.errors.NotFound;
|
||||
import org.signal.chat.one_time_donations.AmountAboveSepaLimitError;
|
||||
import org.signal.chat.one_time_donations.AmountBelowMinimumError;
|
||||
import org.signal.chat.one_time_donations.ConfirmPayPalBoostRequest;
|
||||
import org.signal.chat.one_time_donations.ConfirmPayPalBoostResponse;
|
||||
import org.signal.chat.one_time_donations.CreateBoostReceiptCredentialsRequest;
|
||||
import org.signal.chat.one_time_donations.CreateBoostReceiptCredentialsResponse;
|
||||
import org.signal.chat.one_time_donations.CreateBoostRequest;
|
||||
import org.signal.chat.one_time_donations.CreateBoostResponse;
|
||||
import org.signal.chat.one_time_donations.CreatePayPalBoostRequest;
|
||||
import org.signal.chat.one_time_donations.CreatePayPalBoostResponse;
|
||||
import org.signal.chat.one_time_donations.SimpleOneTimeDonationsGrpc;
|
||||
import org.signal.chat.subscriptions.PaymentRequired;
|
||||
import org.signal.chat.purchase.AmountAboveSepaLimitError;
|
||||
import org.signal.chat.purchase.AmountBelowMinimumError;
|
||||
import org.signal.chat.purchase.ConfirmPayPalBoostRequest;
|
||||
import org.signal.chat.purchase.ConfirmPayPalBoostResponse;
|
||||
import org.signal.chat.purchase.CreateBoostReceiptCredentialsRequest;
|
||||
import org.signal.chat.purchase.CreateBoostReceiptCredentialsResponse;
|
||||
import org.signal.chat.purchase.CreateBoostRequest;
|
||||
import org.signal.chat.purchase.CreateBoostResponse;
|
||||
import org.signal.chat.purchase.CreatePayPalBoostRequest;
|
||||
import org.signal.chat.purchase.CreatePayPalBoostResponse;
|
||||
import org.signal.chat.purchase.SimpleOneTimeDonationsGrpc;
|
||||
import org.signal.chat.purchase.PaymentRequired;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
import org.signal.libsignal.zkgroup.donation.DonationPermit;
|
||||
@@ -53,6 +54,8 @@ import org.whispersystems.textsecuregcm.subscriptions.PaymentDetails;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.PaymentStatus;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.StripeManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidAmountException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorException;
|
||||
|
||||
public class OneTimeDonationsGrpcService extends SimpleOneTimeDonationsGrpc.OneTimeDonationsImplBase {
|
||||
|
||||
@@ -91,7 +94,8 @@ public class OneTimeDonationsGrpcService extends SimpleOneTimeDonationsGrpc.OneT
|
||||
}
|
||||
|
||||
@Override
|
||||
public CreateBoostResponse createBoost(final CreateBoostRequest request) throws RateLimitExceededException {
|
||||
public CreateBoostResponse createBoost(final CreateBoostRequest request)
|
||||
throws RateLimitExceededException {
|
||||
RateLimitUtil.rateLimitByRemoteAddress(rateLimiters.forDescriptor(RateLimiters.For.ONE_TIME_DONATION));
|
||||
|
||||
try {
|
||||
@@ -144,16 +148,23 @@ public class OneTimeDonationsGrpcService extends SimpleOneTimeDonationsGrpc.OneT
|
||||
.setAmountAboveSepaLimit(AmountAboveSepaLimitError.newBuilder()
|
||||
.setMaximum(r.maximum().toString()).build()).build();
|
||||
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.Success _ -> {
|
||||
final com.stripe.model.PaymentIntent paymentIntent = stripeManager.createPaymentIntent(
|
||||
request.getCurrency(), request.getAmount(), request.getLevel(),
|
||||
getClientPlatform(RequestAttributesUtil.getUserAgent().orElse(null))).join();
|
||||
yield CreateBoostResponse.newBuilder().setClientSecret(paymentIntent.getClientSecret()).build();
|
||||
try {
|
||||
final com.stripe.model.PaymentIntent paymentIntent = stripeManager.createPaymentIntent(
|
||||
request.getCurrency(), request.getAmount(), request.getLevel(),
|
||||
getClientPlatform(RequestAttributesUtil.getUserAgent().orElse(null)));
|
||||
yield CreateBoostResponse.newBuilder().setClientSecret(paymentIntent.getClientSecret()).build();
|
||||
} catch (final SubscriptionInvalidAmountException e) {
|
||||
yield CreateBoostResponse.newBuilder()
|
||||
.setInvalidAmount(FailedPrecondition.newBuilder()
|
||||
.setDescription(e.getErrorCode()).build())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public CreatePayPalBoostResponse createPayPalBoost(final CreatePayPalBoostRequest request) {
|
||||
public CreatePayPalBoostResponse createPayPalBoost(final CreatePayPalBoostRequest request) throws IOException {
|
||||
|
||||
final OneTimeDonationUtil.OneTimeDonationRequestValidationResult validationResult =
|
||||
OneTimeDonationUtil.validateOneTimeDonationRequest(
|
||||
@@ -185,7 +196,7 @@ public class OneTimeDonationsGrpcService extends SimpleOneTimeDonationsGrpc.OneT
|
||||
braintreeManager.createOneTimePayment(
|
||||
request.getCurrency().toUpperCase(Locale.ROOT), request.getAmount(),
|
||||
localizedLineItem.locale().toLanguageTag(), request.getReturnUrl(), request.getCancelUrl(),
|
||||
localizedLineItem.itemName()).join();
|
||||
localizedLineItem.itemName());
|
||||
yield CreatePayPalBoostResponse.newBuilder()
|
||||
.setResult(CreatePayPalBoostResponse.CreatePayPalBoostResult.newBuilder()
|
||||
.setApprovalUrl(approvalDetails.approvalUrl())
|
||||
@@ -196,7 +207,7 @@ public class OneTimeDonationsGrpcService extends SimpleOneTimeDonationsGrpc.OneT
|
||||
|
||||
@Override
|
||||
public ConfirmPayPalBoostResponse confirmPayPalBoost(final ConfirmPayPalBoostRequest request)
|
||||
throws RateLimitExceededException {
|
||||
throws RateLimitExceededException, IOException {
|
||||
RateLimitUtil.rateLimitByRemoteAddress(rateLimiters.forDescriptor(RateLimiters.For.ONE_TIME_DONATION));
|
||||
|
||||
final OneTimeDonationUtil.OneTimeDonationRequestValidationResult validationResult =
|
||||
@@ -222,33 +233,39 @@ public class OneTimeDonationsGrpcService extends SimpleOneTimeDonationsGrpc.OneT
|
||||
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.AmountAboveSepaLimit _ ->
|
||||
throw new IllegalStateException("SEPA limit should not trigger for PayPal");
|
||||
case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.Success _ -> {
|
||||
final BraintreeManager.PayPalChargeSuccessDetails chargeSuccessDetails =
|
||||
braintreeManager.captureOneTimePayment(
|
||||
request.getPayerId(), request.getPaymentId(), request.getPaymentToken(),
|
||||
request.getCurrency(), request.getAmount(), request.getLevel(),
|
||||
getClientPlatform(RequestAttributesUtil.getUserAgent().orElse(null))).join();
|
||||
final BraintreeManager.PayPalChargeSuccessDetails chargeSuccessDetails;
|
||||
try {
|
||||
chargeSuccessDetails = braintreeManager.captureOneTimePayment(
|
||||
request.getPayerId(), request.getPaymentId(), request.getPaymentToken(),
|
||||
request.getCurrency(), request.getAmount(), request.getLevel(),
|
||||
SubscriptionsUtil.getClientPlatform(RequestAttributesUtil.getUserAgent().orElse(null)));
|
||||
oneTimeDonationsManager.putPaidAt(chargeSuccessDetails.paymentId(), clock.instant());
|
||||
yield ConfirmPayPalBoostResponse.newBuilder()
|
||||
.setResult(ConfirmPayPalBoostResponse.ConfirmPayPalBoostResult.newBuilder()
|
||||
.setPaymentId(chargeSuccessDetails.paymentId()).build()).build();
|
||||
} catch (final SubscriptionProcessorException e) {
|
||||
yield ConfirmPayPalBoostResponse.newBuilder()
|
||||
.setChargeFailure(SubscriptionsUtil.toChargeFailure(e.getProcessor(), e.getChargeFailure()))
|
||||
.build();
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public CreateBoostReceiptCredentialsResponse createBoostReceiptCredentials(
|
||||
final CreateBoostReceiptCredentialsRequest request) {
|
||||
final CreateBoostReceiptCredentialsRequest request) throws IOException {
|
||||
|
||||
final PaymentProvider processor;
|
||||
final Optional<PaymentDetails> maybePaymentDetails;
|
||||
switch (request.getProcessor()) {
|
||||
case PAYMENT_PROVIDER_STRIPE -> {
|
||||
processor = PaymentProvider.STRIPE;
|
||||
maybePaymentDetails = stripeManager.getPaymentDetails(request.getPaymentIntentId()).join();
|
||||
maybePaymentDetails = stripeManager.getPaymentDetails(request.getPaymentIntentId());
|
||||
}
|
||||
case PAYMENT_PROVIDER_BRAINTREE -> {
|
||||
processor = PaymentProvider.BRAINTREE;
|
||||
maybePaymentDetails = braintreeManager.getPaymentDetails(request.getPaymentIntentId()).join();
|
||||
maybePaymentDetails = braintreeManager.getPaymentDetails(request.getPaymentIntentId());
|
||||
}
|
||||
default -> throw GrpcExceptions.fieldViolation("processor", "Unsupported payment processor");
|
||||
}
|
||||
|
||||
+167
@@ -0,0 +1,167 @@
|
||||
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.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<>();
|
||||
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
@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);
|
||||
}
|
||||
}
|
||||
|
||||
private static Map<String, CurrencyConfiguration> buildCurrencyConfigurations(
|
||||
final SubscriptionConfiguration subscriptionConfiguration,
|
||||
final OneTimeDonationConfiguration oneTimeDonationConfiguration,
|
||||
List<CustomerAwareSubscriptionPaymentProcessor> paymentProcessors) {
|
||||
return SubscriptionsUtil
|
||||
.buildCurrencyConfiguration(paymentProcessors, oneTimeDonationConfiguration, subscriptionConfiguration)
|
||||
.entrySet().stream()
|
||||
.collect(Collectors.toMap(
|
||||
Map.Entry::getKey,
|
||||
e -> toProtoCurrencyConfiguration(e.getKey(), e.getValue())));
|
||||
}
|
||||
|
||||
private static BackupConfiguration buildBackupConfiguration(final SubscriptionConfiguration subscriptionConfiguration,
|
||||
final long backupMediaStorageAllowanceBytes) {
|
||||
final Map<Long, BackupLevelConfiguration> backupLevels =
|
||||
subscriptionConfiguration.getBackupLevels().entrySet().stream().collect(Collectors.toMap(
|
||||
Map.Entry::getKey,
|
||||
e -> BackupLevelConfiguration.newBuilder()
|
||||
.setStorageAllowanceBytes(backupMediaStorageAllowanceBytes)
|
||||
.setPlayProductId(e.getValue().playProductId())
|
||||
.setMediaTtlDays(e.getValue().mediaTtl().toDays())
|
||||
.build()));
|
||||
return BackupConfiguration.newBuilder()
|
||||
.putAllLevels(backupLevels)
|
||||
.setFreeTierMediaDays(subscriptionConfiguration.getbackupFreeTierMediaDuration().toDays())
|
||||
.build();
|
||||
}
|
||||
|
||||
private static CurrencyConfiguration toProtoCurrencyConfiguration(
|
||||
final String currency,
|
||||
final org.whispersystems.textsecuregcm.subscriptions.CurrencyConfiguration config) {
|
||||
final CurrencyConfiguration.Builder builder = CurrencyConfiguration.newBuilder()
|
||||
.setMinimum(config.minimum().toString())
|
||||
.addAllSupportedPaymentMethods(config.supportedPaymentMethods().stream()
|
||||
.map(PaymentMethod::toProtoPaymentMethod)
|
||||
.toList());
|
||||
config.oneTime().forEach((levelId, amounts) ->
|
||||
builder.putOneTime(levelId, AmountList.newBuilder()
|
||||
.addAllAmounts(amounts.stream().map(BigDecimal::toString).toList())
|
||||
.build()));
|
||||
config.subscription()
|
||||
.forEach((levelId, amount) -> builder.putSubscription(levelId, amount.toString()));
|
||||
config.backupSubscription()
|
||||
.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();
|
||||
}
|
||||
}
|
||||
+17
-44
@@ -22,10 +22,8 @@ import org.signal.chat.profile.GetAvatarUploadFormRequest;
|
||||
import org.signal.chat.profile.GetAvatarUploadFormResponse;
|
||||
import org.signal.chat.profile.GetExpiringProfileKeyCredentialAnonymousRequest;
|
||||
import org.signal.chat.profile.GetExpiringProfileKeyCredentialAnonymousResponse;
|
||||
import org.signal.chat.profile.GetUnversionedProfileAnonymousRequest;
|
||||
import org.signal.chat.profile.GetUnversionedProfileAnonymousResponse;
|
||||
import org.signal.chat.profile.GetVersionedProfileAnonymousRequest;
|
||||
import org.signal.chat.profile.GetVersionedProfileAnonymousResponse;
|
||||
import org.signal.chat.profile.GetProfileAnonymousRequest;
|
||||
import org.signal.chat.profile.GetProfileAnonymousResponse;
|
||||
import org.signal.chat.profile.SimpleProfileAnonymousGrpc;
|
||||
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
@@ -36,7 +34,6 @@ import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations;
|
||||
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
|
||||
import org.whispersystems.textsecuregcm.badges.ProfileBadgeConverter;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
|
||||
@@ -101,14 +98,8 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof
|
||||
}
|
||||
|
||||
@Override
|
||||
public GetUnversionedProfileAnonymousResponse getUnversionedProfile(final GetUnversionedProfileAnonymousRequest request) {
|
||||
final ServiceIdentifier targetIdentifier =
|
||||
GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getServiceIdentifier());
|
||||
|
||||
// Callers must be authenticated to request unversioned profiles by PNI
|
||||
if (targetIdentifier.identityType() == IdentityType.PNI) {
|
||||
throw GrpcExceptions.invalidArguments("aci service identifier type required");
|
||||
}
|
||||
public GetProfileAnonymousResponse getProfile(final GetProfileAnonymousRequest request) {
|
||||
final ServiceIdentifier targetIdentifier = GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getAccountIdentifier());
|
||||
|
||||
final Optional<Account> targetAccount = accountsManager.getByServiceIdentifier(targetIdentifier);
|
||||
|
||||
@@ -121,43 +112,25 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof
|
||||
};
|
||||
|
||||
if (!authorized) {
|
||||
return GetUnversionedProfileAnonymousResponse.newBuilder()
|
||||
return GetProfileAnonymousResponse.newBuilder()
|
||||
.setFailedUnidentifiedAuthorization(FailedUnidentifiedAuthorization.getDefaultInstance())
|
||||
.build();
|
||||
}
|
||||
final byte[] version = request.getRequest().getVersion().toByteArray();
|
||||
|
||||
return targetAccount.map(account ->
|
||||
GetUnversionedProfileAnonymousResponse.newBuilder()
|
||||
.setResult(ProfileGrpcHelper.buildUnversionedProfileResult(targetIdentifier,
|
||||
null,
|
||||
account,
|
||||
profileBadgeConverter))
|
||||
.build())
|
||||
.orElseGet(() -> GetUnversionedProfileAnonymousResponse.newBuilder()
|
||||
.setNotFound(NotFound.getDefaultInstance())
|
||||
.build());
|
||||
}
|
||||
return targetAccount.flatMap(account -> ProfileGrpcHelper
|
||||
.getProfile(account, profilesManager, profileBadgeConverter, version)
|
||||
|
||||
@Override
|
||||
public GetVersionedProfileAnonymousResponse getVersionedProfile(final GetVersionedProfileAnonymousRequest request) {
|
||||
final ServiceIdentifier targetIdentifier = GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getAccountIdentifier());
|
||||
// If the etag matches, drop the result
|
||||
.map(profileResult -> request.getRequest().getEtag().equals(profileResult.getEtag())
|
||||
? GetProfileAnonymousResponse.newBuilder().setEtagMatched(true).build()
|
||||
: GetProfileAnonymousResponse.newBuilder().setProfile(profileResult).build())
|
||||
|
||||
final Optional<Account> targetAccount = getTargetAccountAndValidateUnidentifiedAccess(targetIdentifier, request.getUnidentifiedAccessKey().toByteArray());
|
||||
|
||||
return targetAccount.flatMap(account ->
|
||||
ProfileGrpcHelper.getVersionedProfile(account,
|
||||
profilesManager,
|
||||
request.getRequest().getVersion().toByteArray(),
|
||||
request.getRequest().getDataEtag().toByteArray(),
|
||||
request.getRequest().getPaymentAddressEtag().toByteArray()))
|
||||
.map(result ->
|
||||
GetVersionedProfileAnonymousResponse.newBuilder()
|
||||
.setResult(result)
|
||||
.build())
|
||||
.orElseGet(() ->
|
||||
GetVersionedProfileAnonymousResponse.newBuilder()
|
||||
.setNotFound(NotFound.getDefaultInstance())
|
||||
.build());
|
||||
// If we didn't find a v2 profile, try a v1 profile
|
||||
.or(() -> ProfileGrpcHelper
|
||||
.getProfileV1(account, profilesManager, profileBadgeConverter, version)
|
||||
.map(v1Result -> GetProfileAnonymousResponse.newBuilder().setProfileV1(v1Result).build())))
|
||||
.orElseGet(() -> GetProfileAnonymousResponse.newBuilder().setNotFound(NotFound.getDefaultInstance()).build());
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+108
-160
@@ -7,23 +7,21 @@ package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.protobuf.ByteString;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Clock;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import org.signal.chat.common.Badge;
|
||||
import org.signal.chat.common.BadgeSvg;
|
||||
import org.bouncycastle.crypto.digests.TupleHash;
|
||||
import org.signal.chat.common.S3UploadForm;
|
||||
import org.signal.chat.profile.DataEtag;
|
||||
import org.signal.chat.profile.GetExpiringProfileKeyCredentialResult;
|
||||
import org.signal.chat.profile.GetUnversionedProfileResult;
|
||||
import org.signal.chat.profile.GetVersionedProfileResult;
|
||||
import org.signal.chat.profile.GetVersionedProfileV1Response;
|
||||
import org.signal.chat.profile.ProfileResult;
|
||||
import org.signal.chat.profile.ProfileResultOrBuilder;
|
||||
import org.signal.chat.profile.LegacyProfileResult;
|
||||
import org.signal.chat.profile.AccountInfo;
|
||||
import org.signal.libsignal.protocol.ServiceId;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
@@ -33,7 +31,7 @@ import org.signal.libsignal.zkgroup.profiles.ProfileKeyCredentialRequest;
|
||||
import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations;
|
||||
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessChecksum;
|
||||
import org.whispersystems.textsecuregcm.badges.ProfileBadgeConverter;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
@@ -44,154 +42,84 @@ import org.whispersystems.textsecuregcm.util.ProfileHelper;
|
||||
|
||||
public class ProfileGrpcHelper {
|
||||
|
||||
private static final byte[] ETAG_DOMAIN = "ProfileETag/v1".getBytes(StandardCharsets.UTF_8);
|
||||
private static final int ETAG_LENGTH = 10;
|
||||
private static final S3UploadForm PROTOTYPE_AVATAR_UPLOAD_FORM = S3UploadForm.newBuilder()
|
||||
.setAcl(PostPolicyGenerator.ACL)
|
||||
.setAlgorithm(PostPolicyGenerator.ALGORITHM)
|
||||
.build();
|
||||
|
||||
static Optional<GetVersionedProfileResult> getVersionedProfile(final Account account,
|
||||
static Optional<LegacyProfileResult> getProfileV1(final Account account,
|
||||
final ProfilesManager profilesManager,
|
||||
final byte[] requestVersion,
|
||||
final byte[] requestDataEtag,
|
||||
final byte[] requestPaymentAddressEtag) {
|
||||
|
||||
final Optional<VersionedProfile> profile;
|
||||
if (account.hasCapability(DeviceCapability.PROFILES_V2)) {
|
||||
profile = profilesManager.get(account.getUuid(), requestVersion);
|
||||
} else {
|
||||
profile = Optional.empty();
|
||||
}
|
||||
|
||||
final Optional<VersionedProfileV1> v1Profile;
|
||||
if (profile.isEmpty()) {
|
||||
v1Profile = profilesManager.getV1(account.getUuid(), HexFormat.of().formatHex(requestVersion));
|
||||
} else {
|
||||
v1Profile = Optional.empty();
|
||||
}
|
||||
|
||||
if (profile.isEmpty() && v1Profile.isEmpty()) {
|
||||
final ProfileBadgeConverter profileBadgeConverter,
|
||||
final byte[] requestVersion) {
|
||||
final Optional<VersionedProfileV1> maybeV1Profile =
|
||||
profilesManager.getV1(account.getUuid(), HexFormat.of().formatHex(requestVersion));
|
||||
if (maybeV1Profile.isEmpty()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
final VersionedProfileV1 v1Profile = maybeV1Profile.get();
|
||||
|
||||
final GetVersionedProfileResult.Builder responseBuilder = GetVersionedProfileResult.newBuilder();
|
||||
final LegacyProfileResult.Builder builder = LegacyProfileResult.newBuilder()
|
||||
.setAccountInfo(buildAccountInfo(profileBadgeConverter, account))
|
||||
.setName(ByteString.copyFrom(v1Profile.name()))
|
||||
.setAbout(ByteString.copyFrom(v1Profile.about()))
|
||||
.setAboutEmoji(ByteString.copyFrom(v1Profile.aboutEmoji()))
|
||||
.setPhoneNumberSharing(ByteString.copyFrom(v1Profile.phoneNumberSharing()));
|
||||
|
||||
profile.ifPresent(p -> {
|
||||
if (requestDataEtag.length > 0 && Arrays.equals(requestDataEtag, p.dataHash())) {
|
||||
responseBuilder.setDataEtagMatched(true);
|
||||
} else {
|
||||
responseBuilder.setDataEtag(DataEtag.newBuilder()
|
||||
.setData(ByteString.copyFrom(p.data()))
|
||||
.setEtagSha256(ByteString.copyFrom(p.dataHash()))
|
||||
.build());
|
||||
}
|
||||
});
|
||||
|
||||
v1Profile.ifPresent(p -> {
|
||||
final GetVersionedProfileV1Response.Builder v1ResponseBuilder = GetVersionedProfileV1Response.newBuilder();
|
||||
|
||||
v1ResponseBuilder
|
||||
.setName(ByteString.copyFrom(p.name()))
|
||||
.setAbout(ByteString.copyFrom(p.about()))
|
||||
.setAboutEmoji(ByteString.copyFrom(p.aboutEmoji()))
|
||||
.setPhoneNumberSharing(ByteString.copyFrom(p.phoneNumberSharing()));
|
||||
|
||||
if (p.avatar() != null) {
|
||||
v1ResponseBuilder.setAvatar(p.avatar());
|
||||
}
|
||||
|
||||
responseBuilder.setV1Response(v1ResponseBuilder);
|
||||
});
|
||||
|
||||
// Include payment address if the version matches the latest version on Account or the latest version on Account
|
||||
// is empty
|
||||
if (account.getCurrentProfileVersion().map(v -> Arrays.equals(v, requestVersion)).orElse(true)) {
|
||||
final Optional<byte []> paymentAddress = profile.map(VersionedProfile::paymentAddress).or(() -> v1Profile.map(VersionedProfileV1::paymentAddress));
|
||||
|
||||
if (paymentAddress.isPresent()) {
|
||||
|
||||
final boolean paymentAddressETagMatches = requestPaymentAddressEtag.length > 0 &&
|
||||
profile.map(VersionedProfile::paymentAddressHash)
|
||||
.map(h -> Arrays.equals(requestPaymentAddressEtag, h))
|
||||
.orElse(false);
|
||||
|
||||
if (paymentAddressETagMatches) {
|
||||
responseBuilder.setPaymentAddressEtagMatched(true);
|
||||
} else {
|
||||
responseBuilder.setPaymentAddressDataEtag(DataEtag.newBuilder()
|
||||
.setData(ByteString.copyFrom(paymentAddress.get()))
|
||||
.setEtagSha256(ByteString.copyFrom(
|
||||
profile.map(VersionedProfile::paymentAddressHash).orElseGet(() -> hash(paymentAddress.get()))))
|
||||
.build());
|
||||
}
|
||||
}
|
||||
if (v1Profile.avatar() != null) {
|
||||
builder.setAvatar(v1Profile.avatar());
|
||||
}
|
||||
|
||||
return Optional.of(responseBuilder.build());
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static List<Badge> buildBadges(final List<org.whispersystems.textsecuregcm.entities.Badge> badges) {
|
||||
final ArrayList<Badge> grpcBadges = new ArrayList<>();
|
||||
for (final org.whispersystems.textsecuregcm.entities.Badge badge : badges) {
|
||||
grpcBadges.add(Badge.newBuilder()
|
||||
.setId(badge.getId())
|
||||
.setCategory(badge.getCategory())
|
||||
.setName(badge.getName())
|
||||
.setDescription(badge.getDescription())
|
||||
.addAllSprites6(badge.getSprites6())
|
||||
.setSvg(badge.getSvg())
|
||||
.addAllSvgs(buildBadgeSvgs(badge.getSvgs()))
|
||||
.build());
|
||||
}
|
||||
return grpcBadges;
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static List<org.signal.chat.common.DeviceCapability> buildAccountCapabilities(final Account account) {
|
||||
return Arrays.stream(DeviceCapability.values())
|
||||
.filter(DeviceCapability::includeInProfile)
|
||||
.filter(account::hasCapability)
|
||||
.map(DeviceCapabilityUtil::toGrpcDeviceCapability)
|
||||
.toList();
|
||||
}
|
||||
|
||||
private static List<BadgeSvg> buildBadgeSvgs(final List<org.whispersystems.textsecuregcm.entities.BadgeSvg> badgeSvgs) {
|
||||
ArrayList<BadgeSvg> grpcBadgeSvgs = new ArrayList<>();
|
||||
for (final org.whispersystems.textsecuregcm.entities.BadgeSvg badgeSvg : badgeSvgs) {
|
||||
grpcBadgeSvgs.add(BadgeSvg.newBuilder()
|
||||
.setDark(badgeSvg.getDark())
|
||||
.setLight(badgeSvg.getLight())
|
||||
.build());
|
||||
}
|
||||
return grpcBadgeSvgs;
|
||||
}
|
||||
|
||||
static GetUnversionedProfileResult buildUnversionedProfileResult(
|
||||
final ServiceIdentifier targetIdentifier,
|
||||
final UUID requesterUuid,
|
||||
final Account targetAccount,
|
||||
final ProfileBadgeConverter profileBadgeConverter) {
|
||||
final GetUnversionedProfileResult.Builder resultBuilder = GetUnversionedProfileResult.newBuilder()
|
||||
.setIdentityKey(ByteString.copyFrom(targetAccount.getIdentityKey(targetIdentifier.identityType()).serialize()))
|
||||
.addAllCapabilities(buildAccountCapabilities(targetAccount));
|
||||
|
||||
switch (targetIdentifier.identityType()) {
|
||||
case ACI -> {
|
||||
resultBuilder.setUnrestrictedUnidentifiedAccess(targetAccount.isUnrestrictedUnidentifiedAccess())
|
||||
.addAllBadges(
|
||||
buildBadges(profileBadgeConverter.convert(RequestAttributesUtil.getAvailableAcceptedLocales(),
|
||||
targetAccount.getBadges(),
|
||||
ProfileHelper.isSelfProfileRequest(requesterUuid, targetIdentifier))));
|
||||
|
||||
targetAccount.getUnidentifiedAccessKey()
|
||||
.map(UnidentifiedAccessChecksum::generateFor)
|
||||
.map(ByteString::copyFrom)
|
||||
.ifPresent(resultBuilder::setUnidentifiedAccess);
|
||||
}
|
||||
case PNI -> resultBuilder.setUnrestrictedUnidentifiedAccess(false);
|
||||
// If present, include the payment address if the version matches the latest version on Account or the latest
|
||||
// version on Account is empty
|
||||
if (v1Profile.paymentAddress() != null && account.getCurrentProfileVersion().map(v -> Arrays.equals(v, requestVersion)).orElse(true)) {
|
||||
builder.setPaymentAddress(ByteString.copyFrom(v1Profile.paymentAddress()));
|
||||
}
|
||||
|
||||
return resultBuilder.build();
|
||||
return Optional.of(builder.build());
|
||||
}
|
||||
|
||||
static Optional<ProfileResult> getProfile(final Account account,
|
||||
final ProfilesManager profilesManager,
|
||||
final ProfileBadgeConverter profileBadgeConverter,
|
||||
final byte[] requestVersion) {
|
||||
|
||||
final Optional<VersionedProfile> maybeProfile = account.hasCapability(DeviceCapability.PROFILES_V2)
|
||||
? profilesManager.get(account.getUuid(), requestVersion)
|
||||
: Optional.empty();
|
||||
if (maybeProfile.isEmpty()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
final VersionedProfile profile = maybeProfile.get();
|
||||
|
||||
final ProfileResult.Builder builder = ProfileResult.newBuilder()
|
||||
.setData(ByteString.copyFrom(profile.data()))
|
||||
.setAccountInfo(buildAccountInfo(profileBadgeConverter, account));
|
||||
|
||||
// If present, include the payment address if the version matches the latest version on Account or the latest
|
||||
// version on Account is empty
|
||||
if (profile.paymentAddress() != null && account.getCurrentProfileVersion().map(v -> Arrays.equals(v, requestVersion)).orElse(true)) {
|
||||
builder.setPaymentAddress(ByteString.copyFrom(profile.paymentAddress()));
|
||||
}
|
||||
|
||||
builder.setEtag(ByteString.copyFrom(etag(builder)));
|
||||
return Optional.of(builder.build());
|
||||
}
|
||||
|
||||
private static AccountInfo buildAccountInfo(final ProfileBadgeConverter profileBadgeConverter,
|
||||
final Account account) {
|
||||
final AccountInfo.Builder accountInfoBuilder = AccountInfo.newBuilder()
|
||||
.addAllBadgeIds(profileBadgeConverter.visibleBadgeIds(account.getBadges()))
|
||||
.setIdentityKey(ByteString.copyFrom(account.getIdentityKey(IdentityType.ACI).serialize()))
|
||||
.setUnrestrictedUnidentifiedAccess(account.isUnrestrictedUnidentifiedAccess());
|
||||
|
||||
account.getUnidentifiedAccessKey()
|
||||
.map(UnidentifiedAccessChecksum::generateFor)
|
||||
.map(ByteString::copyFrom)
|
||||
.ifPresent(accountInfoBuilder::setUnidentifiedAccessKeyFingerprint);
|
||||
|
||||
return accountInfoBuilder.build();
|
||||
}
|
||||
|
||||
static Optional<GetExpiringProfileKeyCredentialResult> getExpiringProfileKeyCredentialResult(
|
||||
@@ -209,12 +137,14 @@ public class ProfileGrpcHelper {
|
||||
}
|
||||
|
||||
return versionedProfile.map(VersionedProfile::commitment)
|
||||
.or(() -> profilesManager.getV1(account.getUuid(), HexFormat.of().formatHex(version)).map(VersionedProfileV1::commitment))
|
||||
.or(() -> profilesManager.getV1(account.getUuid(), HexFormat.of().formatHex(version))
|
||||
.map(VersionedProfileV1::commitment))
|
||||
.map(commitment -> {
|
||||
|
||||
final ExpiringProfileKeyCredentialResponse profileKeyCredentialResponse;
|
||||
try {
|
||||
profileKeyCredentialResponse = ProfileHelper.getExpiringProfileKeyCredential(new ProfileKeyCredentialRequest(encodedCredentialRequest),
|
||||
profileKeyCredentialResponse = ProfileHelper.getExpiringProfileKeyCredential(
|
||||
new ProfileKeyCredentialRequest(encodedCredentialRequest),
|
||||
new ProfileKeyCommitment(commitment), new ServiceId.Aci(account.getUuid()), zkProfileOperations);
|
||||
} catch (VerificationFailedException | InvalidInputException e) {
|
||||
throw GrpcExceptions.invalidArguments("invalid credential request");
|
||||
@@ -240,19 +170,37 @@ public class ProfileGrpcHelper {
|
||||
.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes the SHA-256 hash of the given data.
|
||||
* <p>
|
||||
* Only needed during the v1 -> v2 migration. See also: VersionedProfile#hash(byte[])
|
||||
*/
|
||||
/// Compute the etag of a [ProfileResult]
|
||||
///
|
||||
/// @implNote This uses the NIST-SP 800-185 TupleHash to provide a cryptographic hash over variable length fields.
|
||||
/// Clients must be able to reproduce the same etag from the data, so hash must be stable.
|
||||
@VisibleForTesting
|
||||
public static byte[] hash(final byte[] data) {
|
||||
final MessageDigest sha256;
|
||||
try {
|
||||
sha256 = MessageDigest.getInstance("SHA-256");
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
return sha256.digest(data);
|
||||
static byte[] etag(final ProfileResultOrBuilder profile) {
|
||||
final TupleHash h = new TupleHash(256, ETAG_DOMAIN, ETAG_LENGTH * Byte.SIZE);
|
||||
final AccountInfo accountInfo = profile.getAccountInfo();
|
||||
|
||||
addByteArray(h, profile.getData().toByteArray());
|
||||
addByteArray(h, profile.getPaymentAddress().toByteArray());
|
||||
addByteArray(h, accountInfo.getIdentityKey().toByteArray());
|
||||
addByteArray(h, accountInfo.getUnidentifiedAccessKeyFingerprint().toByteArray());
|
||||
h.update(accountInfo.getUnrestrictedUnidentifiedAccess() ? (byte) 1 : (byte) 0);
|
||||
|
||||
addInt(h, accountInfo.getBadgeIdsCount());
|
||||
accountInfo.getBadgeIdsList().asByteStringList().stream()
|
||||
.map(ByteString::toByteArray)
|
||||
.sorted(Arrays::compareUnsigned)
|
||||
.forEach(badgeId -> addByteArray(h, badgeId));
|
||||
|
||||
final byte[] out = new byte[ETAG_LENGTH];
|
||||
h.doFinal(out, 0);
|
||||
return out;
|
||||
}
|
||||
|
||||
private static void addByteArray(final TupleHash hash, final byte[] bytes) {
|
||||
hash.update(bytes, 0, bytes.length);
|
||||
}
|
||||
|
||||
private static void addInt(final TupleHash hash, final int v) {
|
||||
addByteArray(hash, ByteBuffer.allocate(Integer.BYTES).order(ByteOrder.BIG_ENDIAN).putInt(v).array());
|
||||
}
|
||||
}
|
||||
+18
-37
@@ -22,10 +22,8 @@ import org.signal.chat.errors.FailedPrecondition;
|
||||
import org.signal.chat.errors.NotFound;
|
||||
import org.signal.chat.profile.GetAvatarCredentialsRequest;
|
||||
import org.signal.chat.profile.GetAvatarCredentialsResponse;
|
||||
import org.signal.chat.profile.GetUnversionedProfileRequest;
|
||||
import org.signal.chat.profile.GetUnversionedProfileResponse;
|
||||
import org.signal.chat.profile.GetVersionedProfileRequest;
|
||||
import org.signal.chat.profile.GetVersionedProfileResponse;
|
||||
import org.signal.chat.profile.GetProfileRequest;
|
||||
import org.signal.chat.profile.GetProfileResponse;
|
||||
import org.signal.chat.profile.PaymentsForbiddenInRegion;
|
||||
import org.signal.chat.profile.ProfilesV2CapabilityRequired;
|
||||
import org.signal.chat.profile.SetProfileRequest;
|
||||
@@ -252,44 +250,27 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
|
||||
}
|
||||
|
||||
@Override
|
||||
public GetUnversionedProfileResponse getUnversionedProfile(final GetUnversionedProfileRequest request) throws RateLimitExceededException {
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
|
||||
final ServiceIdentifier targetIdentifier =
|
||||
GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getServiceIdentifier());
|
||||
final Optional<Account> maybeAccount = validateRateLimitAndGetAccount(authenticatedDevice.accountIdentifier(), targetIdentifier);
|
||||
|
||||
return maybeAccount.map(account -> GetUnversionedProfileResponse.newBuilder()
|
||||
.setResult(ProfileGrpcHelper.buildUnversionedProfileResult(targetIdentifier,
|
||||
authenticatedDevice.accountIdentifier(),
|
||||
account,
|
||||
profileBadgeConverter))
|
||||
.build()).orElseGet(() -> GetUnversionedProfileResponse.newBuilder()
|
||||
.setNotFound(NotFound.getDefaultInstance())
|
||||
.build());
|
||||
}
|
||||
|
||||
@Override
|
||||
public GetVersionedProfileResponse getVersionedProfile(final GetVersionedProfileRequest request) throws RateLimitExceededException {
|
||||
public GetProfileResponse getProfile(final GetProfileRequest request) throws RateLimitExceededException {
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
|
||||
final ServiceIdentifier targetIdentifier =
|
||||
GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getAccountIdentifier());
|
||||
final byte[] version = request.getVersion().toByteArray();
|
||||
final Optional<Account> maybeAccount =
|
||||
validateRateLimitAndGetAccount(authenticatedDevice.accountIdentifier(), targetIdentifier);
|
||||
|
||||
final Optional<Account> maybeAccount = validateRateLimitAndGetAccount(authenticatedDevice.accountIdentifier(), targetIdentifier);
|
||||
return maybeAccount.flatMap(account -> ProfileGrpcHelper
|
||||
.getProfile(account, profilesManager, profileBadgeConverter, version)
|
||||
|
||||
return maybeAccount.map(account ->
|
||||
ProfileGrpcHelper.getVersionedProfile(account, profilesManager,
|
||||
request.getVersion().toByteArray(),
|
||||
request.getDataEtag().toByteArray(),
|
||||
request.getPaymentAddressEtag().toByteArray())
|
||||
.map(result ->
|
||||
GetVersionedProfileResponse.newBuilder()
|
||||
.setResult(result)
|
||||
.build())
|
||||
.orElseGet(() -> GetVersionedProfileResponse.newBuilder()
|
||||
.setNotFound(NotFound.getDefaultInstance())
|
||||
.build())).orElseGet(() -> GetVersionedProfileResponse.newBuilder()
|
||||
.setNotFound(NotFound.getDefaultInstance())
|
||||
.build());
|
||||
// If the etag matches, drop the result
|
||||
.map(profileResult -> request.getEtag().equals(profileResult.getEtag())
|
||||
? GetProfileResponse.newBuilder().setEtagMatched(true).build()
|
||||
: GetProfileResponse.newBuilder().setProfile(profileResult).build())
|
||||
|
||||
// If we didn't find a v2 profile, try a v1 profile
|
||||
.or(() -> ProfileGrpcHelper
|
||||
.getProfileV1(account, profilesManager, profileBadgeConverter, version)
|
||||
.map(v1Result -> GetProfileResponse.newBuilder().setLegacyProfile(v1Result).build())))
|
||||
.orElseGet(() -> GetProfileResponse.newBuilder().setNotFound(NotFound.getDefaultInstance()).build());
|
||||
}
|
||||
|
||||
private Optional<Account> validateRateLimitAndGetAccount(final UUID requesterUuid,
|
||||
|
||||
+71
-160
@@ -5,13 +5,11 @@ import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.getPayPalL
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import com.google.protobuf.Empty;
|
||||
import java.math.BigDecimal;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.time.Clock;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
@@ -19,46 +17,37 @@ import org.signal.chat.errors.FailedPrecondition;
|
||||
import org.signal.chat.errors.FailedUnidentifiedAuthorization;
|
||||
import org.signal.chat.errors.FailedZkAuthentication;
|
||||
import org.signal.chat.errors.NotFound;
|
||||
import org.signal.chat.subscriptions.CreatePayPalPaymentMethodRequest;
|
||||
import org.signal.chat.subscriptions.CreatePayPalPaymentMethodResponse;
|
||||
import org.signal.chat.subscriptions.CreatePaymentMethodRequest;
|
||||
import org.signal.chat.subscriptions.CreatePaymentMethodResponse;
|
||||
import org.signal.chat.subscriptions.DeleteSubscriberRequest;
|
||||
import org.signal.chat.subscriptions.DeleteSubscriberResponse;
|
||||
import org.signal.chat.subscriptions.GetBankMandateRequest;
|
||||
import org.signal.chat.subscriptions.GetBankMandateResponse;
|
||||
import org.signal.chat.subscriptions.GetConfigurationRequest;
|
||||
import org.signal.chat.subscriptions.GetConfigurationResponse;
|
||||
import org.signal.chat.subscriptions.GetReceiptCredentialsRequest;
|
||||
import org.signal.chat.subscriptions.GetReceiptCredentialsResponse;
|
||||
import org.signal.chat.subscriptions.GetSubscriptionInformationRequest;
|
||||
import org.signal.chat.subscriptions.GetSubscriptionInformationResponse;
|
||||
import org.signal.chat.subscriptions.PaymentMethod;
|
||||
import org.signal.chat.subscriptions.PaymentRequired;
|
||||
import org.signal.chat.subscriptions.SetDefaultPaymentMethodRequest;
|
||||
import org.signal.chat.subscriptions.SetDefaultPaymentMethodResponse;
|
||||
import org.signal.chat.subscriptions.SetIapSubscriptionRequest;
|
||||
import org.signal.chat.subscriptions.SetIapSubscriptionResponse;
|
||||
import org.signal.chat.subscriptions.SetSubscriptionLevelRequest;
|
||||
import org.signal.chat.subscriptions.SetSubscriptionLevelResponse;
|
||||
import org.signal.chat.subscriptions.SimpleSubscriptionsGrpc;
|
||||
import org.signal.chat.subscriptions.UpdateSubscriberRequest;
|
||||
import org.signal.chat.subscriptions.UpdateSubscriberResponse;
|
||||
import org.signal.chat.purchase.CreatePayPalPaymentMethodRequest;
|
||||
import org.signal.chat.purchase.CreatePayPalPaymentMethodResponse;
|
||||
import org.signal.chat.purchase.CreatePaymentMethodRequest;
|
||||
import org.signal.chat.purchase.CreatePaymentMethodResponse;
|
||||
import org.signal.chat.purchase.DeleteSubscriberRequest;
|
||||
import org.signal.chat.purchase.DeleteSubscriberResponse;
|
||||
import org.signal.chat.purchase.GetBankMandateRequest;
|
||||
import org.signal.chat.purchase.GetBankMandateResponse;
|
||||
import org.signal.chat.purchase.GetReceiptCredentialsRequest;
|
||||
import org.signal.chat.purchase.GetReceiptCredentialsResponse;
|
||||
import org.signal.chat.purchase.GetSubscriptionInformationRequest;
|
||||
import org.signal.chat.purchase.GetSubscriptionInformationResponse;
|
||||
import org.signal.chat.purchase.PaymentRequired;
|
||||
import org.signal.chat.purchase.SetDefaultPaymentMethodRequest;
|
||||
import org.signal.chat.purchase.SetDefaultPaymentMethodResponse;
|
||||
import org.signal.chat.purchase.SetIapSubscriptionRequest;
|
||||
import org.signal.chat.purchase.SetIapSubscriptionResponse;
|
||||
import org.signal.chat.purchase.SetSubscriptionLevelRequest;
|
||||
import org.signal.chat.purchase.SetSubscriptionLevelResponse;
|
||||
import org.signal.chat.purchase.SimpleSubscriptionsGrpc;
|
||||
import org.signal.chat.purchase.UpdateSubscriberRequest;
|
||||
import org.signal.chat.purchase.UpdateSubscriberResponse;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
import org.signal.libsignal.zkgroup.donation.DonationPermit;
|
||||
import org.whispersystems.textsecuregcm.badges.BadgeTranslator;
|
||||
import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.SubscriptionConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.SubscriptionLevelConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.entities.Badge;
|
||||
import org.whispersystems.textsecuregcm.entities.PurchasableBadge;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.DonationPermitsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriberCredentials;
|
||||
import org.whispersystems.textsecuregcm.storage.SubscriptionManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Subscriptions;
|
||||
@@ -66,7 +55,6 @@ import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.BankMandateTranslator;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.BankTransferType;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.CurrencyConfiguration;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionPaymentProcessor;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.GooglePlayBillingManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.ProcessorCustomer;
|
||||
@@ -91,41 +79,37 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
|
||||
|
||||
private final Clock clock;
|
||||
private final SubscriptionConfiguration subscriptionConfiguration;
|
||||
private final OneTimeDonationConfiguration oneTimeDonationConfiguration;
|
||||
private final SubscriptionManager subscriptionManager;
|
||||
private final DonationPermitsManager donationPermitsManager;
|
||||
private final StripeManager stripeManager;
|
||||
private final BraintreeManager braintreeManager;
|
||||
private final GooglePlayBillingManager googlePlayBillingManager;
|
||||
private final AppleAppStoreManager appleAppStoreManager;
|
||||
private final BadgeTranslator badgeTranslator;
|
||||
private final BankMandateTranslator bankMandateTranslator;
|
||||
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
|
||||
static final String RECEIPT_ISSUED_COUNTER_NAME = MetricsUtil.name(SubscriptionsGrpcService.class, "receiptIssued");
|
||||
static final String PROCESSOR_TAG_NAME = "processor";
|
||||
static final String TYPE_TAG_NAME = "type";
|
||||
private static final String SUBSCRIPTION_TYPE_TAG_NAME = "subscriptionType";
|
||||
|
||||
public SubscriptionsGrpcService(final Clock clock, final SubscriptionConfiguration subscriptionConfiguration,
|
||||
final OneTimeDonationConfiguration oneTimeDonationConfiguration, final SubscriptionManager subscriptionManager,
|
||||
final DonationPermitsManager donationPermitsManager, final StripeManager stripeManager,
|
||||
final BraintreeManager braintreeManager, final GooglePlayBillingManager googlePlayBillingManager,
|
||||
final AppleAppStoreManager appleAppStoreManager, final BadgeTranslator badgeTranslator,
|
||||
final BankMandateTranslator bankMandateTranslator,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
|
||||
public SubscriptionsGrpcService(final Clock clock,
|
||||
final SubscriptionConfiguration subscriptionConfiguration,
|
||||
final SubscriptionManager subscriptionManager,
|
||||
final DonationPermitsManager donationPermitsManager,
|
||||
final StripeManager stripeManager,
|
||||
final BraintreeManager braintreeManager,
|
||||
final GooglePlayBillingManager googlePlayBillingManager,
|
||||
final AppleAppStoreManager appleAppStoreManager,
|
||||
final BankMandateTranslator bankMandateTranslator) {
|
||||
this.clock = clock;
|
||||
this.subscriptionConfiguration = subscriptionConfiguration;
|
||||
this.oneTimeDonationConfiguration = oneTimeDonationConfiguration;
|
||||
this.subscriptionManager = subscriptionManager;
|
||||
this.donationPermitsManager = donationPermitsManager;
|
||||
this.stripeManager = stripeManager;
|
||||
this.braintreeManager = braintreeManager;
|
||||
this.googlePlayBillingManager = googlePlayBillingManager;
|
||||
this.appleAppStoreManager = appleAppStoreManager;
|
||||
this.badgeTranslator = badgeTranslator;
|
||||
this.bankMandateTranslator = bankMandateTranslator;
|
||||
this.dynamicConfigurationManager = dynamicConfigurationManager;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -234,7 +218,8 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
|
||||
}
|
||||
|
||||
@Override
|
||||
public CreatePayPalPaymentMethodResponse createPayPalPaymentMethod(final CreatePayPalPaymentMethodRequest request) {
|
||||
public CreatePayPalPaymentMethodResponse createPayPalPaymentMethod(final CreatePayPalPaymentMethodRequest request)
|
||||
throws IOException {
|
||||
final SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(
|
||||
request.getSubscriberId().toByteArray(), clock);
|
||||
final Locale locale = getPayPalLocale(RequestAttributesUtil.getAvailableAcceptedLocales());
|
||||
@@ -242,7 +227,7 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
|
||||
final BraintreeManager.PayPalBillingAgreementApprovalDetails details = subscriptionManager.addPaymentMethodToCustomer(
|
||||
subscriberCredentials, braintreeManager, getClientPlatform(RequestAttributesUtil.getUserAgent().orElse(null)),
|
||||
(mgr, _) -> mgr.createPayPalBillingAgreement(request.getReturnUrl(), request.getCancelUrl(),
|
||||
locale.toLanguageTag())).join();
|
||||
locale.toLanguageTag()));
|
||||
return CreatePayPalPaymentMethodResponse.newBuilder().setResult(
|
||||
CreatePayPalPaymentMethodResponse.CreatePayPalPaymentMethodResult.newBuilder()
|
||||
.setApprovalUrl(details.approvalUrl()).setToken(details.billingAgreementToken()).build()).build();
|
||||
@@ -259,27 +244,28 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
|
||||
}
|
||||
|
||||
@Override
|
||||
public SetDefaultPaymentMethodResponse setDefaultPaymentMethod(final SetDefaultPaymentMethodRequest request) {
|
||||
final SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(
|
||||
request.getSubscriberId().toByteArray(), clock);
|
||||
final CustomerAwareSubscriptionPaymentProcessor manager;
|
||||
final String paymentMethodId = switch (request.getRequestCase()) {
|
||||
case STRIPE -> {
|
||||
manager = stripeManager;
|
||||
yield request.getStripe().getPaymentMethodToken();
|
||||
}
|
||||
case BRAINTREE -> {
|
||||
manager = braintreeManager;
|
||||
yield request.getBraintree().getPaymentMethodToken();
|
||||
}
|
||||
case SEPA -> {
|
||||
manager = stripeManager;
|
||||
yield stripeManager.getGeneratedSepaIdFromSetupIntent(request.getSepa().getSetupIntentId()).join();
|
||||
}
|
||||
default -> throw GrpcExceptions.fieldViolation("request", "No payment method specified");
|
||||
};
|
||||
|
||||
public SetDefaultPaymentMethodResponse setDefaultPaymentMethod(final SetDefaultPaymentMethodRequest request)
|
||||
throws IOException {
|
||||
try {
|
||||
final SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(
|
||||
request.getSubscriberId().toByteArray(), clock);
|
||||
final CustomerAwareSubscriptionPaymentProcessor manager;
|
||||
final String paymentMethodId = switch (request.getRequestCase()) {
|
||||
case STRIPE -> {
|
||||
manager = stripeManager;
|
||||
yield request.getStripe().getPaymentMethodToken();
|
||||
}
|
||||
case BRAINTREE -> {
|
||||
manager = braintreeManager;
|
||||
yield request.getBraintree().getPaymentMethodToken();
|
||||
}
|
||||
case SEPA -> {
|
||||
manager = stripeManager;
|
||||
yield stripeManager.getGeneratedSepaIdFromSetupIntent(request.getSepa().getSetupIntentId());
|
||||
}
|
||||
default -> throw GrpcExceptions.fieldViolation("request", "No payment method specified");
|
||||
};
|
||||
|
||||
final Subscriptions.Record record = subscriptionManager.getSubscriber(subscriberCredentials);
|
||||
return record.getProcessorCustomer().map(
|
||||
processorCustomer -> setDefaultPaymentMethodForCustomer(manager, processorCustomer, paymentMethodId,
|
||||
@@ -293,6 +279,10 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
|
||||
} catch (final SubscriptionForbiddenException e) {
|
||||
return SetDefaultPaymentMethodResponse.newBuilder().setSubscriberIdMismatch(
|
||||
FailedUnidentifiedAuthorization.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
|
||||
} catch (final SubscriptionProcessorConflictException e) {
|
||||
return SetDefaultPaymentMethodResponse.newBuilder()
|
||||
.setSubscriptionProcessorConflict(
|
||||
FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -308,6 +298,8 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
|
||||
return SetDefaultPaymentMethodResponse.newBuilder()
|
||||
.setPaymentMethodNotSetUp(FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build())
|
||||
.build();
|
||||
} catch (final IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -446,7 +438,7 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
|
||||
.setLevel(info.level()).setEndOfCurrentPeriod(info.endOfCurrentPeriod().getEpochSecond())
|
||||
.setActive(info.active()).setCancelAtPeriodEnd(info.cancelAtPeriodEnd()).setCurrency(info.price().currency())
|
||||
.setAmount(info.price().amount().longValue()).setStatus(toProtoSubscriptionStatus(info.status()))
|
||||
.setProcessor(info.paymentProvider().toProto()).setPaymentMethod(toProtoPaymentMethod(info.paymentMethod()))
|
||||
.setProcessor(info.paymentProvider().toProto()).setPaymentMethod(info.paymentMethod().toProtoPaymentMethod())
|
||||
.setPaymentProcessing(info.paymentProcessing());
|
||||
if (info.billingCycleAnchor() != null) {
|
||||
subscription.setBillingCycleAnchor(info.billingCycleAnchor().getEpochSecond());
|
||||
@@ -503,99 +495,18 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti
|
||||
}
|
||||
}
|
||||
|
||||
private static org.signal.chat.subscriptions.SubscriptionStatus toProtoSubscriptionStatus(
|
||||
private static org.signal.chat.purchase.SubscriptionStatus toProtoSubscriptionStatus(
|
||||
final SubscriptionStatus status) {
|
||||
return switch (status) {
|
||||
case ACTIVE -> org.signal.chat.subscriptions.SubscriptionStatus.SUBSCRIPTION_STATUS_ACTIVE;
|
||||
case INCOMPLETE -> org.signal.chat.subscriptions.SubscriptionStatus.SUBSCRIPTION_STATUS_INCOMPLETE;
|
||||
case PAST_DUE -> org.signal.chat.subscriptions.SubscriptionStatus.SUBSCRIPTION_STATUS_PAST_DUE;
|
||||
case CANCELED -> org.signal.chat.subscriptions.SubscriptionStatus.SUBSCRIPTION_STATUS_CANCELED;
|
||||
case UNPAID -> org.signal.chat.subscriptions.SubscriptionStatus.SUBSCRIPTION_STATUS_UNPAID;
|
||||
case UNKNOWN -> org.signal.chat.subscriptions.SubscriptionStatus.SUBSCRIPTION_STATUS_UNKNOWN;
|
||||
case ACTIVE -> org.signal.chat.purchase.SubscriptionStatus.SUBSCRIPTION_STATUS_ACTIVE;
|
||||
case INCOMPLETE -> org.signal.chat.purchase.SubscriptionStatus.SUBSCRIPTION_STATUS_INCOMPLETE;
|
||||
case PAST_DUE -> org.signal.chat.purchase.SubscriptionStatus.SUBSCRIPTION_STATUS_PAST_DUE;
|
||||
case CANCELED -> org.signal.chat.purchase.SubscriptionStatus.SUBSCRIPTION_STATUS_CANCELED;
|
||||
case UNPAID -> org.signal.chat.purchase.SubscriptionStatus.SUBSCRIPTION_STATUS_UNPAID;
|
||||
case UNKNOWN -> org.signal.chat.purchase.SubscriptionStatus.SUBSCRIPTION_STATUS_UNKNOWN;
|
||||
};
|
||||
}
|
||||
|
||||
private static PaymentMethod toProtoPaymentMethod(
|
||||
final org.whispersystems.textsecuregcm.subscriptions.PaymentMethod paymentMethod) {
|
||||
if (paymentMethod == null) {
|
||||
return PaymentMethod.PAYMENT_METHOD_UNKNOWN;
|
||||
}
|
||||
return switch (paymentMethod) {
|
||||
case CARD -> PaymentMethod.PAYMENT_METHOD_CARD;
|
||||
case SEPA_DEBIT -> PaymentMethod.PAYMENT_METHOD_SEPA_DEBIT;
|
||||
case IDEAL -> PaymentMethod.PAYMENT_METHOD_IDEAL;
|
||||
case PAYPAL -> PaymentMethod.PAYMENT_METHOD_PAYPAL;
|
||||
case GOOGLE_PLAY_BILLING -> PaymentMethod.PAYMENT_METHOD_GOOGLE_PLAY_BILLING;
|
||||
case APPLE_APP_STORE -> PaymentMethod.PAYMENT_METHOD_APPLE_APP_STORE;
|
||||
case UNKNOWN -> PaymentMethod.PAYMENT_METHOD_UNKNOWN;
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public GetConfigurationResponse getConfiguration(final GetConfigurationRequest request) {
|
||||
final long maxBackupBytes = dynamicConfigurationManager.getConfiguration().getBackupConfiguration()
|
||||
.maxTotalMediaSize();
|
||||
|
||||
final Map<Long, GetConfigurationResponse.BackupLevelConfiguration> backupLevels = subscriptionConfiguration.getBackupLevels()
|
||||
.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey,
|
||||
e -> GetConfigurationResponse.BackupLevelConfiguration.newBuilder().setStorageAllowanceBytes(maxBackupBytes)
|
||||
.setPlayProductId(e.getValue().playProductId()).setMediaTtlDays(e.getValue().mediaTtl().toDays())
|
||||
.build()));
|
||||
|
||||
return GetConfigurationResponse.newBuilder().putAllCurrencies(buildCurrencyConfigurations())
|
||||
.putAllLevels(buildLevelConfigurations()).setBackup(
|
||||
GetConfigurationResponse.BackupConfiguration.newBuilder().putAllLevels(backupLevels)
|
||||
.setFreeTierMediaDays(subscriptionConfiguration.getbackupFreeTierMediaDuration().toDays()).build())
|
||||
.setSepaMaximumEuros(oneTimeDonationConfiguration.sepaMaximumEuros().toString()).build();
|
||||
}
|
||||
|
||||
private Map<String, GetConfigurationResponse.CurrencyConfiguration> buildCurrencyConfigurations() {
|
||||
return SubscriptionsUtil.buildCurrencyConfiguration(List.of(stripeManager, braintreeManager),
|
||||
oneTimeDonationConfiguration, subscriptionConfiguration).entrySet().stream()
|
||||
.collect(Collectors.toMap(Map.Entry::getKey, e -> toProtoCurrencyConfiguration(e.getKey(), e.getValue())));
|
||||
}
|
||||
|
||||
private Map<Long, GetConfigurationResponse.LevelConfiguration> buildLevelConfigurations() {
|
||||
return SubscriptionsUtil.buildDonationLevelsConfiguration(subscriptionConfiguration, oneTimeDonationConfiguration,
|
||||
badgeTranslator, RequestAttributesUtil.getAvailableAcceptedLocales()).entrySet().stream().collect(
|
||||
Collectors.toMap(Map.Entry::getKey, entry -> GetConfigurationResponse.LevelConfiguration.newBuilder()
|
||||
.setBadge(toProtoBadge(entry.getValue().badge())).build()));
|
||||
}
|
||||
|
||||
private static GetConfigurationResponse.CurrencyConfiguration toProtoCurrencyConfiguration(final String currency,
|
||||
final CurrencyConfiguration config) {
|
||||
final GetConfigurationResponse.CurrencyConfiguration.Builder builder = GetConfigurationResponse.CurrencyConfiguration.newBuilder()
|
||||
.setMinimum(config.minimum().toString())
|
||||
.addAllSupportedPaymentMethods(
|
||||
config.supportedPaymentMethods().stream().map(SubscriptionsGrpcService::toProtoPaymentMethod).toList());
|
||||
config.oneTime().forEach((levelId, amounts) -> builder.putOneTime(levelId,
|
||||
GetConfigurationResponse.AmountList.newBuilder()
|
||||
.addAllAmounts(
|
||||
amounts.stream().map(BigDecimal::toString).toList())
|
||||
.build()));
|
||||
config.subscription()
|
||||
.forEach((levelId, amount) -> builder.putSubscription(levelId,
|
||||
amount.toString()));
|
||||
config.backupSubscription()
|
||||
.forEach((levelId, amount) -> builder.putBackupSubscription(levelId,
|
||||
amount.toString()));
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
private static GetConfigurationResponse.Badge toProtoBadge(final Badge badge) {
|
||||
final org.signal.chat.common.Badge commonBadge = org.signal.chat.common.Badge.newBuilder().setId(badge.getId())
|
||||
.setCategory(badge.getCategory()).setName(badge.getName()).setDescription(badge.getDescription())
|
||||
.addAllSprites6(badge.getSprites6()).setSvg(badge.getSvg()).addAllSvgs(badge.getSvgs().stream()
|
||||
.map(s -> org.signal.chat.common.BadgeSvg.newBuilder().setLight(s.getLight()).setDark(s.getDark()).build())
|
||||
.toList()).build();
|
||||
final GetConfigurationResponse.Badge.Builder builder = GetConfigurationResponse.Badge.newBuilder()
|
||||
.setBadge(commonBadge);
|
||||
if (badge instanceof final PurchasableBadge purchasableBadge) {
|
||||
builder.setDurationSeconds(purchasableBadge.getDuration().toSeconds());
|
||||
}
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public GetBankMandateResponse getBankMandate(final GetBankMandateRequest request) {
|
||||
final BankTransferType bankTransferType = switch (request.getBankTransferType()) {
|
||||
|
||||
@@ -162,9 +162,9 @@ public class SubscriptionsUtil {
|
||||
.increment();
|
||||
}
|
||||
|
||||
public static org.signal.chat.subscriptions.ChargeFailure toChargeFailure(final PaymentProvider processor,
|
||||
public static org.signal.chat.purchase.ChargeFailure toChargeFailure(final PaymentProvider processor,
|
||||
final ChargeFailure chargeFailure) {
|
||||
final org.signal.chat.subscriptions.ChargeFailure.Builder builder = org.signal.chat.subscriptions.ChargeFailure.newBuilder()
|
||||
final org.signal.chat.purchase.ChargeFailure.Builder builder = org.signal.chat.purchase.ChargeFailure.newBuilder()
|
||||
.setProcessor(processor.toProto()).setCode(chargeFailure.code()).setMessage(chargeFailure.message());
|
||||
if (chargeFailure.outcomeNetworkStatus() != null) {
|
||||
builder.setOutcomeNetworkStatus(chargeFailure.outcomeNetworkStatus());
|
||||
|
||||
+31
@@ -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();
|
||||
}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package org.whispersystems.textsecuregcm.mappers;
|
||||
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import jakarta.ws.rs.ext.ExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockFailureException;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager;
|
||||
|
||||
public class RegistrationLockFailureExceptionMapper implements ExceptionMapper<RegistrationLockFailureException> {
|
||||
|
||||
@Override
|
||||
public Response toResponse(final RegistrationLockFailureException exception) {
|
||||
return Response.status(RegistrationLockVerificationManager.FAILURE_HTTP_STATUS)
|
||||
.entity(exception.getFailure())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+2
@@ -12,6 +12,7 @@ import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import jakarta.ws.rs.ext.ExceptionMapper;
|
||||
import java.util.Map;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriberIdCreationNotPermittedException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionChargeFailurePaymentRequiredException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.ChargeFailure;
|
||||
@@ -63,6 +64,7 @@ public class SubscriptionExceptionMapper implements ExceptionMapper<Subscription
|
||||
case SubscriptionProcessorConflictException _ -> Response.Status.CONFLICT;
|
||||
case SubscriptionPaymentRequiredException _ -> Response.Status.PAYMENT_REQUIRED;
|
||||
case SubscriptionReceiptAlreadyRedeemedException _ -> Response.Status.CONFLICT;
|
||||
case SubscriberIdCreationNotPermittedException _ -> Response.Status.UNAUTHORIZED;
|
||||
default -> Response.Status.INTERNAL_SERVER_ERROR;
|
||||
});
|
||||
|
||||
|
||||
+15
@@ -16,6 +16,7 @@ import io.micrometer.core.instrument.Tags;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.atomic.LongAdder;
|
||||
import javax.annotation.Nullable;
|
||||
import org.glassfish.jersey.server.ContainerResponse;
|
||||
import org.glassfish.jersey.server.monitoring.RequestEvent;
|
||||
@@ -44,6 +45,8 @@ public class MetricsRequestEventListener implements RequestEventListener {
|
||||
public static final String RESPONSE_BYTES_COUNTER_NAME = name(MetricsRequestEventListener.class, "responseBytes");
|
||||
public static final String REQUEST_BYTES_COUNTER_NAME = name(MetricsRequestEventListener.class, "requestBytes");
|
||||
|
||||
private static final String ACTIVE_REQUESTS_GAUGE_NAME = name(MetricsRequestEventListener.class, "activeRequests");
|
||||
|
||||
@VisibleForTesting
|
||||
static final String PATH_TAG = "path";
|
||||
|
||||
@@ -65,6 +68,8 @@ public class MetricsRequestEventListener implements RequestEventListener {
|
||||
private final TrafficSource trafficSource;
|
||||
private final MeterRegistry meterRegistry;
|
||||
|
||||
private final LongAdder activeRequests;
|
||||
|
||||
public MetricsRequestEventListener(final TrafficSource trafficSource, final ClientReleaseManager clientReleaseManager) {
|
||||
this(trafficSource, Metrics.globalRegistry, clientReleaseManager);
|
||||
|
||||
@@ -81,10 +86,20 @@ public class MetricsRequestEventListener implements RequestEventListener {
|
||||
this.trafficSource = trafficSource;
|
||||
this.meterRegistry = meterRegistry;
|
||||
this.clientReleaseManager = clientReleaseManager;
|
||||
|
||||
this.activeRequests = meterRegistry.gauge(ACTIVE_REQUESTS_GAUGE_NAME, new LongAdder());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEvent(final RequestEvent event) {
|
||||
if (event.getType() == RequestEvent.Type.RESOURCE_METHOD_START) {
|
||||
activeRequests.increment();
|
||||
}
|
||||
|
||||
if (event.getType() == RequestEvent.Type.RESOURCE_METHOD_FINISHED) {
|
||||
activeRequests.decrement();
|
||||
}
|
||||
|
||||
if (event.getType() == RequestEvent.Type.FINISHED) {
|
||||
if (!event.getUriInfo().getMatchedTemplates().isEmpty()) {
|
||||
@Nullable final UserAgent userAgent;
|
||||
|
||||
+2
-2
@@ -164,8 +164,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();
|
||||
|
||||
+3
-3
@@ -1,6 +1,6 @@
|
||||
package org.whispersystems.textsecuregcm.spam;
|
||||
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.annotation.Nullable;
|
||||
|
||||
public interface RegistrationRecoveryChecker {
|
||||
|
||||
@@ -11,9 +11,9 @@ public interface RegistrationRecoveryChecker {
|
||||
* @param e164 The E164 formatted phone number of the requester
|
||||
* @return true if the registration recovery attempt is allowed, false otherwise.
|
||||
*/
|
||||
boolean checkRegistrationRecoveryAttempt(final ContainerRequestContext requestContext, final String e164);
|
||||
boolean checkRegistrationRecoveryAttempt(String e164, @Nullable String userAgent, @Nullable String acceptLanguage, @Nullable String mostRecentProxy);
|
||||
|
||||
static RegistrationRecoveryChecker noop() {
|
||||
return (ignoredCtx, ignoredE164) -> true;
|
||||
return (_, _, _, _) -> true;
|
||||
}
|
||||
}
|
||||
@@ -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.getUuid(), redactPhoneNumber(existingAccount.getNumber()), existingAccount.getPhoneNumberIdentifier(),
|
||||
accountToCreate.getUuid(), redactPhoneNumber(accountToCreate.getNumber()), accountToCreate.getPhoneNumberIdentifier()));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
-162
@@ -1,162 +0,0 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Flow;
|
||||
import java.util.function.BiConsumer;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import org.reactivestreams.Subscription;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStream;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import reactor.adapter.JdkFlowAdapter;
|
||||
import reactor.core.publisher.BaseSubscriber;
|
||||
|
||||
/// A temporary message stream that can mirror message acknowledgements (deletion requests) to FoundationDB
|
||||
public class AcknowledgementMirroringMessageStream implements MessageStream {
|
||||
|
||||
private final RedisDynamoDbMessageStream redisDynamoDbMessageStream;
|
||||
private final FoundationDbMessageStream foundationDbMessageStream;
|
||||
|
||||
private final Set<UUID> messagesPendingAcknowledgement = new HashSet<>();
|
||||
|
||||
private static final int HIGH_PENDING_ACKNOWLEDGEMENT_COUNT_WARNING_THRESHOLD = 1024;
|
||||
|
||||
@VisibleForTesting
|
||||
static final int MAX_PENDING_ACKNOWLEDGEMENTS = 8192;
|
||||
|
||||
@VisibleForTesting
|
||||
static final int FOUNDATIONDB_REQUEST_SIZE = 100;
|
||||
|
||||
private static final Counter HIGH_PENDING_ACKNOWLEDGEMENT_COUNT_WARNING_COUNTER =
|
||||
Metrics.counter(MetricsUtil.name(AcknowledgementMirroringMessageStream.class, "highPendingAcknowledgementCount"));
|
||||
|
||||
private static final Counter MAX_PENDING_ACKNOWLEDGEMENT_LIMIT_BREACHED_COUNTER =
|
||||
Metrics.counter(MetricsUtil.name(AcknowledgementMirroringMessageStream.class, "maxPendingAcknowledgementLimitBreached"));
|
||||
|
||||
private static class FoundationDbSubscriber extends BaseSubscriber<MessageStreamEntry.Envelope> {
|
||||
|
||||
private final BiConsumer<UUID, Long> mirroredMessageHandler;
|
||||
|
||||
private long mirroredEntriesDelivered = 0;
|
||||
private long requested = 0;
|
||||
|
||||
private FoundationDbSubscriber(final BiConsumer<UUID, Long> mirroredMessageHandler) {
|
||||
this.mirroredMessageHandler = mirroredMessageHandler;
|
||||
}
|
||||
|
||||
public void handleRedisDynamoDbMessageStreamEntry(final MessageStreamEntry messageStreamEntry) {
|
||||
final boolean isMirroredMessage = switch (messageStreamEntry) {
|
||||
case MessageStreamEntry.Envelope envelopeEntry ->
|
||||
UUIDUtil.fromByteString(envelopeEntry.message().getServerGuid()).version() == 8;
|
||||
|
||||
case MessageStreamEntry.QueueEmpty _ -> false;
|
||||
};
|
||||
|
||||
if (!isMirroredMessage) {
|
||||
return;
|
||||
}
|
||||
|
||||
final boolean requestMore;
|
||||
|
||||
synchronized (this) {
|
||||
requestMore = ++mirroredEntriesDelivered > requested;
|
||||
|
||||
if (requestMore) {
|
||||
requested += FOUNDATIONDB_REQUEST_SIZE;
|
||||
}
|
||||
}
|
||||
|
||||
if (requestMore) {
|
||||
request(FOUNDATIONDB_REQUEST_SIZE);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void hookOnSubscribe(final Subscription subscription) {
|
||||
// The base `hookOnSubscribe` requests `Long.MAX_VALUE` elements, and that is something we're explicitly trying
|
||||
// to avoid with this subscriber
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void hookOnNext(final MessageStreamEntry.Envelope envelope) {
|
||||
mirroredMessageHandler.accept(
|
||||
UUIDUtil.fromByteString(envelope.message().getServerGuid()), envelope.message().getServerTimestamp());
|
||||
}
|
||||
}
|
||||
|
||||
public AcknowledgementMirroringMessageStream(final RedisDynamoDbMessageStream redisDynamoDbMessageStream,
|
||||
final FoundationDbMessageStream foundationDbMessageStream) {
|
||||
|
||||
this.redisDynamoDbMessageStream = redisDynamoDbMessageStream;
|
||||
this.foundationDbMessageStream = foundationDbMessageStream;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Flow.Publisher<MessageStreamEntry> getMessages() {
|
||||
final FoundationDbSubscriber subscriber = new FoundationDbSubscriber(this::handleMirroredMessageAcknowledged);
|
||||
|
||||
JdkFlowAdapter.flowPublisherToFlux(foundationDbMessageStream.getMessages())
|
||||
.filter(messageStreamEntry -> messageStreamEntry instanceof MessageStreamEntry.Envelope)
|
||||
.cast(MessageStreamEntry.Envelope.class)
|
||||
.subscribe(subscriber);
|
||||
|
||||
return JdkFlowAdapter.publisherToFlowPublisher(
|
||||
JdkFlowAdapter.flowPublisherToFlux(redisDynamoDbMessageStream.getMessages())
|
||||
// Mirror demand and termination signals to the FoundationDB message stream
|
||||
.doOnNext(subscriber::handleRedisDynamoDbMessageStreamEntry)
|
||||
.doOnComplete(subscriber::dispose));
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> acknowledgeMessage(final UUID messageGuid, final long serverTimestamp) {
|
||||
// All messages stored in FoundationDB use version 8 UUIDs; if a message has a version 4 UUID, then it only exists
|
||||
// in Redis/DynamoDB
|
||||
if (messageGuid.version() == 8) {
|
||||
handleMirroredMessageAcknowledged(messageGuid, serverTimestamp);
|
||||
}
|
||||
|
||||
return redisDynamoDbMessageStream.acknowledgeMessage(messageGuid, serverTimestamp);
|
||||
}
|
||||
|
||||
private void handleMirroredMessageAcknowledged(final UUID messageGuid, final long serverTimestamp) {
|
||||
// Before we can acknowledge and delete the message in FoundationDB, two things need to happen:
|
||||
//
|
||||
// 1. The client needs to acknowledge the message on the Redis/DDB stream.
|
||||
// 2. The message needs to pass through the FoundationDB message stream pipeline because it needs to be registered
|
||||
// in the acknowledged message buffer machinery before it can be deleted.
|
||||
//
|
||||
// We can't guarantee the order in which these two things happen, so we use a synchronized set to coordinate and
|
||||
// determine when both have happened.
|
||||
synchronized (messagesPendingAcknowledgement) {
|
||||
if (messagesPendingAcknowledgement.remove(messageGuid)) {
|
||||
// One of the two streams had already acknowledged this message, and this is the second acknowledgement. Now we
|
||||
// can pass the acknowledgement along to FoundationDB.
|
||||
foundationDbMessageStream.acknowledgeMessage(messageGuid, serverTimestamp);
|
||||
} else {
|
||||
// Either this message came from FoundationDB and got auto-acknowledged before getting explicitly acknowledged
|
||||
// on the Redis/DynamoDB stream or the message got explicitly acknowledged on the Redis/DynamoDB stream before
|
||||
// passing through the FoundationDB stream. Either way, wait for both streams to have done their part.
|
||||
if (messagesPendingAcknowledgement.add(messageGuid)) {
|
||||
if (messagesPendingAcknowledgement.size() == HIGH_PENDING_ACKNOWLEDGEMENT_COUNT_WARNING_THRESHOLD) {
|
||||
HIGH_PENDING_ACKNOWLEDGEMENT_COUNT_WARNING_COUNTER.increment();
|
||||
}
|
||||
|
||||
if (messagesPendingAcknowledgement.size() > MAX_PENDING_ACKNOWLEDGEMENTS) {
|
||||
MAX_PENDING_ACKNOWLEDGEMENT_LIMIT_BREACHED_COUNTER.increment();
|
||||
throw new IllegalStateException("Too many pending acknowledgements");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+20
-11
@@ -6,11 +6,10 @@ package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import java.io.IOException;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
@@ -22,8 +21,12 @@ import javax.annotation.Nullable;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.InvalidRegistrationSessionException;
|
||||
import org.whispersystems.textsecuregcm.auth.PhoneVerificationTokenManager;
|
||||
import org.whispersystems.textsecuregcm.auth.RecoveryPasswordVerificationFailedException;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockFailureException;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager;
|
||||
import org.whispersystems.textsecuregcm.auth.UnverifiedRegistrationSessionException;
|
||||
import org.whispersystems.textsecuregcm.controllers.AccountControllerV2;
|
||||
import org.whispersystems.textsecuregcm.controllers.MessageDeliveryNotAllowedException;
|
||||
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
|
||||
@@ -41,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 {
|
||||
|
||||
@@ -88,10 +92,10 @@ public class ChangeNumberManager {
|
||||
final Map<Byte, KEMSignedPreKey> devicePqLastResortPreKeys,
|
||||
final List<IncomingMessage> deviceMessages,
|
||||
final Map<Byte, Integer> pniRegistrationIds,
|
||||
final ContainerRequestContext containerRequestContext)
|
||||
throws InterruptedException, MismatchedDevicesException, MessageTooLargeException, RateLimitExceededException, MessageDeliveryNotAllowedException {
|
||||
|
||||
final String senderUserAgent = containerRequestContext.getHeaderString(HttpHeaders.USER_AGENT);
|
||||
@Nullable final String userAgent,
|
||||
@Nullable final String acceptLanguage,
|
||||
@Nullable final String mostRecentProxy)
|
||||
throws InterruptedException, MismatchedDevicesException, MessageTooLargeException, RateLimitExceededException, MessageDeliveryNotAllowedException, RegistrationLockFailureException, UnverifiedRegistrationSessionException, InvalidRegistrationSessionException, IOException, RecoveryPasswordVerificationFailedException {
|
||||
|
||||
final Pair<Account, Optional<Account>> accountAndMaybeExistingAccount =
|
||||
accountsManager.getAccountsForChangeNumber(accountIdentifier, number);
|
||||
@@ -110,16 +114,16 @@ public class ChangeNumberManager {
|
||||
rateLimiters.getRegistrationLimiter().validate(number);
|
||||
|
||||
final PhoneVerificationRequest.VerificationType verificationType =
|
||||
phoneVerificationTokenManager.verify(containerRequestContext, number, sessionId, recoveryPassword);
|
||||
phoneVerificationTokenManager.verify(number, userAgent, acceptLanguage, mostRecentProxy, sessionId, recoveryPassword);
|
||||
|
||||
final Optional<Account> existingAccount = accountAndMaybeExistingAccount.second();
|
||||
|
||||
if (existingAccount.isPresent()) {
|
||||
registrationLockVerificationManager.verifyRegistrationLock(existingAccount.get(), registrationLock,
|
||||
senderUserAgent, RegistrationLockVerificationManager.Flow.CHANGE_NUMBER, verificationType);
|
||||
userAgent, RegistrationLockVerificationManager.Flow.CHANGE_NUMBER, verificationType);
|
||||
}
|
||||
|
||||
Metrics.counter(CHANGE_NUMBER_COUNTER_NAME, Tags.of(UserAgentTagUtil.getPlatformTag(senderUserAgent),
|
||||
Metrics.counter(CHANGE_NUMBER_COUNTER_NAME, Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
Tag.of(VERIFICATION_TYPE_TAG_NAME, verificationType.name())))
|
||||
.increment();
|
||||
}
|
||||
@@ -152,7 +156,7 @@ public class ChangeNumberManager {
|
||||
messagesByDeviceId,
|
||||
registrationIdsByDeviceId,
|
||||
Optional.of(Device.PRIMARY_ID),
|
||||
senderUserAgent);
|
||||
userAgent);
|
||||
}
|
||||
|
||||
final Account updatedAccount = accountsManager.changeNumber(
|
||||
@@ -170,7 +174,12 @@ public class ChangeNumberManager {
|
||||
messagesByDeviceId,
|
||||
registrationIdsByDeviceId,
|
||||
Optional.of(Device.PRIMARY_ID),
|
||||
senderUserAgent);
|
||||
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);
|
||||
|
||||
+56
-37
@@ -7,38 +7,54 @@ package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.EnumSet;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public enum DeviceCapability {
|
||||
STORAGE("storage", AccountCapabilityMode.ANY_DEVICE, false, false, false),
|
||||
TRANSFER("transfer", AccountCapabilityMode.PRIMARY_DEVICE, false, false, false),
|
||||
ATTACHMENT_BACKFILL("attachmentBackfill", AccountCapabilityMode.PRIMARY_DEVICE, false, true, false),
|
||||
SPARSE_POST_QUANTUM_RATCHET("spqr", AccountCapabilityMode.ALL_DEVICES, true, true, true),
|
||||
PROFILES_V2("profiles_v2", AccountCapabilityMode.ALL_DEVICES, false, true, false),
|
||||
USERNAME_CHANGE_SYNC_MESSAGE("usernameChangeSyncMessage", AccountCapabilityMode.ALL_DEVICES, true, true, false);
|
||||
STORAGE("storage", AccountCapabilityMode.ANY_DEVICE, AccountCapabilityVisibility.SERVER, false, false),
|
||||
TRANSFER("transfer", AccountCapabilityMode.PRIMARY_DEVICE, AccountCapabilityVisibility.SERVER, false, false),
|
||||
ATTACHMENT_BACKFILL("attachmentBackfill", AccountCapabilityMode.PRIMARY_DEVICE, AccountCapabilityVisibility.SELF, false, false),
|
||||
SPARSE_POST_QUANTUM_RATCHET("spqr", AccountCapabilityMode.ALL_DEVICES, AccountCapabilityVisibility.PUBLIC, true, true),
|
||||
PROFILES_V2("profiles_v2", AccountCapabilityMode.ALL_DEVICES, AccountCapabilityVisibility.SELF, false, false),
|
||||
USERNAME_CHANGE_SYNC_MESSAGE("usernameChangeSyncMessage", AccountCapabilityMode.ALL_DEVICES, AccountCapabilityVisibility.SELF, true, false);
|
||||
|
||||
public static final List<DeviceCapability> PUBLIC_VISIBLE_CAPABILITIES = Arrays.stream(DeviceCapability.values())
|
||||
.filter(c -> c.accountCapabilityVisibility == AccountCapabilityVisibility.PUBLIC)
|
||||
.toList();
|
||||
|
||||
public static final List<DeviceCapability> SELF_VISIBLE_CAPABILITIES = Arrays.stream(DeviceCapability.values())
|
||||
.filter(c -> c.accountCapabilityVisibility == AccountCapabilityVisibility.PUBLIC
|
||||
|| c.accountCapabilityVisibility == AccountCapabilityVisibility.SELF)
|
||||
.toList();
|
||||
|
||||
public enum AccountCapabilityMode {
|
||||
/**
|
||||
* The account will have the capability iff the primary device has the capability
|
||||
*/
|
||||
/// The account will have the capability iff the primary device has the capability
|
||||
PRIMARY_DEVICE,
|
||||
/**
|
||||
* The account will have the capability iff any device on the account has the capability
|
||||
*/
|
||||
|
||||
/// The account will have the capability iff any device on the account has the capability
|
||||
ANY_DEVICE,
|
||||
/**
|
||||
* The account will have the capability iff all devices on the account have the capability
|
||||
*/
|
||||
|
||||
/// The account will have the capability iff all devices on the account have the capability
|
||||
ALL_DEVICES,
|
||||
/**
|
||||
* The account always has this capability, regardless of the constituent devices' capabilities.
|
||||
* This supports retiring capabilities where older clients still need the field provided.
|
||||
*/
|
||||
|
||||
/// The account always has this capability, regardless of the constituent devices' capabilities.
|
||||
/// This supports retiring capabilities where older clients still need the field provided.
|
||||
ALWAYS_CAPABLE,
|
||||
}
|
||||
|
||||
public enum AccountCapabilityVisibility {
|
||||
/// The capability is only visible to the server.
|
||||
SERVER,
|
||||
|
||||
/// The capability is visible to all devices on the account.
|
||||
SELF,
|
||||
|
||||
/// The capability is publicly visible.
|
||||
PUBLIC
|
||||
}
|
||||
|
||||
public static final Set<DeviceCapability> CAPABILITIES_REQUIRED_FOR_NEW_DEVICES =
|
||||
EnumSet.copyOf(Arrays.stream(DeviceCapability.values())
|
||||
.filter(DeviceCapability::requireForNewDevices)
|
||||
@@ -46,34 +62,32 @@ public enum DeviceCapability {
|
||||
|
||||
private final String name;
|
||||
private final AccountCapabilityMode accountCapabilityMode;
|
||||
private final AccountCapabilityVisibility accountCapabilityVisibility;
|
||||
private final boolean preventDowngrade;
|
||||
private final boolean includeInProfile;
|
||||
private final boolean requireForNewDevices;
|
||||
|
||||
/**
|
||||
* Create a DeviceCapability
|
||||
*
|
||||
* @param name The name of the device capability that clients will see
|
||||
* @param accountCapabilityMode How to combine the constituent device's capabilities in the account to an overall
|
||||
* account capability
|
||||
* @param preventDowngrade If true, don't let linked devices join that don't have a device capability if the
|
||||
* overall account has the capability. Most of the time this should only be used in
|
||||
* conjunction with AccountCapabilityMode.ALL_DEVICES.
|
||||
* @param includeInProfile Whether to return this capability on the account's profile. If false, the capability
|
||||
* is only visible to the server.
|
||||
* @param requireForNewDevices If true, prevent device creation if the new device does not have this capability
|
||||
*/
|
||||
/// Create a DeviceCapability
|
||||
///
|
||||
/// @param name The name of the device capability that clients will see
|
||||
/// @param accountCapabilityMode How to combine the constituent device's capabilities in the account to an
|
||||
/// overall account capability
|
||||
/// @param accountCapabilityVisibility Who should be able to view this capability
|
||||
/// @param preventDowngrade If true, don't let linked devices join that don't have a device capability if
|
||||
/// the overall account has the capability. Most of the time this should only be
|
||||
/// used in conjunction with AccountCapabilityMode.ALL_DEVICES.
|
||||
/// @param requireForNewDevices If true, prevent device creation if the new device does not have this
|
||||
/// capability
|
||||
DeviceCapability(final String name,
|
||||
final AccountCapabilityMode accountCapabilityMode,
|
||||
final AccountCapabilityVisibility accountCapabilityVisibility,
|
||||
final boolean preventDowngrade,
|
||||
final boolean includeInProfile,
|
||||
final boolean requireForNewDevices) {
|
||||
|
||||
this.name = name;
|
||||
this.accountCapabilityMode = accountCapabilityMode;
|
||||
this.preventDowngrade = preventDowngrade;
|
||||
this.includeInProfile = includeInProfile;
|
||||
this.requireForNewDevices = requireForNewDevices;
|
||||
this.accountCapabilityVisibility = accountCapabilityVisibility;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
@@ -84,12 +98,17 @@ public enum DeviceCapability {
|
||||
return accountCapabilityMode;
|
||||
}
|
||||
|
||||
public AccountCapabilityVisibility getAccountCapabilityVisibility() {
|
||||
return accountCapabilityVisibility;
|
||||
}
|
||||
|
||||
public boolean preventDowngrade() {
|
||||
return preventDowngrade;
|
||||
}
|
||||
|
||||
public boolean includeInProfile() {
|
||||
return includeInProfile;
|
||||
public boolean includeInLegacyProfile() {
|
||||
// Profiles v1 does not distinguish between self/public capabilities
|
||||
return accountCapabilityVisibility != AccountCapabilityVisibility.SERVER;
|
||||
}
|
||||
|
||||
public boolean requireForNewDevices() {
|
||||
|
||||
+65
-12
@@ -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;
|
||||
@@ -38,7 +39,6 @@ import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.push.RedisMessageAvailabilityManager;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStore;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStream;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import reactor.core.observability.micrometer.Micrometer;
|
||||
import reactor.core.publisher.Flux;
|
||||
@@ -62,13 +62,16 @@ public class MessagesManager {
|
||||
private static final String PRESENCE_MATCH_COUNTER_NAME =
|
||||
MetricsUtil.name(MessagesManager.class, "presenceMatch");
|
||||
|
||||
private static final String INSERT_FDB_EXCEPTIONS_COUNTER_NAME = name(MessagesManager.class, "insertExceptions");
|
||||
|
||||
@VisibleForTesting
|
||||
static final String MIRROR_INSERTS_EXPERIMENT_NAME = "foundationDbMirrorInserts";
|
||||
|
||||
@VisibleForTesting
|
||||
static final String MIRROR_DELETIONS_EXPERIMENT_NAME = "foundationDbMirrorDeletions";
|
||||
|
||||
private static final long FOUNDATIONDB_INSERT_TIMEOUT_MILLIS = Duration.ofSeconds(2).toMillis();
|
||||
@VisibleForTesting
|
||||
static final String MIRROR_READS_EXPERIMENT_NAME = "foundationDbMirrorReads";
|
||||
|
||||
private final MessagesDynamoDb messagesDynamoDb;
|
||||
private final MessagesCache messagesCache;
|
||||
@@ -128,12 +131,16 @@ public class MessagesManager {
|
||||
|
||||
foundationDbInsertFuture =
|
||||
foundationDbMessageStore.insert(new AciServiceIdentifier(accountIdentifier), minimizedMessagesByDeviceId)
|
||||
.orTimeout(FOUNDATIONDB_INSERT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
|
||||
.exceptionally(e -> {
|
||||
logger.warn("Failed to insert {} message(s) for {} into FoundationDB",
|
||||
minimizedMessagesByDeviceId.size(),
|
||||
accountIdentifier,
|
||||
e);
|
||||
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(),
|
||||
accountIdentifier,
|
||||
e);
|
||||
}
|
||||
|
||||
return Collections.emptyMap();
|
||||
});
|
||||
@@ -284,11 +291,12 @@ public class MessagesManager {
|
||||
new RedisDynamoDbMessageStream(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager,
|
||||
destinationUuid, destinationDevice);
|
||||
|
||||
return experimentEnrollmentManager.isEnrolled(destinationUuid, MIRROR_DELETIONS_EXPERIMENT_NAME)
|
||||
? new AcknowledgementMirroringMessageStream(
|
||||
return new MirroringMessageStream(
|
||||
redisDynamoDbMessageStream,
|
||||
foundationDbMessageStore.getMessages(new AciServiceIdentifier(destinationUuid), destinationDevice.getId()))
|
||||
: redisDynamoDbMessageStream;
|
||||
foundationDbMessageStore.getMessages(new AciServiceIdentifier(destinationUuid), destinationDevice.getId()),
|
||||
experimentEnrollmentManager,
|
||||
destinationUuid,
|
||||
destinationDevice.getId());
|
||||
}
|
||||
|
||||
Publisher<Envelope> getMessagesForDevice(final UUID destinationUuid, final Device destinationDevice) {
|
||||
@@ -387,4 +395,49 @@ public class MessagesManager {
|
||||
final SealedSenderMultiRecipientMessage sealedSenderMultiRecipientMessage) {
|
||||
return messagesCache.insertSharedMultiRecipientMessagePayload(sealedSenderMultiRecipientMessage);
|
||||
}
|
||||
|
||||
/// Record versionstamps for the current time in the FoundationDB database(s).
|
||||
public void recordFoundationDbVersionstamps() {
|
||||
foundationDbMessageStore.recordVersionstamps();
|
||||
}
|
||||
|
||||
/// Clean up expired entries in the FoundationDB versionstamp clock.
|
||||
///
|
||||
/// @param oldestRetainedEntryTimestamp the earliest time for which we still want to be able to obtain a versionstamp
|
||||
public void expireOldFoundationDbVersionstamps(final Instant oldestRetainedEntryTimestamp) {
|
||||
foundationDbMessageStore.expireOldVersionstamps(oldestRetainedEntryTimestamp);
|
||||
}
|
||||
|
||||
/// Delete messages in FoundationDB for the given devices that were inserted before the given
|
||||
/// time. (Expiration of messages from Redis and Dynamo is handled automatically and do not
|
||||
/// require any interaction with this class.)
|
||||
///
|
||||
/// @param accountDeviceIdentifiers a map from ACI to the list of device IDs for which expired messages should be
|
||||
/// trimmed.
|
||||
///
|
||||
/// @param cutoffTime the expiration threshold. Messages inserted before this time may be deleted; messages inserted
|
||||
/// after it will not be.
|
||||
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);
|
||||
}
|
||||
}
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Flow;
|
||||
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.storage.foundationdb.FoundationDbMessageStream;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import reactor.adapter.JdkFlowAdapter;
|
||||
import reactor.core.publisher.BaseSubscriber;
|
||||
|
||||
/// A temporary message stream that can mirror message acknowledgements (deletion requests) to FoundationDB
|
||||
public class MirroringMessageStream implements MessageStream {
|
||||
|
||||
private final RedisDynamoDbMessageStream redisDynamoDbMessageStream;
|
||||
private final FoundationDbMessageStream foundationDbMessageStream;
|
||||
private final ExperimentEnrollmentManager experimentEnrollmentManager;
|
||||
|
||||
private final AciServiceIdentifier accountIdentifier;
|
||||
private final byte deviceId;
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(MirroringMessageStream.class);
|
||||
|
||||
private static class FoundationDbSubscriber extends BaseSubscriber<MessageStreamEntry> {
|
||||
|
||||
public void handleRedisDynamoDbMessageStreamEntry(final MessageStreamEntry messageStreamEntry) {
|
||||
final boolean isMirroredMessage = switch (messageStreamEntry) {
|
||||
case MessageStreamEntry.Envelope envelopeEntry ->
|
||||
UUIDUtil.fromByteString(envelopeEntry.message().getServerGuid()).version() == 8;
|
||||
|
||||
case MessageStreamEntry.QueueEmpty _ -> true;
|
||||
};
|
||||
|
||||
if (isMirroredMessage) {
|
||||
request(1);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void hookOnSubscribe(final Subscription subscription) {
|
||||
// The base `hookOnSubscribe` requests `Long.MAX_VALUE` elements, and that is something we're explicitly trying
|
||||
// to avoid with this subscriber
|
||||
}
|
||||
}
|
||||
|
||||
public MirroringMessageStream(final RedisDynamoDbMessageStream redisDynamoDbMessageStream,
|
||||
final FoundationDbMessageStream foundationDbMessageStream,
|
||||
final ExperimentEnrollmentManager experimentEnrollmentManager,
|
||||
final UUID accountIdentifier,
|
||||
final byte deviceId) {
|
||||
|
||||
this.redisDynamoDbMessageStream = redisDynamoDbMessageStream;
|
||||
this.foundationDbMessageStream = foundationDbMessageStream;
|
||||
this.experimentEnrollmentManager = experimentEnrollmentManager;
|
||||
|
||||
this.accountIdentifier = new AciServiceIdentifier(accountIdentifier);
|
||||
this.deviceId = deviceId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Flow.Publisher<MessageStreamEntry> getMessages() {
|
||||
final FoundationDbSubscriber subscriber = new FoundationDbSubscriber();
|
||||
|
||||
if (experimentEnrollmentManager.isEnrolled(accountIdentifier.uuid(), MessagesManager.MIRROR_READS_EXPERIMENT_NAME)) {
|
||||
JdkFlowAdapter.flowPublisherToFlux(foundationDbMessageStream.getMessages())
|
||||
.subscribe(subscriber);
|
||||
|
||||
return JdkFlowAdapter.publisherToFlowPublisher(
|
||||
JdkFlowAdapter.flowPublisherToFlux(redisDynamoDbMessageStream.getMessages())
|
||||
.doOnNext(subscriber::handleRedisDynamoDbMessageStreamEntry)
|
||||
.doFinally(_ -> {
|
||||
try {
|
||||
subscriber.dispose();
|
||||
} catch (final Exception _) {
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
return redisDynamoDbMessageStream.getMessages();
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> acknowledgeMessage(final UUID messageGuid, final long serverTimestamp) {
|
||||
// All messages stored in FoundationDB use version 8 UUIDs; if a message has a version 4 UUID, then it only exists
|
||||
// in Redis/DynamoDB
|
||||
if (messageGuid.version() == 8 &&
|
||||
experimentEnrollmentManager.isEnrolled(accountIdentifier.uuid(), MessagesManager.MIRROR_DELETIONS_EXPERIMENT_NAME)) {
|
||||
|
||||
foundationDbMessageStream.acknowledgeMessage(messageGuid, serverTimestamp)
|
||||
.whenComplete((_, throwable) -> {
|
||||
if (throwable != null) {
|
||||
logger.warn("Failed to delete message {}/{}/{} from FoundationDb", accountIdentifier.uuid(), deviceId,
|
||||
messageGuid, throwable);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return redisDynamoDbMessageStream.acknowledgeMessage(messageGuid, serverTimestamp);
|
||||
}
|
||||
}
|
||||
+4
-3
@@ -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
-3
@@ -41,6 +41,7 @@ import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorConfl
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptAlreadyRedeemedException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptRequestedForOpenPaymentException;
|
||||
import org.whispersystems.textsecuregcm.util.ThrowingBiFunction;
|
||||
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
|
||||
|
||||
/**
|
||||
@@ -244,6 +245,7 @@ public class SubscriptionManager {
|
||||
* @param <T> A payment processor that has a notion of server-managed customers
|
||||
* @param <R> The return type of the paymentSetupFunction, which should be used by a client
|
||||
* to configure the newly created payment method
|
||||
* @param <E> An exception thrown by the paymentSetupFunction
|
||||
* @return The return value of the paymentSetupFunction
|
||||
* @throws SubscriptionForbiddenException if the subscriber credentials were incorrect
|
||||
* @throws SubscriptionNotFoundException if the subscriber did not exist or did not have a subscription
|
||||
@@ -251,12 +253,12 @@ public class SubscriptionManager {
|
||||
* @throws SubscriptionProcessorConflictException if the new payment processor does not match the existing processor associated with
|
||||
* the subscriberId
|
||||
*/
|
||||
public <T extends CustomerAwareSubscriptionPaymentProcessor, R> R addPaymentMethodToCustomer(
|
||||
public <T extends CustomerAwareSubscriptionPaymentProcessor, R, E extends Exception> R addPaymentMethodToCustomer(
|
||||
final SubscriberCredentials subscriberCredentials,
|
||||
final T subscriptionPaymentProcessor,
|
||||
final ClientPlatform clientPlatform,
|
||||
final BiFunction<T, String, R> paymentSetupFunction)
|
||||
throws SubscriptionForbiddenException, SubscriptionNotFoundException, SubscriptionProcessorConflictException {
|
||||
final ThrowingBiFunction<T, String, R, E> paymentSetupFunction)
|
||||
throws SubscriptionForbiddenException, SubscriptionNotFoundException, SubscriptionProcessorConflictException, E {
|
||||
|
||||
Subscriptions.Record record = this.getSubscriber(subscriberCredentials);
|
||||
if (record.getProcessorCustomer().isEmpty()) {
|
||||
|
||||
-113
@@ -1,113 +0,0 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage.foundationdb;
|
||||
|
||||
import com.apple.foundationdb.tuple.Versionstamp;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.NavigableMap;
|
||||
import java.util.TreeMap;
|
||||
|
||||
/// An acknowledged message buffer keeps track of messages that have been sent, whether they have been acknowledged by
|
||||
/// the recipient, and whether those acknowledgements have been flushed to the underlying data store. It also batches
|
||||
/// acknowledgements into contiguous ranges in the interest of efficiency.
|
||||
class AcknowledgedMessageBuffer {
|
||||
|
||||
/// The maximum number of unacknowledged messages we will send before closing the stream with an error
|
||||
private final int maxUnacknowledgedMessages;
|
||||
|
||||
/// Map of versionstamp -> acknowledged? to keep track of acknowledged versionstamp ranges to clear
|
||||
private final NavigableMap<Versionstamp, Boolean> sentVersionstamps = new TreeMap<>();
|
||||
private int unacknowledgedMessages = 0;
|
||||
|
||||
AcknowledgedMessageBuffer(final int maxUnacknowledgedMessages) {
|
||||
this.maxUnacknowledgedMessages = maxUnacknowledgedMessages;
|
||||
}
|
||||
|
||||
public synchronized void addUnacknowledgedMessage(final Versionstamp versionstamp) throws TooManyUnacknowledgedMessagesException {
|
||||
if (++unacknowledgedMessages > maxUnacknowledgedMessages) {
|
||||
throw new TooManyUnacknowledgedMessagesException();
|
||||
}
|
||||
|
||||
sentVersionstamps.put(versionstamp, false);
|
||||
}
|
||||
|
||||
public synchronized void acknowledgeMessage(final Versionstamp versionstamp) {
|
||||
// If we don't know about this versionstamp, or it's already acknowledged, there's nothing to do
|
||||
if (!sentVersionstamps.containsKey(versionstamp) || sentVersionstamps.get(versionstamp)) {
|
||||
return;
|
||||
}
|
||||
|
||||
unacknowledgedMessages--;
|
||||
sentVersionstamps.put(versionstamp, true);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
int getUnacknowledgedMessageCount() {
|
||||
return unacknowledgedMessages;
|
||||
}
|
||||
|
||||
/// Computes a list of acknowledged contiguous versionstamp ranges that can be cleared from the database and removes
|
||||
/// them from ths unacknowledged mesage buffer.
|
||||
///
|
||||
/// @return a list of acknowledged contiguous versionstamp ranges that can be cleared from the database.
|
||||
public synchronized List<Pair<Versionstamp, Versionstamp>> takeFlushableRanges() {
|
||||
final List<Pair<Versionstamp, Versionstamp>> flushableRanges = computeFlushableRanges();
|
||||
flushableRanges.forEach(range -> sentVersionstamps.subMap(range.first(), true, range.second(), true).clear());
|
||||
|
||||
return flushableRanges;
|
||||
}
|
||||
|
||||
/// Computes a list of acknowledged contiguous versionstamp ranges that can be cleared from the database.
|
||||
///
|
||||
/// @return a list of acknowledged contiguous versionstamp ranges that can be cleared from the database.
|
||||
@VisibleForTesting
|
||||
synchronized List<Pair<Versionstamp, Versionstamp>> computeFlushableRanges() {
|
||||
final List<Pair<Versionstamp, Versionstamp>> flushableRanges = new ArrayList<>();
|
||||
Versionstamp startInclusive = null;
|
||||
Versionstamp endInclusive = null;
|
||||
|
||||
for (final Map.Entry<Versionstamp, Boolean> entry : sentVersionstamps.entrySet()) {
|
||||
if (entry.getValue()) {
|
||||
// Message is acknowledged, so we can either start tracking a new range if we aren't already, or extend our
|
||||
// current range
|
||||
if (startInclusive == null) {
|
||||
startInclusive = entry.getKey();
|
||||
}
|
||||
endInclusive = entry.getKey();
|
||||
} else {
|
||||
// Message is un-acknowledged, which means either it is a "range-breaker" or we never started tracking an
|
||||
// acknowledged range. Mark the currently tracked range flushable, if it exists.
|
||||
if (startInclusive != null) {
|
||||
assert endInclusive != null;
|
||||
flushableRanges.add(new Pair<>(startInclusive, endInclusive));
|
||||
startInclusive = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (startInclusive != null) {
|
||||
assert endInclusive != null;
|
||||
flushableRanges.add(new Pair<>(startInclusive, endInclusive));
|
||||
}
|
||||
|
||||
return flushableRanges;
|
||||
}
|
||||
|
||||
|
||||
/// Acknowledges a stale ephemeral message for cleanup from FoundationDB.
|
||||
/// Ephemeral messages are only delivered when the recipient has an active message stream, so any ephemeral message
|
||||
/// read from the finite publisher is stale by definition and can be immediately acknowledged and discarded.
|
||||
///
|
||||
/// @param versionstamp The versionstamp to acknowledge
|
||||
public synchronized void acknowledgeStaleEphemeralMessage(final Versionstamp versionstamp) {
|
||||
sentVersionstamps.put(versionstamp, true);
|
||||
}
|
||||
|
||||
}
|
||||
+166
-140
@@ -10,24 +10,24 @@ import com.google.protobuf.InvalidProtocolBufferException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.time.Clock;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ScheduledFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Supplier;
|
||||
import javax.annotation.Nullable;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.FluxSink;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
/// Publishes a message stream from a device queue in FoundationDB. Capable of publishing both a finite stream for
|
||||
/// catching up to end-of-queue,and an infinite stream for live updates.
|
||||
@@ -41,9 +41,6 @@ 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;
|
||||
@@ -59,10 +56,6 @@ class FoundationDbMessagePublisher {
|
||||
/// Listener to watch for state machine transitions; used for testing.
|
||||
private final BiConsumer<State, State> stateChangeListener;
|
||||
|
||||
/// A supplier that returns a function to execute before we begin fetching a page; it is passed the transaction that
|
||||
/// is started for the page fetch operations.
|
||||
private final Supplier<Consumer<Transaction>> beforePageFetch;
|
||||
|
||||
/// Whether the publisher is finite or infinite.
|
||||
private final boolean terminateOnQueueEmpty;
|
||||
|
||||
@@ -77,13 +70,27 @@ class FoundationDbMessagePublisher {
|
||||
/// Future that completes when the watch for {@link #messagesAvailableWatchKey} triggers.
|
||||
private CompletableFuture<Void> watchFuture;
|
||||
|
||||
/// A future for refreshing the connected client's presence value at regular intervals.
|
||||
@Nullable private ScheduledFuture<?> renewPresenceFuture;
|
||||
/// An executor service for refreshing the connected client's presence value at regular intervals.
|
||||
@Nullable final ScheduledExecutorService presenceRenewalExecutorService;
|
||||
|
||||
/// A future that represents the next pending presence renewal.
|
||||
@Nullable private CompletableFuture<?> renewPresenceFuture;
|
||||
|
||||
private long totalRequested;
|
||||
private long totalEmitted;
|
||||
|
||||
private static final AtomicInteger NEXT_STREAM_ID = new AtomicInteger();
|
||||
|
||||
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 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,
|
||||
@@ -123,48 +130,40 @@ class FoundationDbMessagePublisher {
|
||||
final Clock clock,
|
||||
final KeySelector beginKeyInclusive,
|
||||
final KeySelector endKeyExclusive,
|
||||
final int maxMessagesPerScan,
|
||||
@Nullable final byte[] presenceKey,
|
||||
@Nullable final ScheduledExecutorService presenceRenewalExecutorService,
|
||||
@Nullable final byte[] messagesAvailableWatchKey,
|
||||
@Nullable final BiConsumer<State, State> stateChangeListener,
|
||||
final Supplier<Consumer<Transaction>> beforePageFetch) {
|
||||
@Nullable final BiConsumer<State, State> stateChangeListener) {
|
||||
|
||||
this.database = database;
|
||||
this.clock = clock;
|
||||
this.beginKeyCursor = beginKeyInclusive;
|
||||
this.endKeyExclusive = endKeyExclusive;
|
||||
this.maxMessagesPerScan = maxMessagesPerScan;
|
||||
this.presenceKey = presenceKey;
|
||||
this.presenceRenewalExecutorService = presenceRenewalExecutorService;
|
||||
this.messagesAvailableWatchKey = messagesAvailableWatchKey;
|
||||
this.terminateOnQueueEmpty = messagesAvailableWatchKey == null;
|
||||
this.stateChangeListener = stateChangeListener != null ? stateChangeListener : (_, _) -> {};
|
||||
this.beforePageFetch = beforePageFetch;
|
||||
|
||||
if (!terminateOnQueueEmpty) {
|
||||
Objects.requireNonNull(presenceKey);
|
||||
Objects.requireNonNull(presenceRenewalExecutorService);
|
||||
}
|
||||
|
||||
this.messagePublisher = Flux.<FoundationDbMessageStreamEntry.Message>create(emitter -> {
|
||||
this.emitter = emitter;
|
||||
emitter.onRequest(_ -> transitionStateOnEvent(Event.DEMAND_REQUESTED));
|
||||
emitter.onDispose(this::onDispose);
|
||||
}).doOnSubscribe(_ -> {
|
||||
if (!terminateOnQueueEmpty) {
|
||||
// Establish presence immediately and block until we do. We must establish presence for watches to work as
|
||||
final Mono<Void> establishPresence = terminateOnQueueEmpty
|
||||
? Mono.empty()
|
||||
// Establish presence before attempting to fetch messages. We must establish presence for watches to work as
|
||||
// expected. If we fail to establish presence, then this non-terminating stream will never learn about new
|
||||
// messages. If establishing presence throws an exception, then the whole publisher will terminate with that
|
||||
// exception.
|
||||
database.run(transaction -> {
|
||||
setPresence(transaction);
|
||||
return null;
|
||||
});
|
||||
: Mono.fromFuture(this::renewPresence).then(Mono.fromRunnable(this::schedulePresenceRenewal));
|
||||
|
||||
// Refresh presence at regular intervals
|
||||
startPresenceRenewal(presenceRenewalExecutorService);
|
||||
}
|
||||
});
|
||||
this.messagePublisher = establishPresence
|
||||
.thenMany(Flux.create(emitter -> {
|
||||
this.emitter = emitter;
|
||||
emitter.onRequest(this::addDemand);
|
||||
emitter.onDispose(this::onDispose);
|
||||
}));
|
||||
}
|
||||
|
||||
/// Creates a [FoundationDbMessagePublisher] that publishes a stream of messages in a queue that terminates when it
|
||||
@@ -175,20 +174,16 @@ class FoundationDbMessagePublisher {
|
||||
final Database database,
|
||||
final Clock clock,
|
||||
final KeySelector beginKeyInclusive,
|
||||
final KeySelector endKeyExclusive,
|
||||
final int maxMessagesPerScan,
|
||||
final Supplier<Consumer<Transaction>> beforePageFetch) {
|
||||
final KeySelector endKeyExclusive) {
|
||||
|
||||
return new FoundationDbMessagePublisher(database,
|
||||
clock,
|
||||
beginKeyInclusive,
|
||||
endKeyExclusive,
|
||||
maxMessagesPerScan,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
beforePageFetch);
|
||||
null);
|
||||
}
|
||||
|
||||
/// Creates a [FoundationDbMessagePublisher] that publishes a non-terminating stream of messages from a device queue.
|
||||
@@ -199,22 +194,18 @@ class FoundationDbMessagePublisher {
|
||||
final Clock clock,
|
||||
final KeySelector beginKeyInclusive,
|
||||
final KeySelector endKeyExclusive,
|
||||
final int maxMessagesPerScan,
|
||||
final byte[] presenceKey,
|
||||
final ScheduledExecutorService presenceRenewalExecutorService,
|
||||
final byte[] messagesAvailableWatchKey,
|
||||
final Supplier<Consumer<Transaction>> beforePageFetch) {
|
||||
final byte[] messagesAvailableWatchKey) {
|
||||
|
||||
return new FoundationDbMessagePublisher(database,
|
||||
clock,
|
||||
beginKeyInclusive,
|
||||
endKeyExclusive,
|
||||
maxMessagesPerScan,
|
||||
presenceKey,
|
||||
presenceRenewalExecutorService,
|
||||
messagesAvailableWatchKey,
|
||||
null,
|
||||
beforePageFetch);
|
||||
null);
|
||||
}
|
||||
|
||||
private synchronized void setState(final State newState, final Event event) {
|
||||
@@ -301,86 +292,87 @@ 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
|
||||
/// a watch for new messages. Execute the function supplied by [#beforePageFetch] in the context of the transaction.
|
||||
/// Additionally, the cursor is updated so that we begin fetching from the right key on
|
||||
/// subsequent scans
|
||||
/// 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() {
|
||||
final Consumer<Transaction> doBeforePageFetch = beforePageFetch.get();
|
||||
/// @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 database.runAsync(transaction -> {
|
||||
doBeforePageFetch.accept(transaction);
|
||||
return FoundationDbUtil.safeRunAsync(database, transaction ->
|
||||
transaction.getRange(beginKeyCursor, endKeyExclusive, maxMessages, false, StreamingMode.EXACT).asList()
|
||||
.thenApply(keyValues -> {
|
||||
if (keyValues.size() < maxMessages && !terminateOnQueueEmpty) {
|
||||
setWatch(transaction);
|
||||
}
|
||||
|
||||
return getItemsInRange(transaction, beginKeyCursor, endKeyExclusive, maxMessagesPerScan)
|
||||
.thenApply(lastKeyReadAndItems -> {
|
||||
if (lastKeyReadAndItems.second().size() < maxMessagesPerScan && !terminateOnQueueEmpty) {
|
||||
setWatch(transaction);
|
||||
}
|
||||
|
||||
return lastKeyReadAndItems;
|
||||
});
|
||||
})
|
||||
// Defer any state mutations until after the transaction has been committed. The transaction block can
|
||||
// fail/retry, and we don't want to trigger spurious state transitions when that happens.
|
||||
.thenApply(lastKeyReadAndItems -> {
|
||||
// Set our beginning key to just past the last key read so that we're ready for our next fetch
|
||||
lastKeyReadAndItems.first()
|
||||
.ifPresent(lastKeyRead -> beginKeyCursor = KeySelector.firstGreaterThan(lastKeyRead));
|
||||
|
||||
if (lastKeyReadAndItems.second().size() < maxMessagesPerScan) {
|
||||
return keyValues;
|
||||
}))
|
||||
.thenApply(keyValues -> {
|
||||
if (keyValues.size() < maxMessages) {
|
||||
transitionStateOnEvent(Event.FETCHED_ALL_AVAILABLE_MESSAGES);
|
||||
}
|
||||
|
||||
return lastKeyReadAndItems.second();
|
||||
});
|
||||
}
|
||||
if (keyValues.isEmpty()) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
/// Fetch messages in the range between `begin` and `end` limited to a batch size of `maxMessagesPerSccan`
|
||||
///
|
||||
/// @param transaction the FoundationDB transaction in which to perform the read query
|
||||
/// @param beginInclusive the range start key (inclusive)
|
||||
/// @param endExclusive the range end key (exclusive)
|
||||
/// @param maxMessagesPerScan maximum number of messages to return in the fetch query
|
||||
/// @return the last key read (if there were non-zero number of messages read) and the list of messages read
|
||||
private CompletableFuture<Pair<Optional<byte[]>, List<FoundationDbMessageStreamEntry.Message>>> getItemsInRange(
|
||||
final Transaction transaction,
|
||||
final KeySelector beginInclusive,
|
||||
final KeySelector endExclusive,
|
||||
final int maxMessagesPerScan) {
|
||||
return transaction.getRange(beginInclusive, endExclusive, maxMessagesPerScan, false, StreamingMode.EXACT).asList()
|
||||
.thenApply(keyValues -> {
|
||||
final Optional<byte[]> lastKeyRead = keyValues.isEmpty()
|
||||
? Optional.empty()
|
||||
: Optional.of(keyValues.getLast().getKey());
|
||||
final List<FoundationDbMessageStreamEntry.Message> messages = keyValues.stream()
|
||||
beginKeyCursor = KeySelector.firstGreaterThan(keyValues.getLast().getKey());
|
||||
|
||||
return keyValues.stream()
|
||||
.map(keyValue -> {
|
||||
final Versionstamp versionstamp = FoundationDbMessageStore.getVersionstamp(keyValue.getKey());
|
||||
|
||||
try {
|
||||
return new FoundationDbMessageStreamEntry.Message(versionstamp, MessageProtos.Envelope.parseFrom(keyValue.getValue()));
|
||||
return new FoundationDbMessageStreamEntry.Message(versionstamp,
|
||||
MessageProtos.Envelope.parseFrom(keyValue.getValue()));
|
||||
} catch (final InvalidProtocolBufferException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
})
|
||||
.toList();
|
||||
return new Pair<>(lastKeyRead, messages);
|
||||
});
|
||||
}
|
||||
|
||||
/// 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);
|
||||
handleEntriesEmitted(messageStreamEntries.size());
|
||||
transitionStateOnEvent(Event.PUBLISHED_MESSAGES);
|
||||
})
|
||||
.exceptionally(t -> {
|
||||
@@ -399,72 +391,107 @@ 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;
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void startPresenceRenewal(final ScheduledExecutorService presenceRenewalExecutorService) {
|
||||
final long renewalIntervalMillis =
|
||||
FoundationDbMessageStore.PRESENCE_STALE_THRESHOLD.multipliedBy(4).dividedBy(5).toMillis();
|
||||
|
||||
renewPresenceFuture = presenceRenewalExecutorService.scheduleWithFixedDelay(this::renewPresence,
|
||||
renewalIntervalMillis,
|
||||
renewalIntervalMillis,
|
||||
TimeUnit.MILLISECONDS);
|
||||
}
|
||||
|
||||
private synchronized void renewPresence() {
|
||||
private synchronized void schedulePresenceRenewal() {
|
||||
if (state == State.TERMINATED || state == State.ERROR) {
|
||||
return;
|
||||
}
|
||||
|
||||
database.runAsync(transaction -> {
|
||||
setPresence(transaction);
|
||||
return CompletableFuture.completedFuture(null);
|
||||
})
|
||||
.whenComplete((_, throwable) -> {
|
||||
assert presenceRenewalExecutorService != null;
|
||||
|
||||
renewPresenceFuture = new CompletableFuture<>();
|
||||
|
||||
final ScheduledFuture<?> scheduledFuture = presenceRenewalExecutorService.schedule(() -> {
|
||||
renewPresence().whenComplete((_, throwable) -> {
|
||||
if (throwable != null) {
|
||||
LOGGER.warn("Failed to renew presence", throwable);
|
||||
renewPresenceFuture.completeExceptionally(throwable);
|
||||
} else {
|
||||
renewPresenceFuture.complete(null);
|
||||
}
|
||||
});
|
||||
}, RENEWAL_INTERVAL_MILLIS, TimeUnit.MILLISECONDS);
|
||||
|
||||
renewPresenceFuture.whenComplete((_, throwable) -> {
|
||||
if (throwable != null) {
|
||||
LOGGER.warn("Failed to renew presence; will terminate publisher", throwable);
|
||||
// We can wind up here in one of two ways:
|
||||
//
|
||||
// 1. We're shutting down the publisher, in which case `throwable` is a `CancellationException`. We don't NEED
|
||||
// to terminate the publisher in this case (since it's already terminated), but it's harmless to issue a
|
||||
// second termination request, which will just be a no-op.
|
||||
// 2. Something unexpected has gone wrong. We DO need to terminate the publisher in this case, because a failure
|
||||
// to renew presence means that we won't get notified of new messages and so the publisher is in a bad state.
|
||||
//
|
||||
// In both cases, we should stop trying to schedule presence renewal.
|
||||
scheduledFuture.cancel(false);
|
||||
terminateWithError(throwable);
|
||||
} else {
|
||||
// We renewed presence successfully and the publisher is still active; renew presence again at some point in the
|
||||
// future.
|
||||
schedulePresenceRenewal();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void setPresence(final Transaction transaction) {
|
||||
transaction.set(presenceKey, FoundationDbMessageStore.getPresenceValue(clock.instant(), streamId));
|
||||
private synchronized CompletableFuture<Void> renewPresence() {
|
||||
if (state == State.TERMINATED || state == State.ERROR) {
|
||||
return CompletableFuture.failedFuture(new IllegalStateException("Publisher already terminated"));
|
||||
}
|
||||
|
||||
return FoundationDbUtil.safeRunAsync(database, transaction -> {
|
||||
transaction.set(presenceKey, FoundationDbMessageStore.getPresenceValue(clock.instant(), streamId));
|
||||
return CompletableFuture.completedFuture(null);
|
||||
});
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
synchronized void clearPresence() {
|
||||
if (renewPresenceFuture != null) {
|
||||
renewPresenceFuture.cancel(true);
|
||||
}
|
||||
|
||||
if (!terminateOnQueueEmpty) {
|
||||
database.runAsync(transaction -> transaction.get(presenceKey).thenAccept(presenceValue -> {
|
||||
final byte[] presenceServerId = FoundationDbMessageStore.getPresenceServerId(presenceValue);
|
||||
final int presenceStreamId = FoundationDbMessageStore.getPresenceStreamId(presenceValue);
|
||||
renewPresenceFuture.whenComplete((_, _) ->
|
||||
FoundationDbUtil.safeRunAsync(database, transaction -> transaction.get(presenceKey).thenAccept(presenceValue -> {
|
||||
if (presenceValue == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (Arrays.equals(presenceServerId, FoundationDbMessageStore.getServerId()) && streamId == presenceStreamId) {
|
||||
transaction.clear(presenceKey);
|
||||
}
|
||||
}))
|
||||
.whenComplete((_, throwable) -> {
|
||||
if (throwable != null) {
|
||||
LOGGER.warn("Failed to clear presence on disposal", throwable);
|
||||
}
|
||||
});
|
||||
final byte[] presenceServerId = FoundationDbMessageStore.getPresenceServerId(presenceValue);
|
||||
final int presenceStreamId = FoundationDbMessageStore.getPresenceStreamId(presenceValue);
|
||||
|
||||
if (Arrays.equals(presenceServerId, FoundationDbMessageStore.getServerId()) && streamId == presenceStreamId) {
|
||||
transaction.clear(presenceKey);
|
||||
}
|
||||
}))
|
||||
.whenComplete((_, throwable) -> {
|
||||
if (throwable != null) {
|
||||
LOGGER.warn("Failed to clear presence on disposal", throwable);
|
||||
}
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -472,9 +499,8 @@ class FoundationDbMessagePublisher {
|
||||
synchronized void terminateWithError(final Throwable throwable) {
|
||||
if (state != State.TERMINATED && state != State.ERROR) {
|
||||
setState(State.ERROR, Event.INTERNAL_TRIGGER);
|
||||
emitter.error(throwable);
|
||||
}
|
||||
|
||||
emitter.error(throwable);
|
||||
}
|
||||
|
||||
private synchronized void onDispose() {
|
||||
|
||||
+238
-27
@@ -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,12 +101,24 @@ 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"));
|
||||
|
||||
private static final Timer INSERT_MESSAGE_BATCH_TIMER =
|
||||
Metrics.timer(MetricsUtil.name(FoundationDbMessageStore.class, "insertMessageBatchTimer"));
|
||||
|
||||
private static final Counter DELETE_MESSAGE_COUNTER =
|
||||
Metrics.counter(MetricsUtil.name(FoundationDbMessageStore.class, "deleteMessage"));
|
||||
|
||||
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
|
||||
@@ -99,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][];
|
||||
|
||||
@@ -121,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.
|
||||
@@ -343,6 +382,25 @@ public class FoundationDbMessageStore {
|
||||
});
|
||||
}
|
||||
|
||||
CompletableFuture<Void> delete(final AciServiceIdentifier aci, final byte deviceId, final UUID messageGuid) {
|
||||
return delete(aci, deviceId, versionstampUUIDCipher.decryptVersionstamp(messageGuid, aci.uuid(), deviceId));
|
||||
}
|
||||
|
||||
CompletableFuture<Void> delete(final AciServiceIdentifier aci, final byte deviceId, final Versionstamp versionstamp) {
|
||||
final Timer.Sample sample = Timer.start();
|
||||
|
||||
final byte[] messageKey = getDeviceQueueSubspace(aci, deviceId).pack(Tuple.from(versionstamp));
|
||||
|
||||
return databasesByEpoch[getConfigurationEpoch(versionstamp)][getShardId(versionstamp)].runAsync(transaction -> {
|
||||
transaction.clear(messageKey);
|
||||
return CompletableFuture.completedFuture(null);
|
||||
})
|
||||
.thenRun(() -> {
|
||||
sample.stop(DELETE_MESSAGE_TIMER);
|
||||
DELETE_MESSAGE_COUNTER.increment();
|
||||
});
|
||||
}
|
||||
|
||||
public void clearAll(final AciServiceIdentifier aci) {
|
||||
doForAllDatabasesWithMessages(aci, database -> database.run(transaction -> {
|
||||
transaction.clear(getAccountSubspace(aci).range());
|
||||
@@ -366,17 +424,10 @@ public class FoundationDbMessageStore {
|
||||
}
|
||||
|
||||
public FoundationDbMessageStream getMessages(final AciServiceIdentifier aci, final byte deviceId) {
|
||||
return getMessages(aci, deviceId, FoundationDbMessageStream.DEFAULT_MAX_MESSAGES_PER_SCAN,
|
||||
FoundationDbMessageStream.DEFAULT_MAX_UNACKNOWLEDGED_MESSAGES, Util.NOOP);
|
||||
return getMessages(aci, deviceId, Util.NOOP);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
FoundationDbMessageStream getMessages(final AciServiceIdentifier aci,
|
||||
final byte deviceId,
|
||||
final int maxMessagesPerScan,
|
||||
final int maxUnacknowledgedMessages,
|
||||
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];
|
||||
|
||||
@@ -384,13 +435,21 @@ public class FoundationDbMessageStore {
|
||||
databasesForQueueByEpoch[epoch] = getShardForAci(aci, epoch);
|
||||
}
|
||||
|
||||
return new FoundationDbMessageStream(getDeviceQueueSubspace(aci, deviceId),
|
||||
getPresenceKey(aci, deviceId),
|
||||
getMessagesAvailableWatchKey(aci),
|
||||
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,
|
||||
maxUnacknowledgedMessages,
|
||||
doAfterCleanup,
|
||||
presenceRenewalExecutorService,
|
||||
clock);
|
||||
@@ -403,6 +462,15 @@ public class FoundationDbMessageStore {
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove any entries from each database's versionstamp-clock namespace that are strictly older than the given timestamp.
|
||||
///
|
||||
/// @param oldestRetainedEntryTimestamp the earliest time for which we still want to be able to obtain a versionstamp
|
||||
public void expireOldVersionstamps(final Instant oldestRetainedEntryTimestamp) {
|
||||
for (VersionstampClock versionstampClock : versionstampClocks.values()) {
|
||||
versionstampClock.clearExpiredEntries(oldestRetainedEntryTimestamp);
|
||||
}
|
||||
}
|
||||
|
||||
/// Delete messages for the given devices that were inserted before the given time.
|
||||
///
|
||||
/// This issues one range delete for every account/device pair in the map for each actual underlying FoundationDB
|
||||
@@ -420,7 +488,6 @@ public class FoundationDbMessageStore {
|
||||
/// @param cutoffTime the expiration threshold. Messages inserted before this time may be deleted; messages inserted
|
||||
/// after it will not be. Deletion depends on the underlying [versionstamp clocks][VersionstampClock] being kept up to
|
||||
/// date.
|
||||
@VisibleForTesting
|
||||
public void deleteMessagesBefore(final Map<AciServiceIdentifier, List<Byte>> accountDeviceIdentifiers, final Instant cutoffTime) {
|
||||
final Map<Database, List<Subspace>> queueSubspacesToTrimByDatabase = new IdentityHashMap<>();
|
||||
|
||||
@@ -436,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;
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -497,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");
|
||||
}
|
||||
@@ -506,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());
|
||||
}
|
||||
|
||||
+44
-127
@@ -5,33 +5,25 @@ import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
import com.apple.foundationdb.Database;
|
||||
import com.apple.foundationdb.KeySelector;
|
||||
import com.apple.foundationdb.StreamingMode;
|
||||
import com.apple.foundationdb.Transaction;
|
||||
import com.apple.foundationdb.subspace.Subspace;
|
||||
import com.apple.foundationdb.tuple.ByteArrayUtil;
|
||||
import com.apple.foundationdb.tuple.Tuple;
|
||||
import com.apple.foundationdb.tuple.Versionstamp;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.time.Clock;
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
import java.util.IdentityHashMap;
|
||||
import java.util.List;
|
||||
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.Flow;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.stream.Collectors;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.storage.MessageStream;
|
||||
import org.whispersystems.textsecuregcm.storage.MessageStreamEntry;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import reactor.adapter.JdkFlowAdapter;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
@@ -42,20 +34,21 @@ import reactor.util.function.Tuples;
|
||||
/// A [MessageStream] implementation that fetches messages from FoundationDB
|
||||
public class FoundationDbMessageStream implements MessageStream {
|
||||
|
||||
private final FoundationDbMessageStore foundationDbMessageStore;
|
||||
private final AciServiceIdentifier aciServiceIdentifier;
|
||||
private final byte deviceId;
|
||||
|
||||
private final Subspace deviceQueueSubspace;
|
||||
private final byte[] presenceKey;
|
||||
private final byte[] messagesAvailableWatchKey;
|
||||
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 final Map<Database, AcknowledgedMessageBuffer> acknowledgedMessageBuffersByDatabase;
|
||||
|
||||
private final Counter messageReadCounter =
|
||||
Metrics.counter(name(FoundationDbMessageStream.class, "messagesRead"));
|
||||
|
||||
@@ -65,48 +58,33 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
private final Counter staleEphemeralMessagesCounter =
|
||||
Metrics.counter(name(FoundationDbMessageStream.class, "staleEphemeralMessages"));
|
||||
|
||||
static final int DEFAULT_MAX_MESSAGES_PER_SCAN = 100;
|
||||
@VisibleForTesting
|
||||
static final int DEFAULT_MAX_UNACKNOWLEDGED_MESSAGES = 16_384;
|
||||
|
||||
private static final Comparator<FoundationDbMessageStreamEntry.Message> STREAM_ENTRY_TIMESTAMP_COMPARATOR =
|
||||
Comparator.comparingLong(streamEntry -> streamEntry.partialEnvelope().getServerTimestamp());
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(FoundationDbMessageStream.class);
|
||||
private static final int PREFETCH = 128;
|
||||
|
||||
FoundationDbMessageStream(final Subspace deviceQueueSubspace,
|
||||
final byte[] presenceKey,
|
||||
final byte[] messagesAvailableWatchKey,
|
||||
private static final Logger logger = LoggerFactory.getLogger(FoundationDbMessageStream.class);
|
||||
|
||||
FoundationDbMessageStream(final FoundationDbMessageStore foundationDbMessageStore,
|
||||
final AciServiceIdentifier aciServiceIdentifier,
|
||||
final byte deviceId,
|
||||
final Database[] databasesByEpoch,
|
||||
final MessageGuidCodec messageGuidCodec,
|
||||
final int maxMessagesPerScan,
|
||||
final int maxUnacknowledgedMessages,
|
||||
final Runnable doAfterCleanup,
|
||||
final ScheduledExecutorService presenceRenewalExecutorService,
|
||||
final Clock clock) {
|
||||
this.deviceQueueSubspace = deviceQueueSubspace;
|
||||
this.presenceKey = presenceKey;
|
||||
this.messagesAvailableWatchKey = messagesAvailableWatchKey;
|
||||
this.foundationDbMessageStore = foundationDbMessageStore;
|
||||
this.aciServiceIdentifier = aciServiceIdentifier;
|
||||
this.deviceId = deviceId;
|
||||
this.deviceQueueSubspace = FoundationDbMessageStore.getDeviceQueueSubspace(aciServiceIdentifier, deviceId);
|
||||
this.presenceKey = FoundationDbMessageStore.getPresenceKey(aciServiceIdentifier, deviceId);
|
||||
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;
|
||||
this.clock = clock;
|
||||
|
||||
// Not all epochs may be in use (this is true most of the time) and if we DO have multiple epochs in play, it's
|
||||
// possible/likely that a given queue will be on the same shard in multiple epochs. We only want acknowledgement
|
||||
// buffer per distinct shard, so find the distinct shards for this queue and create a buffer for each.
|
||||
this.acknowledgedMessageBuffersByDatabase = Arrays.stream(databasesByEpoch)
|
||||
.filter(Objects::nonNull)
|
||||
.distinct()
|
||||
.collect(Collectors.toMap(database -> database,
|
||||
_ -> new AcknowledgedMessageBuffer(maxUnacknowledgedMessages),
|
||||
(_, _) -> {
|
||||
throw new AssertionError("Duplicate database in distinct stream");
|
||||
},
|
||||
IdentityHashMap::new));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -121,25 +99,13 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
/// first to keep track of versionstamps sent to the client.
|
||||
private Flux<MessageStreamEntry> createMessagePublisher() {
|
||||
return createFoundationDbMessagePublisher()
|
||||
.<FoundationDbMessageStreamEntry>handle((messageStreamEntry, sink) -> {
|
||||
if (messageStreamEntry instanceof final FoundationDbMessageStreamEntry.Message message) {
|
||||
try {
|
||||
getAcknowledgedMessageBuffer(message.versionstamp()).addUnacknowledgedMessage(message.versionstamp());
|
||||
} catch (final TooManyUnacknowledgedMessagesException e) {
|
||||
sink.error(e);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
sink.next(messageStreamEntry);
|
||||
})
|
||||
.map(fdbMessageStreamEntry -> fdbMessageStreamEntry.toMessageStreamEntry(messageGuidCodec))
|
||||
.doOnNext(messageStreamEntry -> {
|
||||
if (messageStreamEntry instanceof MessageStreamEntry.Envelope) {
|
||||
messageReadCounter.increment();
|
||||
}
|
||||
})
|
||||
.doFinally(_ -> flushAllAcknowledgedMessages().thenRun(doAfterCleanup));
|
||||
.doFinally(_ -> doAfterCleanup.run());
|
||||
}
|
||||
|
||||
/// Create a message publisher that fetches messages from FoundationDB
|
||||
@@ -160,7 +126,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 -> {
|
||||
@@ -175,15 +141,16 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
database,
|
||||
clock,
|
||||
KeySelector.firstGreaterOrEqual(deviceQueueSubspace.range().begin),
|
||||
endOfQueueKeyExclusive,
|
||||
maxMessagesPerScan,
|
||||
() -> this.clearAcknowledgedMessages(database))
|
||||
endOfQueueKeyExclusive)
|
||||
.getMessages())
|
||||
.orElseGet(Flux::empty)
|
||||
.handle((fdbMessageStreamEntry, sink) -> {
|
||||
final MessageProtos.Envelope partialEnvelope = fdbMessageStreamEntry.partialEnvelope();
|
||||
|
||||
// Ephemeral messages from the finite stream are considered stale and automatically discarded
|
||||
if (fdbMessageStreamEntry.partialEnvelope().getEphemeral()) {
|
||||
acknowledgedMessageBuffersByDatabase.get(database).acknowledgeStaleEphemeralMessage(fdbMessageStreamEntry.versionstamp());
|
||||
if (partialEnvelope.getEphemeral()) {
|
||||
foundationDbMessageStore.delete(aciServiceIdentifier, deviceId, fdbMessageStreamEntry.versionstamp());
|
||||
|
||||
staleEphemeralMessagesCounter.increment();
|
||||
return;
|
||||
}
|
||||
@@ -206,16 +173,14 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
clock,
|
||||
infinitePublisherBeginKey,
|
||||
KeySelector.firstGreaterThan(deviceQueueSubspace.range().end),
|
||||
maxMessagesPerScan,
|
||||
presenceKey,
|
||||
presenceRenewalExecutorService,
|
||||
messagesAvailableWatchKey,
|
||||
() -> clearAcknowledgedMessages(database)).getMessages();
|
||||
messagesAvailableWatchKey).getMessages();
|
||||
})
|
||||
.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
|
||||
@@ -226,7 +191,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));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -236,74 +201,26 @@ 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 -> transaction.getRange(deviceQueueSubspace.range(), 1, true, StreamingMode.EXACT).asList()
|
||||
.thenApply(items -> {
|
||||
if (items.isEmpty()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
assert items.size() == 1;
|
||||
return Optional.of(KeySelector.firstGreaterThan(items.getFirst().getKey()));
|
||||
}));
|
||||
return FoundationDbUtil.safeRunAsync(database, transaction ->
|
||||
transaction.getRange(deviceQueueSubspace.range(), 1, true, StreamingMode.EXACT).asList())
|
||||
.<Optional<KeySelector>>thenApply(items -> {
|
||||
if (items.isEmpty()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
assert items.size() == 1;
|
||||
return Optional.of(KeySelector.firstGreaterThan(items.getFirst().getKey()));
|
||||
})
|
||||
.whenComplete((_, throwable) -> {
|
||||
if (throwable != null) {
|
||||
logger.warn("Failed to fetch end-of-queue key", throwable);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> acknowledgeMessage(final UUID messageGuid, final long serverTimestamp) {
|
||||
final Versionstamp versionstamp = messageGuidCodec.decodeMessageGuid(messageGuid);
|
||||
getAcknowledgedMessageBuffer(versionstamp).acknowledgeMessage(versionstamp);
|
||||
|
||||
messageAcknowledgedCounter.increment();
|
||||
|
||||
return CompletableFuture.completedFuture(null);
|
||||
}
|
||||
|
||||
/// Clear the versionstamp range (startInclusive, endInclusive) in a single FoundationDB operation.
|
||||
///
|
||||
/// @param transaction The FoundationDB transaction in which to perform the range clear
|
||||
/// @param startInclusive The starting versionstamp of the range to be cleared (inclusive)
|
||||
/// @param endInclusive The ending versionstamp of the range to be cleared (inclusive)
|
||||
private void clearRange(final Transaction transaction, final Versionstamp startInclusive, final Versionstamp endInclusive) {
|
||||
final byte[] startKeyInclusive = deviceQueueSubspace.pack(Tuple.from(startInclusive));
|
||||
final byte[] endKeyExclusive = ByteArrayUtil.keyAfter(deviceQueueSubspace.pack(Tuple.from(endInclusive)));
|
||||
transaction.clear(startKeyInclusive, endKeyExclusive);
|
||||
}
|
||||
|
||||
/// Clear all outstanding acknowledged messages. Called when the stream ends
|
||||
private CompletableFuture<Void> flushAllAcknowledgedMessages() {
|
||||
return CompletableFuture.allOf(Arrays.stream(databasesByEpoch)
|
||||
.filter(Objects::nonNull)
|
||||
.distinct()
|
||||
.map(database -> {
|
||||
final Consumer<Transaction> clearAllAcknowlegedMessagedConsumer = clearAcknowledgedMessages(database);
|
||||
|
||||
return database.runAsync(transaction -> {
|
||||
clearAllAcknowlegedMessagedConsumer.accept(transaction);
|
||||
return CompletableFuture.completedFuture((Void) null);
|
||||
})
|
||||
.whenComplete((_, throwable) -> {
|
||||
if (throwable != null) {
|
||||
LOGGER.warn("Failed to clear acknowledged messages", throwable);
|
||||
}
|
||||
});
|
||||
})
|
||||
.toArray(CompletableFuture[]::new));
|
||||
}
|
||||
|
||||
private AcknowledgedMessageBuffer getAcknowledgedMessageBuffer(final Versionstamp versionstamp) {
|
||||
final int epoch = FoundationDbMessageStore.getConfigurationEpoch(versionstamp);
|
||||
final Database database = databasesByEpoch[epoch];
|
||||
|
||||
if (database == null) {
|
||||
throw new IllegalStateException("Read message for unrecognized epoch");
|
||||
}
|
||||
|
||||
return acknowledgedMessageBuffersByDatabase.get(database);
|
||||
}
|
||||
|
||||
private synchronized Consumer<Transaction> clearAcknowledgedMessages(final Database database) {
|
||||
final List<Pair<Versionstamp, Versionstamp>> flushableRanges =
|
||||
acknowledgedMessageBuffersByDatabase.get(database).takeFlushableRanges();
|
||||
|
||||
return transaction -> flushableRanges.forEach(range -> clearRange(transaction, range.first(), range.second()));
|
||||
return foundationDbMessageStore.delete(aciServiceIdentifier, deviceId, messageGuid);
|
||||
}
|
||||
}
|
||||
+24
@@ -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());
|
||||
}
|
||||
}
|
||||
+59
-81
@@ -36,7 +36,7 @@ import com.braintree.graphql.clientoperation.CreatePayPalOneTimePaymentMutation;
|
||||
import com.braintree.graphql.clientoperation.TokenizePayPalBillingAgreementMutation;
|
||||
import com.braintree.graphql.clientoperation.TokenizePayPalOneTimePaymentMutation;
|
||||
import com.braintree.graphql.clientoperation.VaultPaymentMethodMutation;
|
||||
import jakarta.ws.rs.ServiceUnavailableException;
|
||||
import java.io.IOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
@@ -44,7 +44,6 @@ import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import okio.Buffer;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@@ -69,7 +68,7 @@ class BraintreeGraphqlClient {
|
||||
this.httpClient = httpClient;
|
||||
try {
|
||||
this.graphqlUri = new URI(graphqlUri);
|
||||
} catch (URISyntaxException e) {
|
||||
} catch (final URISyntaxException e) {
|
||||
throw new IllegalArgumentException("Invalid URI", e);
|
||||
}
|
||||
// “public”/“private” key is a bit of a misnomer, but we follow the upstream nomenclature
|
||||
@@ -77,36 +76,32 @@ class BraintreeGraphqlClient {
|
||||
this.authorizationHeader = "Basic " + Base64.getEncoder().encodeToString((publicKey + ":" + privateKey).getBytes());
|
||||
}
|
||||
|
||||
CompletableFuture<CreatePayPalOneTimePaymentMutation.CreatePayPalOneTimePayment> createPayPalOneTimePayment(
|
||||
CreatePayPalOneTimePaymentMutation.CreatePayPalOneTimePayment createPayPalOneTimePayment(
|
||||
final BigDecimal amount, final String currency, final String returnUrl,
|
||||
final String cancelUrl, final String locale, final String localizedLineItemName) {
|
||||
final String cancelUrl, final String locale, final String localizedLineItemName) throws IOException {
|
||||
|
||||
final CreatePayPalOneTimePaymentInput input = buildCreatePayPalOneTimePaymentInput(amount, currency, returnUrl,
|
||||
cancelUrl, locale, localizedLineItemName);
|
||||
final CreatePayPalOneTimePaymentMutation mutation = new CreatePayPalOneTimePaymentMutation(input);
|
||||
final HttpRequest request = buildRequest(mutation);
|
||||
|
||||
return httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString())
|
||||
.thenApply(httpResponse ->
|
||||
{
|
||||
// IntelliJ users: type parameters error “no instance of type variable exists so that Data conforms to Data”
|
||||
// is not accurate; this might be fixed in Kotlin 1.8: https://youtrack.jetbrains.com/issue/KTIJ-21905/
|
||||
final ApolloResponse<CreatePayPalOneTimePaymentMutation.Data> apolloResponse =
|
||||
extractApolloResponse(httpResponse, mutation);
|
||||
final CreatePayPalOneTimePaymentMutation.Data data = assertSuccessAndExtractDataFromApolloResponse(apolloResponse);
|
||||
if (data.createPayPalOneTimePayment == null) {
|
||||
logger.warn(
|
||||
"createPayPalOneTimePayment requestId={} currency={} amount={} did not have any errors but data was null. response={}",
|
||||
apolloResponse.extensions.getOrDefault("requestId", "<No-Request-Id>"),
|
||||
currency, amount, httpResponse.body());
|
||||
throw new ServiceUnavailableException();
|
||||
}
|
||||
return data.createPayPalOneTimePayment;
|
||||
});
|
||||
final HttpResponse<String> httpResponse = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
final ApolloResponse<CreatePayPalOneTimePaymentMutation.Data> apolloResponse =
|
||||
extractApolloResponse(httpResponse, mutation);
|
||||
final CreatePayPalOneTimePaymentMutation.Data data = assertSuccessAndExtractDataFromApolloResponse(apolloResponse);
|
||||
if (data.createPayPalOneTimePayment == null) {
|
||||
logger.warn(
|
||||
"createPayPalOneTimePayment requestId={} currency={} amount={} did not have any errors but data was null. response={}",
|
||||
apolloResponse.extensions.getOrDefault("requestId", "<No-Request-Id>"),
|
||||
currency, amount, httpResponse.body());
|
||||
throw new IOException();
|
||||
}
|
||||
return data.createPayPalOneTimePayment;
|
||||
|
||||
}
|
||||
|
||||
private static CreatePayPalOneTimePaymentInput buildCreatePayPalOneTimePaymentInput(BigDecimal amount,
|
||||
String currency, String returnUrl, String cancelUrl, String locale, String localizedLineItemName) {
|
||||
private static CreatePayPalOneTimePaymentInput buildCreatePayPalOneTimePaymentInput(final BigDecimal amount,
|
||||
final String currency, final String returnUrl, final String cancelUrl, final String locale, final String localizedLineItemName) {
|
||||
|
||||
// Note locale and localizedLineItemName are a best-effort, and it's possible that they will not match.
|
||||
// We could try to align with the locales PayPal documents <https://developer.paypal.com/reference/locale-codes/#supported-locale-codes>
|
||||
@@ -148,8 +143,8 @@ class BraintreeGraphqlClient {
|
||||
);
|
||||
}
|
||||
|
||||
CompletableFuture<TokenizePayPalOneTimePaymentMutation.TokenizePayPalOneTimePayment> tokenizePayPalOneTimePayment(
|
||||
final String payerId, final String paymentId, final String paymentToken) {
|
||||
TokenizePayPalOneTimePaymentMutation.TokenizePayPalOneTimePayment tokenizePayPalOneTimePayment(
|
||||
final String payerId, final String paymentId, final String paymentToken) throws IOException {
|
||||
|
||||
final TokenizePayPalOneTimePaymentInput input = new TokenizePayPalOneTimePaymentInput(
|
||||
Optional.absent(),
|
||||
@@ -159,18 +154,15 @@ class BraintreeGraphqlClient {
|
||||
|
||||
final TokenizePayPalOneTimePaymentMutation mutation = new TokenizePayPalOneTimePaymentMutation(input);
|
||||
final HttpRequest request = buildRequest(mutation);
|
||||
final HttpResponse<String> httpResponse = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
return httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString())
|
||||
.thenApply(httpResponse -> {
|
||||
// IntelliJ users: type parameters error “no instance of type variable exists so that Data conforms to Data”
|
||||
// is not accurate; this might be fixed in Kotlin 1.8: https://youtrack.jetbrains.com/issue/KTIJ-21905/
|
||||
final TokenizePayPalOneTimePaymentMutation.Data data = assertSuccessAndExtractData(httpResponse, mutation);
|
||||
return data.tokenizePayPalOneTimePayment;
|
||||
});
|
||||
final TokenizePayPalOneTimePaymentMutation.Data data = assertSuccessAndExtractData(httpResponse, mutation);
|
||||
return data.tokenizePayPalOneTimePayment;
|
||||
}
|
||||
|
||||
CompletableFuture<ChargePayPalOneTimePaymentMutation.ChargePaymentMethod> chargeOneTimePayment(
|
||||
final String paymentMethodId, final BigDecimal amount, final String merchantAccount, final long level) {
|
||||
ChargePayPalOneTimePaymentMutation.ChargePaymentMethod chargeOneTimePayment(
|
||||
final String paymentMethodId, final BigDecimal amount, final String merchantAccount, final long level)
|
||||
throws IOException {
|
||||
|
||||
final List<CustomFieldInput> customFields = List.of(
|
||||
new CustomFieldInput("level", Optional.present(Long.toString(level))));
|
||||
@@ -180,18 +172,14 @@ class BraintreeGraphqlClient {
|
||||
final ChargePayPalOneTimePaymentMutation mutation = new ChargePayPalOneTimePaymentMutation(input);
|
||||
final HttpRequest request = buildRequest(mutation);
|
||||
|
||||
return httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString())
|
||||
.thenApply(httpResponse -> {
|
||||
// IntelliJ users: type parameters error “no instance of type variable exists so that Data conforms to Data”
|
||||
// is not accurate; this might be fixed in Kotlin 1.8: https://youtrack.jetbrains.com/issue/KTIJ-21905/
|
||||
final ChargePayPalOneTimePaymentMutation.Data data = assertSuccessAndExtractData(httpResponse,
|
||||
mutation);
|
||||
return data.chargePaymentMethod;
|
||||
});
|
||||
final HttpResponse<String> httpResponse = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
final ChargePayPalOneTimePaymentMutation.Data data = assertSuccessAndExtractData(httpResponse,
|
||||
mutation);
|
||||
return data.chargePaymentMethod;
|
||||
}
|
||||
|
||||
private static ChargePaymentMethodInput buildChargePaymentMethodInput(String paymentMethodId, BigDecimal amount,
|
||||
String merchantAccount, List<CustomFieldInput> customFields) {
|
||||
private static ChargePaymentMethodInput buildChargePaymentMethodInput(final String paymentMethodId, final BigDecimal amount,
|
||||
final String merchantAccount, final List<CustomFieldInput> customFields) {
|
||||
|
||||
return new ChargePaymentMethodInput(
|
||||
Optional.absent(),
|
||||
@@ -221,25 +209,21 @@ class BraintreeGraphqlClient {
|
||||
);
|
||||
}
|
||||
|
||||
public CompletableFuture<CreatePayPalBillingAgreementMutation.CreatePayPalBillingAgreement> createPayPalBillingAgreement(
|
||||
final String returnUrl, final String cancelUrl, final String locale) {
|
||||
public CreatePayPalBillingAgreementMutation.CreatePayPalBillingAgreement createPayPalBillingAgreement(
|
||||
final String returnUrl, final String cancelUrl, final String locale) throws IOException {
|
||||
|
||||
final CreatePayPalBillingAgreementInput input = buildCreatePayPalBillingAgreementInput(returnUrl, cancelUrl,
|
||||
locale);
|
||||
final CreatePayPalBillingAgreementMutation mutation = new CreatePayPalBillingAgreementMutation(input);
|
||||
final HttpRequest request = buildRequest(mutation);
|
||||
|
||||
return httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString())
|
||||
.thenApply(httpResponse -> {
|
||||
// IntelliJ users: type parameters error “no instance of type variable exists so that Data conforms to Data”
|
||||
// is not accurate; this might be fixed in Kotlin 1.8: https://youtrack.jetbrains.com/issue/KTIJ-21905/
|
||||
final CreatePayPalBillingAgreementMutation.Data data = assertSuccessAndExtractData(httpResponse, mutation);
|
||||
return data.createPayPalBillingAgreement;
|
||||
});
|
||||
final HttpResponse<String> httpResponse = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
final CreatePayPalBillingAgreementMutation.Data data = assertSuccessAndExtractData(httpResponse, mutation);
|
||||
return data.createPayPalBillingAgreement;
|
||||
}
|
||||
|
||||
private static CreatePayPalBillingAgreementInput buildCreatePayPalBillingAgreementInput(String returnUrl,
|
||||
String cancelUrl, String locale) {
|
||||
private static CreatePayPalBillingAgreementInput buildCreatePayPalBillingAgreementInput(final String returnUrl,
|
||||
final String cancelUrl, final String locale) {
|
||||
|
||||
return new CreatePayPalBillingAgreementInput(
|
||||
Optional.absent(),
|
||||
@@ -263,8 +247,8 @@ class BraintreeGraphqlClient {
|
||||
);
|
||||
}
|
||||
|
||||
public CompletableFuture<TokenizePayPalBillingAgreementMutation.TokenizePayPalBillingAgreement> tokenizePayPalBillingAgreement(
|
||||
final String billingAgreementToken) {
|
||||
public TokenizePayPalBillingAgreementMutation.TokenizePayPalBillingAgreement tokenizePayPalBillingAgreement(
|
||||
final String billingAgreementToken) throws IOException {
|
||||
|
||||
final TokenizePayPalBillingAgreementInput input = new TokenizePayPalBillingAgreementInput(
|
||||
Optional.absent(),
|
||||
@@ -272,32 +256,24 @@ class BraintreeGraphqlClient {
|
||||
final TokenizePayPalBillingAgreementMutation mutation = new TokenizePayPalBillingAgreementMutation(input);
|
||||
final HttpRequest request = buildRequest(mutation);
|
||||
|
||||
return httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString())
|
||||
.thenApply(httpResponse -> {
|
||||
// IntelliJ users: type parameters error “no instance of type variable exists so that Data conforms to Data”
|
||||
// is not accurate; this might be fixed in Kotlin 1.8: https://youtrack.jetbrains.com/issue/KTIJ-21905/
|
||||
final TokenizePayPalBillingAgreementMutation.Data data = assertSuccessAndExtractData(httpResponse, mutation);
|
||||
return data.tokenizePayPalBillingAgreement;
|
||||
});
|
||||
final HttpResponse<String> httpResponse = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
final TokenizePayPalBillingAgreementMutation.Data data = assertSuccessAndExtractData(httpResponse, mutation);
|
||||
return data.tokenizePayPalBillingAgreement;
|
||||
}
|
||||
|
||||
public CompletableFuture<VaultPaymentMethodMutation.VaultPaymentMethod> vaultPaymentMethod(final String customerId,
|
||||
final String paymentMethodId) {
|
||||
public VaultPaymentMethodMutation.VaultPaymentMethod vaultPaymentMethod(final String customerId,
|
||||
final String paymentMethodId) throws IOException {
|
||||
|
||||
final VaultPaymentMethodInput input = buildVaultPaymentMethodInput(customerId, paymentMethodId);
|
||||
final VaultPaymentMethodMutation mutation = new VaultPaymentMethodMutation(input);
|
||||
final HttpRequest request = buildRequest(mutation);
|
||||
|
||||
return httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString())
|
||||
.thenApply(httpResponse -> {
|
||||
// IntelliJ users: type parameters error “no instance of type variable exists so that Data conforms to Data”
|
||||
// is not accurate; this might be fixed in Kotlin 1.8: https://youtrack.jetbrains.com/issue/KTIJ-21905/
|
||||
final VaultPaymentMethodMutation.Data data = assertSuccessAndExtractData(httpResponse, mutation);
|
||||
return data.vaultPaymentMethod;
|
||||
});
|
||||
final HttpResponse<String> httpResponse = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
final VaultPaymentMethodMutation.Data data = assertSuccessAndExtractData(httpResponse, mutation);
|
||||
return data.vaultPaymentMethod;
|
||||
}
|
||||
|
||||
private static VaultPaymentMethodInput buildVaultPaymentMethodInput(String customerId, String paymentMethodId) {
|
||||
private static VaultPaymentMethodInput buildVaultPaymentMethodInput(final String customerId, final String paymentMethodId) {
|
||||
return new VaultPaymentMethodInput(
|
||||
Optional.absent(),
|
||||
paymentMethodId,
|
||||
@@ -311,26 +287,28 @@ class BraintreeGraphqlClient {
|
||||
|
||||
/**
|
||||
* Verifies that the HTTP response has a {@code 200} status code and the GraphQL response has no errors, otherwise
|
||||
* throws a {@link ServiceUnavailableException}.
|
||||
* throws a {@link IOException}.
|
||||
*/
|
||||
private static <T extends Operation<U>, U extends Operation.Data> U assertSuccessAndExtractData(
|
||||
HttpResponse<String> httpResponse, T operation) {
|
||||
final HttpResponse<String> httpResponse, final T operation) throws IOException {
|
||||
return assertSuccessAndExtractDataFromApolloResponse(extractApolloResponse(httpResponse, operation));
|
||||
}
|
||||
|
||||
private static <T extends Operation<U>, U extends Operation.Data> ApolloResponse<U> extractApolloResponse(
|
||||
HttpResponse<String> httpResponse, T operation) {
|
||||
final HttpResponse<String> httpResponse, final T operation) throws IOException {
|
||||
|
||||
if (httpResponse.statusCode() != 200) {
|
||||
logger.warn("Received HTTP response status {} ({})", httpResponse.statusCode(),
|
||||
httpResponse.headers().firstValue("paypal-debug-id").orElse("<debug id absent>"));
|
||||
throw new ServiceUnavailableException();
|
||||
throw new IOException();
|
||||
}
|
||||
|
||||
return Operations.parseJsonResponse(operation, httpResponse.body());
|
||||
}
|
||||
|
||||
private static <T extends Operation<U>, U extends Operation.Data> U assertSuccessAndExtractDataFromApolloResponse(final ApolloResponse<U> response) {
|
||||
private static <T extends Operation<U>, U extends Operation.Data> U assertSuccessAndExtractDataFromApolloResponse(
|
||||
final ApolloResponse<U> response)
|
||||
throws IOException {
|
||||
if (response.hasErrors() || response.data == null) {
|
||||
//noinspection ConstantConditions
|
||||
response.errors.forEach(
|
||||
@@ -342,7 +320,7 @@ class BraintreeGraphqlClient {
|
||||
response.operation.name(), error.getMessage(), legacyCode);
|
||||
});
|
||||
|
||||
throw new ServiceUnavailableException();
|
||||
throw new IOException();
|
||||
}
|
||||
|
||||
return response.data;
|
||||
|
||||
+114
-113
@@ -5,7 +5,11 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
|
||||
import com.braintree.graphql.clientoperation.ChargePayPalOneTimePaymentMutation;
|
||||
import com.braintree.graphql.clientoperation.CreatePayPalBillingAgreementMutation;
|
||||
import com.braintree.graphql.clientoperation.CreatePayPalOneTimePaymentMutation;
|
||||
import com.braintree.graphql.clientoperation.TokenizePayPalBillingAgreementMutation;
|
||||
import com.braintree.graphql.clientoperation.TokenizePayPalOneTimePaymentMutation;
|
||||
import com.braintree.graphql.clientoperation.VaultPaymentMethodMutation;
|
||||
import com.braintreegateway.BraintreeGateway;
|
||||
import com.braintreegateway.ClientTokenRequest;
|
||||
@@ -36,7 +40,6 @@ import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Executor;
|
||||
import javax.annotation.Nullable;
|
||||
import org.slf4j.Logger;
|
||||
@@ -45,7 +48,6 @@ import org.whispersystems.textsecuregcm.currency.CurrencyConversionManager;
|
||||
import org.whispersystems.textsecuregcm.http.FaultTolerantHttpClient;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.PaymentTime;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.ExecutorUtil;
|
||||
import org.whispersystems.textsecuregcm.util.GoogleApiUtil;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
@@ -128,92 +130,88 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
return paymentMethod == PaymentMethod.PAYPAL;
|
||||
}
|
||||
|
||||
public CompletableFuture<Optional<PaymentDetails>> getPaymentDetails(final String paymentId) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
try {
|
||||
final Transaction transaction = braintreeGateway.transaction().find(paymentId);
|
||||
ChargeFailure chargeFailure = null;
|
||||
if (!getPaymentStatus(transaction.getStatus()).equals(PaymentStatus.SUCCEEDED)) {
|
||||
chargeFailure = createChargeFailure(transaction);
|
||||
}
|
||||
return Optional.of(new PaymentDetails(transaction.getGraphQLId(),
|
||||
transaction.getCustomFields(),
|
||||
getPaymentStatus(transaction.getStatus()),
|
||||
transaction.getCreatedAt().toInstant(),
|
||||
chargeFailure));
|
||||
|
||||
} catch (final NotFoundException e) {
|
||||
return Optional.empty();
|
||||
public Optional<PaymentDetails> getPaymentDetails(final String paymentId) {
|
||||
try {
|
||||
final Transaction transaction = braintreeGateway.transaction().find(paymentId);
|
||||
ChargeFailure chargeFailure = null;
|
||||
if (!getPaymentStatus(transaction.getStatus()).equals(PaymentStatus.SUCCEEDED)) {
|
||||
chargeFailure = createChargeFailure(transaction);
|
||||
}
|
||||
}, executor);
|
||||
return Optional.of(new PaymentDetails(transaction.getGraphQLId(),
|
||||
transaction.getCustomFields(),
|
||||
getPaymentStatus(transaction.getStatus()),
|
||||
transaction.getCreatedAt().toInstant(),
|
||||
chargeFailure));
|
||||
|
||||
} catch (final NotFoundException e) {
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
public CompletableFuture<PayPalOneTimePaymentApprovalDetails> createOneTimePayment(String currency, long amount,
|
||||
String locale, String returnUrl, String cancelUrl, String localizedLineItemname) {
|
||||
return braintreeGraphqlClient.createPayPalOneTimePayment(convertApiAmountToBraintreeAmount(currency, amount),
|
||||
currency.toUpperCase(Locale.ROOT), returnUrl,
|
||||
cancelUrl, locale, localizedLineItemname)
|
||||
.thenApply(result -> new PayPalOneTimePaymentApprovalDetails((String) result.approvalUrl, result.paymentId));
|
||||
public PayPalOneTimePaymentApprovalDetails createOneTimePayment(final String currency, final long amount,
|
||||
final String locale, final String returnUrl, final String cancelUrl, final String localizedLineItemName) throws IOException {
|
||||
final CreatePayPalOneTimePaymentMutation.CreatePayPalOneTimePayment result = braintreeGraphqlClient.createPayPalOneTimePayment(
|
||||
convertApiAmountToBraintreeAmount(currency, amount),
|
||||
currency.toUpperCase(Locale.ROOT), returnUrl,
|
||||
cancelUrl, locale, localizedLineItemName);
|
||||
return new PayPalOneTimePaymentApprovalDetails((String) result.approvalUrl, result.paymentId);
|
||||
}
|
||||
|
||||
public CompletableFuture<PayPalChargeSuccessDetails> captureOneTimePayment(String payerId, String paymentId,
|
||||
String paymentToken, String currency, long amount, long level, @Nullable ClientPlatform clientPlatform) {
|
||||
return braintreeGraphqlClient.tokenizePayPalOneTimePayment(payerId, paymentId, paymentToken)
|
||||
.thenCompose(response -> braintreeGraphqlClient.chargeOneTimePayment(
|
||||
response.paymentMethod.id,
|
||||
convertApiAmountToBraintreeAmount(currency, amount),
|
||||
currenciesToMerchantAccounts.get(currency.toLowerCase(Locale.ROOT)),
|
||||
level)
|
||||
.thenComposeAsync(chargeResponse -> {
|
||||
public PayPalChargeSuccessDetails captureOneTimePayment(final String payerId, final String paymentId,
|
||||
final String paymentToken, final String currency, final long amount, final long level, @Nullable final ClientPlatform clientPlatform)
|
||||
throws SubscriptionProcessorException, IOException {
|
||||
final TokenizePayPalOneTimePaymentMutation.TokenizePayPalOneTimePayment response = braintreeGraphqlClient.tokenizePayPalOneTimePayment(
|
||||
payerId, paymentId, paymentToken);
|
||||
final ChargePayPalOneTimePaymentMutation.ChargePaymentMethod chargeResponse = braintreeGraphqlClient.chargeOneTimePayment(
|
||||
response.paymentMethod.id,
|
||||
convertApiAmountToBraintreeAmount(currency, amount),
|
||||
currenciesToMerchantAccounts.get(currency.toLowerCase(Locale.ROOT)),
|
||||
level);
|
||||
|
||||
final PaymentStatus paymentStatus = getPaymentStatus(chargeResponse.transaction.status);
|
||||
if (paymentStatus == PaymentStatus.SUCCEEDED || paymentStatus == PaymentStatus.PROCESSING) {
|
||||
publishDonationEvent(amount, currency, Instant.now(), clientPlatform);
|
||||
return CompletableFuture.completedFuture(new PayPalChargeSuccessDetails(chargeResponse.transaction.id));
|
||||
}
|
||||
final PaymentStatus paymentStatus = getPaymentStatus(chargeResponse.transaction.status);
|
||||
if (paymentStatus == PaymentStatus.SUCCEEDED || paymentStatus == PaymentStatus.PROCESSING) {
|
||||
publishDonationEvent(amount, currency, Instant.now(), clientPlatform);
|
||||
return new PayPalChargeSuccessDetails(chargeResponse.transaction.id);
|
||||
}
|
||||
|
||||
// the GraphQL/Apollo interfaces are a tad unwieldy for this type of status checking
|
||||
final Transaction unsuccessfulTx = braintreeGateway.transaction().find(chargeResponse.transaction.id);
|
||||
// the GraphQL/Apollo interfaces are a tad unwieldy for this type of status checking
|
||||
final Transaction unsuccessfulTx = braintreeGateway.transaction().find(chargeResponse.transaction.id);
|
||||
|
||||
if (PAYPAL_PAYMENT_ALREADY_COMPLETED_PROCESSOR_CODE.equals(unsuccessfulTx.getProcessorResponseCode())
|
||||
|| Transaction.GatewayRejectionReason.DUPLICATE.equals(unsuccessfulTx.getGatewayRejectionReason())) {
|
||||
// the payment has already been charged - maybe a previous call timed out or was interrupted -
|
||||
// in any case, check for a successful transaction with the paymentId
|
||||
final ResourceCollection<Transaction> search = braintreeGateway.transaction()
|
||||
.search(new TransactionSearchRequest()
|
||||
.paypalPaymentId().is(paymentId)
|
||||
.status().in(
|
||||
Transaction.Status.SETTLED,
|
||||
Transaction.Status.SETTLING,
|
||||
Transaction.Status.SUBMITTED_FOR_SETTLEMENT,
|
||||
Transaction.Status.SETTLEMENT_PENDING
|
||||
)
|
||||
);
|
||||
if (PAYPAL_PAYMENT_ALREADY_COMPLETED_PROCESSOR_CODE.equals(unsuccessfulTx.getProcessorResponseCode())
|
||||
|| Transaction.GatewayRejectionReason.DUPLICATE.equals(unsuccessfulTx.getGatewayRejectionReason())) {
|
||||
// the payment has already been charged - maybe a previous call timed out or was interrupted -
|
||||
// in any case, check for a successful transaction with the paymentId
|
||||
final ResourceCollection<Transaction> search = braintreeGateway.transaction()
|
||||
.search(new TransactionSearchRequest()
|
||||
.paypalPaymentId().is(paymentId)
|
||||
.status().in(
|
||||
Transaction.Status.SETTLED,
|
||||
Transaction.Status.SETTLING,
|
||||
Transaction.Status.SUBMITTED_FOR_SETTLEMENT,
|
||||
Transaction.Status.SETTLEMENT_PENDING
|
||||
)
|
||||
);
|
||||
|
||||
if (search.getMaximumSize() == 0) {
|
||||
return CompletableFuture.failedFuture(ExceptionUtils.wrap(new IOException()));
|
||||
}
|
||||
if (search.getMaximumSize() == 0) {
|
||||
throw new IOException();
|
||||
}
|
||||
|
||||
final Transaction successfulTx = search.getFirst();
|
||||
final Transaction successfulTx = search.getFirst();
|
||||
|
||||
publishDonationEvent(amount, currency, successfulTx.getCreatedAt().toInstant(), clientPlatform);
|
||||
publishDonationEvent(amount, currency, successfulTx.getCreatedAt().toInstant(), clientPlatform);
|
||||
|
||||
return CompletableFuture.completedFuture(
|
||||
new PayPalChargeSuccessDetails(successfulTx.getGraphQLId()));
|
||||
}
|
||||
return new PayPalChargeSuccessDetails(successfulTx.getGraphQLId());
|
||||
}
|
||||
|
||||
return switch (unsuccessfulTx.getProcessorResponseCode()) {
|
||||
case GENERIC_DECLINED_PROCESSOR_CODE, PAYPAL_FUNDING_INSTRUMENT_DECLINED_PROCESSOR_CODE ->
|
||||
CompletableFuture.failedFuture(
|
||||
new SubscriptionProcessorException(getProvider(), createChargeFailure(unsuccessfulTx)));
|
||||
switch (unsuccessfulTx.getProcessorResponseCode()) {
|
||||
case GENERIC_DECLINED_PROCESSOR_CODE, PAYPAL_FUNDING_INSTRUMENT_DECLINED_PROCESSOR_CODE ->
|
||||
throw new SubscriptionProcessorException(getProvider(), createChargeFailure(unsuccessfulTx));
|
||||
|
||||
default -> {
|
||||
logger.info("PayPal charge unexpectedly failed: {}", unsuccessfulTx.getProcessorResponseCode());
|
||||
|
||||
yield CompletableFuture.failedFuture(ExceptionUtils.wrap(new IOException()));
|
||||
}
|
||||
};
|
||||
}, executor));
|
||||
default -> {
|
||||
logger.info("PayPal charge unexpectedly failed: {}", unsuccessfulTx.getProcessorResponseCode());
|
||||
throw new IOException();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void publishDonationEvent(final long amount,
|
||||
@@ -264,7 +262,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
return amount.multiply(ONE_MILLION).longValueExact();
|
||||
}
|
||||
|
||||
private static PaymentStatus getPaymentStatus(Transaction.Status status) {
|
||||
private static PaymentStatus getPaymentStatus(final Transaction.Status status) {
|
||||
return switch (status) {
|
||||
case SETTLEMENT_CONFIRMED, SETTLING, SUBMITTED_FOR_SETTLEMENT, SETTLED -> PaymentStatus.SUCCEEDED;
|
||||
case AUTHORIZATION_EXPIRED, GATEWAY_REJECTED, PROCESSOR_DECLINED, SETTLEMENT_DECLINED, VOIDED, FAILED ->
|
||||
@@ -273,9 +271,9 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
};
|
||||
}
|
||||
|
||||
private static PaymentStatus getPaymentStatus(com.braintree.graphql.client.type.PaymentStatus status) {
|
||||
private static PaymentStatus getPaymentStatus(final com.braintree.graphql.client.type.PaymentStatus status) {
|
||||
try {
|
||||
Transaction.Status transactionStatus = Transaction.Status.valueOf(status.rawValue);
|
||||
final Transaction.Status transactionStatus = Transaction.Status.valueOf(status.rawValue);
|
||||
|
||||
return getPaymentStatus(transactionStatus);
|
||||
} catch (final Exception e) {
|
||||
@@ -283,7 +281,8 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
}
|
||||
}
|
||||
|
||||
private static SubscriptionStatus getSubscriptionStatus(final Subscription.Status status, final boolean latestTransactionFailed) {
|
||||
private static SubscriptionStatus getSubscriptionStatus(final Subscription.Status status,
|
||||
final boolean latestTransactionFailed) {
|
||||
return switch (status) {
|
||||
// Stripe returns a PAST_DUE status if the subscription's most recent payment failed.
|
||||
// This check ensures that Braintree is consistent with Stripe.
|
||||
@@ -316,7 +315,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
|
||||
@Override
|
||||
public ProcessorCustomer createCustomer(final byte[] subscriberUser, @Nullable final ClientPlatform clientPlatform) {
|
||||
CustomerRequest request = new CustomerRequest()
|
||||
final CustomerRequest request = new CustomerRequest()
|
||||
.customField("subscriber_user", HexFormat.of().formatHex(subscriberUser));
|
||||
|
||||
if (clientPlatform != null) {
|
||||
@@ -332,19 +331,19 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
|
||||
@Override
|
||||
public String createPaymentMethodSetupToken(final String customerId) {
|
||||
ClientTokenRequest request = new ClientTokenRequest().customerId(customerId);
|
||||
final ClientTokenRequest request = new ClientTokenRequest().customerId(customerId);
|
||||
|
||||
return braintreeGateway.clientToken().generate(request);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setDefaultPaymentMethodForCustomer(String customerId, String billingAgreementToken,
|
||||
@Nullable String currentSubscriptionId) {
|
||||
public void setDefaultPaymentMethodForCustomer(final String customerId, final String billingAgreementToken,
|
||||
@Nullable final String currentSubscriptionId) throws IOException {
|
||||
final Optional<String> maybeSubscriptionId = Optional.ofNullable(currentSubscriptionId);
|
||||
final TokenizePayPalBillingAgreementMutation.TokenizePayPalBillingAgreement tokenizePayPalBillingAgreement =
|
||||
braintreeGraphqlClient.tokenizePayPalBillingAgreement(billingAgreementToken).join();
|
||||
braintreeGraphqlClient.tokenizePayPalBillingAgreement(billingAgreementToken);
|
||||
final VaultPaymentMethodMutation.VaultPaymentMethod vaultPaymentMethod =
|
||||
braintreeGraphqlClient.vaultPaymentMethod(customerId, tokenizePayPalBillingAgreement.paymentMethod.id).join();
|
||||
braintreeGraphqlClient.vaultPaymentMethod(customerId, tokenizePayPalBillingAgreement.paymentMethod.id);
|
||||
final Result<Customer> result = braintreeGateway.customer()
|
||||
.update(customerId, new CustomerRequest().defaultPaymentMethodToken(vaultPaymentMethod.paymentMethod.id));
|
||||
maybeSubscriptionId.ifPresent(subscriptionId ->
|
||||
@@ -353,13 +352,13 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getSubscription(String subscriptionId) {
|
||||
public Object getSubscription(final String subscriptionId) {
|
||||
return braintreeGateway.subscription().find(subscriptionId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public SubscriptionId createSubscription(String customerId, String planId, long level,
|
||||
long lastSubscriptionCreatedAt)
|
||||
public SubscriptionId createSubscription(final String customerId, final String planId, final long level,
|
||||
final long lastSubscriptionCreatedAt)
|
||||
throws SubscriptionProcessorConflictException, SubscriptionProcessorException {
|
||||
|
||||
final com.braintreegateway.PaymentMethod paymentMethod = getDefaultPaymentMethod(customerId);
|
||||
@@ -406,14 +405,15 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
return new SubscriptionId(result.getTarget().getId());
|
||||
}
|
||||
|
||||
private com.braintreegateway.PaymentMethod getDefaultPaymentMethod(String customerId) {
|
||||
private com.braintreegateway.PaymentMethod getDefaultPaymentMethod(final String customerId) {
|
||||
return braintreeGateway.customer().find(customerId).getDefaultPaymentMethod();
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public CustomerAwareSubscriptionPaymentProcessor.SubscriptionId updateSubscription(Object subscriptionObj, String planId, long level,
|
||||
String idempotencyKey) throws SubscriptionProcessorConflictException, SubscriptionProcessorException {
|
||||
public CustomerAwareSubscriptionPaymentProcessor.SubscriptionId updateSubscription(final Object subscriptionObj,
|
||||
final String planId, final long level,
|
||||
final String idempotencyKey) throws SubscriptionProcessorConflictException, SubscriptionProcessorException {
|
||||
|
||||
if (!(subscriptionObj instanceof final Subscription subscription)) {
|
||||
throw new IllegalArgumentException("invalid subscription object: " + subscriptionObj.getClass().getName());
|
||||
@@ -425,7 +425,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
endSubscription(subscription);
|
||||
|
||||
final Transaction transaction = getLatestTransactionForSubscription(subscription)
|
||||
.orElseThrow(() -> ExceptionUtils.wrap(new SubscriptionProcessorConflictException()));
|
||||
.orElseThrow(SubscriptionProcessorConflictException::new);
|
||||
|
||||
final Customer customer = transaction.getCustomer();
|
||||
|
||||
@@ -434,13 +434,13 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
}
|
||||
|
||||
@Override
|
||||
public LevelAndCurrency getLevelAndCurrencyForSubscription(Object subscriptionObj) {
|
||||
public LevelAndCurrency getLevelAndCurrencyForSubscription(final Object subscriptionObj) {
|
||||
final Subscription subscription = getSubscription(subscriptionObj);
|
||||
final Plan plan = findPlan(subscription.getPlanId());
|
||||
return new LevelAndCurrency(getLevelForPlan(plan), plan.getCurrencyIsoCode().toLowerCase(Locale.ROOT));
|
||||
}
|
||||
|
||||
private Plan findPlan(String planId) {
|
||||
private Plan findPlan(final String planId) {
|
||||
return braintreeGateway.plan().find(planId);
|
||||
}
|
||||
|
||||
@@ -449,7 +449,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
try {
|
||||
metadata = SystemMapper.jsonMapper().readValue(plan.getDescription(), BraintreePlanMetadata.class);
|
||||
|
||||
} catch (JsonProcessingException e) {
|
||||
} catch (final JsonProcessingException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
@@ -458,7 +458,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
|
||||
@Override
|
||||
public SubscriptionInformation getSubscriptionInformation(final String subscriptionId) {
|
||||
final Subscription subscription = getSubscription(getSubscription(subscriptionId));
|
||||
final Subscription subscription = getSubscription(getSubscription(subscriptionId));
|
||||
final Plan plan = braintreeGateway.plan().find(subscription.getPlanId());
|
||||
final long level = getLevelForPlan(plan);
|
||||
|
||||
@@ -500,11 +500,12 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
return new TransactionInfo(paymentMethod, paymentProcessing, false, null);
|
||||
}
|
||||
|
||||
private PaymentMethod getPaymentMethodFromTransaction(Transaction transaction) {
|
||||
private PaymentMethod getPaymentMethodFromTransaction(final Transaction transaction) {
|
||||
if (transaction.getPayPalDetails() != null) {
|
||||
return PaymentMethod.PAYPAL;
|
||||
}
|
||||
logger.error("Unexpected payment method from Braintree: {}, transaction id {}", transaction.getPaymentInstrumentType(), transaction.getId());
|
||||
logger.error("Unexpected payment method from Braintree: {}, transaction id {}",
|
||||
transaction.getPaymentInstrumentType(), transaction.getId());
|
||||
return PaymentMethod.UNKNOWN;
|
||||
}
|
||||
|
||||
@@ -512,7 +513,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
return status == Transaction.Status.SETTLEMENT_PENDING;
|
||||
}
|
||||
|
||||
private ChargeFailure createChargeFailure(Transaction transaction) {
|
||||
private ChargeFailure createChargeFailure(final Transaction transaction) {
|
||||
|
||||
final String code;
|
||||
final String message;
|
||||
@@ -539,7 +540,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
}
|
||||
|
||||
@Override
|
||||
public void cancelAllActiveSubscriptions(String customerId) {
|
||||
public void cancelAllActiveSubscriptions(final String customerId) {
|
||||
final Customer customer = braintreeGateway.customer().find(customerId);
|
||||
ExecutorUtil.runAll(executor, Optional.ofNullable(customer.getDefaultPaymentMethod())
|
||||
.stream()
|
||||
@@ -548,7 +549,7 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
.toList());
|
||||
}
|
||||
|
||||
private void endSubscription(Subscription subscription) {
|
||||
private void endSubscription(final Subscription subscription) {
|
||||
final boolean latestTransactionFailed = getLatestTransactionForSubscription(subscription)
|
||||
.map(this::getTransactionInfo)
|
||||
.map(TransactionInfo::transactionFailed)
|
||||
@@ -563,20 +564,20 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
}
|
||||
}
|
||||
|
||||
private void cancelSubscriptionAtEndOfCurrentPeriod(Subscription subscription) {
|
||||
private void cancelSubscriptionAtEndOfCurrentPeriod(final Subscription subscription) {
|
||||
braintreeGateway
|
||||
.subscription()
|
||||
.update(subscription.getId(),
|
||||
new SubscriptionRequest().numberOfBillingCycles(subscription.getCurrentBillingCycle()));
|
||||
}
|
||||
|
||||
private void cancelSubscriptionImmediately(Subscription subscription) {
|
||||
private void cancelSubscriptionImmediately(final Subscription subscription) {
|
||||
braintreeGateway.subscription().cancel(subscription.getId());
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public ReceiptItem getReceiptItem(String subscriptionId)
|
||||
public ReceiptItem getReceiptItem(final String subscriptionId)
|
||||
throws SubscriptionReceiptRequestedForOpenPaymentException, SubscriptionChargeFailurePaymentRequiredException {
|
||||
final Subscription subscription = getSubscription(getSubscription(subscriptionId));
|
||||
final Transaction transaction = getLatestTransactionForSubscription(subscription)
|
||||
@@ -597,31 +598,31 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess
|
||||
try {
|
||||
metadata = SystemMapper.jsonMapper().readValue(plan.getDescription(), BraintreePlanMetadata.class);
|
||||
|
||||
} catch (JsonProcessingException e) {
|
||||
} catch (final JsonProcessingException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
return new ReceiptItem(transaction.getId(), PaymentTime.periodStart(paidAt), metadata.level());
|
||||
}
|
||||
|
||||
private static Subscription getSubscription(Object subscriptionObj) {
|
||||
private static Subscription getSubscription(final Object subscriptionObj) {
|
||||
if (!(subscriptionObj instanceof final Subscription subscription)) {
|
||||
throw new IllegalArgumentException("Invalid subscription object: " + subscriptionObj.getClass().getName());
|
||||
}
|
||||
return subscription;
|
||||
}
|
||||
|
||||
private Optional<Transaction> getLatestTransactionForSubscription(Subscription subscription) {
|
||||
private Optional<Transaction> getLatestTransactionForSubscription(final Subscription subscription) {
|
||||
return subscription.getTransactions().stream()
|
||||
.max(Comparator.comparing(Transaction::getCreatedAt));
|
||||
.max(Comparator.comparing(Transaction::getCreatedAt));
|
||||
}
|
||||
|
||||
public CompletableFuture<PayPalBillingAgreementApprovalDetails> createPayPalBillingAgreement(final String returnUrl,
|
||||
final String cancelUrl, final String locale) {
|
||||
return braintreeGraphqlClient.createPayPalBillingAgreement(returnUrl, cancelUrl, locale)
|
||||
.thenApply(response ->
|
||||
new PayPalBillingAgreementApprovalDetails((String) response.approvalUrl, response.billingAgreementToken)
|
||||
);
|
||||
public PayPalBillingAgreementApprovalDetails createPayPalBillingAgreement(final String returnUrl,
|
||||
final String cancelUrl, final String locale)
|
||||
throws IOException {
|
||||
final CreatePayPalBillingAgreementMutation.CreatePayPalBillingAgreement response = braintreeGraphqlClient.createPayPalBillingAgreement(
|
||||
returnUrl, cancelUrl, locale);
|
||||
return new PayPalBillingAgreementApprovalDetails((String) response.approvalUrl, response.billingAgreementToken);
|
||||
}
|
||||
|
||||
public record PayPalBillingAgreementApprovalDetails(String approvalUrl, String billingAgreementToken) {
|
||||
|
||||
+4
-2
@@ -5,6 +5,7 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Set;
|
||||
import javax.annotation.Nullable;
|
||||
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
|
||||
@@ -41,10 +42,11 @@ public interface CustomerAwareSubscriptionPaymentProcessor extends SubscriptionP
|
||||
* {@link #createPaymentMethodSetupToken}
|
||||
* @param currentSubscriptionId (nullable) an active subscription ID, in case it needs an explicit update
|
||||
* @throws SubscriptionInvalidArgumentsException If the paymentMethodToken is invalid or the payment method has not
|
||||
* finished being set up
|
||||
* finished being set up
|
||||
* @throws IOException If there was an error talking to the external payment provider
|
||||
*/
|
||||
void setDefaultPaymentMethodForCustomer(String customerId, String paymentMethodToken,
|
||||
@Nullable String currentSubscriptionId) throws SubscriptionInvalidArgumentsException;
|
||||
@Nullable String currentSubscriptionId) throws SubscriptionInvalidArgumentsException, IOException;
|
||||
|
||||
Object getSubscription(String subscriptionId);
|
||||
|
||||
|
||||
-1
@@ -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");
|
||||
}
|
||||
|
||||
|
||||
+14
-1
@@ -24,5 +24,18 @@ public enum PaymentMethod {
|
||||
*/
|
||||
IDEAL,
|
||||
GOOGLE_PLAY_BILLING,
|
||||
APPLE_APP_STORE
|
||||
APPLE_APP_STORE;
|
||||
|
||||
|
||||
public org.signal.chat.purchase.PaymentMethod toProtoPaymentMethod() {
|
||||
return switch (this) {
|
||||
case CARD -> org.signal.chat.purchase.PaymentMethod.PAYMENT_METHOD_CARD;
|
||||
case SEPA_DEBIT -> org.signal.chat.purchase.PaymentMethod.PAYMENT_METHOD_SEPA_DEBIT;
|
||||
case IDEAL -> org.signal.chat.purchase.PaymentMethod.PAYMENT_METHOD_IDEAL;
|
||||
case PAYPAL -> org.signal.chat.purchase.PaymentMethod.PAYMENT_METHOD_PAYPAL;
|
||||
case GOOGLE_PLAY_BILLING -> org.signal.chat.purchase.PaymentMethod.PAYMENT_METHOD_GOOGLE_PLAY_BILLING;
|
||||
case APPLE_APP_STORE -> org.signal.chat.purchase.PaymentMethod.PAYMENT_METHOD_APPLE_APP_STORE;
|
||||
case UNKNOWN -> org.signal.chat.purchase.PaymentMethod.PAYMENT_METHOD_UNKNOWN;
|
||||
};
|
||||
}
|
||||
}
|
||||
+5
-5
@@ -48,12 +48,12 @@ public enum PaymentProvider {
|
||||
return id;
|
||||
}
|
||||
|
||||
public org.signal.chat.subscriptions.PaymentProvider toProto() {
|
||||
public org.signal.chat.purchase.PaymentProvider toProto() {
|
||||
return switch (this) {
|
||||
case STRIPE -> org.signal.chat.subscriptions.PaymentProvider.PAYMENT_PROVIDER_STRIPE;
|
||||
case BRAINTREE -> org.signal.chat.subscriptions.PaymentProvider.PAYMENT_PROVIDER_BRAINTREE;
|
||||
case GOOGLE_PLAY_BILLING -> org.signal.chat.subscriptions.PaymentProvider.PAYMENT_PROVIDER_GOOGLE_PLAY_BILLING;
|
||||
case APPLE_APP_STORE -> org.signal.chat.subscriptions.PaymentProvider.PAYMENT_PROVIDER_APPLE_APP_STORE;
|
||||
case STRIPE -> org.signal.chat.purchase.PaymentProvider.PAYMENT_PROVIDER_STRIPE;
|
||||
case BRAINTREE -> org.signal.chat.purchase.PaymentProvider.PAYMENT_PROVIDER_BRAINTREE;
|
||||
case GOOGLE_PLAY_BILLING -> org.signal.chat.purchase.PaymentProvider.PAYMENT_PROVIDER_GOOGLE_PLAY_BILLING;
|
||||
case APPLE_APP_STORE -> org.signal.chat.purchase.PaymentProvider.PAYMENT_PROVIDER_APPLE_APP_STORE;
|
||||
};
|
||||
}
|
||||
}
|
||||
+180
-180
@@ -62,11 +62,8 @@ import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.function.Consumer;
|
||||
import javax.annotation.Nonnull;
|
||||
import javax.annotation.Nullable;
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
@@ -76,11 +73,11 @@ import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerVersion;
|
||||
import org.whispersystems.textsecuregcm.storage.PaymentTime;
|
||||
import org.whispersystems.textsecuregcm.util.Conversions;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.ExecutorUtil;
|
||||
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
|
||||
|
||||
public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(StripeManager.class);
|
||||
private static final String METADATA_KEY_LEVEL = "level";
|
||||
private static final String METADATA_KEY_CLIENT_PLATFORM = "clientPlatform";
|
||||
@@ -93,12 +90,14 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
|
||||
@VisibleForTesting
|
||||
StripeManager(
|
||||
@Nonnull StripeClient stripeClient,
|
||||
@Nonnull Executor executor,
|
||||
@Nonnull byte[] idempotencyKeyGenerator,
|
||||
@Nonnull String boostDescription,
|
||||
@Nonnull Map<PaymentMethod, Set<String>> supportedCurrenciesByPaymentMethod) {
|
||||
final StripeClient stripeClient,
|
||||
final Executor executor,
|
||||
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);
|
||||
@@ -109,13 +108,15 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
this.boostDescription = Objects.requireNonNull(boostDescription);
|
||||
this.supportedCurrenciesByPaymentMethod = supportedCurrenciesByPaymentMethod;
|
||||
}
|
||||
|
||||
public StripeManager(
|
||||
@Nonnull String apiKey,
|
||||
@Nonnull Executor executor,
|
||||
@Nonnull byte[] idempotencyKeyGenerator,
|
||||
@Nonnull String boostDescription,
|
||||
@Nonnull Map<PaymentMethod, Set<String>> supportedCurrenciesByPaymentMethod) {
|
||||
this(new StripeClient(apiKey), executor, idempotencyKeyGenerator, boostDescription, supportedCurrenciesByPaymentMethod);
|
||||
final String apiKey,
|
||||
final Executor executor,
|
||||
final byte[] idempotencyKeyGenerator,
|
||||
final String boostDescription,
|
||||
final Map<PaymentMethod, Set<String>> supportedCurrenciesByPaymentMethod) {
|
||||
this(new StripeClient(apiKey), executor, idempotencyKeyGenerator, boostDescription,
|
||||
supportedCurrenciesByPaymentMethod);
|
||||
|
||||
if (StringUtils.isEmpty(apiKey)) {
|
||||
throw new IllegalArgumentException("apiKey cannot be empty");
|
||||
@@ -128,7 +129,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supportsPaymentMethod(PaymentMethod paymentMethod) {
|
||||
public boolean supportsPaymentMethod(final PaymentMethod paymentMethod) {
|
||||
return paymentMethod == PaymentMethod.CARD
|
||||
|| paymentMethod == PaymentMethod.SEPA_DEBIT
|
||||
|| paymentMethod == PaymentMethod.IDEAL;
|
||||
@@ -138,7 +139,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
return commonOptions(null);
|
||||
}
|
||||
|
||||
private RequestOptions commonOptions(@Nullable String idempotencyKey) {
|
||||
private RequestOptions commonOptions(@Nullable final String idempotencyKey) {
|
||||
return RequestOptions.builder()
|
||||
.setIdempotencyKey(idempotencyKey)
|
||||
.build();
|
||||
@@ -157,46 +158,46 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
final Customer customer = stripeClient.v1().customers()
|
||||
.create(builder.build(), commonOptions(generateIdempotencyKeyForSubscriberUser(subscriberUser)));
|
||||
return new ProcessorCustomer(customer.getId(), getProvider());
|
||||
} catch (StripeException e) {
|
||||
} catch (final StripeException e) {
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
}
|
||||
|
||||
public Customer getCustomer(String customerId) {
|
||||
CustomerRetrieveParams params = CustomerRetrieveParams.builder().build();
|
||||
public Customer getCustomer(final String customerId) {
|
||||
final CustomerRetrieveParams params = CustomerRetrieveParams.builder().build();
|
||||
try {
|
||||
return stripeClient.v1().customers().retrieve(customerId, params, commonOptions());
|
||||
} catch (StripeException e) {
|
||||
} catch (final StripeException e) {
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setDefaultPaymentMethodForCustomer(String customerId, String paymentMethodId,
|
||||
@Nullable String currentSubscriptionId) throws SubscriptionInvalidArgumentsException {
|
||||
CustomerUpdateParams params = CustomerUpdateParams.builder()
|
||||
.setInvoiceSettings(InvoiceSettings.builder()
|
||||
.setDefaultPaymentMethod(paymentMethodId)
|
||||
.build())
|
||||
.build();
|
||||
try {
|
||||
stripeClient.v1().customers().update(customerId, params, commonOptions());
|
||||
} catch (InvalidRequestException e) {
|
||||
// Could happen if the paymentMethodId was bunk or the client didn't actually finish setting it up
|
||||
throw new SubscriptionInvalidArgumentsException(e.getMessage());
|
||||
} catch (StripeException e) {
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
public void setDefaultPaymentMethodForCustomer(final String customerId, final String paymentMethodId,
|
||||
@Nullable final String currentSubscriptionId) throws SubscriptionInvalidArgumentsException {
|
||||
final CustomerUpdateParams params = CustomerUpdateParams.builder()
|
||||
.setInvoiceSettings(InvoiceSettings.builder()
|
||||
.setDefaultPaymentMethod(paymentMethodId)
|
||||
.build())
|
||||
.build();
|
||||
try {
|
||||
stripeClient.v1().customers().update(customerId, params, commonOptions());
|
||||
} catch (final InvalidRequestException e) {
|
||||
// Could happen if the paymentMethodId was bunk or the client didn't actually finish setting it up
|
||||
throw new SubscriptionInvalidArgumentsException(e.getMessage());
|
||||
} catch (final StripeException e) {
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String createPaymentMethodSetupToken(String customerId) {
|
||||
SetupIntentCreateParams params = SetupIntentCreateParams.builder()
|
||||
public String createPaymentMethodSetupToken(final String customerId) {
|
||||
final SetupIntentCreateParams params = SetupIntentCreateParams.builder()
|
||||
.setCustomer(customerId)
|
||||
.build();
|
||||
try {
|
||||
return stripeClient.v1().setupIntents().create(params, commonOptions()).getClientSecret();
|
||||
} catch (StripeException e) {
|
||||
} catch (final StripeException e) {
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
}
|
||||
@@ -207,70 +208,65 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a payment intent. May throw a {@link SubscriptionInvalidAmountException} if stripe rejects the
|
||||
* attempt if the amount is too large or too small
|
||||
* Creates a payment intent. May throw a {@link SubscriptionInvalidAmountException} if stripe rejects the attempt if
|
||||
* the amount is too large or too small
|
||||
*/
|
||||
public CompletableFuture<PaymentIntent> createPaymentIntent(final String currency,
|
||||
public PaymentIntent createPaymentIntent(final String currency,
|
||||
final long amount,
|
||||
final long level,
|
||||
@Nullable final ClientPlatform clientPlatform) {
|
||||
@Nullable final ClientPlatform clientPlatform) throws SubscriptionInvalidAmountException {
|
||||
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
final PaymentIntentCreateParams.Builder builder = PaymentIntentCreateParams.builder()
|
||||
.setAmount(amount)
|
||||
.setCurrency(currency.toLowerCase(Locale.ROOT))
|
||||
.setDescription(boostDescription)
|
||||
.setCaptureMethod(PaymentIntentCreateParams.CaptureMethod.AUTOMATIC)
|
||||
.putMetadata("level", Long.toString(level));
|
||||
final PaymentIntentCreateParams.Builder builder = PaymentIntentCreateParams.builder()
|
||||
.setAmount(amount)
|
||||
.setCurrency(currency.toLowerCase(Locale.ROOT))
|
||||
.setDescription(boostDescription)
|
||||
.setCaptureMethod(PaymentIntentCreateParams.CaptureMethod.AUTOMATIC)
|
||||
.putMetadata("level", Long.toString(level));
|
||||
|
||||
if (clientPlatform != null) {
|
||||
builder.putMetadata(METADATA_KEY_CLIENT_PLATFORM, clientPlatform.name().toLowerCase());
|
||||
if (clientPlatform != null) {
|
||||
builder.putMetadata(METADATA_KEY_CLIENT_PLATFORM, clientPlatform.name().toLowerCase());
|
||||
}
|
||||
|
||||
try {
|
||||
return stripeClient.v1().paymentIntents().create(builder.build(), commonOptions());
|
||||
} catch (final StripeException e) {
|
||||
final String errorCode = e.getCode() == null
|
||||
? "unknown"
|
||||
: e.getCode().toLowerCase(Locale.ROOT);
|
||||
switch (errorCode) {
|
||||
case "amount_too_small", "amount_too_large" -> throw new SubscriptionInvalidAmountException(errorCode);
|
||||
default -> throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
try {
|
||||
return stripeClient.v1().paymentIntents().create(builder.build(), commonOptions());
|
||||
} catch (StripeException e) {
|
||||
final String errorCode = e.getCode() == null
|
||||
? "unknown"
|
||||
: e.getCode().toLowerCase(Locale.ROOT);
|
||||
switch (errorCode) {
|
||||
case "amount_too_small","amount_too_large" ->
|
||||
throw ExceptionUtils.wrap(new SubscriptionInvalidAmountException(errorCode));
|
||||
default -> throw new CompletionException(e);
|
||||
}
|
||||
}
|
||||
}, executor);
|
||||
}
|
||||
}
|
||||
|
||||
public CompletableFuture<Optional<PaymentDetails>> getPaymentDetails(final String paymentIntentId) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
try {
|
||||
final PaymentIntent paymentIntent = getPaymentIntent(paymentIntentId);
|
||||
public Optional<PaymentDetails> getPaymentDetails(final String paymentIntentId) throws IOException {
|
||||
try {
|
||||
final PaymentIntent paymentIntent = getPaymentIntent(paymentIntentId);
|
||||
|
||||
ChargeFailure chargeFailure = null;
|
||||
if (paymentIntent.getLatestChargeObject() != null) {
|
||||
final Charge charge = paymentIntent.getLatestChargeObject();
|
||||
if (charge.getFailureCode() != null || charge.getFailureMessage() != null) {
|
||||
chargeFailure = createChargeFailure(charge);
|
||||
}
|
||||
}
|
||||
|
||||
return Optional.of(new PaymentDetails(paymentIntent.getId(),
|
||||
paymentIntent.getMetadata() == null ? Collections.emptyMap() : paymentIntent.getMetadata(),
|
||||
getPaymentStatusForStatus(paymentIntent.getStatus()),
|
||||
Instant.ofEpochSecond(paymentIntent.getCreated()),
|
||||
chargeFailure));
|
||||
} catch (StripeException e) {
|
||||
if (e.getStatusCode() == 404) {
|
||||
return Optional.empty();
|
||||
} else {
|
||||
throw new CompletionException(e);
|
||||
ChargeFailure chargeFailure = null;
|
||||
if (paymentIntent.getLatestChargeObject() != null) {
|
||||
final Charge charge = paymentIntent.getLatestChargeObject();
|
||||
if (charge.getFailureCode() != null || charge.getFailureMessage() != null) {
|
||||
chargeFailure = createChargeFailure(charge);
|
||||
}
|
||||
}
|
||||
}, executor);
|
||||
|
||||
return Optional.of(new PaymentDetails(paymentIntent.getId(),
|
||||
paymentIntent.getMetadata() == null ? Collections.emptyMap() : paymentIntent.getMetadata(),
|
||||
getPaymentStatusForStatus(paymentIntent.getStatus()),
|
||||
Instant.ofEpochSecond(paymentIntent.getCreated()),
|
||||
chargeFailure));
|
||||
} catch (final StripeException e) {
|
||||
if (e.getStatusCode() == 404) {
|
||||
return Optional.empty();
|
||||
} else {
|
||||
throw new IOException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static PaymentStatus getPaymentStatusForStatus(String status) {
|
||||
private static PaymentStatus getPaymentStatusForStatus(final String status) {
|
||||
return switch (status.toLowerCase(Locale.ROOT)) {
|
||||
case "processing" -> PaymentStatus.PROCESSING;
|
||||
case "succeeded" -> PaymentStatus.SUCCEEDED;
|
||||
@@ -283,13 +279,13 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
}
|
||||
|
||||
@Override
|
||||
public SubscriptionId createSubscription(String customerId, String priceId, long level,
|
||||
long lastSubscriptionCreatedAt)
|
||||
public SubscriptionId createSubscription(final String customerId, final String priceId, final long level,
|
||||
final long lastSubscriptionCreatedAt)
|
||||
throws SubscriptionProcessorException, SubscriptionInvalidIdempotencyKeyException,
|
||||
SubscriptionPaymentRequiresActionException {
|
||||
// this relies on Stripe's idempotency key to avoid creating more than one subscription if the client
|
||||
// retries this request
|
||||
SubscriptionCreateParams params = SubscriptionCreateParams.builder()
|
||||
final SubscriptionCreateParams params = SubscriptionCreateParams.builder()
|
||||
.setCustomer(customerId)
|
||||
.setOffSession(true)
|
||||
.setPaymentBehavior(SubscriptionCreateParams.PaymentBehavior.ERROR_IF_INCOMPLETE)
|
||||
@@ -307,11 +303,11 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
params,
|
||||
commonOptions(generateIdempotencyKeyForCreateSubscription(customerId, lastSubscriptionCreatedAt)));
|
||||
return new SubscriptionId(subscription.getId());
|
||||
} catch (IdempotencyException e) {
|
||||
} catch (final IdempotencyException e) {
|
||||
throw new SubscriptionInvalidIdempotencyKeyException(e.getStripeError().getMessage());
|
||||
} catch (CardException e) {
|
||||
} catch (final CardException e) {
|
||||
throw new SubscriptionProcessorException(getProvider(), createChargeFailureFromCardException(e));
|
||||
} catch (StripeException e) {
|
||||
} catch (final StripeException e) {
|
||||
if ("subscription_payment_intent_requires_action".equals(e.getCode())) {
|
||||
throw new SubscriptionPaymentRequiresActionException();
|
||||
}
|
||||
@@ -320,7 +316,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
}
|
||||
|
||||
@Override
|
||||
public SubscriptionId updateSubscription(Object subscriptionObj, String priceId, long level, String idempotencyKey)
|
||||
public SubscriptionId updateSubscription(final Object subscriptionObj, final String priceId, final long level, final String idempotencyKey)
|
||||
throws SubscriptionInvalidIdempotencyKeyException, SubscriptionPaymentRequiresActionException,
|
||||
SubscriptionProcessorException {
|
||||
|
||||
@@ -332,7 +328,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
return createSubscription(subscription.getCustomer(), priceId, level, subscription.getCreated());
|
||||
}
|
||||
|
||||
List<SubscriptionUpdateParams.Item> items = new ArrayList<>();
|
||||
final List<SubscriptionUpdateParams.Item> items = new ArrayList<>();
|
||||
try {
|
||||
final StripeCollection<SubscriptionItem> subscriptionItems = stripeClient.v1().subscriptionItems()
|
||||
.list(SubscriptionItemListParams.builder().setSubscription(subscription.getId()).build(),
|
||||
@@ -346,7 +342,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
items.add(SubscriptionUpdateParams.Item.builder()
|
||||
.setPrice(priceId)
|
||||
.build());
|
||||
SubscriptionUpdateParams params = SubscriptionUpdateParams.builder()
|
||||
final SubscriptionUpdateParams params = SubscriptionUpdateParams.builder()
|
||||
.putMetadata(METADATA_KEY_LEVEL, Long.toString(level))
|
||||
|
||||
// since badge redemption is untrackable by design and unrevokable, subscription changes must be immediate and
|
||||
@@ -360,56 +356,57 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
final Subscription subscription1 = stripeClient.v1().subscriptions().update(subscription.getId(), params,
|
||||
commonOptions(generateIdempotencyKeyForSubscriptionUpdate(subscription.getCustomer(), idempotencyKey)));
|
||||
return new SubscriptionId(subscription1.getId());
|
||||
} catch (IdempotencyException e) {
|
||||
} catch (final IdempotencyException e) {
|
||||
throw new SubscriptionInvalidIdempotencyKeyException(e.getStripeError().getMessage());
|
||||
} catch (CardException e) {
|
||||
} catch (final CardException e) {
|
||||
throw new SubscriptionProcessorException(getProvider(), createChargeFailureFromCardException(e));
|
||||
} catch (StripeException e) {
|
||||
} catch (final StripeException e) {
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
}
|
||||
|
||||
/// Retrieves the subscription object with `latest_invoice.payments` expanded
|
||||
@Override
|
||||
public Object getSubscription(String subscriptionId) {
|
||||
SubscriptionRetrieveParams params = SubscriptionRetrieveParams.builder()
|
||||
public Object getSubscription(final String subscriptionId) {
|
||||
final SubscriptionRetrieveParams params = SubscriptionRetrieveParams.builder()
|
||||
.addExpand("latest_invoice.payments")
|
||||
.build();
|
||||
try {
|
||||
return stripeClient.v1().subscriptions().retrieve(subscriptionId, params, commonOptions());
|
||||
} catch (StripeException e) {
|
||||
} catch (final StripeException e) {
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
}
|
||||
|
||||
/// Retrieves the payment intent object with `latest_charge` expanded
|
||||
public PaymentIntent getPaymentIntent(String paymentIntentId) throws StripeException {
|
||||
PaymentIntentRetrieveParams params = PaymentIntentRetrieveParams.builder()
|
||||
public PaymentIntent getPaymentIntent(final String paymentIntentId) throws StripeException {
|
||||
final PaymentIntentRetrieveParams params = PaymentIntentRetrieveParams.builder()
|
||||
.addExpand("latest_charge")
|
||||
.build();
|
||||
return stripeClient.v1().paymentIntents().retrieve(paymentIntentId, params, commonOptions());
|
||||
}
|
||||
|
||||
public Charge getCharge(String chargeId) {
|
||||
ChargeRetrieveParams params = ChargeRetrieveParams.builder()
|
||||
public Charge getCharge(final String chargeId) {
|
||||
final ChargeRetrieveParams params = ChargeRetrieveParams.builder()
|
||||
.build();
|
||||
try {
|
||||
return stripeClient.v1().charges().retrieve(chargeId, params, commonOptions());
|
||||
} catch (StripeException e) {
|
||||
} catch (final StripeException e) {
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void cancelAllActiveSubscriptions(String customerId) {
|
||||
public void cancelAllActiveSubscriptions(final String customerId) {
|
||||
final Customer customer = getCustomer(customerId);
|
||||
if (customer == null) {
|
||||
throw new UncheckedIOException(new IOException("no customer record found for id " + customerId));
|
||||
}
|
||||
if (StringUtils.isBlank(customer.getId()) || (!customer.getId().equals(customerId))) {
|
||||
logger.error("customer ID returned by Stripe ({}) did not match query ({})", customerId, customer.getSubscriptions());
|
||||
throw new UncheckedIOException(new IOException("unexpected customer ID returned by Stripe"));
|
||||
}
|
||||
if (customer == null) {
|
||||
throw new UncheckedIOException(new IOException("no customer record found for id " + customerId));
|
||||
}
|
||||
if (StringUtils.isBlank(customer.getId()) || (!customer.getId().equals(customerId))) {
|
||||
logger.error("customer ID returned by Stripe ({}) did not match query ({})", customerId,
|
||||
customer.getSubscriptions());
|
||||
throw new UncheckedIOException(new IOException("unexpected customer ID returned by Stripe"));
|
||||
}
|
||||
|
||||
final Collection<Subscription> subscriptions = listNonCanceledSubscriptions(customer);
|
||||
if (subscriptions.stream()
|
||||
@@ -423,20 +420,20 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
.toList());
|
||||
}
|
||||
|
||||
public Collection<Subscription> listNonCanceledSubscriptions(Customer customer) {
|
||||
SubscriptionListParams params = SubscriptionListParams.builder()
|
||||
public Collection<Subscription> listNonCanceledSubscriptions(final Customer customer) {
|
||||
final SubscriptionListParams params = SubscriptionListParams.builder()
|
||||
.setCustomer(customer.getId())
|
||||
.build();
|
||||
try {
|
||||
return Lists.newArrayList(
|
||||
stripeClient.v1().subscriptions().list(params, commonOptions()).autoPagingIterable());
|
||||
} catch (StripeException e) {
|
||||
} catch (final StripeException e) {
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
void endSubscription(Subscription subscription) {
|
||||
void endSubscription(final Subscription subscription) {
|
||||
|
||||
final SubscriptionStatus status = SubscriptionStatus.forApiValue(subscription.getStatus());
|
||||
switch (status) {
|
||||
@@ -459,30 +456,30 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
cancelSubscriptionAtEndOfCurrentPeriod(subscription);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
private void cancelSubscriptionImmediately(Subscription subscription) {
|
||||
SubscriptionCancelParams params = SubscriptionCancelParams.builder().build();
|
||||
private void cancelSubscriptionImmediately(final Subscription subscription) {
|
||||
final SubscriptionCancelParams params = SubscriptionCancelParams.builder().build();
|
||||
try {
|
||||
stripeClient.v1().subscriptions().cancel(subscription.getId(), params, commonOptions());
|
||||
} catch (StripeException e) {
|
||||
} catch (final StripeException e) {
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
}
|
||||
|
||||
private void cancelSubscriptionAtEndOfCurrentPeriod(Subscription subscription) {
|
||||
SubscriptionUpdateParams params = SubscriptionUpdateParams.builder()
|
||||
private void cancelSubscriptionAtEndOfCurrentPeriod(final Subscription subscription) {
|
||||
final SubscriptionUpdateParams params = SubscriptionUpdateParams.builder()
|
||||
.setCancelAtPeriodEnd(true)
|
||||
.build();
|
||||
try {
|
||||
stripeClient.v1().subscriptions().update(subscription.getId(), params, commonOptions());
|
||||
} catch (StripeException e) {
|
||||
} catch (final StripeException e) {
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
}
|
||||
|
||||
public Collection<SubscriptionItem> getItemsForSubscription(Subscription subscription) {
|
||||
public Collection<SubscriptionItem> getItemsForSubscription(final Subscription subscription) {
|
||||
try {
|
||||
final StripeCollection<SubscriptionItem> subscriptionItems = stripeClient.v1().subscriptionItems().list(
|
||||
SubscriptionItemListParams.builder().setSubscription(subscription.getId()).build(), commonOptions());
|
||||
@@ -493,7 +490,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
}
|
||||
}
|
||||
|
||||
public Price getPriceForSubscription(Subscription subscription) {
|
||||
public Price getPriceForSubscription(final Subscription subscription) {
|
||||
final Collection<SubscriptionItem> subscriptionItems = getItemsForSubscription(subscription);
|
||||
if (subscriptionItems.isEmpty()) {
|
||||
throw new IllegalStateException("no items found in subscription " + subscription.getId());
|
||||
@@ -505,12 +502,12 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
}
|
||||
}
|
||||
|
||||
private Product getProductForSubscription(Subscription subscription) {
|
||||
private Product getProductForSubscription(final Subscription subscription) {
|
||||
return getProductForPrice(getPriceForSubscription(subscription).getId());
|
||||
}
|
||||
|
||||
@Override
|
||||
public LevelAndCurrency getLevelAndCurrencyForSubscription(Object subscriptionObj) {
|
||||
public LevelAndCurrency getLevelAndCurrencyForSubscription(final Object subscriptionObj) {
|
||||
final Subscription subscription = getSubscription(subscriptionObj);
|
||||
|
||||
final Product product = getProductForSubscription(subscription);
|
||||
@@ -519,25 +516,25 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
subscription.getCurrency().toLowerCase(Locale.ROOT));
|
||||
}
|
||||
|
||||
public long getLevelForPrice(Price price) {
|
||||
public long getLevelForPrice(final Price price) {
|
||||
return getLevelForProduct(getProductForPrice(price.getId()));
|
||||
}
|
||||
|
||||
public Product getProductForPrice(String priceId) {
|
||||
PriceRetrieveParams params = PriceRetrieveParams.builder().addExpand("product").build();
|
||||
public Product getProductForPrice(final String priceId) {
|
||||
final PriceRetrieveParams params = PriceRetrieveParams.builder().addExpand("product").build();
|
||||
try {
|
||||
return stripeClient.v1().prices().retrieve(priceId, params, commonOptions()).getProductObject();
|
||||
} catch (StripeException e) {
|
||||
} catch (final StripeException e) {
|
||||
throw new UncheckedIOException(new IOException(e));
|
||||
}
|
||||
}
|
||||
|
||||
public long getLevelForProduct(Product product) {
|
||||
public long getLevelForProduct(final Product product) {
|
||||
return Long.parseLong(product.getMetadata().get(METADATA_KEY_LEVEL));
|
||||
}
|
||||
|
||||
private static ChargeFailure createChargeFailure(final Charge charge) {
|
||||
Charge.Outcome outcome = charge.getOutcome();
|
||||
final Charge.Outcome outcome = charge.getOutcome();
|
||||
return new ChargeFailure(
|
||||
charge.getFailureCode(),
|
||||
charge.getFailureMessage(),
|
||||
@@ -546,7 +543,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
outcome != null ? outcome.getType() : null);
|
||||
}
|
||||
|
||||
private static ChargeFailure createChargeFailureFromCardException(CardException e) {
|
||||
private static ChargeFailure createChargeFailureFromCardException(final CardException e) {
|
||||
return new ChargeFailure(
|
||||
StringUtils.defaultIfBlank(e.getDeclineCode(), e.getCode()),
|
||||
e.getStripeError().getMessage(),
|
||||
@@ -583,7 +580,8 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
|
||||
if (charge.getPaymentMethodDetails() != null
|
||||
&& charge.getPaymentMethodDetails().getType() != null) {
|
||||
paymentMethod = getPaymentMethodFromStripeString(charge.getPaymentMethodDetails().getType(), invoice.getId());
|
||||
paymentMethod = getPaymentMethodFromStripeString(charge.getPaymentMethodDetails().getType(),
|
||||
invoice.getId());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -604,7 +602,8 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
);
|
||||
}
|
||||
|
||||
private static PaymentMethod getPaymentMethodFromStripeString(final String paymentMethodString, final String invoiceId) {
|
||||
private static PaymentMethod getPaymentMethodFromStripeString(final String paymentMethodString,
|
||||
final String invoiceId) {
|
||||
return switch (paymentMethodString) {
|
||||
case "sepa_debit" -> PaymentMethod.SEPA_DEBIT;
|
||||
case "card" -> PaymentMethod.CARD;
|
||||
@@ -615,7 +614,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
};
|
||||
}
|
||||
|
||||
private Subscription getSubscription(Object subscriptionObj) {
|
||||
private Subscription getSubscription(final Object subscriptionObj) {
|
||||
if (!(subscriptionObj instanceof final Subscription subscription)) {
|
||||
throw new IllegalArgumentException("invalid subscription object: " + subscriptionObj.getClass().getName());
|
||||
}
|
||||
@@ -624,18 +623,19 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
}
|
||||
|
||||
@Override
|
||||
public ReceiptItem getReceiptItem(String subscriptionId)
|
||||
public ReceiptItem getReceiptItem(final String subscriptionId)
|
||||
throws SubscriptionPaymentRequiredException, SubscriptionReceiptRequestedForOpenPaymentException {
|
||||
final Invoice invoice = getSubscription(getSubscription(subscriptionId)).getLatestInvoiceObject();
|
||||
return convertInvoiceToReceipt(invoice, subscriptionId);
|
||||
}
|
||||
|
||||
private ReceiptItem convertInvoiceToReceipt(Invoice latestSubscriptionInvoice, String subscriptionId)
|
||||
private ReceiptItem convertInvoiceToReceipt(final Invoice latestSubscriptionInvoice, final String subscriptionId)
|
||||
throws SubscriptionReceiptRequestedForOpenPaymentException, SubscriptionPaymentRequiredException {
|
||||
if (latestSubscriptionInvoice == null) {
|
||||
throw new SubscriptionReceiptRequestedForOpenPaymentException();
|
||||
}
|
||||
if ("open".equalsIgnoreCase(latestSubscriptionInvoice.getStatus()) || "draft".equalsIgnoreCase(latestSubscriptionInvoice.getStatus())) {
|
||||
if ("open".equalsIgnoreCase(latestSubscriptionInvoice.getStatus()) || "draft".equalsIgnoreCase(
|
||||
latestSubscriptionInvoice.getStatus())) {
|
||||
throw new SubscriptionReceiptRequestedForOpenPaymentException();
|
||||
}
|
||||
if (!"paid".equalsIgnoreCase(latestSubscriptionInvoice.getStatus())) {
|
||||
@@ -660,7 +660,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
}
|
||||
|
||||
final Collection<InvoiceLineItem> invoiceLineItems = getInvoiceLineItemsForInvoice(latestSubscriptionInvoice);
|
||||
Collection<InvoiceLineItem> subscriptionLineItems = invoiceLineItems.stream()
|
||||
final Collection<InvoiceLineItem> subscriptionLineItems = invoiceLineItems.stream()
|
||||
.filter(invoiceLineItem -> "subscription_item_details".equalsIgnoreCase(invoiceLineItem.getParent().getType()))
|
||||
.toList();
|
||||
if (subscriptionLineItems.isEmpty()) {
|
||||
@@ -673,11 +673,11 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
+ "; invoiceId=" + latestSubscriptionInvoice.getId() + "; count=" + subscriptionLineItems.size());
|
||||
}
|
||||
|
||||
InvoiceLineItem subscriptionLineItem = subscriptionLineItems.stream().findAny().get();
|
||||
final InvoiceLineItem subscriptionLineItem = subscriptionLineItems.stream().findAny().get();
|
||||
return getReceiptForSubscription(subscriptionLineItem, latestSubscriptionInvoice);
|
||||
}
|
||||
|
||||
private ReceiptItem getReceiptForSubscription(InvoiceLineItem subscriptionLineItem, Invoice invoice) {
|
||||
private ReceiptItem getReceiptForSubscription(final InvoiceLineItem subscriptionLineItem, final Invoice invoice) {
|
||||
final Instant paidAt;
|
||||
if (invoice.getStatusTransitions().getPaidAt() != null) {
|
||||
paidAt = Instant.ofEpochSecond(invoice.getStatusTransitions().getPaidAt());
|
||||
@@ -693,7 +693,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
getLevelForProduct(product));
|
||||
}
|
||||
|
||||
public Collection<InvoiceLineItem> getInvoiceLineItemsForInvoice(Invoice invoice) {
|
||||
public Collection<InvoiceLineItem> getInvoiceLineItemsForInvoice(final Invoice invoice) {
|
||||
try {
|
||||
final StripeCollection<InvoiceLineItem> lineItems = stripeClient.v1().invoices().lineItems()
|
||||
.list(invoice.getId(), commonOptions());
|
||||
@@ -703,31 +703,31 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
}
|
||||
}
|
||||
|
||||
public CompletableFuture<String> getGeneratedSepaIdFromSetupIntent(String setupIntentId) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
SetupIntentRetrieveParams params = SetupIntentRetrieveParams.builder()
|
||||
.addExpand("latest_attempt")
|
||||
.build();
|
||||
try {
|
||||
final SetupIntent setupIntent = stripeClient.v1().setupIntents().retrieve(setupIntentId, params, commonOptions());
|
||||
if (setupIntent.getLatestAttemptObject() == null
|
||||
|| setupIntent.getLatestAttemptObject().getPaymentMethodDetails() == null
|
||||
|| setupIntent.getLatestAttemptObject().getPaymentMethodDetails().getIdeal() == null
|
||||
|| setupIntent.getLatestAttemptObject().getPaymentMethodDetails().getIdeal().getGeneratedSepaDebit() == null) {
|
||||
// This usually indicates that the client has made requests out of order, either by not confirming
|
||||
// the SetupIntent or not having the user authorize the transaction.
|
||||
logger.debug("setupIntent {} missing expected fields", setupIntentId);
|
||||
throw ExceptionUtils.wrap(new SubscriptionProcessorConflictException());
|
||||
}
|
||||
return setupIntent.getLatestAttemptObject().getPaymentMethodDetails().getIdeal().getGeneratedSepaDebit();
|
||||
} catch (StripeException e) {
|
||||
if (e.getStatusCode() == 404) {
|
||||
throw ExceptionUtils.wrap(new SubscriptionNotFoundException());
|
||||
}
|
||||
logger.error("unexpected error from Stripe when retrieving setupIntent {}", setupIntentId, e);
|
||||
throw ExceptionUtils.wrap(e);
|
||||
public String getGeneratedSepaIdFromSetupIntent(final String setupIntentId)
|
||||
throws SubscriptionNotFoundException, SubscriptionProcessorConflictException, IOException {
|
||||
final SetupIntentRetrieveParams params = SetupIntentRetrieveParams.builder()
|
||||
.addExpand("latest_attempt")
|
||||
.build();
|
||||
try {
|
||||
final SetupIntent setupIntent = stripeClient.v1().setupIntents().retrieve(setupIntentId, params, commonOptions());
|
||||
if (setupIntent.getLatestAttemptObject() == null
|
||||
|| setupIntent.getLatestAttemptObject().getPaymentMethodDetails() == null
|
||||
|| setupIntent.getLatestAttemptObject().getPaymentMethodDetails().getIdeal() == null
|
||||
|| setupIntent.getLatestAttemptObject().getPaymentMethodDetails().getIdeal().getGeneratedSepaDebit()
|
||||
== null) {
|
||||
// This usually indicates that the client has made requests out of order, either by not confirming
|
||||
// the SetupIntent or not having the user authorize the transaction.
|
||||
logger.debug("setupIntent {} missing expected fields", setupIntentId);
|
||||
throw new SubscriptionProcessorConflictException();
|
||||
}
|
||||
}, executor);
|
||||
return setupIntent.getLatestAttemptObject().getPaymentMethodDetails().getIdeal().getGeneratedSepaDebit();
|
||||
} catch (final StripeException e) {
|
||||
if (e.getStatusCode() == 404) {
|
||||
throw new SubscriptionNotFoundException();
|
||||
}
|
||||
logger.error("unexpected error from Stripe when retrieving setupIntent {}", setupIntentId, e);
|
||||
throw new IOException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private Optional<InvoicePayment> getMostRecentInvoicePayment(final Invoice invoice) {
|
||||
@@ -757,32 +757,32 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor
|
||||
* it is intentionally sending a repeat of the update to level 2 request because user is changing again, so in this
|
||||
* case we derive idempotency from the client.
|
||||
*/
|
||||
private String generateIdempotencyKeyForSubscriptionUpdate(String customerId, String idempotencyKey) {
|
||||
private String generateIdempotencyKeyForSubscriptionUpdate(final String customerId, final String idempotencyKey) {
|
||||
return generateIdempotencyKey("subscriptionUpdate", mac -> {
|
||||
mac.update(customerId.getBytes(StandardCharsets.UTF_8));
|
||||
mac.update(idempotencyKey.getBytes(StandardCharsets.UTF_8));
|
||||
});
|
||||
}
|
||||
|
||||
private String generateIdempotencyKeyForSubscriberUser(byte[] subscriberUser) {
|
||||
private String generateIdempotencyKeyForSubscriberUser(final byte[] subscriberUser) {
|
||||
return generateIdempotencyKey("subscriberUser", mac -> mac.update(subscriberUser));
|
||||
}
|
||||
|
||||
private String generateIdempotencyKeyForCreateSubscription(String customerId, long lastSubscriptionCreatedAt) {
|
||||
private String generateIdempotencyKeyForCreateSubscription(final String customerId, final long lastSubscriptionCreatedAt) {
|
||||
return generateIdempotencyKey("customerId", mac -> {
|
||||
mac.update(customerId.getBytes(StandardCharsets.UTF_8));
|
||||
mac.update(Conversions.longToByteArray(lastSubscriptionCreatedAt));
|
||||
});
|
||||
}
|
||||
|
||||
private String generateIdempotencyKey(String type, Consumer<Mac> byteConsumer) {
|
||||
private String generateIdempotencyKey(final String type, final Consumer<Mac> byteConsumer) {
|
||||
try {
|
||||
Mac mac = Mac.getInstance("HmacSHA256");
|
||||
final Mac mac = Mac.getInstance("HmacSHA256");
|
||||
mac.init(new SecretKeySpec(idempotencyKeyGenerator, "HmacSHA256"));
|
||||
mac.update(type.getBytes(StandardCharsets.UTF_8));
|
||||
byteConsumer.accept(mac);
|
||||
return Base64.getUrlEncoder().encodeToString(mac.doFinal());
|
||||
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
|
||||
} catch (final NoSuchAlgorithmException | InvalidKeyException e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
|
||||
+2
-1
@@ -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;
|
||||
}
|
||||
|
||||
+2
-1
@@ -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,20 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.util;
|
||||
|
||||
/// Represents an operation that two argument and returns a result, but may throw a checked exception. Unlike most other
|
||||
/// functional interfaces, `ThrowingBiFunction` is expected to operate via side-effects.
|
||||
@FunctionalInterface
|
||||
public interface ThrowingBiFunction<T, U, R, E extends Exception> {
|
||||
|
||||
/// Performs this operation on the given arguments and returns a result.
|
||||
///
|
||||
/// @param t the first input argument
|
||||
/// @param u the second input argument
|
||||
/// @return the result of applying the function
|
||||
/// @throws E at the implementation's discretion
|
||||
R apply(T t, U u) throws E;
|
||||
}
|
||||
+30
@@ -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);
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -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}", ""));
|
||||
}
|
||||
|
||||
}
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.stream.Collectors;
|
||||
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.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
import reactor.core.publisher.Flux;
|
||||
|
||||
public class ClearExpiredFoundationDbMessagesCommand extends AbstractSinglePassCrawlAccountsCommand {
|
||||
|
||||
private final Clock clock;
|
||||
|
||||
@VisibleForTesting
|
||||
static final String DRY_RUN_ARGUMENT = "dry-run";
|
||||
|
||||
@VisibleForTesting
|
||||
static final String BATCH_SIZE_ARGUMENT = "batch-size";
|
||||
|
||||
@VisibleForTesting
|
||||
static final String MESSAGE_TTL_DAYS_ARGUMENT = "message-ttl-days";
|
||||
|
||||
@VisibleForTesting
|
||||
static final String VERSIONSTAMP_TTL_DAYS_ARGUMENT = "versionstamp-ttl-days";
|
||||
|
||||
@VisibleForTesting
|
||||
static final Duration TIMESTAMP_RETENTION_PERIOD = Duration.ofDays(60);
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(ClearExpiredFoundationDbMessagesCommand.class);
|
||||
|
||||
public ClearExpiredFoundationDbMessagesCommand(final Clock clock) {
|
||||
super("clear-expired-foundationdb-messages", "Removes expired messages from FoundationDB");
|
||||
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
@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 delete any messages (but do still make entries in the versionstamp clock)");
|
||||
|
||||
subparser.addArgument("--batch-size")
|
||||
.type(Integer.class)
|
||||
.dest(BATCH_SIZE_ARGUMENT)
|
||||
.required(false)
|
||||
.setDefault(10000)
|
||||
.help("Maximum number of queues to trim in a single transaction");
|
||||
|
||||
subparser.addArgument("--message-ttl-days")
|
||||
.type(Integer.class)
|
||||
.dest(MESSAGE_TTL_DAYS_ARGUMENT)
|
||||
.required(true)
|
||||
.help("Desired message TTL in days");
|
||||
|
||||
subparser.addArgument("--versionstamp-ttl-days")
|
||||
.type(Integer.class)
|
||||
.dest(VERSIONSTAMP_TTL_DAYS_ARGUMENT)
|
||||
.required(false)
|
||||
.setDefault(180)
|
||||
.help("Desired versionstamp-clock TTL in days");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void crawlAccounts(final Flux<Account> accounts) {
|
||||
final MessagesManager messagesManager = getCommandDependencies().messagesManager();
|
||||
|
||||
// Record the current versionstamp/time pair for the benefit of future runs. Because this job runs regularly, it has
|
||||
// the dual role of clearing messages and keeping the versionstamp/time mappings populated.
|
||||
messagesManager.recordFoundationDbVersionstamps();
|
||||
|
||||
final int batchSize = getNamespace().getInt(BATCH_SIZE_ARGUMENT);
|
||||
final boolean dryRun = getNamespace().getBoolean(DRY_RUN_ARGUMENT);
|
||||
final int messageTtlDays = getNamespace().getInt(MESSAGE_TTL_DAYS_ARGUMENT);
|
||||
final int versionstampTtlDays = getNamespace().getInt(VERSIONSTAMP_TTL_DAYS_ARGUMENT);
|
||||
|
||||
final Instant oldestMessageTime = clock.instant().minus(Duration.ofDays(messageTtlDays));
|
||||
final Instant oldestVersionstampTime = clock.instant().minus(Duration.ofDays(versionstampTtlDays));
|
||||
|
||||
accounts
|
||||
.buffer(batchSize)
|
||||
.map(batch -> batch.stream().collect(
|
||||
Collectors.toMap(
|
||||
account -> new AciServiceIdentifier(account.getIdentifier(IdentityType.ACI)),
|
||||
account -> account.getDevices().stream().map(Device::getId).toList())))
|
||||
.doOnNext(
|
||||
dryRun ? _ -> {}
|
||||
: deviceIdsByAccountIdentifier -> messagesManager.deleteFoundationDbMessagesBefore(deviceIdsByAccountIdentifier, oldestMessageTime))
|
||||
.then()
|
||||
.block();
|
||||
|
||||
messagesManager.expireOldFoundationDbVersionstamps(oldestVersionstampTime);
|
||||
}
|
||||
}
|
||||
+10
-4
@@ -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,
|
||||
@@ -351,7 +357,7 @@ public record CommandDependencies(
|
||||
final GenericServerSecretParams backupsGenericZkSecretParams;
|
||||
try {
|
||||
backupsGenericZkSecretParams =
|
||||
new GenericServerSecretParams(configuration.getBackupsZkConfig().serverSecret().value());
|
||||
new GenericServerSecretParams(configuration.getChatZkConfig().serverSecret().value());
|
||||
} catch (InvalidInputException e) {
|
||||
throw new IllegalArgumentException(e);
|
||||
}
|
||||
@@ -368,7 +374,7 @@ public record CommandDependencies(
|
||||
secureValueRecoveryBCredentialsGenerator,
|
||||
secureValueRecoveryBClient,
|
||||
clock,
|
||||
dynamicConfigurationManager);
|
||||
configuration.getBackupConfiguration());
|
||||
|
||||
final IssuedReceiptsManager issuedReceiptsManager = new IssuedReceiptsManager(
|
||||
configuration.getDynamoDbTables().getIssuedReceipts().getTableName(),
|
||||
@@ -377,7 +383,7 @@ public record CommandDependencies(
|
||||
configuration.getDynamoDbTables().getIssuedReceipts().getGenerator(),
|
||||
configuration.getDynamoDbTables().getIssuedReceipts().getmaxIssuedReceiptsPerPaymentId());
|
||||
|
||||
final ServerSecretParams zkSecretParams = new ServerSecretParams(configuration.getZkConfig().serverSecret().value());
|
||||
final ServerSecretParams zkSecretParams = new ServerSecretParams(configuration.getGroupsZkConfig().serverSecret().value());
|
||||
final ServerZkReceiptOperations zkReceiptOperations = new ServerZkReceiptOperations(zkSecretParams);
|
||||
GooglePlayBillingManager googlePlayBillingManager = new GooglePlayBillingManager(
|
||||
new ByteArrayInputStream(configuration.getGooglePlayBilling().credentialsJson().getBytes(StandardCharsets.UTF_8)),
|
||||
|
||||
+139
@@ -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, "trimmedQueues");
|
||||
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,16 +4,24 @@ 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";
|
||||
import "org/signal/chat/require.proto";
|
||||
import "org/signal/chat/tag.proto";
|
||||
|
||||
// Provides methods for working with Signal accounts.
|
||||
service Accounts {
|
||||
option (require.auth) = AUTH_ONLY_AUTHENTICATED;
|
||||
|
||||
// Returns basic identifiers for the authenticated account.
|
||||
rpc GetAccountIdentity(GetAccountIdentityRequest) returns (GetAccountIdentityResponse) {}
|
||||
|
||||
// Returns entitlements for the authenticated account.
|
||||
rpc GetEntitlements(GetEntitlementsRequest) returns (GetEntitlementsResponse) {}
|
||||
|
||||
// Deletes the authenticated account, purging all associated data in the
|
||||
// process.
|
||||
rpc DeleteAccount(DeleteAccountRequest) returns (DeleteAccountResponse) {}
|
||||
@@ -60,11 +68,22 @@ service Accounts {
|
||||
|
||||
// Store a public key used to issue and verify zero-knowledge (anonymous) credentials for the account.
|
||||
rpc SetZkCredentialKey(SetZkCredentialKeyRequest) returns (SetZkCredentialKeyResponse) {}
|
||||
|
||||
// Changes the phone number associated with the authenticated account.
|
||||
rpc ChangeNumber(ChangeNumberRequest) returns (ChangeNumberResponse) {}
|
||||
|
||||
// Produces a report of non-ephemeral account data stored by the service
|
||||
rpc GetAccountDataReport(GetAccountDataReportRequest) returns (GetAccountDataReportResponse) {}
|
||||
|
||||
// Gets the capabilities for the authenticated account.
|
||||
rpc GetCapabilities(GetCapabilitiesRequest) returns (GetCapabilitiesResponse) {}
|
||||
}
|
||||
|
||||
// Provides methods for looking up Signal accounts. Callers must not provide
|
||||
// identifying credentials when calling methods in this service.
|
||||
service AccountsAnonymous {
|
||||
option (require.auth) = AUTH_ONLY_ANONYMOUS;
|
||||
|
||||
// Checks whether an account with the given service identifier exists.
|
||||
rpc CheckAccountExistence(CheckAccountExistenceRequest) returns (CheckAccountExistenceResponse) {}
|
||||
|
||||
@@ -74,16 +93,49 @@ service AccountsAnonymous {
|
||||
|
||||
// Finds the encrypted username identified by a given username link handle.
|
||||
rpc LookupUsernameLink(LookupUsernameLinkRequest) returns (LookupUsernameLinkResponse) {}
|
||||
|
||||
// Gets the publicly-visible capabilities enabled on the account identified by
|
||||
// the provided ACI.
|
||||
rpc GetCapabilities(GetCapabilitiesAnonymousRequest) returns (GetCapabilitiesAnonymousResponse) {}
|
||||
}
|
||||
|
||||
message GetAccountIdentityRequest {
|
||||
}
|
||||
|
||||
message GetAccountIdentityResponse {
|
||||
// A set of account identifiers for the authenticated account.
|
||||
// The identifiers for the authenticated account.
|
||||
common.AccountIdentifiers account_identifiers = 1;
|
||||
}
|
||||
|
||||
message GetEntitlementsRequest {
|
||||
}
|
||||
|
||||
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.
|
||||
string badge_id = 1;
|
||||
// When the badge expires, in number of seconds since epoch
|
||||
uint64 expiration_epoch_seconds = 2;
|
||||
// Whether the badge is currently configured to be visible
|
||||
bool visible = 3;
|
||||
}
|
||||
|
||||
message BackupEntitlement {
|
||||
// The backup level of the account
|
||||
uint64 level = 1;
|
||||
// When the backup entitlement expires, in number of seconds since epoch
|
||||
uint64 expiration_epoch_seconds = 2;
|
||||
}
|
||||
|
||||
// Active badges added via Donations.redeemReceipt
|
||||
repeated BadgeEntitlement badges = 1;
|
||||
|
||||
// If present, the backup level set via Backups.redeemReceipt
|
||||
BackupEntitlement backup = 2;
|
||||
}
|
||||
|
||||
message DeleteAccountRequest {
|
||||
}
|
||||
|
||||
@@ -137,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;
|
||||
@@ -192,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 {
|
||||
@@ -280,3 +335,149 @@ message SetZkCredentialKeyResponse {
|
||||
// as reverting to the previous key will result in a new rotation ID.
|
||||
uint64 rotation_id = 1;
|
||||
}
|
||||
|
||||
message ChangeNumberRequest {
|
||||
// A means of authenticating the change-number request for the new phone
|
||||
// number. Exactly one must be provided.
|
||||
oneof verification {
|
||||
// A verified registration session ID (as returned by the registration
|
||||
// service) for the new phone number.
|
||||
bytes session_id = 1 [(require.nonEmpty) = true];
|
||||
|
||||
// A registration recovery password for the new phone number.
|
||||
bytes recovery_password = 2 [(require.exactlySize) = 32];
|
||||
}
|
||||
|
||||
// The new phone number for the authenticated account.
|
||||
string number = 3 [(require.e164) = true];
|
||||
|
||||
// The registration lock secret for the new phone number, if the account
|
||||
// associated with the new phone number has a registration lock configured.
|
||||
bytes registration_lock = 4 [(require.exactlySize) = 0, (require.exactlySize) = 32];
|
||||
|
||||
// The new public identity key to use for the phone-number identity (PNI)
|
||||
// associated with the new phone number.
|
||||
bytes pni_identity_key = 5 [(require.nonEmpty) = true];
|
||||
|
||||
// Synchronization messages to send to companion devices to supply the private
|
||||
// keys associated with the new identity key and their new pre-keys. Exactly
|
||||
// one message must be supplied for each device other than the sending
|
||||
// (primary) device. May be omitted if no companion devices are linked to the
|
||||
// account.
|
||||
messages.IndividualRecipientMessageBundle device_messages = 6;
|
||||
|
||||
// A new signed EC pre-key for each device on the account, including the
|
||||
// sending device, keyed by device ID. Each must be accompanied by a valid
|
||||
// signature from the identity key in this request.
|
||||
map<uint32, common.EcSignedPreKey> device_pni_signed_pre_keys = 7;
|
||||
|
||||
// A new signed post-quantum last-resort pre-key for each device on the
|
||||
// account, including the sending device, keyed by device ID. Each must be
|
||||
// accompanied by a valid signature from the identity key in this request.
|
||||
map<uint32, common.KemSignedPreKey> device_pni_pq_last_resort_pre_keys = 8;
|
||||
|
||||
// The new phone-number-identity registration ID for each device on the
|
||||
// account, including the sending device, keyed by device ID.
|
||||
map<uint32, uint32> pni_registration_ids = 9;
|
||||
}
|
||||
|
||||
message ChangeNumberResponse {
|
||||
oneof response {
|
||||
// The identifiers of the account after the successful
|
||||
// number change.
|
||||
common.AccountIdentifiers account_identifiers = 1;
|
||||
|
||||
// Mismatched number of devices or device ids in 'devices to notify' list
|
||||
messages.MismatchedDevices mismatched_devices = 2 [(tag.reason) = "mismatched_devices"];
|
||||
|
||||
// The account associated with the new phone number has a registration lock,
|
||||
// and the provided registration lock secret was missing or incorrect.
|
||||
RegistrationLockFailure registration_lock_failure = 3 [(tag.reason) = "registration_lock_failure"];
|
||||
|
||||
// Mismatched registration ids in 'devices to notify' list
|
||||
StaleDevices stale_devices = 4 [(tag.reason) = "stale_devices"];
|
||||
|
||||
// One or more device messages was too large
|
||||
errors.FailedPrecondition message_too_large = 5 [(tag.reason) = "message_too_large"];
|
||||
|
||||
// The registration session is unverified
|
||||
errors.FailedPrecondition unverified_registration_session = 6 [(tag.reason) = "unverified_registration_session"];
|
||||
|
||||
// The number does not match the registration session, or the registration session is invalid
|
||||
errors.FailedPrecondition invalid_registration_session = 7 [(tag.reason) = "invalid_registration_session"];
|
||||
|
||||
errors.FailedPrecondition recovery_password_verification_failed = 8 [(tag.reason) = "recovery_password_verification_failed"];
|
||||
}
|
||||
}
|
||||
|
||||
// Information about the current Registration lock and SVR credentials. With a correct PIN, the credentials can
|
||||
// be used to recover the secret used to derive the registration lock password.
|
||||
message RegistrationLockFailure {
|
||||
// Time remaining in milliseconds before the existing registration lock expires
|
||||
uint64 time_remaining_millis = 1;
|
||||
|
||||
// Credentials that can be used with SVR2
|
||||
ExternalServiceCredentials svr2_credentials = 2;
|
||||
}
|
||||
|
||||
// A username/password pair for authenticating with an external service.
|
||||
message ExternalServiceCredentials {
|
||||
// A username that can be presented to authenticate with the external service.
|
||||
string username = 1;
|
||||
|
||||
// A password that can be presented to authenticate with the external service.
|
||||
string password = 2;
|
||||
}
|
||||
|
||||
// A list of devices that are linked to the account but presented a stale
|
||||
// registration ID (indicating the device has likely been replaced by another
|
||||
// device).
|
||||
message StaleDevices {
|
||||
// The IDs of devices that are no longer active.
|
||||
repeated uint32 stale_devices = 1 [(require.each) = {range: {max: 0x7f}}];
|
||||
}
|
||||
|
||||
message GetAccountDataReportRequest {
|
||||
}
|
||||
|
||||
message GetAccountDataReportResponse {
|
||||
// The JSON representation of the data report
|
||||
string json = 3;
|
||||
// A plaintext representation of the data report
|
||||
string text = 4;
|
||||
}
|
||||
|
||||
message GetCapabilitiesRequest {
|
||||
}
|
||||
|
||||
message Capabilities {
|
||||
// A list of capabilities enabled on the account.
|
||||
repeated common.DeviceCapability capabilities = 1;
|
||||
}
|
||||
|
||||
message GetCapabilitiesResponse {
|
||||
// A list of capabilities enabled on the account.
|
||||
Capabilities capabilities = 1;
|
||||
}
|
||||
|
||||
message GetCapabilitiesAnonymousRequest {
|
||||
// The ACI of the account for which to get capabilities.
|
||||
common.ServiceIdentifier account_identifier = 1 [(require.present) = true, (require.identityType) = IDENTITY_TYPE_ACI];
|
||||
|
||||
oneof authentication {
|
||||
// The unidentified access key for the targeted account.
|
||||
bytes unidentified_access_key = 2 [(require.exactlySize) = 16];
|
||||
|
||||
// A group send endorsement token for the targeted account.
|
||||
bytes group_send_token = 3 [(require.nonEmpty) = true];
|
||||
}
|
||||
}
|
||||
|
||||
message GetCapabilitiesAnonymousResponse {
|
||||
oneof response {
|
||||
// A list of capabilities enabled on the account.
|
||||
Capabilities capabilities = 1;
|
||||
errors.NotFound not_found = 2 [(tag.reason) = "not_found"];
|
||||
errors.FailedUnidentifiedAuthorization failed_unidentified_authorization = 3 [(tag.reason) = "failed_unidentified_authorization"];
|
||||
}
|
||||
}
|
||||
@@ -9,8 +9,11 @@ option java_multiple_files = true;
|
||||
|
||||
package org.signal.chat.calling.quality;
|
||||
|
||||
import "org/signal/chat/require.proto";
|
||||
|
||||
// Provides methods for submitting call quality surveys
|
||||
service CallQuality {
|
||||
option (require.auth) = AUTH_ONLY_ANONYMOUS;
|
||||
|
||||
// Submits a call quality survey response.
|
||||
rpc SubmitCallQualitySurvey(SubmitCallQualitySurveyRequest) returns (SubmitCallQualitySurveyResponse) {}
|
||||
|
||||
@@ -9,9 +9,12 @@ option java_multiple_files = true;
|
||||
|
||||
package org.signal.chat.calling;
|
||||
|
||||
import "org/signal/chat/require.proto";
|
||||
|
||||
// Provides methods for getting credentials and relay options for one-on-one
|
||||
// calls.
|
||||
service Calling {
|
||||
option (require.auth) = AUTH_ONLY_AUTHENTICATED;
|
||||
|
||||
// Retrieves TURN credentials and relay options for one-on-one calls.
|
||||
rpc GetCallingRelays(GetCallingRelaysRequest) returns (GetCallingRelaysResponse) {}
|
||||
|
||||
@@ -25,16 +25,22 @@ 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.
|
||||
string e164 = 2;
|
||||
string e164 = 2 [(org.signal.chat.require.e164) = true];
|
||||
|
||||
// The username hash (if any) associated with the identified account. May be
|
||||
// empty if no username is associated with the identified account.
|
||||
bytes username_hash = 3;
|
||||
bytes username_hash = 3 [(org.signal.chat.require.exactlySize) = 0, (org.signal.chat.require.exactlySize) = 32];
|
||||
|
||||
// The username link handle UUID associated with the identified account.
|
||||
// May be empty if no username is associated with the identified account.
|
||||
bytes username_link_handle = 4 [(org.signal.chat.require.exactlySize) = 0, (org.signal.chat.require.exactlySize) = 16];
|
||||
}
|
||||
|
||||
message EcPreKey {
|
||||
|
||||
Loaded 100 of 162 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user