Compare commits

...
44 Commits
Author SHA1 Message Date
Chris Eager 3ec51c1200 Remove profiles_v2 capability 2026-11-19 11:28:29 -05:00
Cody Henthorne d0ef28cbfd Add a device capability for admin remove and delete 2026-11-19 11:27:45 -05:00
Ameya Lokare cb8a3fb7d6 Use slf4j key-value pairs instead of logstash marker entries
Also, drop the logstash dependency
2026-11-19 11:27:18 -05:00
Jon Chambers 7ec705e616 Update to the latest version of the spam filter 2026-11-19 11:26:32 -05:00
Jon Chambers 9dfbb454d1 Throttle requests when a client has a suspected delivery loop 2026-11-18 15:49:11 -05:00
Jon Chambers 5de899da4b Fix a trivial typo in a comment 2026-11-18 15:38:08 -05:00
Jon Chambers cbfc2720d5 Reset "reads since message last acknowledged" counter when acknowledging messages 2026-11-18 15:38:08 -05:00
Jon Chambers 0100901667 Increment a counter when reading the first message from a stream 2026-11-18 15:38:08 -05:00
Greyson Parrelli b3db95c3ea Add device capability for contact deletion 2026-11-18 15:33:58 -05:00
Ravi Khadiwala a9f87693ba Use 'Metadata' instead of 'header' when describing RPC Metadata 2026-11-18 15:30:07 -05:00
tina-signal b06709b63b Add a device capability for "reply privately" 2026-11-18 15:15:42 -05:00
Chris Eager 99278dcd1f Update CheckIdentityKeys response stream to be 1:1 with request 2026-11-18 15:15:02 -05:00
Ravi Khadiwala 2d6eb7951a Handle non-idempotent integration test operations
- Retry 441s during webauthn recovery
- Assume a 401 during delete means the account is already gone
- Check the session state to determine whether verification is complete
2026-11-18 15:13:30 -05:00
Ravi Khadiwala 7e26b7fe0a Fix permanentFailure field in verification-code responses 2026-11-18 15:12:55 -05:00
Jon Chambers 2f955582a4 Update AWS SDK to 2.59.1 2026-11-18 15:12:12 -05:00
Jon Chambers 31bb5ff621 Update libsignal-server to 0.108.0 2026-11-18 15:12:12 -05:00
dependabot[bot] c21ad7a3aa Bump actions/setup-java
Bumps the minor-actions-dependencies group with 1 update: [actions/setup-java](https://github.com/actions/setup-java).


Updates `actions/setup-java` from 6.2.0 to 6.3.0
- [Release notes](https://github.com/actions/setup-java/releases)
- [Commits](https://github.com/actions/setup-java/compare/77dd5b2ce225ea11469928ac317850245a74ae78...d1374f8ac74474200d16ef8ecee22c7ae7a51880)

---
updated-dependencies:
- dependency-name: actions/setup-java
  dependency-version: 6.3.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-actions-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-18 14:39:59 -05:00
dependabot[bot] 4a48066d87 Bump com.stripe:stripe-java from 33.4.2 to 34.1.0 in /service
Bumps [com.stripe:stripe-java](https://github.com/stripe/stripe-java) from 33.4.2 to 34.1.0.
- [Release notes](https://github.com/stripe/stripe-java/releases)
- [Changelog](https://github.com/stripe/stripe-java/blob/master/CHANGELOG.md)
- [Commits](https://github.com/stripe/stripe-java/compare/v33.4.2...v34.1.0)

---
updated-dependencies:
- dependency-name: com.stripe:stripe-java
  dependency-version: 34.1.0
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-18 14:34:56 -05:00
Ravi Khadiwala a0cdb5d3b6 Fix DCAttestationParameters call 2026-11-18 14:19:56 -05:00
Jon Chambers 3f1b678095 Retire AppAttestAssertionConverter 2026-11-18 14:19:56 -05:00
Jon Chambers ffb821e344 Remove special-case handling for old-format Benin phone numbers 2026-11-18 14:19:56 -05:00
Jon Chambers d9bf32dd9c Remove jackson-databind dependency convergence sentinel 2026-11-18 14:19:56 -05:00
dependabot[bot] 2fe70c89fa Bump the minor-java-dependencies group across 4 directories with 21 updates
Bumps the minor-java-dependencies group with 15 updates in the /api-doc directory:

| Package | From | To |
| --- | --- | --- |
| [com.fasterxml.jackson:jackson-bom](https://github.com/FasterXML/jackson-bom) | `2.22.4` | `2.23.0` |
| [com.google.cloud:libraries-bom](https://github.com/googleapis/google-cloud-java) | `26.91.0` | `26.93.0` |
| software.amazon.awssdk:bom | `2.57.6` | `2.59.0` |
| [net.bytebuddy:byte-buddy](https://github.com/raphw/byte-buddy) | `1.18.16-jdk5` | `1.18.17-jdk5` |
| [net.bytebuddy:byte-buddy-agent](https://github.com/raphw/byte-buddy) | `1.18.16-jdk5` | `1.18.17-jdk5` |
| [net.bytebuddy:byte-buddy-agent](https://github.com/raphw/byte-buddy) | `1.18.16-jdk5` | `1.18.17-jdk5` |
| [com.googlecode.libphonenumber:libphonenumber](https://github.com/google/libphonenumber) | `9.0.42` | `9.0.43` |
| [com.braintreepayments.gateway:braintree-java](https://github.com/braintree/braintree_java) | `3.55.1` | `3.56.0` |
| [com.google.guava:guava](https://github.com/google/guava) | `33.7.2-jre` | `33.8.0-jre` |
| [org.signal:libsignal-server](https://github.com/signalapp/libsignal) | `0.106.1` | `0.107.0` |
| [org.signal:simple-grpc-runtime](https://github.com/signalapp/simple-grpc) | `0.2.1` | `0.3.0` |
| [org.codehaus.mojo:exec-maven-plugin](https://github.com/mojohaus/exec-maven-plugin) | `3.6.4` | `3.7.0` |
| [org.codehaus.mojo:properties-maven-plugin](https://github.com/mojohaus/properties-maven-plugin) | `1.3.1` | `1.4.0` |

Bumps the minor-java-dependencies group with 16 updates in the /integration-tests directory:

| Package | From | To |
| --- | --- | --- |
| [com.fasterxml.jackson:jackson-bom](https://github.com/FasterXML/jackson-bom) | `2.22.4` | `2.23.0` |
| [com.google.cloud:libraries-bom](https://github.com/googleapis/google-cloud-java) | `26.91.0` | `26.93.0` |
| software.amazon.awssdk:bom | `2.57.6` | `2.59.0` |
| [net.bytebuddy:byte-buddy](https://github.com/raphw/byte-buddy) | `1.18.16-jdk5` | `1.18.17-jdk5` |
| [net.bytebuddy:byte-buddy-agent](https://github.com/raphw/byte-buddy) | `1.18.16-jdk5` | `1.18.17-jdk5` |
| [com.googlecode.libphonenumber:libphonenumber](https://github.com/google/libphonenumber) | `9.0.42` | `9.0.43` |
| [com.braintreepayments.gateway:braintree-java](https://github.com/braintree/braintree_java) | `3.55.1` | `3.56.0` |
| [com.google.guava:guava](https://github.com/google/guava) | `33.7.2-jre` | `33.8.0-jre` |
| [org.signal:libsignal-server](https://github.com/signalapp/libsignal) | `0.106.1` | `0.107.0` |
| [org.signal:simple-grpc-runtime](https://github.com/signalapp/simple-grpc) | `0.2.1` | `0.3.0` |
| [org.codehaus.mojo:exec-maven-plugin](https://github.com/mojohaus/exec-maven-plugin) | `3.6.4` | `3.7.0` |
| [org.codehaus.mojo:properties-maven-plugin](https://github.com/mojohaus/properties-maven-plugin) | `1.3.1` | `1.4.0` |
| [com.webauthn4j:webauthn4j-test](https://github.com/webauthn4j/webauthn4j) | `0.31.11.RELEASE` | `0.32.0.RELEASE` |

Bumps the minor-java-dependencies group with 21 updates in the /service directory:

| Package | From | To |
| --- | --- | --- |
| [com.fasterxml.jackson:jackson-bom](https://github.com/FasterXML/jackson-bom) | `2.22.4` | `2.23.0` |
| [com.google.cloud:libraries-bom](https://github.com/googleapis/google-cloud-java) | `26.91.0` | `26.93.0` |
| software.amazon.awssdk:bom | `2.57.6` | `2.59.0` |
| [net.bytebuddy:byte-buddy](https://github.com/raphw/byte-buddy) | `1.18.16-jdk5` | `1.18.17-jdk5` |
| [net.bytebuddy:byte-buddy-agent](https://github.com/raphw/byte-buddy) | `1.18.16-jdk5` | `1.18.17-jdk5` |
| [com.googlecode.libphonenumber:libphonenumber](https://github.com/google/libphonenumber) | `9.0.42` | `9.0.43` |
| [com.braintreepayments.gateway:braintree-java](https://github.com/braintree/braintree_java) | `3.55.1` | `3.56.0` |
| [com.google.guava:guava](https://github.com/google/guava) | `33.7.2-jre` | `33.8.0-jre` |
| [org.signal:libsignal-server](https://github.com/signalapp/libsignal) | `0.106.1` | `0.107.0` |
| [org.signal:simple-grpc-runtime](https://github.com/signalapp/simple-grpc) | `0.2.1` | `0.3.0` |
| [org.codehaus.mojo:exec-maven-plugin](https://github.com/mojohaus/exec-maven-plugin) | `3.6.4` | `3.7.0` |
| [org.codehaus.mojo:properties-maven-plugin](https://github.com/mojohaus/properties-maven-plugin) | `1.3.1` | `1.4.0` |
| [com.webauthn4j:webauthn4j-test](https://github.com/webauthn4j/webauthn4j) | `0.31.11.RELEASE` | `0.32.0.RELEASE` |
| [com.webauthn4j:webauthn4j-appattest](https://github.com/webauthn4j/webauthn4j) | `0.31.11.RELEASE` | `0.32.0.RELEASE` |
| [com.webauthn4j:webauthn4j-core](https://github.com/webauthn4j/webauthn4j) | `0.31.11.RELEASE` | `0.32.0.RELEASE` |
| [com.google.firebase:firebase-admin](https://github.com/firebase/firebase-admin-java) | `9.11.0` | `9.12.0` |
| [com.googlecode.libphonenumber:geocoder](https://github.com/google/libphonenumber) | `3.42` | `3.43` |
| [org.codehaus.mojo:templating-maven-plugin](https://github.com/mojohaus/templating-maven-plugin) | `3.1.1` | `3.2.0` |

Bumps the minor-java-dependencies group with 15 updates in the /websocket-resources directory:

| Package | From | To |
| --- | --- | --- |
| [com.fasterxml.jackson:jackson-bom](https://github.com/FasterXML/jackson-bom) | `2.22.4` | `2.23.0` |
| [com.google.cloud:libraries-bom](https://github.com/googleapis/google-cloud-java) | `26.91.0` | `26.93.0` |
| software.amazon.awssdk:bom | `2.57.6` | `2.59.0` |
| [net.bytebuddy:byte-buddy](https://github.com/raphw/byte-buddy) | `1.18.16-jdk5` | `1.18.17-jdk5` |
| [net.bytebuddy:byte-buddy-agent](https://github.com/raphw/byte-buddy) | `1.18.16-jdk5` | `1.18.17-jdk5` |
| [com.googlecode.libphonenumber:libphonenumber](https://github.com/google/libphonenumber) | `9.0.42` | `9.0.43` |
| [com.braintreepayments.gateway:braintree-java](https://github.com/braintree/braintree_java) | `3.55.1` | `3.56.0` |
| [com.google.guava:guava](https://github.com/google/guava) | `33.7.2-jre` | `33.8.0-jre` |
| [org.signal:libsignal-server](https://github.com/signalapp/libsignal) | `0.106.1` | `0.107.0` |
| [org.signal:simple-grpc-runtime](https://github.com/signalapp/simple-grpc) | `0.2.1` | `0.3.0` |
| [org.codehaus.mojo:exec-maven-plugin](https://github.com/mojohaus/exec-maven-plugin) | `3.6.4` | `3.7.0` |
| [org.codehaus.mojo:properties-maven-plugin](https://github.com/mojohaus/properties-maven-plugin) | `1.3.1` | `1.4.0` |

Updates `com.fasterxml.jackson:jackson-bom` from 2.22.4 to 2.23.0
- [Commits](https://github.com/FasterXML/jackson-bom/compare/jackson-bom-2.22.4...jackson-bom-2.23.0)

Updates `org.eclipse.jetty.ee10:jetty-ee10-bom` from 12.1.9 to 12.1.15
- [Release notes](https://github.com/jetty/jetty.project/releases)
- [Commits](https://github.com/jetty/jetty.project/compare/jetty-12.1.9...jetty-12.1.15)

Updates `org.eclipse.jetty.ee10:jetty-ee10-bom` from 12.1.9 to 12.1.15
- [Release notes](https://github.com/jetty/jetty.project/releases)
- [Commits](https://github.com/jetty/jetty.project/compare/jetty-12.1.9...jetty-12.1.15)

Updates `com.google.cloud:libraries-bom` from 26.91.0 to 26.93.0
- [Release notes](https://github.com/googleapis/google-cloud-java/releases)
- [Changelog](https://github.com/googleapis/google-cloud-java/blob/main/CHANGELOG.md)
- [Commits](https://github.com/googleapis/google-cloud-java/compare/libraries-bom/v26.91.0...libraries-bom/v26.93.0)

Updates `software.amazon.awssdk:bom` from 2.57.6 to 2.59.0

Updates `net.bytebuddy:byte-buddy` from 1.18.16-jdk5 to 1.18.17-jdk5
- [Release notes](https://github.com/raphw/byte-buddy/releases)
- [Changelog](https://github.com/raphw/byte-buddy/blob/master/release-notes.md)
- [Commits](https://github.com/raphw/byte-buddy/commits)

Updates `net.bytebuddy:byte-buddy-agent` from 1.18.16-jdk5 to 1.18.17-jdk5
- [Release notes](https://github.com/raphw/byte-buddy/releases)
- [Changelog](https://github.com/raphw/byte-buddy/blob/master/release-notes.md)
- [Commits](https://github.com/raphw/byte-buddy/commits)

Updates `net.bytebuddy:byte-buddy-agent` from 1.18.16-jdk5 to 1.18.17-jdk5
- [Release notes](https://github.com/raphw/byte-buddy/releases)
- [Changelog](https://github.com/raphw/byte-buddy/blob/master/release-notes.md)
- [Commits](https://github.com/raphw/byte-buddy/commits)

Updates `com.googlecode.libphonenumber:libphonenumber` from 9.0.42 to 9.0.43
- [Release notes](https://github.com/google/libphonenumber/releases)
- [Changelog](https://github.com/google/libphonenumber/blob/master/release_notes.txt)
- [Commits](https://github.com/google/libphonenumber/compare/v9.0.42...v9.0.43)

Updates `com.braintreepayments.gateway:braintree-java` from 3.55.1 to 3.56.0
- [Changelog](https://github.com/braintree/braintree_java/blob/master/CHANGELOG.md)
- [Commits](https://github.com/braintree/braintree_java/compare/3.55.1...3.56.0)

Updates `com.google.guava:guava` from 33.7.2-jre to 33.8.0-jre
- [Release notes](https://github.com/google/guava/releases)
- [Commits](https://github.com/google/guava/commits)

Updates `org.signal:libsignal-server` from 0.106.1 to 0.107.0
- [Release notes](https://github.com/signalapp/libsignal/releases)
- [Changelog](https://github.com/signalapp/libsignal/blob/v0.107.0/RELEASE_NOTES.md)
- [Commits](https://github.com/signalapp/libsignal/compare/v0.106.1...v0.107.0)

Updates `org.signal:simple-grpc-runtime` from 0.2.1 to 0.3.0
- [Commits](https://github.com/signalapp/simple-grpc/compare/0.2.1...0.3.0)

Updates `org.codehaus.mojo:exec-maven-plugin` from 3.6.4 to 3.7.0
- [Release notes](https://github.com/mojohaus/exec-maven-plugin/releases)
- [Commits](https://github.com/mojohaus/exec-maven-plugin/compare/3.6.4...3.7.0)

Updates `org.codehaus.mojo:properties-maven-plugin` from 1.3.1 to 1.4.0
- [Release notes](https://github.com/mojohaus/properties-maven-plugin/releases)
- [Commits](https://github.com/mojohaus/properties-maven-plugin/compare/properties-maven-plugin-1.3.1...1.4.0)

Updates `com.fasterxml.jackson:jackson-bom` from 2.22.4 to 2.23.0
- [Commits](https://github.com/FasterXML/jackson-bom/compare/jackson-bom-2.22.4...jackson-bom-2.23.0)

Updates `org.eclipse.jetty:jetty-bom` from 12.1.9 to 12.1.15
- [Release notes](https://github.com/jetty/jetty.project/releases)
- [Commits](https://github.com/jetty/jetty.project/compare/jetty-12.1.9...jetty-12.1.15)

Updates `org.eclipse.jetty.ee10:jetty-ee10-bom` from 12.1.9 to 12.1.15
- [Release notes](https://github.com/jetty/jetty.project/releases)
- [Commits](https://github.com/jetty/jetty.project/compare/jetty-12.1.9...jetty-12.1.15)

Updates `com.google.cloud:libraries-bom` from 26.91.0 to 26.93.0
- [Release notes](https://github.com/googleapis/google-cloud-java/releases)
- [Changelog](https://github.com/googleapis/google-cloud-java/blob/main/CHANGELOG.md)
- [Commits](https://github.com/googleapis/google-cloud-java/compare/libraries-bom/v26.91.0...libraries-bom/v26.93.0)

Updates `software.amazon.awssdk:bom` from 2.57.6 to 2.59.0

Updates `net.bytebuddy:byte-buddy` from 1.18.16-jdk5 to 1.18.17-jdk5
- [Release notes](https://github.com/raphw/byte-buddy/releases)
- [Changelog](https://github.com/raphw/byte-buddy/blob/master/release-notes.md)
- [Commits](https://github.com/raphw/byte-buddy/commits)

Updates `net.bytebuddy:byte-buddy-agent` from 1.18.16-jdk5 to 1.18.17-jdk5
- [Release notes](https://github.com/raphw/byte-buddy/releases)
- [Changelog](https://github.com/raphw/byte-buddy/blob/master/release-notes.md)
- [Commits](https://github.com/raphw/byte-buddy/commits)

Updates `com.googlecode.libphonenumber:libphonenumber` from 9.0.42 to 9.0.43
- [Release notes](https://github.com/google/libphonenumber/releases)
- [Changelog](https://github.com/google/libphonenumber/blob/master/release_notes.txt)
- [Commits](https://github.com/google/libphonenumber/compare/v9.0.42...v9.0.43)

Updates `org.foundationdb:fdb-java` from 7.3.76 to 7.3.81
- [Release notes](https://github.com/apple/foundationdb/releases)
- [Commits](https://github.com/apple/foundationdb/compare/7.3.76...7.3.81)

Updates `com.braintreepayments.gateway:braintree-java` from 3.55.1 to 3.56.0
- [Changelog](https://github.com/braintree/braintree_java/blob/master/CHANGELOG.md)
- [Commits](https://github.com/braintree/braintree_java/compare/3.55.1...3.56.0)

Updates `com.google.guava:guava` from 33.7.2-jre to 33.8.0-jre
- [Release notes](https://github.com/google/guava/releases)
- [Commits](https://github.com/google/guava/commits)

Updates `org.signal:libsignal-server` from 0.106.1 to 0.107.0
- [Release notes](https://github.com/signalapp/libsignal/releases)
- [Changelog](https://github.com/signalapp/libsignal/blob/v0.107.0/RELEASE_NOTES.md)
- [Commits](https://github.com/signalapp/libsignal/compare/v0.106.1...v0.107.0)

Updates `org.signal:simple-grpc-runtime` from 0.2.1 to 0.3.0
- [Commits](https://github.com/signalapp/simple-grpc/compare/0.2.1...0.3.0)

Updates `org.codehaus.mojo:exec-maven-plugin` from 3.6.4 to 3.7.0
- [Release notes](https://github.com/mojohaus/exec-maven-plugin/releases)
- [Commits](https://github.com/mojohaus/exec-maven-plugin/compare/3.6.4...3.7.0)

Updates `org.codehaus.mojo:properties-maven-plugin` from 1.3.1 to 1.4.0
- [Release notes](https://github.com/mojohaus/properties-maven-plugin/releases)
- [Commits](https://github.com/mojohaus/properties-maven-plugin/compare/properties-maven-plugin-1.3.1...1.4.0)

Updates `com.webauthn4j:webauthn4j-test` from 0.31.11.RELEASE to 0.32.0.RELEASE
- [Release notes](https://github.com/webauthn4j/webauthn4j/releases)
- [Commits](https://github.com/webauthn4j/webauthn4j/compare/0.31.11.RELEASE...0.32.0.RELEASE)

Updates `com.fasterxml.jackson:jackson-bom` from 2.22.4 to 2.23.0
- [Commits](https://github.com/FasterXML/jackson-bom/compare/jackson-bom-2.22.4...jackson-bom-2.23.0)

Updates `org.eclipse.jetty:jetty-bom` from 12.1.9 to 12.1.15
- [Release notes](https://github.com/jetty/jetty.project/releases)
- [Commits](https://github.com/jetty/jetty.project/compare/jetty-12.1.9...jetty-12.1.15)

Updates `org.eclipse.jetty.ee10:jetty-ee10-bom` from 12.1.9 to 12.1.15
- [Release notes](https://github.com/jetty/jetty.project/releases)
- [Commits](https://github.com/jetty/jetty.project/compare/jetty-12.1.9...jetty-12.1.15)

Updates `com.google.cloud:libraries-bom` from 26.91.0 to 26.93.0
- [Release notes](https://github.com/googleapis/google-cloud-java/releases)
- [Changelog](https://github.com/googleapis/google-cloud-java/blob/main/CHANGELOG.md)
- [Commits](https://github.com/googleapis/google-cloud-java/compare/libraries-bom/v26.91.0...libraries-bom/v26.93.0)

Updates `software.amazon.awssdk:bom` from 2.57.6 to 2.59.0

Updates `net.bytebuddy:byte-buddy` from 1.18.16-jdk5 to 1.18.17-jdk5
- [Release notes](https://github.com/raphw/byte-buddy/releases)
- [Changelog](https://github.com/raphw/byte-buddy/blob/master/release-notes.md)
- [Commits](https://github.com/raphw/byte-buddy/commits)

Updates `net.bytebuddy:byte-buddy-agent` from 1.18.16-jdk5 to 1.18.17-jdk5
- [Release notes](https://github.com/raphw/byte-buddy/releases)
- [Changelog](https://github.com/raphw/byte-buddy/blob/master/release-notes.md)
- [Commits](https://github.com/raphw/byte-buddy/commits)

Updates `com.googlecode.libphonenumber:libphonenumber` from 9.0.42 to 9.0.43
- [Release notes](https://github.com/google/libphonenumber/releases)
- [Changelog](https://github.com/google/libphonenumber/blob/master/release_notes.txt)
- [Commits](https://github.com/google/libphonenumber/compare/v9.0.42...v9.0.43)

Updates `org.foundationdb:fdb-java` from 7.3.76 to 7.3.81
- [Release notes](https://github.com/apple/foundationdb/releases)
- [Commits](https://github.com/apple/foundationdb/compare/7.3.76...7.3.81)

Updates `com.braintreepayments.gateway:braintree-java` from 3.55.1 to 3.56.0
- [Changelog](https://github.com/braintree/braintree_java/blob/master/CHANGELOG.md)
- [Commits](https://github.com/braintree/braintree_java/compare/3.55.1...3.56.0)

Updates `com.google.guava:guava` from 33.7.2-jre to 33.8.0-jre
- [Release notes](https://github.com/google/guava/releases)
- [Commits](https://github.com/google/guava/commits)

Updates `org.signal:libsignal-server` from 0.106.1 to 0.107.0
- [Release notes](https://github.com/signalapp/libsignal/releases)
- [Changelog](https://github.com/signalapp/libsignal/blob/v0.107.0/RELEASE_NOTES.md)
- [Commits](https://github.com/signalapp/libsignal/compare/v0.106.1...v0.107.0)

Updates `org.signal:simple-grpc-runtime` from 0.2.1 to 0.3.0
- [Commits](https://github.com/signalapp/simple-grpc/compare/0.2.1...0.3.0)

Updates `org.codehaus.mojo:exec-maven-plugin` from 3.6.4 to 3.7.0
- [Release notes](https://github.com/mojohaus/exec-maven-plugin/releases)
- [Commits](https://github.com/mojohaus/exec-maven-plugin/compare/3.6.4...3.7.0)

Updates `org.codehaus.mojo:properties-maven-plugin` from 1.3.1 to 1.4.0
- [Release notes](https://github.com/mojohaus/properties-maven-plugin/releases)
- [Commits](https://github.com/mojohaus/properties-maven-plugin/compare/properties-maven-plugin-1.3.1...1.4.0)

Updates `com.webauthn4j:webauthn4j-test` from 0.31.11.RELEASE to 0.32.0.RELEASE
- [Release notes](https://github.com/webauthn4j/webauthn4j/releases)
- [Commits](https://github.com/webauthn4j/webauthn4j/compare/0.31.11.RELEASE...0.32.0.RELEASE)

Updates `com.webauthn4j:webauthn4j-appattest` from 0.31.11.RELEASE to 0.32.0.RELEASE
- [Release notes](https://github.com/webauthn4j/webauthn4j/releases)
- [Commits](https://github.com/webauthn4j/webauthn4j/compare/0.31.11.RELEASE...0.32.0.RELEASE)

Updates `com.webauthn4j:webauthn4j-core` from 0.31.11.RELEASE to 0.32.0.RELEASE
- [Release notes](https://github.com/webauthn4j/webauthn4j/releases)
- [Commits](https://github.com/webauthn4j/webauthn4j/compare/0.31.11.RELEASE...0.32.0.RELEASE)

Updates `com.google.firebase:firebase-admin` from 9.11.0 to 9.12.0
- [Release notes](https://github.com/firebase/firebase-admin-java/releases)
- [Commits](https://github.com/firebase/firebase-admin-java/compare/v9.11.0...v9.12.0)

Updates `com.googlecode.libphonenumber:geocoder` from 3.42 to 3.43
- [Release notes](https://github.com/google/libphonenumber/releases)
- [Changelog](https://github.com/google/libphonenumber/blob/master/release_notes.txt)
- [Commits](https://github.com/google/libphonenumber/commits)

Updates `org.codehaus.mojo:templating-maven-plugin` from 3.1.1 to 3.2.0
- [Release notes](https://github.com/mojohaus/templating-maven-plugin/releases)
- [Commits](https://github.com/mojohaus/templating-maven-plugin/compare/templating-maven-plugin-3.1.1...3.2.0)

Updates `com.fasterxml.jackson:jackson-bom` from 2.22.4 to 2.23.0
- [Commits](https://github.com/FasterXML/jackson-bom/compare/jackson-bom-2.22.4...jackson-bom-2.23.0)

Updates `org.eclipse.jetty:jetty-bom` from 12.1.9 to 12.1.15
- [Release notes](https://github.com/jetty/jetty.project/releases)
- [Commits](https://github.com/jetty/jetty.project/compare/jetty-12.1.9...jetty-12.1.15)

Updates `org.eclipse.jetty.ee10:jetty-ee10-bom` from 12.1.9 to 12.1.15
- [Release notes](https://github.com/jetty/jetty.project/releases)
- [Commits](https://github.com/jetty/jetty.project/compare/jetty-12.1.9...jetty-12.1.15)

Updates `com.google.cloud:libraries-bom` from 26.91.0 to 26.93.0
- [Release notes](https://github.com/googleapis/google-cloud-java/releases)
- [Changelog](https://github.com/googleapis/google-cloud-java/blob/main/CHANGELOG.md)
- [Commits](https://github.com/googleapis/google-cloud-java/compare/libraries-bom/v26.91.0...libraries-bom/v26.93.0)

Updates `software.amazon.awssdk:bom` from 2.57.6 to 2.59.0

Updates `net.bytebuddy:byte-buddy` from 1.18.16-jdk5 to 1.18.17-jdk5
- [Release notes](https://github.com/raphw/byte-buddy/releases)
- [Changelog](https://github.com/raphw/byte-buddy/blob/master/release-notes.md)
- [Commits](https://github.com/raphw/byte-buddy/commits)

Updates `net.bytebuddy:byte-buddy-agent` from 1.18.16-jdk5 to 1.18.17-jdk5
- [Release notes](https://github.com/raphw/byte-buddy/releases)
- [Changelog](https://github.com/raphw/byte-buddy/blob/master/release-notes.md)
- [Commits](https://github.com/raphw/byte-buddy/commits)

Updates `com.googlecode.libphonenumber:libphonenumber` from 9.0.42 to 9.0.43
- [Release notes](https://github.com/google/libphonenumber/releases)
- [Changelog](https://github.com/google/libphonenumber/blob/master/release_notes.txt)
- [Commits](https://github.com/google/libphonenumber/compare/v9.0.42...v9.0.43)

Updates `org.foundationdb:fdb-java` from 7.3.76 to 7.3.81
- [Release notes](https://github.com/apple/foundationdb/releases)
- [Commits](https://github.com/apple/foundationdb/compare/7.3.76...7.3.81)

Updates `com.braintreepayments.gateway:braintree-java` from 3.55.1 to 3.56.0
- [Changelog](https://github.com/braintree/braintree_java/blob/master/CHANGELOG.md)
- [Commits](https://github.com/braintree/braintree_java/compare/3.55.1...3.56.0)

Updates `com.google.guava:guava` from 33.7.2-jre to 33.8.0-jre
- [Release notes](https://github.com/google/guava/releases)
- [Commits](https://github.com/google/guava/commits)

Updates `org.signal:libsignal-server` from 0.106.1 to 0.107.0
- [Release notes](https://github.com/signalapp/libsignal/releases)
- [Changelog](https://github.com/signalapp/libsignal/blob/v0.107.0/RELEASE_NOTES.md)
- [Commits](https://github.com/signalapp/libsignal/compare/v0.106.1...v0.107.0)

Updates `org.signal:simple-grpc-runtime` from 0.2.1 to 0.3.0
- [Commits](https://github.com/signalapp/simple-grpc/compare/0.2.1...0.3.0)

Updates `org.codehaus.mojo:exec-maven-plugin` from 3.6.4 to 3.7.0
- [Release notes](https://github.com/mojohaus/exec-maven-plugin/releases)
- [Commits](https://github.com/mojohaus/exec-maven-plugin/compare/3.6.4...3.7.0)

Updates `org.codehaus.mojo:properties-maven-plugin` from 1.3.1 to 1.4.0
- [Release notes](https://github.com/mojohaus/properties-maven-plugin/releases)
- [Commits](https://github.com/mojohaus/properties-maven-plugin/compare/properties-maven-plugin-1.3.1...1.4.0)

---
updated-dependencies:
- dependency-name: com.fasterxml.jackson:jackson-bom
  dependency-version: 2.23.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: org.eclipse.jetty:jetty-bom
  dependency-version: 12.1.15
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: org.eclipse.jetty.ee10:jetty-ee10-bom
  dependency-version: 12.1.15
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: org.eclipse.jetty.ee10:jetty-ee10-bom
  dependency-version: 12.1.15
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: com.google.cloud:libraries-bom
  dependency-version: 26.93.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: software.amazon.awssdk:bom
  dependency-version: 2.59.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: net.bytebuddy:byte-buddy
  dependency-version: 1.18.17-jdk5
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: net.bytebuddy:byte-buddy-agent
  dependency-version: 1.18.17-jdk5
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: net.bytebuddy:byte-buddy-agent
  dependency-version: 1.18.17-jdk5
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: com.googlecode.libphonenumber:libphonenumber
  dependency-version: 9.0.43
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: org.foundationdb:fdb-java
  dependency-version: 7.3.81
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: com.braintreepayments.gateway:braintree-java
  dependency-version: 3.56.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: com.google.guava:guava
  dependency-version: 33.8.0-jre
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: org.signal:libsignal-server
  dependency-version: 0.107.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: org.signal:simple-grpc-runtime
  dependency-version: 0.3.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: org.codehaus.mojo:exec-maven-plugin
  dependency-version: 3.7.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: org.codehaus.mojo:properties-maven-plugin
  dependency-version: 1.4.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: com.fasterxml.jackson:jackson-bom
  dependency-version: 2.23.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: org.eclipse.jetty:jetty-bom
  dependency-version: 12.1.15
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: org.eclipse.jetty.ee10:jetty-ee10-bom
  dependency-version: 12.1.15
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: com.google.cloud:libraries-bom
  dependency-version: 26.93.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: software.amazon.awssdk:bom
  dependency-version: 2.59.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: net.bytebuddy:byte-buddy
  dependency-version: 1.18.17-jdk5
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: net.bytebuddy:byte-buddy-agent
  dependency-version: 1.18.17-jdk5
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: com.googlecode.libphonenumber:libphonenumber
  dependency-version: 9.0.43
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: org.foundationdb:fdb-java
  dependency-version: 7.3.81
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: com.braintreepayments.gateway:braintree-java
  dependency-version: 3.56.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: com.google.guava:guava
  dependency-version: 33.8.0-jre
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: org.signal:libsignal-server
  dependency-version: 0.107.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: org.signal:simple-grpc-runtime
  dependency-version: 0.3.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: org.codehaus.mojo:exec-maven-plugin
  dependency-version: 3.7.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: org.codehaus.mojo:properties-maven-plugin
  dependency-version: 1.4.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: com.webauthn4j:webauthn4j-test
  dependency-version: 0.32.0.RELEASE
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: com.fasterxml.jackson:jackson-bom
  dependency-version: 2.23.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: org.eclipse.jetty:jetty-bom
  dependency-version: 12.1.15
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: org.eclipse.jetty.ee10:jetty-ee10-bom
  dependency-version: 12.1.15
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: com.google.cloud:libraries-bom
  dependency-version: 26.93.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: software.amazon.awssdk:bom
  dependency-version: 2.59.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: net.bytebuddy:byte-buddy
  dependency-version: 1.18.17-jdk5
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: net.bytebuddy:byte-buddy-agent
  dependency-version: 1.18.17-jdk5
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: com.googlecode.libphonenumber:libphonenumber
  dependency-version: 9.0.43
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: org.foundationdb:fdb-java
  dependency-version: 7.3.81
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: com.braintreepayments.gateway:braintree-java
  dependency-version: 3.56.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: com.google.guava:guava
  dependency-version: 33.8.0-jre
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: org.signal:libsignal-server
  dependency-version: 0.107.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: org.signal:simple-grpc-runtime
  dependency-version: 0.3.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: org.codehaus.mojo:exec-maven-plugin
  dependency-version: 3.7.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: org.codehaus.mojo:properties-maven-plugin
  dependency-version: 1.4.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: com.webauthn4j:webauthn4j-test
  dependency-version: 0.32.0.RELEASE
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: com.webauthn4j:webauthn4j-appattest
  dependency-version: 0.32.0.RELEASE
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: com.webauthn4j:webauthn4j-core
  dependency-version: 0.32.0.RELEASE
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: com.google.firebase:firebase-admin
  dependency-version: 9.12.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: com.googlecode.libphonenumber:geocoder
  dependency-version: '3.43'
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: org.codehaus.mojo:templating-maven-plugin
  dependency-version: 3.2.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: com.fasterxml.jackson:jackson-bom
  dependency-version: 2.23.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: org.eclipse.jetty:jetty-bom
  dependency-version: 12.1.15
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: org.eclipse.jetty.ee10:jetty-ee10-bom
  dependency-version: 12.1.15
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: com.google.cloud:libraries-bom
  dependency-version: 26.93.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: software.amazon.awssdk:bom
  dependency-version: 2.59.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: net.bytebuddy:byte-buddy
  dependency-version: 1.18.17-jdk5
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: net.bytebuddy:byte-buddy-agent
  dependency-version: 1.18.17-jdk5
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: com.googlecode.libphonenumber:libphonenumber
  dependency-version: 9.0.43
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: org.foundationdb:fdb-java
  dependency-version: 7.3.81
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: com.braintreepayments.gateway:braintree-java
  dependency-version: 3.56.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: com.google.guava:guava
  dependency-version: 33.8.0-jre
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: org.signal:libsignal-server
  dependency-version: 0.107.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: org.signal:simple-grpc-runtime
  dependency-version: 0.3.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: org.codehaus.mojo:exec-maven-plugin
  dependency-version: 3.7.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: org.codehaus.mojo:properties-maven-plugin
  dependency-version: 1.4.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-18 14:19:56 -05:00
Ravi Khadiwala 9d6589110e Update to the latest version of the spam filter 2026-11-17 16:39:59 -06:00
Ravi Khadiwala e67272033b Update to the latest version of the spam filter 2026-11-17 14:15:30 -06:00
Ravi Khadiwala 0e7afd9f90 Update to the latest version of the spam filter 2026-11-17 14:09:15 -06:00
dependabot[bot] cbbfc3966a Bump actions/setup-java
Bumps the minor-actions-dependencies group with 1 update: [actions/setup-java](https://github.com/actions/setup-java).


Updates `actions/setup-java` from 6.1.0 to 6.2.0
- [Release notes](https://github.com/actions/setup-java/releases)
- [Commits](https://github.com/actions/setup-java/compare/b843ebf9b913146b38da2eaa7aeddf76074ae1ad...77dd5b2ce225ea11469928ac317850245a74ae78)

---
updated-dependencies:
- dependency-name: actions/setup-java
  dependency-version: 6.2.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-actions-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-16 09:54:39 -05:00
andrew-signal 59f5adc934 Request gzip'd responses from KT backend 2026-11-16 09:45:06 -05:00
Chris Eager 67ab444604 Use full avatar URL in gRPC responses 2026-11-16 09:40:56 -05:00
Andrew 5e44fbd4e9 Rename kem_one_time_pre_key to more truthful kem_pre_key 2026-11-16 09:39:32 -05:00
Chris Eager 8abb61ebe6 dependabot: remove jetty ignore 2026-11-16 09:39:18 -05:00
Ameya Lokare 50634ae07e Update to java version that removes tainted root certificates 2026-11-10 13:53:24 -08:00
Jon Chambers 8d426b788d Simplify process for getting distinct databases for an account 2026-11-10 13:51:06 -08:00
Jon Chambers a57dd64196 Expect a collection of distinct databases when constructing a FoundationDbMessageStream 2026-11-10 13:51:06 -08:00
Jon Chambers 451bbf1da9 Replace .flatMap with .then to avoid a no-op on empty Mono 2026-11-10 13:49:25 -08:00
Ravi Khadiwala 358fb8e58a Switch all-idle timeout to read-idle timeout
idle-timeouts now fire when we haven't read anything from the client
after the configured timeout. This ensures timeouts still fire if
our outbound writes are just being buffered somewhere.

Also, update the default timeout to 1 minute
2026-11-10 13:48:00 -08:00
Jon Chambers 1a36eff391 Retire "delete and get message" methods 2026-11-09 15:05:47 -05:00
Ravi Khadiwala cc487aa2ac Fix flaky replaceConnectionAfterGoAway
Make sure that the pipeline modification finishes before we write and
flush the GOAWAY
2026-11-09 12:27:58 -06:00
dependabot[bot] 21be842303 Bump the minor-java-dependencies group across 4 directories with 9 updates
Bumps the minor-java-dependencies group with 8 updates in the /api-doc directory:

| Package | From | To |
| --- | --- | --- |
| [com.google.cloud:libraries-bom](https://github.com/googleapis/google-cloud-java) | `26.90.0` | `26.91.0` |
| software.amazon.awssdk:bom | `2.57.3` | `2.57.6` |
| [net.bytebuddy:byte-buddy](https://github.com/raphw/byte-buddy) | `1.18.15-jdk5` | `1.18.16-jdk5` |
| [net.bytebuddy:byte-buddy-agent](https://github.com/raphw/byte-buddy) | `1.18.15-jdk5` | `1.18.16-jdk5` |
| [net.bytebuddy:byte-buddy-agent](https://github.com/raphw/byte-buddy) | `1.18.15-jdk5` | `1.18.16-jdk5` |
| [io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom](https://github.com/open-telemetry/opentelemetry-java-instrumentation) | `2.33.0` | `2.33.1` |
| [com.redis:testcontainers-redis](https://github.com/redis-field-engineering/testcontainers-redis) | `3.0.0` | `3.0.1` |
| [org.signal:libsignal-server](https://github.com/signalapp/libsignal) | `0.105.4` | `0.106.1` |
| [org.apache.maven.plugins:maven-enforcer-plugin](https://github.com/apache/maven-enforcer) | `3.6.3` | `3.7.0` |

Bumps the minor-java-dependencies group with 8 updates in the /integration-tests directory:

| Package | From | To |
| --- | --- | --- |
| [com.google.cloud:libraries-bom](https://github.com/googleapis/google-cloud-java) | `26.90.0` | `26.91.0` |
| software.amazon.awssdk:bom | `2.57.3` | `2.57.6` |
| [net.bytebuddy:byte-buddy](https://github.com/raphw/byte-buddy) | `1.18.15-jdk5` | `1.18.16-jdk5` |
| [net.bytebuddy:byte-buddy-agent](https://github.com/raphw/byte-buddy) | `1.18.15-jdk5` | `1.18.16-jdk5` |
| [io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom](https://github.com/open-telemetry/opentelemetry-java-instrumentation) | `2.33.0` | `2.33.1` |
| [com.redis:testcontainers-redis](https://github.com/redis-field-engineering/testcontainers-redis) | `3.0.0` | `3.0.1` |
| [org.signal:libsignal-server](https://github.com/signalapp/libsignal) | `0.105.4` | `0.106.1` |
| [org.apache.maven.plugins:maven-enforcer-plugin](https://github.com/apache/maven-enforcer) | `3.6.3` | `3.7.0` |

Bumps the minor-java-dependencies group with 9 updates in the /service directory:

| Package | From | To |
| --- | --- | --- |
| [com.google.cloud:libraries-bom](https://github.com/googleapis/google-cloud-java) | `26.90.0` | `26.91.0` |
| software.amazon.awssdk:bom | `2.57.3` | `2.57.6` |
| [net.bytebuddy:byte-buddy](https://github.com/raphw/byte-buddy) | `1.18.15-jdk5` | `1.18.16-jdk5` |
| [net.bytebuddy:byte-buddy-agent](https://github.com/raphw/byte-buddy) | `1.18.15-jdk5` | `1.18.16-jdk5` |
| [io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom](https://github.com/open-telemetry/opentelemetry-java-instrumentation) | `2.33.0` | `2.33.1` |
| [com.redis:testcontainers-redis](https://github.com/redis-field-engineering/testcontainers-redis) | `3.0.0` | `3.0.1` |
| [org.signal:libsignal-server](https://github.com/signalapp/libsignal) | `0.105.4` | `0.106.1` |
| [org.apache.maven.plugins:maven-enforcer-plugin](https://github.com/apache/maven-enforcer) | `3.6.3` | `3.7.0` |
| [io.opentelemetry.instrumentation:opentelemetry-logback-appender-1.0](https://github.com/open-telemetry/opentelemetry-java-instrumentation) | `2.33.0-alpha` | `2.33.1-alpha` |

Bumps the minor-java-dependencies group with 8 updates in the /websocket-resources directory:

| Package | From | To |
| --- | --- | --- |
| [com.google.cloud:libraries-bom](https://github.com/googleapis/google-cloud-java) | `26.90.0` | `26.91.0` |
| software.amazon.awssdk:bom | `2.57.3` | `2.57.6` |
| [net.bytebuddy:byte-buddy](https://github.com/raphw/byte-buddy) | `1.18.15-jdk5` | `1.18.16-jdk5` |
| [net.bytebuddy:byte-buddy-agent](https://github.com/raphw/byte-buddy) | `1.18.15-jdk5` | `1.18.16-jdk5` |
| [io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom](https://github.com/open-telemetry/opentelemetry-java-instrumentation) | `2.33.0` | `2.33.1` |
| [com.redis:testcontainers-redis](https://github.com/redis-field-engineering/testcontainers-redis) | `3.0.0` | `3.0.1` |
| [org.signal:libsignal-server](https://github.com/signalapp/libsignal) | `0.105.4` | `0.106.1` |
| [org.apache.maven.plugins:maven-enforcer-plugin](https://github.com/apache/maven-enforcer) | `3.6.3` | `3.7.0` |



Updates `com.google.cloud:libraries-bom` from 26.90.0 to 26.91.0
- [Release notes](https://github.com/googleapis/google-cloud-java/releases)
- [Changelog](https://github.com/googleapis/google-cloud-java/blob/main/CHANGELOG.md)
- [Commits](https://github.com/googleapis/google-cloud-java/compare/libraries-bom/v26.90.0...libraries-bom/v26.91.0)

Updates `software.amazon.awssdk:bom` from 2.57.3 to 2.57.6

Updates `net.bytebuddy:byte-buddy` from 1.18.15-jdk5 to 1.18.16-jdk5
- [Release notes](https://github.com/raphw/byte-buddy/releases)
- [Changelog](https://github.com/raphw/byte-buddy/blob/master/release-notes.md)
- [Commits](https://github.com/raphw/byte-buddy/commits)

Updates `net.bytebuddy:byte-buddy-agent` from 1.18.15-jdk5 to 1.18.16-jdk5
- [Release notes](https://github.com/raphw/byte-buddy/releases)
- [Changelog](https://github.com/raphw/byte-buddy/blob/master/release-notes.md)
- [Commits](https://github.com/raphw/byte-buddy/commits)

Updates `net.bytebuddy:byte-buddy-agent` from 1.18.15-jdk5 to 1.18.16-jdk5
- [Release notes](https://github.com/raphw/byte-buddy/releases)
- [Changelog](https://github.com/raphw/byte-buddy/blob/master/release-notes.md)
- [Commits](https://github.com/raphw/byte-buddy/commits)

Updates `io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom` from 2.33.0 to 2.33.1
- [Release notes](https://github.com/open-telemetry/opentelemetry-java-instrumentation/releases)
- [Changelog](https://github.com/open-telemetry/opentelemetry-java-instrumentation/blob/v2.33.1/CHANGELOG.md)
- [Commits](https://github.com/open-telemetry/opentelemetry-java-instrumentation/compare/v2.33.0...v2.33.1)

Updates `com.redis:testcontainers-redis` from 3.0.0 to 3.0.1
- [Release notes](https://github.com/redis-field-engineering/testcontainers-redis/releases)
- [Commits](https://github.com/redis-field-engineering/testcontainers-redis/compare/v3.0.0...v3.0.1)

Updates `org.signal:libsignal-server` from 0.105.4 to 0.106.1
- [Release notes](https://github.com/signalapp/libsignal/releases)
- [Changelog](https://github.com/signalapp/libsignal/blob/main/RELEASE_NOTES.md)
- [Commits](https://github.com/signalapp/libsignal/compare/v0.105.4...v0.106.1)

Updates `org.apache.maven.plugins:maven-enforcer-plugin` from 3.6.3 to 3.7.0
- [Release notes](https://github.com/apache/maven-enforcer/releases)
- [Commits](https://github.com/apache/maven-enforcer/compare/enforcer-3.6.3...enforcer-3.7.0)

Updates `com.google.cloud:libraries-bom` from 26.90.0 to 26.91.0
- [Release notes](https://github.com/googleapis/google-cloud-java/releases)
- [Changelog](https://github.com/googleapis/google-cloud-java/blob/main/CHANGELOG.md)
- [Commits](https://github.com/googleapis/google-cloud-java/compare/libraries-bom/v26.90.0...libraries-bom/v26.91.0)

Updates `software.amazon.awssdk:bom` from 2.57.3 to 2.57.6

Updates `net.bytebuddy:byte-buddy` from 1.18.15-jdk5 to 1.18.16-jdk5
- [Release notes](https://github.com/raphw/byte-buddy/releases)
- [Changelog](https://github.com/raphw/byte-buddy/blob/master/release-notes.md)
- [Commits](https://github.com/raphw/byte-buddy/commits)

Updates `net.bytebuddy:byte-buddy-agent` from 1.18.15-jdk5 to 1.18.16-jdk5
- [Release notes](https://github.com/raphw/byte-buddy/releases)
- [Changelog](https://github.com/raphw/byte-buddy/blob/master/release-notes.md)
- [Commits](https://github.com/raphw/byte-buddy/commits)

Updates `io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom` from 2.33.0 to 2.33.1
- [Release notes](https://github.com/open-telemetry/opentelemetry-java-instrumentation/releases)
- [Changelog](https://github.com/open-telemetry/opentelemetry-java-instrumentation/blob/v2.33.1/CHANGELOG.md)
- [Commits](https://github.com/open-telemetry/opentelemetry-java-instrumentation/compare/v2.33.0...v2.33.1)

Updates `com.redis:testcontainers-redis` from 3.0.0 to 3.0.1
- [Release notes](https://github.com/redis-field-engineering/testcontainers-redis/releases)
- [Commits](https://github.com/redis-field-engineering/testcontainers-redis/compare/v3.0.0...v3.0.1)

Updates `org.signal:libsignal-server` from 0.105.4 to 0.106.1
- [Release notes](https://github.com/signalapp/libsignal/releases)
- [Changelog](https://github.com/signalapp/libsignal/blob/main/RELEASE_NOTES.md)
- [Commits](https://github.com/signalapp/libsignal/compare/v0.105.4...v0.106.1)

Updates `org.apache.maven.plugins:maven-enforcer-plugin` from 3.6.3 to 3.7.0
- [Release notes](https://github.com/apache/maven-enforcer/releases)
- [Commits](https://github.com/apache/maven-enforcer/compare/enforcer-3.6.3...enforcer-3.7.0)

Updates `com.google.cloud:libraries-bom` from 26.90.0 to 26.91.0
- [Release notes](https://github.com/googleapis/google-cloud-java/releases)
- [Changelog](https://github.com/googleapis/google-cloud-java/blob/main/CHANGELOG.md)
- [Commits](https://github.com/googleapis/google-cloud-java/compare/libraries-bom/v26.90.0...libraries-bom/v26.91.0)

Updates `software.amazon.awssdk:bom` from 2.57.3 to 2.57.6

Updates `net.bytebuddy:byte-buddy` from 1.18.15-jdk5 to 1.18.16-jdk5
- [Release notes](https://github.com/raphw/byte-buddy/releases)
- [Changelog](https://github.com/raphw/byte-buddy/blob/master/release-notes.md)
- [Commits](https://github.com/raphw/byte-buddy/commits)

Updates `net.bytebuddy:byte-buddy-agent` from 1.18.15-jdk5 to 1.18.16-jdk5
- [Release notes](https://github.com/raphw/byte-buddy/releases)
- [Changelog](https://github.com/raphw/byte-buddy/blob/master/release-notes.md)
- [Commits](https://github.com/raphw/byte-buddy/commits)

Updates `io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom` from 2.33.0 to 2.33.1
- [Release notes](https://github.com/open-telemetry/opentelemetry-java-instrumentation/releases)
- [Changelog](https://github.com/open-telemetry/opentelemetry-java-instrumentation/blob/v2.33.1/CHANGELOG.md)
- [Commits](https://github.com/open-telemetry/opentelemetry-java-instrumentation/compare/v2.33.0...v2.33.1)

Updates `com.redis:testcontainers-redis` from 3.0.0 to 3.0.1
- [Release notes](https://github.com/redis-field-engineering/testcontainers-redis/releases)
- [Commits](https://github.com/redis-field-engineering/testcontainers-redis/compare/v3.0.0...v3.0.1)

Updates `org.signal:libsignal-server` from 0.105.4 to 0.106.1
- [Release notes](https://github.com/signalapp/libsignal/releases)
- [Changelog](https://github.com/signalapp/libsignal/blob/main/RELEASE_NOTES.md)
- [Commits](https://github.com/signalapp/libsignal/compare/v0.105.4...v0.106.1)

Updates `org.apache.maven.plugins:maven-enforcer-plugin` from 3.6.3 to 3.7.0
- [Release notes](https://github.com/apache/maven-enforcer/releases)
- [Commits](https://github.com/apache/maven-enforcer/compare/enforcer-3.6.3...enforcer-3.7.0)

Updates `io.opentelemetry.instrumentation:opentelemetry-logback-appender-1.0` from 2.33.0-alpha to 2.33.1-alpha
- [Release notes](https://github.com/open-telemetry/opentelemetry-java-instrumentation/releases)
- [Changelog](https://github.com/open-telemetry/opentelemetry-java-instrumentation/blob/main/CHANGELOG.md)
- [Commits](https://github.com/open-telemetry/opentelemetry-java-instrumentation/commits)

Updates `com.google.cloud:libraries-bom` from 26.90.0 to 26.91.0
- [Release notes](https://github.com/googleapis/google-cloud-java/releases)
- [Changelog](https://github.com/googleapis/google-cloud-java/blob/main/CHANGELOG.md)
- [Commits](https://github.com/googleapis/google-cloud-java/compare/libraries-bom/v26.90.0...libraries-bom/v26.91.0)

Updates `software.amazon.awssdk:bom` from 2.57.3 to 2.57.6

Updates `net.bytebuddy:byte-buddy` from 1.18.15-jdk5 to 1.18.16-jdk5
- [Release notes](https://github.com/raphw/byte-buddy/releases)
- [Changelog](https://github.com/raphw/byte-buddy/blob/master/release-notes.md)
- [Commits](https://github.com/raphw/byte-buddy/commits)

Updates `net.bytebuddy:byte-buddy-agent` from 1.18.15-jdk5 to 1.18.16-jdk5
- [Release notes](https://github.com/raphw/byte-buddy/releases)
- [Changelog](https://github.com/raphw/byte-buddy/blob/master/release-notes.md)
- [Commits](https://github.com/raphw/byte-buddy/commits)

Updates `io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom` from 2.33.0 to 2.33.1
- [Release notes](https://github.com/open-telemetry/opentelemetry-java-instrumentation/releases)
- [Changelog](https://github.com/open-telemetry/opentelemetry-java-instrumentation/blob/v2.33.1/CHANGELOG.md)
- [Commits](https://github.com/open-telemetry/opentelemetry-java-instrumentation/compare/v2.33.0...v2.33.1)

Updates `com.redis:testcontainers-redis` from 3.0.0 to 3.0.1
- [Release notes](https://github.com/redis-field-engineering/testcontainers-redis/releases)
- [Commits](https://github.com/redis-field-engineering/testcontainers-redis/compare/v3.0.0...v3.0.1)

Updates `org.signal:libsignal-server` from 0.105.4 to 0.106.1
- [Release notes](https://github.com/signalapp/libsignal/releases)
- [Changelog](https://github.com/signalapp/libsignal/blob/main/RELEASE_NOTES.md)
- [Commits](https://github.com/signalapp/libsignal/compare/v0.105.4...v0.106.1)

Updates `org.apache.maven.plugins:maven-enforcer-plugin` from 3.6.3 to 3.7.0
- [Release notes](https://github.com/apache/maven-enforcer/releases)
- [Commits](https://github.com/apache/maven-enforcer/compare/enforcer-3.6.3...enforcer-3.7.0)

---
updated-dependencies:
- dependency-name: com.google.cloud:libraries-bom
  dependency-version: 26.91.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: software.amazon.awssdk:bom
  dependency-version: 2.57.6
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: net.bytebuddy:byte-buddy
  dependency-version: 1.18.16-jdk5
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: net.bytebuddy:byte-buddy-agent
  dependency-version: 1.18.16-jdk5
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: net.bytebuddy:byte-buddy-agent
  dependency-version: 1.18.16-jdk5
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom
  dependency-version: 2.33.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: com.redis:testcontainers-redis
  dependency-version: 3.0.1
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: org.signal:libsignal-server
  dependency-version: 0.106.1
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: org.apache.maven.plugins:maven-enforcer-plugin
  dependency-version: 3.7.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: com.google.cloud:libraries-bom
  dependency-version: 26.91.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: software.amazon.awssdk:bom
  dependency-version: 2.57.6
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: net.bytebuddy:byte-buddy
  dependency-version: 1.18.16-jdk5
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: net.bytebuddy:byte-buddy-agent
  dependency-version: 1.18.16-jdk5
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom
  dependency-version: 2.33.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: com.redis:testcontainers-redis
  dependency-version: 3.0.1
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: org.signal:libsignal-server
  dependency-version: 0.106.1
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: org.apache.maven.plugins:maven-enforcer-plugin
  dependency-version: 3.7.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: com.google.cloud:libraries-bom
  dependency-version: 26.91.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: software.amazon.awssdk:bom
  dependency-version: 2.57.6
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: net.bytebuddy:byte-buddy
  dependency-version: 1.18.16-jdk5
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: net.bytebuddy:byte-buddy-agent
  dependency-version: 1.18.16-jdk5
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom
  dependency-version: 2.33.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: com.redis:testcontainers-redis
  dependency-version: 3.0.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: org.signal:libsignal-server
  dependency-version: 0.106.1
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: org.apache.maven.plugins:maven-enforcer-plugin
  dependency-version: 3.7.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: io.opentelemetry.instrumentation:opentelemetry-logback-appender-1.0
  dependency-version: 2.33.1-alpha
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: com.google.cloud:libraries-bom
  dependency-version: 26.91.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: software.amazon.awssdk:bom
  dependency-version: 2.57.6
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: net.bytebuddy:byte-buddy
  dependency-version: 1.18.16-jdk5
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: net.bytebuddy:byte-buddy-agent
  dependency-version: 1.18.16-jdk5
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom
  dependency-version: 2.33.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: com.redis:testcontainers-redis
  dependency-version: 3.0.1
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: minor-java-dependencies
- dependency-name: org.signal:libsignal-server
  dependency-version: 0.106.1
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
- dependency-name: org.apache.maven.plugins:maven-enforcer-plugin
  dependency-version: 3.7.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: minor-java-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-04 14:25:30 -06:00
Chris Eager 7af5bd4d2e Add GrpcCompressionInterceptor 2026-11-04 14:22:39 -06:00
Jon Chambers f8e22ae674 Enforce attachment upload rate limits 2026-11-04 14:22:09 -06:00
Ravi Khadiwala a4a5c1bb29 Add connection pooling for the gRPC omnibus backend 2026-11-04 14:19:32 -06:00
Ravi Khadiwala 2220f750dd Move omnibus h2 connection logic into a factory 2026-11-04 14:19:01 -06:00
Chris Eager 27980ed25d Update to Netty 4.2.20 2026-11-04 14:16:50 -06:00
91 changed files with 1987 additions and 1058 deletions

No files matched your search

-6
View File
@@ -26,14 +26,8 @@ updates:
# https://github.com/dropwizard/dropwizard/pull/11273
- dependency-name: "ch.qos.logback:*"
versions: [">=1.6.0"]
# https://github.com/jetty/jetty.project/issues/15657
- dependency-name: "org.eclipse.jetty:*"
versions: ["<=12.1.14"]
- dependency-name: "org.eclipse.jetty.ee10:*"
versions: ["<=12.1.14"]
# Dependency convergence sentinels, pinned to specific versions
- dependency-name: "tools.jackson.core:jackson-databind"
- dependency-name: "com.squareup.okio:okio-jvm"
groups:
+1 -1
View File
@@ -18,7 +18,7 @@ jobs:
# setup-java requires gpg
sudo apt-get install -y protobuf-compiler gpg
pip install sabledocs
- uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6.1.0
- uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6.3.0
with:
distribution: 'temurin'
java-version-file: .java-version
+1 -1
View File
@@ -25,7 +25,7 @@ jobs:
# setup-java requires gpg
sudo apt update
sudo apt install -y gpg
- uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6.1.0
- uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6.3.0
with:
distribution: 'temurin'
java-version-file: .java-version
+1 -1
View File
@@ -50,7 +50,7 @@ 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@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6.1.0
uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6.3.0
with:
distribution: 'temurin'
java-version-file: .java-version
@@ -8,6 +8,7 @@ package org.signal.integration;
import static java.util.Objects.requireNonNull;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.io.Resources;
import com.google.common.net.HttpHeaders;
import com.webauthn4j.data.AuthenticatorAssertionResponse;
@@ -56,6 +57,7 @@ import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
@@ -121,6 +123,8 @@ public final class Operations {
private static final FaultTolerantHttpClient CLIENT = buildClient();
private static final FaultTolerantHttpClient NO_RETRY_CLIENT = buildNoRetryClient();
private static final WebSocketClient WEB_SOCKET_CLIENT = buildWebSocketClient();
private static final ManagedChannel GRPC_CHANNEL = buildGrpcChannel();
@@ -257,50 +261,66 @@ public final class Operations {
Optional.empty()));
// we expect (and need) failure with status 441, which will contain the WebAuthn challenge
final MfaFailureExceptionMapper.MfaFailureResponse mfaFailureResponse = apiPost("/v1/registration", initialRequest)
MfaFailureExceptionMapper.MfaFailureResponse mfaFailureResponse = apiPost("/v1/registration", initialRequest)
// For a numberless account recovery, the username is the ACI
.authorized(testUser.aciUuid().toString(), testUser.accountPassword())
.executeExpectStatusCode(441, MfaFailureExceptionMapper.MfaFailureResponse.class);
Validate.isTrue(mfaFailureResponse.webAuthnParameters().allowedCredentialIds()
.stream()
.anyMatch(allowedId -> Arrays.equals(allowedId, credentialId)),
"Expected MFA failure to contain credentialId");
// Retry a 441 to 3 times. It's possible we burned a challenge on a 500 that actually succeeded, but we didn't see
// the response, so we can retry on the new challenge.
int attempt = 0;
while (true) {
attempt++;
Validate.isTrue(mfaFailureResponse.webAuthnParameters().allowedCredentialIds()
.stream()
.anyMatch(allowedId -> Arrays.equals(allowedId, credentialId)),
"Expected MFA failure to contain credentialId");
final PublicKeyCredential<AuthenticatorAssertionResponse, ?> credential =
clientPlatform.get(new PublicKeyCredentialRequestOptions(
new DefaultChallenge(mfaFailureResponse.webAuthnParameters().challenge()),
null,
relyingPartyId,
List.of(new PublicKeyCredentialDescriptor(PublicKeyCredentialType.PUBLIC_KEY, credentialId, null)),
UserVerificationRequirement.DISCOURAGED,
null));
final PublicKeyCredential<AuthenticatorAssertionResponse, ?> credential =
clientPlatform.get(new PublicKeyCredentialRequestOptions(
new DefaultChallenge(mfaFailureResponse.webAuthnParameters().challenge()),
null,
relyingPartyId,
List.of(new PublicKeyCredentialDescriptor(PublicKeyCredentialType.PUBLIC_KEY, credentialId, null)),
UserVerificationRequirement.DISCOURAGED,
null));
final RegistrationRequest registrationRequest = new RegistrationRequest(null,
testUser.registrationPassword(),
null,
null,
webAuthnVerificationResponseJson(credential),
recoveredUser.accountAttributes(),
true,
new IdentityKey(aciIdentityKeyPair.getPublicKey()),
new IdentityKey(pniIdentityKeyPair.getPublicKey()),
new DeviceActivationRequest(generateSignedECPreKey(1, aciIdentityKeyPair),
Optional.of(generateSignedECPreKey(2, pniIdentityKeyPair)),
generateSignedKEMPreKey(3, aciIdentityKeyPair),
Optional.of(generateSignedKEMPreKey(4, pniIdentityKeyPair)),
Optional.empty(),
Optional.empty()));
final RegistrationRequest registrationRequest = new RegistrationRequest(null,
testUser.registrationPassword(),
null,
null,
webAuthnVerificationResponseJson(credential),
recoveredUser.accountAttributes(),
true,
new IdentityKey(aciIdentityKeyPair.getPublicKey()),
new IdentityKey(pniIdentityKeyPair.getPublicKey()),
new DeviceActivationRequest(generateSignedECPreKey(1, aciIdentityKeyPair),
Optional.of(generateSignedECPreKey(2, pniIdentityKeyPair)),
generateSignedKEMPreKey(3, aciIdentityKeyPair),
Optional.of(generateSignedKEMPreKey(4, pniIdentityKeyPair)),
Optional.empty(),
Optional.empty()));
final AccountIdentityResponse registrationResponse = apiPost("/v1/registration", registrationRequest)
// For a numberless account recovery, the username is the ACI
.authorized(testUser.aciUuid().toString(), testUser.accountPassword())
.executeExpectSuccess(AccountIdentityResponse.class);
final Pair<Integer, JsonNode> registrationResponse = apiPost("/v1/registration", registrationRequest)
// For a numberless account recovery, the username is the ACI
.authorized(testUser.aciUuid().toString(), testUser.accountPassword())
.execute(JsonNode.class);
recoveredUser.setAciUuid(registrationResponse.uuid());
return recoveredUser;
if (registrationResponse.getLeft() == 441 && attempt < 3) {
mfaFailureResponse = SystemMapper.jsonMapper()
.convertValue(registrationResponse.getRight(), MfaFailureExceptionMapper.MfaFailureResponse.class);
continue;
}
Validate.isTrue(HttpUtils.isSuccessfulResponse(registrationResponse.getLeft()),
"Unexpected response code: %d, body: %s", registrationResponse.getLeft(), registrationResponse.getRight());
recoveredUser.setAciUuid(SystemMapper.jsonMapper()
.convertValue(registrationResponse.getRight(), AccountIdentityResponse.class).uuid());
return recoveredUser;
}
}
public static TestUser newRegisteredUser(final String number) {
final byte[] registrationPassword = populateRandomRecoveryPassword(number);
final String accountPassword = Base64.getEncoder().encodeToString(randomBytes(32));
@@ -347,7 +367,24 @@ public final class Operations {
}
public static void deleteUser(final TestUser user) {
apiDelete("/v1/accounts/me").authorized(user).executeExpectSuccess();
final AtomicInteger attempts = new AtomicInteger();
final Retry retry = Retry.of("integration-test-delete-user",
new RetryConfiguration().<Integer>toRetryConfigBuilder()
.retryOnResult(statusCode -> statusCode >= 500)
.build());
final int statusCode = retry.executeSupplier(() -> {
attempts.incrementAndGet();
return apiDelete("/v1/accounts/me")
.authorized(user)
// disable retries, since this endpoint is not idempotent
.withoutRetries()
.execute()
.getLeft();
});
// If we had to retry a 500 where the account was already deleted, we would fail authorization
Validate.isTrue(HttpUtils.isSuccessfulResponse(statusCode) || (attempts.get() > 1 && statusCode == 401),
"Unexpected response code: %d", statusCode);
}
public static String peekVerificationSessionPushChallenge(final String sessionId) {
@@ -486,6 +523,7 @@ public final class Operations {
private final List<String> queryParams = new ArrayList<>();
private boolean retryServerErrors = true;
private RequestBuilder(final HttpRequest.Builder builder, final String endpoint) {
this.builder = builder;
@@ -523,6 +561,12 @@ public final class Operations {
return this;
}
/// Don't automatically retry 5xx responses, for requests that aren't safe to blindly retry
public RequestBuilder withoutRetries() {
retryServerErrors = false;
return this;
}
public Pair<Integer, Void> execute() {
return execute(Void.class);
}
@@ -572,7 +616,8 @@ public final class Operations {
private RawResponse executeRaw() {
builder.uri(serverUri(endpoint, queryParams))
.header(HttpHeaders.USER_AGENT, USER_AGENT);
return CLIENT.sendAsync(builder.build(), HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8))
return (retryServerErrors ? CLIENT : NO_RETRY_CLIENT)
.sendAsync(builder.build(), HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8))
.whenComplete((response, error) -> {
if (error != null) {
logger.error("request error", error);
@@ -615,6 +660,16 @@ public final class Operations {
}
}
private static FaultTolerantHttpClient buildNoRetryClient() {
try {
return FaultTolerantHttpClient.newBuilder("integration-test-no-retry", Executors.newFixedThreadPool(16))
.withTrustedServerCertificates(CONFIG.rootCerts().toArray(String[]::new))
.build();
} catch (final CertificateException e) {
throw new RuntimeException(e);
}
}
private static WebSocketClient buildWebSocketClient() {
try {
final KeyStore trustStore = CertificateUtil.buildKeyStoreForPem(CONFIG.rootCerts().toArray(String[]::new));
@@ -66,6 +66,7 @@ import org.signal.libsignal.usernames.BaseUsernameException;
import org.signal.libsignal.usernames.Username;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.VerificationFailedException;
import org.signal.libsignal.zkgroup.internal.ByteArray;
import org.whispersystems.textsecuregcm.entities.AccountIdentifierResponse;
import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse;
import org.whispersystems.textsecuregcm.entities.ChangeNumberRequest;
@@ -289,7 +290,10 @@ public class AccountTest {
// reserve a username
final ReserveUsernameHashRequest reserveUsernameHashRequest = new ReserveUsernameHashRequest(
candidates.stream().map(Username::getHash).toList());
candidates.stream()
.map(Username::getHash)
.map(ByteArray::serialize)
.toList());
// try unauthorized
Operations
.apiPut("/v1/accounts/username_hash/reserve", reserveUsernameHashRequest)
@@ -303,13 +307,13 @@ public class AccountTest {
// find which one is the reserved username
final byte[] reservedHash = reserveUsernameHashResponse.usernameHash();
final Username reservedUsername = candidates.stream()
.filter(u -> Arrays.equals(u.getHash(), reservedHash))
.filter(u -> Arrays.equals(u.getHash().serialize(), reservedHash))
.findAny()
.orElseThrow();
// confirm a username
final ConfirmUsernameHashRequest confirmUsernameHashRequest = new ConfirmUsernameHashRequest(
reservedUsername.getHash(),
reservedUsername.getHash().serialize(),
reservedUsername.generateProof(),
"cluck cluck i'm a parrot".getBytes()
);
@@ -6,6 +6,7 @@
package org.signal.integration;
import io.micrometer.common.util.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.whispersystems.textsecuregcm.entities.CreateVerificationSessionRequest;
@@ -54,8 +55,13 @@ public class RegistrationTest {
// verify code
final SubmitVerificationCodeRequest submitVerificationCodeRequest = new SubmitVerificationCodeRequest(
params.verificationCode());
final VerificationSessionResponse codeVerified = Operations
final Pair<Integer, VerificationSessionResponse> codeVerified = Operations
.apiPut("/v1/verification/session/%s/code".formatted(sessionId), submitVerificationCodeRequest)
.executeExpectSuccess(VerificationSessionResponse.class);
.execute(VerificationSessionResponse.class);
// If we succeeded but then retried a 500, we might have submitted a code when we were already verified
Assertions.assertTrue(codeVerified.getLeft() == 200 || codeVerified.getLeft() == 409,
"Unexpected response code: " + codeVerified.getLeft());
Assertions.assertTrue(codeVerified.getRight().verified());
}
}
+19 -25
View File
@@ -45,12 +45,12 @@
</modules>
<properties>
<aws.sdk2.version>2.57.3</aws.sdk2.version>
<braintree.version>3.55.1</braintree.version>
<aws.sdk2.version>2.59.1</aws.sdk2.version>
<braintree.version>3.56.0</braintree.version>
<!-- Weird stuff happens with parameter annotation counts under Java 27 with versions of Byte Buddy older than
1.18.9, so we need to pull in a newer version than we'd get via Dropwizard -> Mockito -> Byte Buddy. We can drop
this when Dropwizard updates and pulls in a newer version of Byte Buddy. -->
<byte-buddy.version>1.18.15-jdk5</byte-buddy.version>
<byte-buddy.version>1.18.17-jdk5</byte-buddy.version>
<commons-csv.version>1.14.1</commons-csv.version>
<commons-io.version>2.22.0</commons-io.version>
<dropwizard.version>5.0.2</dropwizard.version>
@@ -59,12 +59,12 @@
<foundationdb.version>7.3.76</foundationdb.version>
<foundationdb.api-version>730</foundationdb.api-version>
<foundationdb.client-library-sha256>af099848721d08904ff9e5d38fade0de24d92e86451ea491d9ab5ce84adcf62a</foundationdb.client-library-sha256>
<google-cloud-libraries.version>26.90.0</google-cloud-libraries.version>
<google-cloud-libraries.version>26.93.0</google-cloud-libraries.version>
<grpc.version>1.76.3</grpc.version> <!-- should be kept in sync with the value from Google libraries-bom -->
<guava.version>33.7.2-jre</guava.version>
<guava.version>33.8.0-jre</guava.version>
<!-- several libraries (AWS, Google Cloud) use Apache httpclient transitively, and we need to align them -->
<httpclient.version>4.5.14</httpclient.version>
<jackson.version>2.22.4</jackson.version>
<jackson.version>2.23.0</jackson.version>
<java-otp.version>1.0.0</java-otp.version>
<jetty.version>12.1.9</jetty.version>
<junit-pioneer.version>2.3.0</junit-pioneer.version>
@@ -74,16 +74,15 @@
<logback.version>1.5.38</logback.version>
<logback-access-common.version>2.0.15</logback-access-common.version>
<lettuce.version>7.9.0.RELEASE</lettuce.version>
<libphonenumber.version>9.0.42</libphonenumber.version>
<logstash.logback.version>9.0</logstash.logback.version>
<libphonenumber.version>9.0.43</libphonenumber.version>
<log4j-bom.version>2.26.1</log4j-bom.version>
<luajava.version>4.1.0</luajava.version>
<micrometer.version>1.17.2</micrometer.version>
<netty.version>4.2.19.Final</netty.version>
<netty.version>4.2.20.Final</netty.version>
<!-- netty-bom doesn't manage the BoringSSL uber-jar; keep in sync with netty's tcnative.version -->
<netty-tcnative.version>2.0.84.Final</netty-tcnative.version>
<netty-tcnative.version>2.0.85.Final</netty-tcnative.version>
<!-- Instrumentation releases target upstream opentelemetry versions and include that BOM by reference -->
<opentelemetry-instrumentation.version>2.33.0</opentelemetry-instrumentation.version>
<opentelemetry-instrumentation.version>2.33.1</opentelemetry-instrumentation.version>
<!-- must be greater than or equal to the value from Google libraries-bom, see https://protobuf.dev/support/cross-version-runtime-guarantee/ -->
<!-- the latest 4.x should be fine https://central.sonatype.com/artifact/com.google.protobuf/protobuf-java/versions -->
<protobuf.version>4.36.2</protobuf.version>
@@ -91,12 +90,12 @@
<reactor-bom.version>2025.0.8</reactor-bom.version> <!-- 3.8.4, see https://github.com/reactor/reactor#bom-versioning-scheme -->
<resilience4j.version>2.4.0</resilience4j.version>
<semver4j.version>3.1.0</semver4j.version>
<simple-grpc.version>0.2.1</simple-grpc.version>
<simple-grpc.version>0.3.0</simple-grpc.version>
<slf4j.version>2.0.20</slf4j.version>
<stripe.version>33.4.2</stripe.version>
<stripe.version>34.1.0</stripe.version>
<swagger.version>2.2.55</swagger.version>
<testcontainers.version>2.0.5</testcontainers.version>
<webauthn4j.version>0.31.11.RELEASE</webauthn4j.version>
<webauthn4j.version>0.32.0.RELEASE</webauthn4j.version>
<!-- Images to use in tests via testcontainers. See also: prepull-testcontainers-images <profile> -->
<dynamodb.image>amazon/dynamodb-local:3.3.1@sha256:ff89bd48ff32cd8d9be5fee8873b65b8854dc408f1afe881be6eb00247bc0dab</dynamodb.image>
@@ -104,7 +103,7 @@
<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>
<docker.image>eclipse-temurin:27-jre-resolute@sha256:492896faf0de16f8959951fcc97e84d6b1db7b1cbc327e732b4e740cd27409e9</docker.image>
<docker.image>eclipse-temurin:27-jre-resolute@sha256:16a0cae9bfb17ab4257ac64e3d7585fc49233e7bdf3d376c4545289eaf193929</docker.image>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
@@ -267,11 +266,6 @@
<artifactId>lettuce-core</artifactId>
<version>${lettuce.version}</version>
</dependency>
<dependency>
<groupId>net.logstash.logback</groupId>
<artifactId>logstash-logback-encoder</artifactId>
<version>${logstash.logback.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-csv</artifactId>
@@ -321,13 +315,13 @@
<dependency>
<groupId>com.redis</groupId>
<artifactId>testcontainers-redis</artifactId>
<version>3.0.0</version>
<version>3.0.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.signal</groupId>
<artifactId>libsignal-server</artifactId>
<version>0.105.4</version>
<version>0.108.0</version>
</dependency>
<dependency>
<groupId>org.signal</groupId>
@@ -529,12 +523,12 @@
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>3.6.4</version>
<version>3.7.0</version>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>properties-maven-plugin</artifactId>
<version>1.3.1</version>
<version>1.4.0</version>
</plugin>
</plugins>
</pluginManagement>
@@ -617,7 +611,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId>
<version>3.6.3</version>
<version>3.7.0</version>
<executions>
<execution>
<goals>
+2 -1
View File
@@ -255,7 +255,8 @@ fcm: # FCM configuration
credentials: secret://fcm.credentials
cdn:
bucket: cdn # S3 Bucket name
baseUrl: https://cdn.example.com # Public base URL for objects in the bucket
bucket: cdn # S3 Bucket name
credentials:
accessKeyId: secret://cdn.accessKey
secretAccessKey: secret://cdn.accessSecret
+3 -22
View File
@@ -14,8 +14,8 @@
<apollo-api-jvm.version>3.8.6</apollo-api-jvm.version>
<commons-compress.version>1.28.0</commons-compress.version>
<dynamodb-lock-client.version>1.5.0</dynamodb-lock-client.version>
<firebase-admin.version>9.11.0</firebase-admin.version>
<libphonenumber-geocoder.version>3.42</libphonenumber-geocoder.version>
<firebase-admin.version>9.12.0</firebase-admin.version>
<libphonenumber-geocoder.version>3.43</libphonenumber-geocoder.version>
<google-androidpublisher.version>v3-rev20250904-2.0.0</google-androidpublisher.version>
<java-jwt.version>4.6.2</java-jwt.version>
<java-uuid-generator.version>5.2.0</java-uuid-generator.version>
@@ -177,25 +177,6 @@
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
</dependency>
<dependency>
<groupId>net.logstash.logback</groupId>
<artifactId>logstash-logback-encoder</artifactId>
<exclusions>
<!-- conflicts with webauthn4j-appattest -->
<exclusion>
<groupId>tools.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- sentinel for dependency convergence -->
<dependency>
<groupId>tools.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<!-- update dependabot.yml when this dependency is removed -->
<version>3.2.3</version>
</dependency>
<dependency>
<groupId>io.dropwizard.metrics</groupId>
<artifactId>metrics-core</artifactId>
@@ -875,7 +856,7 @@
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>templating-maven-plugin</artifactId>
<version>3.1.1</version>
<version>3.2.0</version>
<executions>
<execution>
<id>filter-src</id>
@@ -33,10 +33,11 @@ import io.lettuce.core.metrics.MicrometerOptions;
import io.lettuce.core.resource.ClientResources;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.binder.jvm.ExecutorServiceMetrics;
import io.netty.channel.DefaultEventLoopGroup;
import io.netty.channel.MultiThreadIoEventLoopGroup;
import io.netty.channel.local.LocalAddress;
import io.netty.channel.local.LocalIoHandler;
import io.netty.channel.local.LocalServerChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.nio.NioIoHandler;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.ssl.SslContext;
@@ -176,6 +177,7 @@ import org.whispersystems.textsecuregcm.grpc.ErrorMappingInterceptor;
import org.whispersystems.textsecuregcm.grpc.ExternalServiceDefinitions;
import org.whispersystems.textsecuregcm.grpc.GroupSendTokenUtil;
import org.whispersystems.textsecuregcm.grpc.GrpcAllowListInterceptor;
import org.whispersystems.textsecuregcm.grpc.GrpcCompressionInterceptor;
import org.whispersystems.textsecuregcm.grpc.KeyTransparencyGrpcService;
import org.whispersystems.textsecuregcm.grpc.KeysAnonymousGrpcService;
import org.whispersystems.textsecuregcm.grpc.KeysGrpcService;
@@ -184,6 +186,7 @@ import org.whispersystems.textsecuregcm.grpc.MessageDispatcher;
import org.whispersystems.textsecuregcm.grpc.MessagesAnonymousGrpcService;
import org.whispersystems.textsecuregcm.grpc.MessagesGrpcService;
import org.whispersystems.textsecuregcm.grpc.MetricServerInterceptor;
import org.whispersystems.textsecuregcm.grpc.MetricServerStreamTracer;
import org.whispersystems.textsecuregcm.grpc.OneTimeDonationsGrpcService;
import org.whispersystems.textsecuregcm.grpc.PaymentsGrpcService;
import org.whispersystems.textsecuregcm.grpc.ProductConfigurationGrpcService;
@@ -193,11 +196,14 @@ import org.whispersystems.textsecuregcm.grpc.RemoteConfigurationGrpcService;
import org.whispersystems.textsecuregcm.grpc.RequestAttributesInterceptor;
import org.whispersystems.textsecuregcm.grpc.SubscriptionsGrpcService;
import org.whispersystems.textsecuregcm.grpc.ValidatingInterceptor;
import org.whispersystems.textsecuregcm.grpc.net.H2ConnectionFactory;
import org.whispersystems.textsecuregcm.grpc.net.ManagedEventLoopGroup;
import org.whispersystems.textsecuregcm.grpc.net.ManagedGrpcServer;
import org.whispersystems.textsecuregcm.grpc.net.OmnibusH2Server;
import org.whispersystems.textsecuregcm.grpc.net.OmnibusRouter;
import org.whispersystems.textsecuregcm.grpc.net.PooledH2ConnectionFactory;
import org.whispersystems.textsecuregcm.grpc.net.SniMapper;
import org.whispersystems.textsecuregcm.grpc.net.UnpooledH2ConnectionFactory;
import org.whispersystems.textsecuregcm.grpc.validators.ValidatorUtils;
import org.whispersystems.textsecuregcm.jetty.JettyHttpConfigurationCustomizer;
import org.whispersystems.textsecuregcm.keytransparency.KeyTransparencyServiceClient;
@@ -726,7 +732,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
ScheduledExecutorService messagePollExecutor = ScheduledExecutorServiceBuilder.of(environment, "messagePollExecutor").threads(1).build();
ScheduledExecutorService provisioningWebsocketTimeoutExecutor = ScheduledExecutorServiceBuilder.of(environment, "provisioningWebsocketTimeout").threads(1).build();
final ManagedEventLoopGroup<NioEventLoopGroup> dnsResolutionEventLoopGroup = new ManagedEventLoopGroup<>(new NioEventLoopGroup());
final ManagedEventLoopGroup<MultiThreadIoEventLoopGroup> dnsResolutionEventLoopGroup =
new ManagedEventLoopGroup<>(new MultiThreadIoEventLoopGroup(NioIoHandler.newFactory()));
final DnsNameResolver cloudflareDnsResolver = new DnsNameResolverBuilder(dnsResolutionEventLoopGroup.getEventLoopGroup().next())
.resolvedAddressTypes(ResolvedAddressTypes.IPV6_PREFERRED)
.completeOncePreferredResolved(false)
@@ -1097,6 +1104,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
final ErrorMappingInterceptor errorMappingInterceptor = new ErrorMappingInterceptor();
final ErrorConformanceInterceptor errorConformanceInterceptor = new ErrorConformanceInterceptor();
final GrpcAllowListInterceptor grpcAllowListInterceptor = new GrpcAllowListInterceptor(dynamicConfigurationManager);
final GrpcCompressionInterceptor grpcCompressionInterceptor = new GrpcCompressionInterceptor(dynamicConfigurationManager);
final RequestAttributesInterceptor requestAttributesInterceptor = new RequestAttributesInterceptor();
final ValidatingInterceptor validatingInterceptor = new ValidatingInterceptor();
@@ -1133,7 +1141,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
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, asnInfoProviderSupplier, dynamicConfigurationManager, config.getBadges(), profileCdnPolicyGenerator, chatGenericZkSecretParams, profileBadgeConverter, rateLimiters),
new ProfileGrpcService(clock, accountsManager, profilesManager, asnInfoProviderSupplier, dynamicConfigurationManager, config.getBadges(), profileCdnPolicyGenerator,
config.getCdnConfiguration().baseUrl(), chatGenericZkSecretParams, profileBadgeConverter, rateLimiters),
new MessagesGrpcService(accountsManager, reportMessageManager, phoneNumberIdentifiers, rateLimiters, messageSender, messageByteLimitCardinalityEstimator, spamChecker, messageDispatcher, Clock.systemUTC()),
new BackupsGrpcService(accountsManager, backupAuthManager, backupMetrics),
new DevicesGrpcService(accountsManager),
@@ -1153,6 +1162,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
validatingInterceptor,
errorMappingInterceptor,
errorConformanceInterceptor,
grpcCompressionInterceptor,
grpcAllowListInterceptor,
remoteDeprecationFilter,
metricServerInterceptor,
@@ -1166,7 +1176,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new KeysAnonymousGrpcService(accountsManager, keysManager, groupZkSecretParams, Clock.systemUTC()),
new KeyTransparencyGrpcService(rateLimiters, keyTransparencyServiceClient),
new LoginPurchaseGrpcService(loginPurchaseManager, dynamicConfigurationManager),
new ProfileAnonymousGrpcService(accountsManager, profilesManager, profileBadgeConverter, profileCdnPolicyGenerator, chatGenericZkSecretParams, groupZkSecretParams, rateLimiters, clock),
new ProfileAnonymousGrpcService(accountsManager, profilesManager, profileBadgeConverter, profileCdnPolicyGenerator,
config.getCdnConfiguration().baseUrl(), 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()), rateLimiters),
@@ -1185,6 +1196,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
validatingInterceptor,
errorMappingInterceptor,
errorConformanceInterceptor,
grpcCompressionInterceptor,
grpcAllowListInterceptor,
remoteDeprecationFilter,
metricServerInterceptor,
@@ -1196,15 +1208,18 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
verifyServiceAuth(authenticatedServices, Auth.AUTH_ONLY_AUTHENTICATED);
verifyServiceAuth(unauthenticatedServices, Auth.AUTH_ONLY_ANONYMOUS);
final ManagedEventLoopGroup<DefaultEventLoopGroup> omnibusLocalEventLoopGroup = new ManagedEventLoopGroup<>(new DefaultEventLoopGroup());
final ManagedEventLoopGroup<NioEventLoopGroup> omnibusNioEventLoopGroup = new ManagedEventLoopGroup<>(new NioEventLoopGroup());
final ManagedEventLoopGroup<MultiThreadIoEventLoopGroup> omnibusLocalEventLoopGroup =
new ManagedEventLoopGroup<>(new MultiThreadIoEventLoopGroup(LocalIoHandler.newFactory()));
final ManagedEventLoopGroup<MultiThreadIoEventLoopGroup> omnibusNioEventLoopGroup =
new ManagedEventLoopGroup<>(new MultiThreadIoEventLoopGroup(NioIoHandler.newFactory()));
final LocalAddress grpcLocalAddress = new LocalAddress("grpc");
final ServerBuilder<?> serverBuilder = NettyServerBuilder
.forAddress(grpcLocalAddress)
.channelType(LocalServerChannel.class)
.bossEventLoopGroup(omnibusLocalEventLoopGroup.getEventLoopGroup())
.workerEventLoopGroup(omnibusLocalEventLoopGroup.getEventLoopGroup())
.executor(ManagedExecutors.newVirtualThreadPerTaskExecutor("managed-grpc-virtual-thread", environment));
.executor(ManagedExecutors.newVirtualThreadPerTaskExecutor("managed-grpc-virtual-thread", environment))
.addStreamTracerFactory(new MetricServerStreamTracer.Factory());
authenticatedServices.forEach(serverBuilder::addService);
unauthenticatedServices.forEach(serverBuilder::addService);
final ManagedGrpcServer localGrpcServer = new ManagedGrpcServer(serverBuilder.build());
@@ -1214,10 +1229,13 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
final SocketAddress websocketAddress =
new InetSocketAddress(config.getGrpc().websocketAddress(), config.getGrpc().websocketPort());
final H2ConnectionFactory grpcH2ConnectionFactory = new PooledH2ConnectionFactory(grpcLocalAddress,
omnibusLocalEventLoopGroup.getEventLoopGroup());
final H2ConnectionFactory websocketH2ConnectionFactory = new UnpooledH2ConnectionFactory(websocketAddress, omnibusNioEventLoopGroup.getEventLoopGroup());
final OmnibusRouter omnibusRouter = new OmnibusRouter(Map.of(
websocketServletPath, websocketAddress,
provisioningWebsocketServletPath, websocketAddress),
grpcLocalAddress);
websocketServletPath, websocketH2ConnectionFactory,
provisioningWebsocketServletPath, websocketH2ConnectionFactory),
grpcH2ConnectionFactory);
@Nullable final Mapping<String, SslContext> sniMapping = config.getGrpc().h2c()
? null
: SniMapper.buildSniMapping(config.getTlsKeyStoreConfiguration().path(),
@@ -1226,7 +1244,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
final OmnibusH2Server omnibusH2Server = new OmnibusH2Server(
sniMapping,
omnibusNioEventLoopGroup.getEventLoopGroup(),
omnibusLocalEventLoopGroup.getEventLoopGroup(),
new InetSocketAddress(config.getGrpc().bindAddress(), config.getGrpc().port()), omnibusRouter,
() -> dynamicConfigurationManager.getConfiguration().getOmnibus(),
config.getGrpc().idleTimeout());
@@ -12,6 +12,7 @@ import javax.annotation.Nullable;
import java.net.URI;
public record CdnConfiguration(@NotNull @Valid StaticAwsCredentialsFactory credentials,
@NotBlank String baseUrl,
@NotBlank String bucket,
@NotBlank String region,
@Nullable URI endpointOverride) {
@@ -14,7 +14,9 @@ import java.time.Duration;
/// @param port The port to bind the omnibus server to
/// @param websocketAddress The address of a listening websocket server for handling legacy requests
/// @param websocketPort The port of a listening websocket server for handling legacy requests
/// @param idleTimeout The duration after which an idle connection may be disconnected
/// @param idleTimeout The duration after which a connection the client has not written to may be disconnected.
/// Clients are expected to send some periodic write traffic (application-level or h2-level
/// pings) to keep otherwise idle connections open
/// @param h2c If true, listen for plaintext h2c with prior-knowledge
/// @param sslProvider The TLS implementation used to terminate TLS. Defaults to `OPENSSL`.
public record GrpcConfiguration(
@@ -34,7 +36,7 @@ public record GrpcConfiguration(
websocketAddress = "localhost";
}
if (idleTimeout == null) {
idleTimeout = Duration.ofMinutes(5);
idleTimeout = Duration.ofSeconds(60);
}
if (sslProvider == null) {
sslProvider = SslProvider.OPENSSL;
@@ -77,6 +77,10 @@ public class DynamicConfiguration {
@Valid
private DynamicGrpcAllowListConfiguration grpcAllowList = new DynamicGrpcAllowListConfiguration();
@JsonProperty
@Valid
private DynamicGrpcCompressionConfiguration grpcCompression = new DynamicGrpcCompressionConfiguration();
@JsonProperty
@Valid
private DynamicOmnibusConfiguration omnibus = new DynamicOmnibusConfiguration(BigDecimal.ZERO);
@@ -151,6 +155,10 @@ public class DynamicConfiguration {
return grpcAllowList;
}
public DynamicGrpcCompressionConfiguration getGrpcCompression() {
return grpcCompression;
}
public DynamicOmnibusConfiguration getOmnibus() {
return omnibus;
}
@@ -0,0 +1,35 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration.dynamic;
import java.util.Collections;
import java.util.Set;
/// Configure which gRPC methods may compress their responses
///
/// @param compressedServices A list of fully qualified service names for which all RPC responses should be compressed.
/// For example, `kt_query.KeyTransparencyQueryService` would compress responses for all RPCs
/// on that service.
/// @param compressedMethods A list of fully qualified method names of RPCs whose responses should be compressed. For
/// example, `kt_query.KeyTransparencyQueryService/Search` would compress responses for the
/// `Search` RPC method
public record DynamicGrpcCompressionConfiguration(
Set<String> compressedServices,
Set<String> compressedMethods) {
public DynamicGrpcCompressionConfiguration {
if (compressedServices == null) {
compressedServices = Collections.emptySet();
}
if (compressedMethods == null) {
compressedMethods = Collections.emptySet();
}
}
public DynamicGrpcCompressionConfiguration() {
// By default, no gRPC responses are compressed
this(Collections.emptySet(), Collections.emptySet());
}
}
@@ -40,6 +40,7 @@ import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
import org.glassfish.jersey.server.ManagedAsync;
import org.signal.libsignal.usernames.BaseUsernameException;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
@@ -356,7 +357,7 @@ public class AccountController {
try {
usernameHashZkProofVerifier.verifyProof(confirmRequest.zkProof(), confirmRequest.usernameHash());
} catch (final BaseUsernameException e) {
} catch (final BaseUsernameException | InvalidInputException e) {
throw new WebApplicationException(Response.status(422).build());
}
@@ -9,13 +9,11 @@ import com.google.common.net.HttpHeaders;
import io.dropwizard.auth.Auth;
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.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.headers.Header;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Positive;
import jakarta.ws.rs.ClientErrorException;
import jakarta.ws.rs.GET;
@@ -27,7 +25,6 @@ import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.security.SecureRandom;
import java.util.Map;
import java.util.Optional;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.glassfish.jersey.server.ManagedAsync;
@@ -104,30 +101,27 @@ public class AttachmentControllerV4 {
public AttachmentDescriptorV3 getAttachmentUploadForm(
@Auth AuthenticatedDevice auth,
@Parameter(description = "The size of the attachment to upload in bytes")
@QueryParam("uploadLength") final @Valid Optional<@Positive Long> maybeUploadLength,
@QueryParam("uploadLength") @Positive final long uploadLength,
@HeaderParam(HttpHeaders.USER_AGENT) @Nullable final String userAgent)
throws RateLimitExceededException {
final long uploadLength = maybeUploadLength.orElse(maxUploadLength);
if (uploadLength > maxUploadLength) {
throw new ClientErrorException("exceeded maximum uploadLength", Response.Status.REQUEST_ENTITY_TOO_LARGE);
}
countRateLimiter.validate(auth.accountIdentifier());
if (maybeUploadLength.isPresent()) {
// Ideally we'd check these two rate limits transactionally and only update them if both permits were acquired.
// However, just undoing the first modification if the second one fails is close enough for our purposes
try {
bytesRateLimiter.validate(auth.accountIdentifier(), maybeUploadLength.get());
} catch (RateLimitExceededException e) {
countRateLimiter.restorePermits(auth.accountIdentifier(), 1);
throw e;
}
// Ideally we'd check these two rate limits transactionally and only update them if both permits were acquired.
// However, just undoing the first modification if the second one fails is close enough for our purposes
try {
bytesRateLimiter.validate(auth.accountIdentifier(), uploadLength);
} catch (RateLimitExceededException e) {
countRateLimiter.restorePermits(auth.accountIdentifier(), 1);
throw e;
}
DistributionSummary.builder(ATTACHMENT_SIZE_NAME)
.tags(Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
Tag.of("uploadLengthSupplied", Boolean.toString(maybeUploadLength.isPresent()))))
.tags(Tags.of(UserAgentTagUtil.getPlatformTag(userAgent)))
.register(Metrics.globalRegistry)
.record(uploadLength);
@@ -168,7 +168,6 @@ public class ProfileController {
@ApiResponse(responseCode = "400", description = "Invalid create profile request.")
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
@ApiResponse(responseCode = "403", description = "The request contained a payment address, but payments are not supported in the region of the account’s phone number or the caller's ASN if the account does not have a phone number.")
@ApiResponse(responseCode = "412", description = "The requesting account has the profiles_v2 capability")
@ApiResponse(responseCode = "422", description = "Invalid request format")
@ManagedAsync
public Response setProfile(@Auth AuthenticatedDevice auth,
@@ -178,10 +177,6 @@ public class ProfileController {
final Account account = accountsManager.getByAccountIdentifier(auth.accountIdentifier())
.orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));
if (account.hasCapability(DeviceCapability.PROFILES_V2)) {
return Response.status(Response.Status.PRECONDITION_FAILED).build();
}
final Optional<VersionedProfileV1> currentProfile =
profilesManager.getV1(auth.accountIdentifier(), request.version());
@@ -263,7 +263,7 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
try {
usernameHashZkProofVerifier.verifyProof(request.getZkProof().toByteArray(), request.getUsernameHash().toByteArray());
} catch (final BaseUsernameException e) {
} catch (final BaseUsernameException | InvalidInputException e) {
throw GrpcExceptions.invalidArguments("Could not verify proof");
}
@@ -18,9 +18,11 @@ public class DeviceCapabilityUtil {
case DEVICE_CAPABILITY_TRANSFER -> DeviceCapability.TRANSFER;
case DEVICE_CAPABILITY_ATTACHMENT_BACKFILL -> DeviceCapability.ATTACHMENT_BACKFILL;
case DEVICE_CAPABILITY_SPARSE_POST_QUANTUM_RATCHET -> DeviceCapability.SPARSE_POST_QUANTUM_RATCHET;
case DEVICE_CAPABILITY_PROFILES_V2 -> DeviceCapability.PROFILES_V2;
case DEVICE_CAPABILITY_USERNAME_CHANGE_SYNC_MESSAGE -> DeviceCapability.USERNAME_CHANGE_SYNC_MESSAGE;
case DEVICE_CAPABILITY_OPTIONAL_PHONE_NUMBER -> DeviceCapability.OPTIONAL_PHONE_NUMBER;
case DEVICE_CAPABILITY_REPLY_PRIVATELY -> DeviceCapability.REPLY_PRIVATELY;
case DEVICE_CAPABILITY_CONTACT_DELETE -> DeviceCapability.CONTACT_DELETE;
case DEVICE_CAPABILITY_ADMIN_REMOVE_AND_DELETE -> DeviceCapability.ADMIN_REMOVE_AND_DELETE;
case DEVICE_CAPABILITY_UNSPECIFIED, UNRECOGNIZED ->
throw GrpcExceptions.invalidArguments("unrecognized device capability");
};
@@ -32,9 +34,11 @@ public class DeviceCapabilityUtil {
case TRANSFER -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_TRANSFER;
case ATTACHMENT_BACKFILL -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_ATTACHMENT_BACKFILL;
case SPARSE_POST_QUANTUM_RATCHET -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_SPARSE_POST_QUANTUM_RATCHET;
case PROFILES_V2 -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_PROFILES_V2;
case USERNAME_CHANGE_SYNC_MESSAGE -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_USERNAME_CHANGE_SYNC_MESSAGE;
case OPTIONAL_PHONE_NUMBER -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_OPTIONAL_PHONE_NUMBER;
case REPLY_PRIVATELY -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_REPLY_PRIVATELY;
case CONTACT_DELETE -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_CONTACT_DELETE;
case ADMIN_REMOVE_AND_DELETE -> org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_ADMIN_REMOVE_AND_DELETE;
};
}
}
@@ -0,0 +1,43 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc;
import io.grpc.Metadata;
import io.grpc.MethodDescriptor;
import io.grpc.ServerCall;
import io.grpc.ServerCallHandler;
import io.grpc.ServerInterceptor;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicGrpcCompressionConfiguration;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
/// Requests gzip compression of responses for configured gRPC methods. Compression is only applied if the client
/// advertises gzip in its `grpc-accept-encoding` header; otherwise gRPC falls back to sending uncompressed responses.
public class GrpcCompressionInterceptor implements ServerInterceptor {
private static final String GZIP = "gzip";
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
public GrpcCompressionInterceptor(
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
this.dynamicConfigurationManager = dynamicConfigurationManager;
}
@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(final ServerCall<ReqT, RespT> serverCall,
final Metadata metadata, final ServerCallHandler<ReqT, RespT> next) {
final DynamicGrpcCompressionConfiguration compressionConfiguration =
this.dynamicConfigurationManager.getConfiguration().getGrpcCompression();
final MethodDescriptor<ReqT, RespT> methodDescriptor = serverCall.getMethodDescriptor();
if (compressionConfiguration.compressedServices().contains(methodDescriptor.getServiceName()) ||
compressionConfiguration.compressedMethods().contains(methodDescriptor.getFullMethodName())) {
// This does not necessarily enable compression. The implementation will handle negotiation with the client
// and may fall back to no compression.
serverCall.setCompression(GZIP);
}
return next.startCall(serverCall, metadata);
}
}
@@ -6,6 +6,7 @@
package org.whispersystems.textsecuregcm.grpc;
import com.google.protobuf.ByteString;
import com.google.protobuf.Empty;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Clock;
@@ -33,6 +34,8 @@ import reactor.util.function.Tuples;
public class KeysAnonymousGrpcService extends SimpleKeysAnonymousGrpc.KeysAnonymousImplBase {
private static final int CHECK_KEYS_MAX_CONCURRENCY = 16;
private final AccountsManager accountsManager;
private final KeysManager keysManager;
private final GroupSendTokenUtil groupSendTokenUtil;
@@ -99,20 +102,22 @@ public class KeysAnonymousGrpcService extends SimpleKeysAnonymousGrpc.KeysAnonym
return JdkFlowAdapter.publisherToFlowPublisher(JdkFlowAdapter.flowPublisherToFlux(requests)
.map(request -> Tuples.of(GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getTargetIdentifier()),
request.getFingerprint().toByteArray()))
.flatMap(serviceIdentifierAndFingerprint -> Mono.fromFuture(
.flatMapSequential(serviceIdentifierAndFingerprint -> Mono.fromFuture(
() -> accountsManager.getByServiceIdentifierAsync(serviceIdentifierAndFingerprint.getT1()))
.map(maybeAccount -> maybeAccount.flatMap(
account -> switch (serviceIdentifierAndFingerprint.getT1().identityType()) {
case ACI -> Optional.of(account.getAccountIdentityKey());
case PNI -> account.getPhoneNumberIdentityKey();
}))
.flatMap(Mono::justOrEmpty)
.filter(identityKey -> !fingerprintMatches(identityKey, serviceIdentifierAndFingerprint.getT2()))
.map(identityKey -> CheckIdentityKeyResponse.newBuilder()
.setTargetIdentifier(
GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(serviceIdentifierAndFingerprint.getT1()))
.setIdentityKey(ByteString.copyFrom(identityKey.serialize()))
.build())));
.map(maybeIdentityKey -> {
final CheckIdentityKeyResponse.Builder builder = CheckIdentityKeyResponse.newBuilder();
return maybeIdentityKey.map(identityKey ->
fingerprintMatches(identityKey, serviceIdentifierAndFingerprint.getT2())
? builder.setMatched(Empty.getDefaultInstance()).build()
: builder.setIdentityKey(ByteString.copyFrom(identityKey.serialize())).build())
.orElseGet(() -> builder.setTargetNotFound(NotFound.getDefaultInstance()).build());
}), CHECK_KEYS_MAX_CONCURRENCY));
}
private static boolean fingerprintMatches(final IdentityKey identityKey, final byte[] fingerprint) {
@@ -104,7 +104,7 @@ class KeysGrpcHelper {
.setKeyId(KeyIdUtil.toUnsignedInt(devicePreKeys.ecSignedPreKey().keyId()))
.setPublicKey(ByteString.copyFrom(devicePreKeys.ecSignedPreKey().serializedPublicKey()))
.setSignature(ByteString.copyFrom(devicePreKeys.ecSignedPreKey().signature())))
.setKemOneTimePreKey(KemSignedPreKey.newBuilder()
.setKemPreKey(KemSignedPreKey.newBuilder()
.setKeyId(KeyIdUtil.toUnsignedInt(devicePreKeys.kemSignedPreKey().keyId()))
.setPublicKey(ByteString.copyFrom(devicePreKeys.kemSignedPreKey().serializedPublicKey()))
.setSignature(ByteString.copyFrom(devicePreKeys.kemSignedPreKey().signature())))
@@ -8,10 +8,10 @@ import com.google.common.annotations.VisibleForTesting;
import com.google.protobuf.Empty;
import io.grpc.StatusRuntimeException;
import io.micrometer.core.instrument.Metrics;
import java.time.Clock;
import java.time.Duration;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.Nullable;
import org.signal.chat.messages.GetMessagesResponse;
import org.signal.chat.messages.GetMessagesStreamClosed;
@@ -48,7 +48,8 @@ public class MessageDispatcher {
private static final Logger log = LoggerFactory.getLogger(MessageDispatcher.class);
@VisibleForTesting
static final int MAX_UNACKED_MESSAGES = 256;
static final int DEFAULT_MAX_UNACKED_MESSAGES = 256;
@VisibleForTesting
static final Duration CLOSE_WITH_PENDING_MESSAGES_NOTIFICATION_DELAY = Duration.ofMinutes(1);
private static final int MESSAGE_PUBLISHER_LIMIT_RATE = 100;
@@ -133,10 +134,21 @@ public class MessageDispatcher {
pushNotificationManager.handleMessagesRetrieved(account, device, userAgentString);
final Flux<GetMessagesResponse> messages = JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages())
.name(SEND_MESSAGES_FLUX_NAME)
.tap(Micrometer.metrics(Metrics.globalRegistry))
.limitRate(MESSAGE_PUBLISHER_LIMIT_RATE)
final AtomicInteger maxUnacknowledgedMessages = new AtomicInteger(DEFAULT_MAX_UNACKED_MESSAGES);
final Flux<GetMessagesResponse> messages = Mono.fromFuture(() -> messagesManager.hasSuspectedDeliveryLoop(account.getAccountIdentifier(), device.getId()))
.flatMapMany(hasSuspectedDeliveryLoop -> {
if (hasSuspectedDeliveryLoop) {
maxUnacknowledgedMessages.set(1);
MessageMetrics.recordSuspectedDeliveryLoop(MessageMetrics.GRPC_CHANNEL, userAgent, clientReleaseManager);
}
return JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages())
.name(SEND_MESSAGES_FLUX_NAME)
.tag("hasSuspectedDeliveryLoop", String.valueOf(hasSuspectedDeliveryLoop))
.tap(Micrometer.metrics(Metrics.globalRegistry))
.limitRate(maxUnacknowledgedMessages.get());
})
.flatMapSequential(entry -> switch (entry) {
case MessageStreamEntry.Envelope(final MessageProtos.Envelope envelope) -> {
final UUID serverGuid = UUIDUtil.fromByteString(envelope.getServerGuid());
@@ -156,7 +168,7 @@ public class MessageDispatcher {
pendingAcknowledgementTracker.markEndOfQueue();
yield Mono.empty();
}
}, MAX_UNACKED_MESSAGES)
}, maxUnacknowledgedMessages.get())
.onErrorMap(ConflictingMessageConsumerException.class, _ -> {
messageMetrics.measureMessageStreamDisplaced(MessageMetrics.GRPC_CHANNEL, userAgent, true);
return CONFLICTING_STREAM_EXCEPTION;
@@ -165,7 +177,7 @@ public class MessageDispatcher {
// Only emit envelopes when the permit flux emits a value. Initially it is seeded MAX_UNACKED_MESSAGES permits,
// after that a permit is emitted every time we receive an ack.
final Sinks.Many<Boolean> ackPermits = Sinks.many().unicast().onBackpressureBuffer();
final Flux<Boolean> permits = Flux.range(0, MAX_UNACKED_MESSAGES)
final Flux<Boolean> permits = Flux.range(0, maxUnacknowledgedMessages.get())
.map(_ -> true)
.concatWith(ackPermits.asFlux());
final Mono<GetMessagesResponse> ackCompletions = acknowledgedMessageGuids
@@ -185,7 +197,7 @@ public class MessageDispatcher {
.doOnSuccess(_ -> unacked.handleMessageAcknowledged())
// Just have to emit some value that indicates we can release a permit
.thenReturn(true);
}, MAX_UNACKED_MESSAGES)
}, maxUnacknowledgedMessages.get())
.doOnNext(_ -> ackPermits.tryEmitNext(true))
.ignoreElements()
.cast(GetMessagesResponse.class);
@@ -59,6 +59,7 @@ public class MetricServerInterceptor implements ServerInterceptor {
static final String REQUEST_BYTES_COUNTER_NAME = MetricsUtil.name(MetricServerInterceptor.class, "requestBytes");
@VisibleForTesting
static final String RESPONSE_COUNTER_NAME = MetricsUtil.name(MetricServerInterceptor.class, "responseMessage");
/// Response bytes as written to the wire (i.e. after compression), as reported by [MetricServerStreamTracer]
@VisibleForTesting
static final String RESPONSE_BYTES_COUNTER_NAME = MetricsUtil.name(MetricServerInterceptor.class, "responseBytes");
@VisibleForTesting
@@ -113,15 +114,16 @@ public class MetricServerInterceptor implements ServerInterceptor {
private class MetricServerCall<ReqT, RespT> extends ForwardingServerCall.SimpleForwardingServerCall<ReqT, RespT> {
private final Counter responseMessageCounter;
private final Counter responseBytesCounter;
private final Tags tags;
private @Nullable String reason = null;
MetricServerCall(final ServerCall<ReqT, RespT> delegate, final Tags tags) {
super(delegate);
this.responseMessageCounter = meterRegistry.counter(RESPONSE_COUNTER_NAME, tags);
this.responseBytesCounter = meterRegistry.counter(RESPONSE_BYTES_COUNTER_NAME, tags);
this.tags = tags;
MetricServerStreamTracer.current().ifPresent(tracer ->
tracer.setResponseBytesCounter(meterRegistry.counter(RESPONSE_BYTES_COUNTER_NAME, tags)));
}
@Override
@@ -143,10 +145,6 @@ public class MetricServerInterceptor implements ServerInterceptor {
public void sendMessage(final RespT responseMessage) {
this.responseMessageCounter.increment();
if (responseMessage instanceof GeneratedMessage generatedMessage) {
this.responseBytesCounter.increment(generatedMessage.getSerializedSize());
}
// Extract the annotated reason (if any) from the message
final String messageReason = MetricServerCall.reason(responseMessage);
@@ -0,0 +1,55 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc;
import io.grpc.Context;
import io.grpc.Metadata;
import io.grpc.ServerStreamTracer;
import io.micrometer.core.instrument.Counter;
import java.util.Optional;
import javax.annotation.Nullable;
/// Records on-the-wire (i.e. possibly compressed) sizes of response messages.
///
/// Stream tracers are created before the method being called has been resolved. The tracer makes itself available
/// via the call's [Context], and [MetricServerInterceptor] (which only runs for registered methods) supplies the
/// counter to increment; without it, nothing is recorded.
public class MetricServerStreamTracer extends ServerStreamTracer {
private static final Context.Key<MetricServerStreamTracer> CONTEXT_KEY = Context.key("metricServerStreamTracer");
@Nullable
private volatile Counter responseBytesCounter;
public static class Factory extends ServerStreamTracer.Factory {
@Override
public ServerStreamTracer newServerStreamTracer(final String fullMethodName, final Metadata headers) {
return new MetricServerStreamTracer();
}
}
/// @return the tracer for the current call, if a [Factory] is installed on the server
static Optional<MetricServerStreamTracer> current() {
return Optional.ofNullable(CONTEXT_KEY.get());
}
void setResponseBytesCounter(final Counter responseBytesCounter) {
this.responseBytesCounter = responseBytesCounter;
}
@Override
public Context filterContext(final Context context) {
return context.withValue(CONTEXT_KEY, this);
}
@Override
public void outboundWireSize(final long bytes) {
final Counter counter = responseBytesCounter;
if (counter != null) {
counter.increment(bytes);
}
}
}
@@ -11,6 +11,7 @@ import io.micrometer.core.instrument.Metrics;
import java.time.Clock;
import java.util.Base64;
import java.util.Optional;
import org.apache.commons.lang3.Strings;
import org.signal.chat.errors.FailedUnidentifiedAuthorization;
import org.signal.chat.errors.FailedZkAuthentication;
import org.signal.chat.errors.NotFound;
@@ -56,6 +57,7 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof
private final GroupSendTokenUtil groupSendTokenUtil;
private final PostPolicyGenerator policyGenerator;
private final String cdnBaseUrl;
private final RateLimiters rateLimiters;
@@ -66,6 +68,7 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof
final ProfilesManager profilesManager,
final ProfileBadgeConverter profileBadgeConverter,
final PostPolicyGenerator policyGenerator,
final String cdnBaseUrl,
final GenericServerSecretParams genericServerSecretParams,
final ServerSecretParams serverSecretParams,
final RateLimiters rateLimiters,
@@ -74,6 +77,7 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof
profilesManager,
profileBadgeConverter,
policyGenerator,
cdnBaseUrl,
genericServerSecretParams,
rateLimiters,
clock,
@@ -86,6 +90,7 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof
final ProfilesManager profilesManager,
final ProfileBadgeConverter profileBadgeConverter,
final PostPolicyGenerator policyGenerator,
final String cdnBaseUrl,
final GenericServerSecretParams genericServerSecretParams,
final RateLimiters rateLimiters,
final Clock clock,
@@ -95,6 +100,7 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof
this.profilesManager = profilesManager;
this.profileBadgeConverter = profileBadgeConverter;
this.policyGenerator = policyGenerator;
this.cdnBaseUrl = Strings.CS.removeEnd(cdnBaseUrl, "/");
this.genericServerSecretParams = genericServerSecretParams;
this.rateLimiters = rateLimiters;
this.clock = clock;
@@ -133,7 +139,7 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof
// If we didn't find a v2 profile, try a v1 profile
.or(() -> ProfileGrpcHelper
.getProfileV1(account, profilesManager, profileBadgeConverter, version)
.getProfileV1(account, profilesManager, profileBadgeConverter, cdnBaseUrl, version)
.map(v1Result -> GetProfileAnonymousResponse.newBuilder().setProfileV1(v1Result).build())))
.orElseGet(() -> GetProfileAnonymousResponse.newBuilder().setNotFound(NotFound.getDefaultInstance()).build());
@@ -238,7 +244,7 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof
return profilesManager.extendAvatarTtlForIdentity(identity)
.map(extendedPath -> ExtendAvatarTTLResponse.newBuilder()
.setPath(extendedPath)
.setUrl(ProfileGrpcHelper.cdnUrl(cdnBaseUrl, extendedPath))
.build())
.orElseGet(() -> ExtendAvatarTTLResponse.newBuilder()
.setNotFound(NotFound.getDefaultInstance())
@@ -14,6 +14,7 @@ import java.time.Clock;
import java.util.Arrays;
import java.util.HexFormat;
import java.util.Optional;
import org.apache.commons.lang3.Strings;
import org.bouncycastle.crypto.digests.TupleHash;
import org.signal.chat.common.S3UploadForm;
import org.signal.chat.profile.AccountInfo;
@@ -32,7 +33,6 @@ import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessChecksum;
import org.whispersystems.textsecuregcm.badges.ProfileBadgeConverter;
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
import org.whispersystems.textsecuregcm.storage.VersionedProfile;
import org.whispersystems.textsecuregcm.storage.VersionedProfileV1;
@@ -47,9 +47,14 @@ public class ProfileGrpcHelper {
.setAlgorithm(PostPolicyGenerator.ALGORITHM)
.build();
static String cdnUrl(final String cdnBaseUrl, final String path) {
return Strings.CS.removeEnd(cdnBaseUrl, "/") + "/" + Strings.CS.removeStart(path, "/");
}
static Optional<LegacyProfileResult> getProfileV1(final Account account,
final ProfilesManager profilesManager,
final ProfileBadgeConverter profileBadgeConverter,
final String cdnBaseUrl,
final byte[] requestVersion) {
final Optional<VersionedProfileV1> maybeV1Profile =
profilesManager.getV1(account.getAccountIdentifier(), HexFormat.of().formatHex(requestVersion));
@@ -74,7 +79,7 @@ public class ProfileGrpcHelper {
builder.setPhoneNumberSharing(ByteString.copyFrom(v1Profile.phoneNumberSharing()));
}
if (v1Profile.avatar() != null) {
builder.setAvatar(v1Profile.avatar());
builder.setAvatarUrl(cdnUrl(cdnBaseUrl, v1Profile.avatar()));
}
// If present, include the payment address if the version matches the latest version on Account or the latest
@@ -91,9 +96,7 @@ public class ProfileGrpcHelper {
final ProfileBadgeConverter profileBadgeConverter,
final byte[] requestVersion) {
final Optional<VersionedProfile> maybeProfile = account.hasCapability(DeviceCapability.PROFILES_V2)
? profilesManager.get(account.getAccountIdentifier(), requestVersion)
: Optional.empty();
final Optional<VersionedProfile> maybeProfile = profilesManager.get(account.getAccountIdentifier(), requestVersion);
if (maybeProfile.isEmpty()) {
return Optional.empty();
}
@@ -135,14 +138,8 @@ public class ProfileGrpcHelper {
final ProfilesManager profilesManager,
final ServerZkProfileOperations zkProfileOperations) {
final Optional<VersionedProfile> versionedProfile;
if (account.hasCapability(DeviceCapability.PROFILES_V2)) {
versionedProfile = profilesManager.get(account.getAccountIdentifier(), version);
} else {
versionedProfile = Optional.empty();
}
return versionedProfile.map(VersionedProfile::commitment)
return profilesManager.get(account.getAccountIdentifier(), version)
.map(VersionedProfile::commitment)
.or(() -> profilesManager.getV1(account.getAccountIdentifier(), HexFormat.of().formatHex(version))
.map(VersionedProfileV1::commitment))
.map(commitment -> {
@@ -151,7 +148,8 @@ public class ProfileGrpcHelper {
try {
profileKeyCredentialResponse = ProfileHelper.getExpiringProfileKeyCredential(
new ProfileKeyCredentialRequest(encodedCredentialRequest),
new ProfileKeyCommitment(commitment), new ServiceId.Aci(account.getAccountIdentifier()), zkProfileOperations);
new ProfileKeyCommitment(commitment), new ServiceId.Aci(account.getAccountIdentifier()),
zkProfileOperations);
} catch (VerificationFailedException | InvalidInputException e) {
throw GrpcExceptions.invalidArguments("invalid credential request");
}
@@ -18,6 +18,7 @@ import java.util.UUID;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import org.apache.commons.lang3.Strings;
import org.signal.chat.common.S3UploadForm;
import org.signal.chat.errors.FailedPrecondition;
import org.signal.chat.errors.NotFound;
@@ -73,6 +74,7 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
private final GenericServerSecretParams genericServerSecretParams;
private final ProfileBadgeConverter profileBadgeConverter;
private final RateLimiters rateLimiters;
private final String cdnBaseUrl;
private record AvatarData(Optional<String> currentAvatar,
Optional<String> finalAvatar,
@@ -86,6 +88,7 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
final BadgesConfiguration badgesConfiguration,
final PostPolicyGenerator policyGenerator,
final String cdnBaseUrl,
final GenericServerSecretParams genericServerSecretParams,
final ProfileBadgeConverter profileBadgeConverter,
final RateLimiters rateLimiters) {
@@ -97,6 +100,7 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
this.badgeConfigurationMap = badgesConfiguration.getBadges().stream()
.collect(Collectors.toMap(BadgeConfiguration::getId, Function.identity()));
this.policyGenerator = policyGenerator;
this.cdnBaseUrl = Strings.CS.removeEnd(cdnBaseUrl, "/");
this.genericServerSecretParams = genericServerSecretParams;
this.profileBadgeConverter = profileBadgeConverter;
this.rateLimiters = rateLimiters;
@@ -268,7 +272,7 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
// If we didn't find a v2 profile, try a v1 profile
.or(() -> ProfileGrpcHelper
.getProfileV1(account, profilesManager, profileBadgeConverter, version)
.getProfileV1(account, profilesManager, profileBadgeConverter, cdnBaseUrl, version)
.map(v1Result -> GetProfileResponse.newBuilder().setLegacyProfile(v1Result).build())))
.orElseGet(() -> GetProfileResponse.newBuilder().setNotFound(NotFound.getDefaultInstance()).build());
}
@@ -1,111 +0,0 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc.net;
import com.google.common.annotations.VisibleForTesting;
import io.netty.handler.ssl.OpenSsl;
import java.net.Socket;
import java.security.Principal;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Optional;
import javax.net.ssl.ExtendedSSLSession;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.X509ExtendedKeyManager;
/// A server key manager for netty's BoringSSL provider that uses a client's signature algorithm preferences, enabling
/// support for ed25519.
///
/// This works around [netty#17690](https://github.com/netty/netty/issues/17690):
/// netty’s engine only asks the key manager for RSA- and EC-family key types, so it never selects an Ed25519 key.
class BoringSslServerKeyManager extends X509ExtendedKeyManager {
private final X509ExtendedKeyManager delegate;
@VisibleForTesting
BoringSslServerKeyManager(final X509ExtendedKeyManager delegate) {
if (!"BoringSSL".equals(OpenSsl.versionString())) {
throw new IllegalStateException("BoringSSL required, found " + OpenSsl.versionString());
}
this.delegate = delegate;
}
/// @throws IllegalArgumentException if `keyManagers` contains no [X509ExtendedKeyManager]
static BoringSslServerKeyManager wrap(final KeyManager[] keyManagers) {
return Arrays.stream(keyManagers)
.filter(X509ExtendedKeyManager.class::isInstance)
.map(X509ExtendedKeyManager.class::cast)
.findFirst()
.map(BoringSslServerKeyManager::new)
.orElseThrow(() -> new IllegalArgumentException("No X509ExtendedKeyManager found"));
}
@Override
public String chooseEngineServerAlias(final String keyType, final Principal[] issuers, final SSLEngine engine) {
if (!(engine.getHandshakeSession() instanceof ExtendedSSLSession session)) {
return null;
}
// Netty will only call this with EC/RSA key types (https://github.com/netty/netty/issues/17690).
// We can safely ignore `keyType` and loop through the peer's signature algorithms to find the best matching key.
for (final String signatureAlgorithm : session.getPeerSupportedSignatureAlgorithms()) {
final Optional<String> maybeAlias = getJdkKeyType(signatureAlgorithm)
.map(jdkKeyType -> delegate.chooseEngineServerAlias(jdkKeyType, issuers, engine));
if (maybeAlias.isPresent()) {
return maybeAlias.get();
}
}
return null;
}
/// Maps a JDK signature algorithm name to the JDK key type that can produce it
@VisibleForTesting
static Optional<String> getJdkKeyType(final String signatureAlgorithm) {
if (signatureAlgorithm.equals("Ed25519")) {
return Optional.of("EdDSA");
} else if (signatureAlgorithm.endsWith("withECDSA")) {
return Optional.of("EC");
} else if (signatureAlgorithm.endsWith("withRSA")) {
return Optional.of("RSA");
}
// We don't need to be exhaustive, because we require TLS 1.3 and only use a limited number of key types.
return Optional.empty();
}
@Override
public String chooseServerAlias(final String keyType, final Principal[] issuers, final Socket socket) {
return delegate.chooseServerAlias(keyType, issuers, socket);
}
@Override
public String[] getServerAliases(final String keyType, final Principal[] issuers) {
return delegate.getServerAliases(keyType, issuers);
}
@Override
public String chooseClientAlias(final String[] keyTypes, final Principal[] issuers, final Socket socket) {
return delegate.chooseClientAlias(keyTypes, issuers, socket);
}
@Override
public String[] getClientAliases(final String keyType, final Principal[] issuers) {
return delegate.getClientAliases(keyType, issuers);
}
@Override
public X509Certificate[] getCertificateChain(final String alias) {
return delegate.getCertificateChain(alias);
}
@Override
public PrivateKey getPrivateKey(final String alias) {
return delegate.getPrivateKey(alias);
}
}
@@ -0,0 +1,25 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc.net;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoop;
import java.net.SocketAddress;
/// A factory that creates h2 connections to some configured target address
public interface H2ConnectionFactory {
/// Retrieve a h2 connection to [#address()]
///
/// @param callerEventLoop The event loop of the channel making this call
ChannelFuture getConnectionChannelFuture(final EventLoop callerEventLoop);
/// Release a connection previously acquired via [#getConnectionChannelFuture]
void release(final Channel connection);
/// @return The [SocketAddress] that this factory targets
SocketAddress address();
}
@@ -14,9 +14,9 @@ import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.DefaultEventLoopGroup;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleUserEventChannelHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.nio.NioIoHandler;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DecoderException;
@@ -67,8 +67,7 @@ public class OmnibusH2Server implements Managed {
private final OmnibusRouter router;
private final Supplier<DynamicOmnibusConfiguration> configurationSupplier;
private final Duration idleTimeout;
private final DefaultEventLoopGroup localEventLoopGroup;
private final NioEventLoopGroup nioEventLoopGroup;
private final EventLoopGroup nioEventLoopGroup;
private final SocketAddress bindAddress;
private Channel serverChannel;
@@ -77,16 +76,14 @@ public class OmnibusH2Server implements Managed {
///
/// @param sslContextBySni If not null, a mapping between domain (SNI) and the appropriate SslContext to use for
/// that SNI. If null, the server will not include TLS (h2c with prior-knowledge)
/// @param nioEventLoopGroup Event loop to use for all NIO channel pipelines
/// @param localEventLoopGroup Event loop to use for all local channel pipelines
/// @param nioEventLoopGroup An Event loop with a [NioIoHandler#newFactory()] to use for all NIO channel pipelines
/// @param bindAddress The address the server should listen on
/// @param router How the server should select backends based on request paths
/// @param configurationSupplier Dynamic configuration supplier
/// @param idleTimeout How long to wait before terminating idle TCP connections
/// @param idleTimeout How long to wait since the last data was received from the client before terminating TCP connections
public OmnibusH2Server(
final @Nullable Mapping<String, SslContext> sslContextBySni,
final NioEventLoopGroup nioEventLoopGroup,
final DefaultEventLoopGroup localEventLoopGroup,
final EventLoopGroup nioEventLoopGroup,
final SocketAddress bindAddress,
final OmnibusRouter router,
final Supplier<DynamicOmnibusConfiguration> configurationSupplier,
@@ -94,7 +91,6 @@ public class OmnibusH2Server implements Managed {
this.sslContextBySni = sslContextBySni;
this.configurationSupplier = configurationSupplier;
this.nioEventLoopGroup = nioEventLoopGroup;
this.localEventLoopGroup = localEventLoopGroup;
this.bindAddress = bindAddress;
this.router = router;
this.idleTimeout = idleTimeout;
@@ -113,7 +109,7 @@ public class OmnibusH2Server implements Managed {
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(final SocketChannel ch) {
ch.pipeline().addLast(new IdleStateHandler(0, 0, idleTimeout.toMillis(), TimeUnit.MILLISECONDS));
ch.pipeline().addLast(new IdleStateHandler(idleTimeout.toMillis(), 0, 0, TimeUnit.MILLISECONDS));
ch.pipeline().addLast(new SimpleUserEventChannelHandler<IdleStateEvent>() {
@Override
protected void eventReceived(final ChannelHandlerContext ctx, final IdleStateEvent evt) {
@@ -184,7 +180,7 @@ public class OmnibusH2Server implements Managed {
pipeline.addLast(new Http2MultiplexHandler(new ChannelInitializer<Http2StreamChannel>() {
@Override
protected void initChannel(final Http2StreamChannel ch) {
ch.pipeline().addLast(new OmnibusH2StreamHandler(nioEventLoopGroup, localEventLoopGroup, router));
ch.pipeline().addLast(new OmnibusH2StreamHandler(router));
}
}));
pipeline.addLast(SESSION_EXCEPTION_HANDLER);
@@ -7,36 +7,22 @@ package org.whispersystems.textsecuregcm.grpc.net;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Timer;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.DefaultEventLoopGroup;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.local.LocalAddress;
import io.netty.channel.local.LocalChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http2.DefaultHttp2Headers;
import io.netty.handler.codec.http2.DefaultHttp2HeadersFrame;
import io.netty.handler.codec.http2.DefaultHttp2ResetFrame;
import io.netty.handler.codec.http2.Http2Error;
import io.netty.handler.codec.http2.Http2FrameCodecBuilder;
import io.netty.handler.codec.http2.Http2HeadersFrame;
import io.netty.handler.codec.http2.Http2MultiplexHandler;
import io.netty.handler.codec.http2.Http2Settings;
import io.netty.handler.codec.http2.Http2StreamChannel;
import io.netty.handler.codec.http2.Http2StreamChannelBootstrap;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.ReferenceCounted;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.List;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -46,7 +32,7 @@ import org.slf4j.LoggerFactory;
///
/// When this handler receives an H2 header for a new stream-id=X on our parent H2 connection it will
/// - Receive the stream-id=X header and check the path to determine the correct backend
/// - Make a new H2 connection to the backend
/// - Get or create an H2 connection to the backend
/// - Forward the header with stream-id=Y to the backend
/// - Install a [H2FrameProxyHandler] on the backend stream pipeline that forwards the received stream-id=Y frames from
/// the backend back to the client on stream-id=X
@@ -56,25 +42,13 @@ public class OmnibusH2StreamHandler extends ChannelInboundHandlerAdapter {
private static final Logger logger = LoggerFactory.getLogger(OmnibusH2StreamHandler.class);
private static final OmnibusExceptionHandler BACKEND_CONNECTION_EXCEPTION_HANDLER =
new OmnibusExceptionHandler("backend-connection", List.of());
private static final String BACKEND_STREAM_COUNTER_NAME = name(OmnibusH2StreamHandler.class, "backendStream");
private static final String BACKEND_CONNECT_DURATION_NAME = name(OmnibusH2StreamHandler.class,
"backendConnectDuration");
private static final String BACKEND_TAG = "backend";
private final OmnibusRouter router;
private final DefaultEventLoopGroup localEventLoopGroup;
private final NioEventLoopGroup nioEventLoopGroup;
public OmnibusH2StreamHandler(
final NioEventLoopGroup nioEventLoopGroup,
final DefaultEventLoopGroup localEventLoopGroup,
final OmnibusRouter router) {
public OmnibusH2StreamHandler(final OmnibusRouter router) {
this.router = router;
this.localEventLoopGroup = localEventLoopGroup;
this.nioEventLoopGroup = nioEventLoopGroup;
}
@Override
@@ -96,8 +70,8 @@ public class OmnibusH2StreamHandler extends ChannelInboundHandlerAdapter {
// Select the target backend based on the path
final String path = Optional.ofNullable(headersFrame.headers().path()).map(CharSequence::toString).orElse("");
final SocketAddress target = router.match(path);
final String backendTag = target.toString();
final H2ConnectionFactory connectionFactory = router.match(path);
final String backendTag = connectionFactory.address().toString();
Metrics.counter(BACKEND_STREAM_COUNTER_NAME, BACKEND_TAG, backendTag).increment();
@@ -109,55 +83,38 @@ public class OmnibusH2StreamHandler extends ChannelInboundHandlerAdapter {
? proxyRemoteAddress.getHostAddress()
: ((InetSocketAddress) ctx.channel().remoteAddress()).getHostString());
// Make a new H2 connection to the target backend
final Timer.Sample connectSample = Timer.start();
new Bootstrap()
.group(selectEventLoop(ctx, target))
.channel(target instanceof LocalAddress ? LocalChannel.class : NioSocketChannel.class)
.handler(new ChannelInitializer<>() {
@Override
protected void initChannel(final Channel ch) {
ch.pipeline()
.addLast(Http2FrameCodecBuilder.forClient().initialSettings(Http2Settings.defaultSettings()).build());
// Http2MultiplexHandler takes handler that is added to new inbound streams. A client Http2MultiplexHandler
// like we're defining here should never receive an inbound H2 stream so we can just pass a noop handler
ch.pipeline().addLast(new Http2MultiplexHandler(new NoopInboundStreamHandler()));
ch.pipeline().addLast(BACKEND_CONNECTION_EXCEPTION_HANDLER);
}
})
.connect(target)
// Make an H2 connection to the target backend
connectionFactory.getConnectionChannelFuture(ctx.channel().eventLoop())
.addListener((ChannelFuture connectFuture) -> {
connectSample.stop(Timer.builder(BACKEND_CONNECT_DURATION_NAME)
.tag(BACKEND_TAG, backendTag)
.tag("outcome", connectFuture.isSuccess() ? "success" : "failure")
.register(Metrics.globalRegistry));
if (!connectFuture.isSuccess()) {
// Close the client stream with a 502: Bad Gateway if the backend wasn't available
logger.warn("Failed to connect to backend {}", target, connectFuture.cause());
logger.warn("Failed to connect to backend {}", backendTag, connectFuture.cause());
ctx.channel()
.writeAndFlush(new DefaultHttp2HeadersFrame(
new DefaultHttp2Headers().status("502"), true))
.addListener(ChannelFutureListener.CLOSE);
connectionFactory.release(connectFuture.channel());
return;
}
// Connected, open a new H2 stream to the backend so we can proxy the client's frames
logger.trace("Opening a HTTP/2 stream to the backend {}", target);
logger.trace("Opening a HTTP/2 stream to the backend {}", backendTag);
final Channel backendConnection = connectFuture.channel();
createBackendProxyStream(ctx, backendConnection, headersFrame, backendTag);
createBackendProxyStream(ctx, connectionFactory, backendConnection, headersFrame, backendTag);
});
}
/// Create a proxy stream on the provided `backendConnection` that forwards H2 frames to/from the client H2 stream.
///
/// @param clientStreamCtx The context for a client H2 stream that targets the backend
/// @param connectionFactory The factory `backendConnection` came from
/// @param backendConnection An established H2 connection [Channel], on which a new h2 stream will be opened
/// @param headersFrame The first `headersFrame` from the client h2 stream that should be forwarded to the new
/// backend stream
/// @param backendTag The backend this stream targets, for metrics
private void createBackendProxyStream(
final ChannelHandlerContext clientStreamCtx,
final H2ConnectionFactory connectionFactory,
final Channel backendConnection,
final Http2HeadersFrame headersFrame,
final String backendTag) {
@@ -171,15 +128,13 @@ public class OmnibusH2StreamHandler extends ChannelInboundHandlerAdapter {
clientStreamCtx.channel()
.writeAndFlush(new DefaultHttp2ResetFrame(Http2Error.INTERNAL_ERROR))
.addListener(ChannelFutureListener.CLOSE);
backendConnection.close();
connectionFactory.release(backendConnection);
return;
}
final Http2StreamChannel backendStream = streamFuture.getNow();
// Close the entire H2 connection whenever the stream we just opened closes. We only plan on using
// a single stream on this connection.
backendStream.closeFuture().addListener(_ -> backendConnection.close());
backendStream.closeFuture().addListener(_ -> connectionFactory.release(backendConnection));
// We're going to modify the inbound H2 stream channel, which runs on a different eventloop than the
// outbound channel we've made to the backend. We have to submit our updates back to the inbound
@@ -188,7 +143,7 @@ public class OmnibusH2StreamHandler extends ChannelInboundHandlerAdapter {
if (!clientStreamCtx.channel().isActive()) {
// The client disconnected already and the client pipeline is already torn down.
backendConnection.close();
backendStream.close();
return;
}
@@ -204,29 +159,4 @@ public class OmnibusH2StreamHandler extends ChannelInboundHandlerAdapter {
});
});
}
private EventLoopGroup selectEventLoop(final ChannelHandlerContext inboundCtx, SocketAddress target) {
final boolean localInbound = inboundCtx.channel() instanceof LocalChannel;
final boolean localTarget = target instanceof LocalAddress;
// If the inbound eventloop matches the target type, we can just reuse the inbound's event loop
if (localInbound == localTarget) {
return inboundCtx.channel().eventLoop();
}
return localTarget ? this.localEventLoopGroup : this.nioEventLoopGroup;
}
private static class NoopInboundStreamHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRegistered(final ChannelHandlerContext ctx) {
logger.error("Inbound stream handler was registered when no inbound streams expected");
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
logger.error("Received unexpected message: {} on inbound stream from backend", msg);
super.channelRead(ctx, msg);
}
}
}
@@ -4,22 +4,21 @@
*/
package org.whispersystems.textsecuregcm.grpc.net;
import java.net.SocketAddress;
import java.util.Map;
public class OmnibusRouter {
private final Map<String, SocketAddress> routes;
private final SocketAddress defaultBackend;
private final Map<String, H2ConnectionFactory> routesByPath;
private final H2ConnectionFactory defaultBackend;
public OmnibusRouter(final Map<String, SocketAddress> routes, final SocketAddress defaultBackend) {
this.routes = routes;
public OmnibusRouter(final Map<String, H2ConnectionFactory> routesByPath, final H2ConnectionFactory defaultBackend) {
this.routesByPath = routesByPath;
this.defaultBackend = defaultBackend;
}
SocketAddress match(final String fullPath) {
H2ConnectionFactory match(final String fullPath) {
final int queryIndex = fullPath.indexOf('?');
final String path = queryIndex >= 0 ? fullPath.substring(0, queryIndex) : fullPath;
return routes.getOrDefault(path, defaultBackend);
return routesByPath.getOrDefault(path, defaultBackend);
}
}
@@ -0,0 +1,187 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc.net;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.google.common.annotations.VisibleForTesting;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tags;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.EventLoop;
import io.netty.channel.EventLoopGroup;
import io.netty.handler.codec.http2.DefaultHttp2WindowUpdateFrame;
import io.netty.handler.codec.http2.Http2CodecUtil;
import io.netty.handler.codec.http2.Http2GoAwayFrame;
import io.netty.util.AttributeKey;
import io.netty.util.ReferenceCountUtil;
import java.net.SocketAddress;
import java.time.Duration;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import org.whispersystems.textsecuregcm.util.ClosableEpoch;
/// An [H2ConnectionFactory] that creates one shared h2 connection per calling event loop.
///
/// A connection is replaced the next time it's requested if it failed to connect, has closed, has received a GOAWAY, or
/// is older than `retireAfterNanos`. Retiring connections bounds how many stream IDs a connection uses since eventually
/// stream-ids are exhausted.
///
/// A replaced connection is never handed out again, and is closed once every stream it was handed out for has been
/// [#release]ed.
public class PooledH2ConnectionFactory implements H2ConnectionFactory {
private static final AttributeKey<Boolean> GOAWAY_RECEIVED =
AttributeKey.valueOf(PooledH2ConnectionFactory.class, "goawayReceived");
// Key for a [ClosableEpoch] attached to every new connection's channel. When the connection is replaced,
// [ClosableEpoch#close] is called, and when all streams are released the underlying netty channel is closed.
private static final AttributeKey<ClosableEpoch> CONNECTION_EPOCH =
AttributeKey.valueOf(PooledH2ConnectionFactory.class, "connection_epoch");
private static final PooledConnectionHandler POOLED_CONNECTION_HANDLER = new PooledConnectionHandler();
private static final String CONNECTION_REPLACED_COUNTER_NAME =
name(PooledH2ConnectionFactory.class, "connectionReplaced");
private static final String OPEN_CONNECTIONS_GAUGE_NAME = name(PooledH2ConnectionFactory.class, "openConnections");
// How long to use a pooled connection for
private static final Duration RETIRE_AFTER = Duration.ofMinutes(30);
private final UnpooledH2ConnectionFactory connectionFactory;
private final long retireAfterNanos;
private final ConcurrentHashMap<EventLoop, PooledConnection> connectionsByCallerEventLoop = new ConcurrentHashMap<>();
// Count of all open connections (including replaced ones waiting for outstanding streams to terminate)
private final AtomicInteger openConnections;
private record PooledConnection(ChannelFuture connectFuture, long createdNanos) {}
/// Create a pooled H2 connection factory
///
/// @param targetAddress The [SocketAddress] connections should target
/// @param eventLoopGroup The eventLoopGroup on which connections will be made. Must match the type of the [SocketAddress]
public PooledH2ConnectionFactory(final SocketAddress targetAddress, final EventLoopGroup eventLoopGroup) {
this(targetAddress, eventLoopGroup, RETIRE_AFTER);
}
@VisibleForTesting
PooledH2ConnectionFactory(final SocketAddress targetAddress,
final EventLoopGroup eventLoopGroup,
final Duration retireAfter) {
this.connectionFactory = new UnpooledH2ConnectionFactory(targetAddress, eventLoopGroup, POOLED_CONNECTION_HANDLER);
this.retireAfterNanos = retireAfter.toNanos();
this.openConnections = Metrics.gauge(OPEN_CONNECTIONS_GAUGE_NAME, Tags.of("backend", targetAddress.toString()),
new AtomicInteger());
}
@Override
public ChannelFuture getConnectionChannelFuture(final EventLoop callerEventLoop) {
assert callerEventLoop.inEventLoop();
final ChannelFuture connection = connectionsByCallerEventLoop.compute(callerEventLoop, (_, existing) -> {
if (existing == null) {
return newConnection(callerEventLoop);
} else if (!isUsable(existing)) {
existing.connectFuture().channel().attr(CONNECTION_EPOCH).get().close();
return newConnection(callerEventLoop);
} else {
return existing;
}
})
.connectFuture();
// Compute always hands us a connection with an open epoch and we can't race with anyone because we're in
// callerEventLoop, so we should always be able to enter the epoch
final boolean arrived = connection.channel().attr(CONNECTION_EPOCH).get().tryArrive();
assert arrived;
return connection;
}
private PooledConnection newConnection(final EventLoop callerEventLoop) {
final ChannelFuture connectFuture = connectionFactory.getConnectionChannelFuture(callerEventLoop);
final Channel channel = connectFuture.channel();
channel.attr(CONNECTION_EPOCH).set(new ClosableEpoch(channel::close));
openConnections.incrementAndGet();
channel.closeFuture().addListener(_ -> openConnections.decrementAndGet());
return new PooledConnection(connectFuture, System.nanoTime());
}
/// Whether a pooled connection can still be handed out
private boolean isUsable(final PooledConnection pooledConnection) {
final ChannelFuture connectionFuture = pooledConnection.connectFuture();
if (!connectionFuture.isDone()) {
return true;
}
final Channel connection = connectionFuture.channel();
// We know the future is done, see if we actually connected or if we've since disconnected
final boolean active = connection.isActive();
// We might still be connected but have gotten a GOAWAY indicating we shouldn't open new streams
final boolean goawayReceived = Boolean.TRUE.equals(connection.attr(GOAWAY_RECEIVED).get());
// The connection might be fine but old enough that we want a fresh one
final boolean retired = System.nanoTime() - pooledConnection.createdNanos() > retireAfterNanos;
final boolean usable = active && !goawayReceived && !retired;
if (!usable) {
Metrics.counter(CONNECTION_REPLACED_COUNTER_NAME,
"backend", address().toString(),
"active", String.valueOf(active),
"goaway", String.valueOf(goawayReceived),
"retired", String.valueOf(retired))
.increment();
}
return usable;
}
@Override
public void release(final Channel connection) {
connection.attr(CONNECTION_EPOCH).get().depart();
}
@Override
public SocketAddress address() {
return connectionFactory.address();
}
/// Initializes the connection with a large window, and marks a connection as draining when the backend sends a GOAWAY
@ChannelHandler.Sharable
private static class PooledConnectionHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelActive(final ChannelHandlerContext ctx) {
// Every new H2 connection starts with a connection flow-control window of 64K. Each stream on the connection also
// starts with a per-stream window of 64K. See https://www.rfc-editor.org/rfc/rfc9113.html#section-6.9.2.
//
// Because we're pooling many distinct, h2 streams from different remote clients may share this single h2
// connection to the backend. So, by default, if a single stream is slow to receive a large response from the
// backend, they could consume the entire connection window.
//
// To avoid this, as soon as we open the connection tell the server we're willing to accept more at the connection
// level. We update the connection window to the max value by sending a WINDOW_UPDATE (6.9) to add enough credit
// to reach the max connection window size of INT_MAX. The individual streams still retain the default window-size
// of 64K.
ctx.writeAndFlush(new DefaultHttp2WindowUpdateFrame(Integer.MAX_VALUE - Http2CodecUtil.DEFAULT_WINDOW_SIZE));
ctx.fireChannelActive();
}
@Override
public void channelRead(final ChannelHandlerContext ctx, final Object msg) {
if (msg instanceof Http2GoAwayFrame) {
ctx.channel().attr(GOAWAY_RECEIVED).set(true);
ReferenceCountUtil.release(msg);
return;
}
ctx.fireChannelRead(msg);
}
}
}
@@ -100,12 +100,7 @@ public class SniMapper {
private static SslContext buildSslContext(final KeyManagerFactory kmf, final SslProvider sslProvider)
throws SSLException {
final SslContextBuilder sslContextBuilder = sslProvider == SslProvider.OPENSSL
// work around netty's OpenSSL provider not selecting Ed25519 certificates on its own
? SslContextBuilder.forServer(BoringSslServerKeyManager.wrap(kmf.getKeyManagers()))
: SslContextBuilder.forServer(kmf);
return sslContextBuilder
return SslContextBuilder.forServer(kmf)
.sslProvider(sslProvider)
.applicationProtocolConfig(new ApplicationProtocolConfig(
ApplicationProtocolConfig.Protocol.ALPN,
@@ -0,0 +1,122 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc.net;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.google.common.collect.ImmutableSet;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Timer;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoop;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.local.LocalAddress;
import io.netty.channel.local.LocalChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http2.Http2FrameCodecBuilder;
import io.netty.handler.codec.http2.Http2MultiplexHandler;
import io.netty.handler.codec.http2.Http2Settings;
import io.netty.util.concurrent.EventExecutor;
import java.net.SocketAddress;
import java.util.List;
import java.util.Set;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class UnpooledH2ConnectionFactory implements H2ConnectionFactory {
private static final Logger logger = LoggerFactory.getLogger(UnpooledH2ConnectionFactory.class);
private static final OmnibusExceptionHandler BACKEND_CONNECTION_EXCEPTION_HANDLER =
new OmnibusExceptionHandler("backend-connection", List.of());
private static final String BACKEND_CONNECT_TIMER_NAME = name(UnpooledH2ConnectionFactory.class,
"backendConnectDuration");
private static final String BACKEND_TAG = "backend";
private final SocketAddress targetAddress;
private final Class<? extends Channel> channelClass;
private final EventLoopGroup eventLoopGroup;
private final Set<EventExecutor> eventLoops;
@Nullable
private final ChannelHandler connectionHandler;
public UnpooledH2ConnectionFactory(final SocketAddress targetAddress, final EventLoopGroup eventLoopGroup) {
this(targetAddress, eventLoopGroup, null);
}
UnpooledH2ConnectionFactory(
final SocketAddress targetAddress,
final EventLoopGroup eventLoopGroup,
@Nullable final ChannelHandler connectionHandler) {
this.targetAddress = targetAddress;
this.channelClass = targetAddress instanceof LocalAddress ? LocalChannel.class : NioSocketChannel.class;
this.eventLoopGroup = eventLoopGroup;
this.eventLoops = ImmutableSet.copyOf(eventLoopGroup);
this.connectionHandler = connectionHandler;
}
@Override
public ChannelFuture getConnectionChannelFuture(final EventLoop callerEventLoop) {
// Make a new H2 connection to the target backend
final Timer.Sample connectSample = Timer.start();
return new Bootstrap()
// If the caller is already on one of our event loops, connect on that loop so this connection runs on the
// caller's thread
.group(eventLoops.contains(callerEventLoop) ? callerEventLoop : eventLoopGroup)
.channel(channelClass)
.handler(new ChannelInitializer<>() {
@Override
protected void initChannel(final Channel ch) {
ch.pipeline()
.addLast(Http2FrameCodecBuilder.forClient().initialSettings(Http2Settings.defaultSettings()).build());
// Http2MultiplexHandler takes handler that is added to new inbound streams. A client Http2MultiplexHandler
// like we're defining here should never receive an inbound H2 stream so we can just pass a noop handler
ch.pipeline().addLast(new Http2MultiplexHandler(new NoopInboundStreamHandler()));
if (connectionHandler != null) {
ch.pipeline().addLast(connectionHandler);
}
ch.pipeline().addLast(BACKEND_CONNECTION_EXCEPTION_HANDLER);
}
})
.connect(targetAddress)
.addListener((ChannelFuture connectFuture) ->
connectSample.stop(Timer.builder(BACKEND_CONNECT_TIMER_NAME)
.tag(BACKEND_TAG, targetAddress.toString())
.tag("outcome", connectFuture.isSuccess() ? "success" : "failure")
.register(Metrics.globalRegistry)));
}
@Override
public void release(final Channel connection) {
// Each connection only ever carries one stream
connection.close();
}
@Override
public SocketAddress address() {
return targetAddress;
}
private static class NoopInboundStreamHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRegistered(final ChannelHandlerContext ctx) {
logger.error("Inbound stream handler was registered when no inbound streams expected");
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
logger.error("Received unexpected message: {} on inbound stream from backend", msg);
super.channelRead(ctx, msg);
}
}
}
@@ -184,7 +184,8 @@ public class KeyTransparencyServiceClient implements Managed {
channel = Grpc.newChannelBuilderForAddress(host, port, tlsChannelCredentials)
.idleTimeout(1, TimeUnit.MINUTES)
.build();
stub = KeyTransparencyQueryServiceGrpc.newBlockingStub(channel);
stub = KeyTransparencyQueryServiceGrpc.newBlockingStub(channel)
.withCompression("gzip");
}
@Override
@@ -51,6 +51,8 @@ public final class MessageMetrics {
private static final String DISPLACEMENT_COUNTER_NAME = name(WebSocketConnection.class, "displacement");
private static final Duration SLOW_DRAIN_THRESHOLD = Duration.ofSeconds(10);
private static final String SUSPECTED_DELIVERY_LOOP_COUNTER_NAME = name(MessageMetrics.class, "suspectedDeliveryLoop");
private final MeterRegistry metricRegistry;
private final Counter sendMessageCounter;
private final Counter bytesSentCounter;
@@ -145,4 +147,16 @@ public final class MessageMetrics {
.tags(Tags.of(UserAgentTagUtil.getPlatformTag(userAgent), Tag.of("channel", channel)))
.register(metricRegistry));
}
public static void recordSuspectedDeliveryLoop(final String channel,
@Nullable final UserAgent userAgent,
final ClientReleaseManager clientReleaseManager) {
final Tags tags = UserAgentTagUtil.getClientVersionTag(userAgent, clientReleaseManager)
.map(Tags::of)
.orElseGet(Tags::empty)
.and(UserAgentTagUtil.getPlatformTag(userAgent));
Metrics.counter(SUSPECTED_DELIVERY_LOOP_COUNTER_NAME, tags).increment();
}
}
@@ -8,7 +8,6 @@ package org.whispersystems.textsecuregcm.metrics;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.Appender;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
import io.dropwizard.logging.common.AbstractAppenderFactory;
import io.dropwizard.logging.common.async.AsyncAppenderFactory;
@@ -19,9 +18,6 @@ import io.opentelemetry.instrumentation.logback.appender.v1_0.OpenTelemetryAppen
@JsonTypeName("otlp")
public class OpenTelemetryAppenderFactory extends AbstractAppenderFactory<ILoggingEvent> {
@JsonProperty
private String destination;
@Override
public Appender<ILoggingEvent> build(
final LoggerContext context,
@@ -32,8 +28,7 @@ public class OpenTelemetryAppenderFactory extends AbstractAppenderFactory<ILoggi
final OpenTelemetryAppender appender = new OpenTelemetryAppender();
appender.setCaptureCodeAttributes(true);
appender.setCaptureLoggerContext(true);
appender.setCaptureLogstashMarkerAttributes(true);
appender.setKeyValuePairAttributesIncluded("*");
// The installation of an OpenTelemetry configuration happens in
// WhisperServerService (or CommandDependencies), in order to let us tie
@@ -8,10 +8,8 @@ package org.whispersystems.textsecuregcm.metrics;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import io.micrometer.core.instrument.Metrics;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import net.logstash.logback.marker.Markers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
@@ -49,10 +47,10 @@ public class ReportedMessageMetricsListener implements ReportedMessageListener {
accountsManager.getByAccountIdentifier(reporterUuid).ifPresent(reporter -> {
final String destinationCountryCode = Util.getCountryCode(reporter);
logger.info(Markers.appendEntries(Map.of(
"sourceCountry", sourceCountryCode,
"destinationCountry", destinationCountryCode)),
"Message reported");
logger.atInfo()
.addKeyValue("sourceCountry", sourceCountryCode)
.addKeyValue("destinationCountry", destinationCountryCode)
.log("Message reported");
Metrics.counter(REPORTER_COUNTER_NAME, COUNTRY_CODE_TAG_NAME, destinationCountryCode).increment();
});
@@ -365,7 +365,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor,
// since badge redemption is untrackable by design and unrevokable, subscription changes must be immediate and
// not prorated
.setProrationBehavior(ProrationBehavior.NONE)
.setBillingCycleAnchor(BillingCycleAnchor.NOW)
.setBillingCycleAnchor(BillingCycleAnchor.builder().setType(BillingCycleAnchor.Type.NOW).build())
.setOffSession(true)
.setPaymentBehavior(SubscriptionUpdateParams.PaymentBehavior.ERROR_IF_INCOMPLETE)
.addAllItem(items)
@@ -170,22 +170,22 @@ public class RegistrationServiceClient implements Managed {
throw new RegistrationServiceException(buildSessionResponseFromMetadata(response.getSessionMetadata()));
case SEND_VERIFICATION_CODE_ERROR_TYPE_SENDER_REJECTED ->
throw RegistrationServiceSenderException.rejected(response.getError().getMayRetry());
throw RegistrationServiceSenderException.rejected(!response.getError().getMayRetry());
case SEND_VERIFICATION_CODE_ERROR_TYPE_SUSPECTED_FRAUD ->
throw new RegistrationFraudException(
RegistrationServiceSenderException.rejected(response.getError().getMayRetry()));
RegistrationServiceSenderException.rejected(!response.getError().getMayRetry()));
case SEND_VERIFICATION_CODE_ERROR_TYPE_SENDER_ILLEGAL_ARGUMENT ->
throw RegistrationServiceSenderException.illegalArgument(response.getError().getMayRetry());
throw RegistrationServiceSenderException.illegalArgument(!response.getError().getMayRetry());
case SEND_VERIFICATION_CODE_ERROR_TYPE_UNSPECIFIED ->
throw RegistrationServiceSenderException.unknown(response.getError().getMayRetry());
throw RegistrationServiceSenderException.unknown(!response.getError().getMayRetry());
case SEND_VERIFICATION_CODE_ERROR_TYPE_TRANSPORT_NOT_ALLOWED ->
throw new TransportNotAllowedException(buildSessionResponseFromMetadata(response.getSessionMetadata()));
case SEND_VERIFICATION_CODE_ERROR_NO_SENDER_AVAILABLE ->
throw RegistrationServiceSenderException.unavailable(response.getError().getMayRetry());
throw RegistrationServiceSenderException.unavailable(!response.getError().getMayRetry());
default -> throw new RuntimeException("Failed to send verification code: " + response.getError().getErrorType());
}
@@ -17,9 +17,11 @@ public enum DeviceCapability {
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),
OPTIONAL_PHONE_NUMBER("optionalPhoneNumber", AccountCapabilityMode.ALL_DEVICES, AccountCapabilityVisibility.SERVER, false, false);
OPTIONAL_PHONE_NUMBER("optionalPhoneNumber", AccountCapabilityMode.ALL_DEVICES, AccountCapabilityVisibility.SERVER, false, false),
REPLY_PRIVATELY("replyPrivately", AccountCapabilityMode.ALL_DEVICES, AccountCapabilityVisibility.PUBLIC, false, false),
CONTACT_DELETE("contactDelete", AccountCapabilityMode.ALL_DEVICES, AccountCapabilityVisibility.PUBLIC, false, false),
ADMIN_REMOVE_AND_DELETE("adminRemoveAndDelete", AccountCapabilityMode.ALL_DEVICES, AccountCapabilityVisibility.PUBLIC, false, false);
public static final List<DeviceCapability> PUBLIC_VISIBLE_CAPABILITIES = Arrays.stream(DeviceCapability.values())
.filter(c -> c.accountCapabilityVisibility == AccountCapabilityVisibility.PUBLIC)
@@ -5,6 +5,7 @@
package org.whispersystems.textsecuregcm.storage;
import com.apple.foundationdb.FDBException;
import com.google.common.annotations.VisibleForTesting;
import com.google.protobuf.ByteString;
import java.time.Clock;
import java.time.Instant;
@@ -16,6 +17,7 @@ import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.function.Function;
import java.util.function.UnaryOperator;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
@@ -39,6 +41,9 @@ public class MessagesManager {
private final ExecutorService messageDeletionExecutor;
private final Clock clock;
@VisibleForTesting
static final long DELIVERY_LOOP_READ_THRESHOLD = 10;
public MessagesManager(
final MessagesDynamoDb messagesDynamoDb,
final FoundationDbMessageStore foundationDbMessageStore,
@@ -222,6 +227,19 @@ public class MessagesManager {
.toFuture();
}
/// Checks whether the given device is in a suspected "delivery loop" where it is repeatedly requesting but not
/// acknowledging messages.
///
/// @param accountIdentifier the identifier of the account to check for a delivery loop
/// @param deviceId the ID of the device to check for a delivery loop
///
/// @return a future that yields `true` if the identified device is suspected of being stuck in a message delivery
/// loop or `false` otherwise
public CompletableFuture<Boolean> hasSuspectedDeliveryLoop(final UUID accountIdentifier, final byte deviceId) {
return foundationDbMessageStore.getReadsSinceLastAcknowledgedMessage(new AciServiceIdentifier(accountIdentifier), deviceId)
.thenApply(readsSinceLastAcknowledgedMessage -> readsSinceLastAcknowledgedMessage >= DELIVERY_LOOP_READ_THRESHOLD);
}
/// Record versionstamps for the current time in the FoundationDB database(s).
public void recordFoundationDbVersionstamps() {
foundationDbMessageStore.recordVersionstamps();
@@ -263,7 +281,7 @@ public class MessagesManager {
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();
final Function<Mono<Boolean>, Mono<Boolean>> deleteModifier = dryRun ? _ -> Mono.just(true) : Function.identity();
return foundationDbMessageStore.trimQueue(aci, device, maxQueueSizeBytes, targetQueueSizeBytes, rangeSplitChunkSizeBytes, deleteModifier);
}
}
@@ -102,11 +102,7 @@ public class ProfilesManager {
redisSet(uuid, null, versionedProfile);
try {
// until the PROFILES_V2 capability prevents downgrades, if a client sets a v2 profile, and then the account
// downgrades to v1, all v2 profiles are stale
assert !DeviceCapability.PROFILES_V2.preventDowngrade();
profilesV2.deleteAll(uuid);
profilesV2.deleteAll(uuid).join();
} catch (final Exception e) {
logger.warn("Failed to delete v2 profile data: {}", uuid, e);
}
@@ -1,84 +0,0 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage.devicecheck;
import com.webauthn4j.appattest.DeviceCheckManager;
import com.webauthn4j.appattest.data.DCAssertion;
import com.webauthn4j.appattest.data.DCAssertionData;
import com.webauthn4j.appattest.data.DCAssertionRequest;
import com.webauthn4j.converter.AuthenticatorDataConverter;
import com.webauthn4j.converter.exception.DataConversionException;
import com.webauthn4j.converter.util.ObjectConverter;
import com.webauthn4j.data.attestation.authenticator.AuthenticatorData;
import com.webauthn4j.data.extension.authenticator.AuthenticationExtensionAuthenticatorOutput;
import tools.jackson.core.JacksonException;
import java.util.Arrays;
/// Parses Apple App Attest assertions
///
/// App Attest assertions since iOS 27 include an extensions map and don't include attested credential data. They
/// set the AT flag which indicates data, so a standards-compliant parser barfs because there's an extensions map where
/// the AT data should/ be.
///
/// If Apple fixes their headers or webauthn4j adopts some workaround, this class should be removed
///
/// [webauthn4j #1497](https://github.com/webauthn4j/webauthn4j/issues/1497)
/// [webauthn4j #1518](https://github.com/webauthn4j/webauthn4j/pull/1518)
class AppAttestAssertionConverter {
// https://www.w3.org/TR/webauthn/#sctn-authenticator-data
// rpIdHash(32) || flags(1) || signCount(4) || attestedCredentialData(variable) || extensions(variable)
private static final int FLAGS_OFFSET = 32;
private static final int HEADER_LENGTH = 37;
// https://www.rfc-editor.org/info/rfc8949/#section-3.1:~:text=the%20CBOR%20Encoding-,3.1%20Major%20Types,-3.2%20Indefinite%20Lengths
// CBOR major type 5 (map), covering both definite and indefinite length maps
private static final int CBOR_MAJOR_TYPE_MASK = 0xe0;
private static final int CBOR_MAP_MAJOR_TYPE = 0xa0;
private static final ObjectConverter OBJECT_CONVERTER = DeviceCheckManager.createObjectConverter();
private static final AuthenticatorDataConverter AUTHENTICATOR_DATA_CONVERTER = new AuthenticatorDataConverter(OBJECT_CONVERTER);
/// Parse an assertion request that potentially has misconfigured FLAGS. The returned data must still be verified.
static DCAssertionData parseAppleAssertion(final DCAssertionRequest request) throws DataConversionException {
final DCAssertion assertion = OBJECT_CONVERTER.getCborMapper().readValue(request.getAssertion(), DCAssertion.class);
final byte[] authenticatorDataBytes = assertion == null ? null : assertion.getAuthenticatorData();
final AuthenticatorData<AuthenticationExtensionAuthenticatorOutput> authenticatorData =
authenticatorDataBytes == null ? null : convertAuthenticatorData(authenticatorDataBytes);
return new DCAssertionData(request.getKeyId(), authenticatorData, authenticatorDataBytes,
request.getClientDataHash(), assertion == null ? null : assertion.getSignature());
}
private static AuthenticatorData<AuthenticationExtensionAuthenticatorOutput> convertAuthenticatorData(final byte[] original) {
if (!hasAppleAssertionExtensions(original)) {
return AUTHENTICATOR_DATA_CONVERTER.convert(original);
}
final AuthenticatorData<AuthenticationExtensionAuthenticatorOutput> parsed;
try {
// Create a copy just for parsing and set the flags as Apple should have set them
final byte[] modified = Arrays.copyOf(original, original.length);
modified[FLAGS_OFFSET] = (byte) ((original[FLAGS_OFFSET] & ~AuthenticatorData.BIT_AT) | AuthenticatorData.BIT_ED);
parsed = AUTHENTICATOR_DATA_CONVERTER.convert(modified);
} catch (final JacksonException _) {
// Jackson error messages can include the (untrusted) extension contents
throw new DataConversionException("Invalid App Attest assertion extension data");
}
// Return the parsed structures but keep the original (incorrect) flags, so signature validation works
return new AuthenticatorData<>(parsed.getRpIdHash(), original[FLAGS_OFFSET], parsed.getSignCount(),
parsed.getExtensions());
}
private static boolean hasAppleAssertionExtensions(final byte[] data) {
// If we don't have AT or Extensions at all, webauthn can handle them being incorrectly set without any conversion
return data.length > HEADER_LENGTH
// If the data correctly sets the AT flag, webauthn can also handle it
&& AuthenticatorData.checkFlagAT(data[FLAGS_OFFSET])
// If the first byte after the header looks like an extension, this is the special case. Valid assertions
// shouldn't have attestedCredentialData anyway, and if it did it should be a CBOR string
&& (data[HEADER_LENGTH] & CBOR_MAJOR_TYPE_MASK) == CBOR_MAP_MAJOR_TYPE;
}
}
@@ -138,7 +138,8 @@ public class AppleDeviceCheckManager {
final DCAttestationData dcAttestationData;
try {
dcAttestationData = deviceCheckManager.validate(dcAttestationRequest,
new DCAttestationParameters(new DCServerProperty(teamId, bundleId, new DefaultChallenge(challenge))));
new DCAttestationParameters(new DCServerProperty(teamId, bundleId,
new DefaultChallenge(challenge.getBytes(StandardCharsets.UTF_8)))));
} catch (VerificationException e) {
logger.info("Failed to verify attestation", e);
throw new DeviceCheckVerificationFailedException(e);
@@ -204,7 +205,7 @@ public class AppleDeviceCheckManager {
new DCAssertionParameters(new DCServerProperty(teamId, bundleId, new DefaultChallenge(request)), appleDevice);
try {
deviceCheckManager.validate(AppAttestAssertionConverter.parseAppleAssertion(dcAssertionRequest), dcAssertionParameters);
deviceCheckManager.validate(dcAssertionRequest, dcAssertionParameters);
} catch (MaliciousCounterValueException e) {
// We will only accept assertions that have a sign count greater than the last assertion we saw. Step 5 here:
// https://developer.apple.com/documentation/devicecheck/validating-apps-that-connect-to-your-server#Verify-the-assertion
@@ -1,6 +1,7 @@
package org.whispersystems.textsecuregcm.storage.foundationdb;
import com.apple.foundationdb.KeySelector;
import com.apple.foundationdb.MutationType;
import com.apple.foundationdb.StreamingMode;
import com.apple.foundationdb.Transaction;
import com.apple.foundationdb.tuple.Versionstamp;
@@ -8,6 +9,8 @@ import com.google.common.annotations.VisibleForTesting;
import com.google.protobuf.InvalidProtocolBufferException;
import io.micrometer.core.instrument.Metrics;
import java.io.UncheckedIOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.time.Clock;
import java.util.Arrays;
import java.util.Collections;
@@ -42,6 +45,8 @@ class FoundationDbMessagePublisher {
/// time the publisher was created. For an infinite publisher, this is the end of subspace range.
private final KeySelector endKeyExclusive;
private final byte[] readsSinceLastAcknowledgedMessageKey;
/// 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;
@@ -87,6 +92,12 @@ class FoundationDbMessagePublisher {
private static final int STREAM_ID_UNASSIGNED = -1;
// FoundationDB's `ADD` mutation operate on little-endian, 64-bit integers rather than on tuple-encoded integers
private static final byte[] ONE_LITTLE_ENDIAN = ByteBuffer.allocate(Long.BYTES)
.order(ByteOrder.LITTLE_ENDIAN)
.putLong(1L)
.array();
private static final Logger LOGGER = LoggerFactory.getLogger(FoundationDbMessagePublisher.class);
private static final String WATCHES_COUNTER = MetricsUtil.name(FoundationDbMessagePublisher.class, "watches");
@@ -131,6 +142,7 @@ class FoundationDbMessagePublisher {
final KeySelector beginKeyInclusive,
final KeySelector endKeyExclusive,
final int streamId,
final byte[] readsSinceLastAcknowledgedMessageKey,
@Nullable final byte[] presenceKey,
@Nullable final ScheduledExecutorService presenceRenewalExecutorService,
@Nullable final byte[] messagesAvailableWatchKey,
@@ -141,6 +153,7 @@ class FoundationDbMessagePublisher {
this.beginKeyCursor = beginKeyInclusive;
this.endKeyExclusive = endKeyExclusive;
this.streamId = streamId;
this.readsSinceLastAcknowledgedMessageKey = readsSinceLastAcknowledgedMessageKey;
this.presenceKey = presenceKey;
this.presenceRenewalExecutorService = presenceRenewalExecutorService;
this.messagesAvailableWatchKey = messagesAvailableWatchKey;
@@ -176,13 +189,15 @@ class FoundationDbMessagePublisher {
final FaultTolerantDatabase database,
final Clock clock,
final KeySelector beginKeyInclusive,
final KeySelector endKeyExclusive) {
final KeySelector endKeyExclusive,
final byte[] readsSinceHeadAcknowledgedKey) {
return new FoundationDbMessagePublisher(database,
clock,
beginKeyInclusive,
endKeyExclusive,
STREAM_ID_UNASSIGNED,
readsSinceHeadAcknowledgedKey,
null,
null,
null,
@@ -198,6 +213,7 @@ class FoundationDbMessagePublisher {
final KeySelector beginKeyInclusive,
final KeySelector endKeyExclusive,
final int streamId,
final byte[] readsSinceHeadAcknowledgedKey,
final byte[] presenceKey,
final ScheduledExecutorService presenceRenewalExecutorService,
final byte[] messagesAvailableWatchKey) {
@@ -207,6 +223,7 @@ class FoundationDbMessagePublisher {
beginKeyInclusive,
endKeyExclusive,
streamId,
readsSinceHeadAcknowledgedKey,
presenceKey,
presenceRenewalExecutorService,
messagesAvailableWatchKey,
@@ -345,7 +362,14 @@ class FoundationDbMessagePublisher {
transaction.getRange(beginKeyCursor, endKeyExclusive, maxMessages, false, StreamingMode.EXACT).asList(),
(_, keyValues) -> keyValues)
.thenApply(keyValues -> {
if (keyValues.size() < maxMessages && !terminateOnQueueEmpty) {
final int keyValuesSize = keyValues.size();
if (keyValuesSize > 0 && !hasEmittedEntry()) {
// We're about to emit our first message; increment the "sent head of queue since last ACK" counter
incrementReadsSinceHeadAcknowledged(transaction);
}
if (keyValuesSize < maxMessages && !terminateOnQueueEmpty) {
setWatch(transaction);
}
@@ -398,6 +422,10 @@ class FoundationDbMessagePublisher {
return (int) Math.min(totalRequested - totalEmitted, Integer.MAX_VALUE);
}
private synchronized boolean hasEmittedEntry() {
return totalEmitted > 0;
}
/// 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
@@ -426,6 +454,10 @@ class FoundationDbMessagePublisher {
return this.messagePublisher;
}
private void incrementReadsSinceHeadAcknowledged(final Transaction transaction) {
transaction.mutate(MutationType.ADD, readsSinceLastAcknowledgedMessageKey, ONE_LITTLE_ENDIAN);
}
private synchronized void setWatch(final Transaction transaction) {
assert messagesAvailableWatchKey != null;
if (isTerminated()) {
@@ -21,6 +21,7 @@ import io.micrometer.core.instrument.Tags;
import io.micrometer.core.instrument.Timer;
import java.io.UncheckedIOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
@@ -31,7 +32,6 @@ 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;
@@ -80,7 +80,7 @@ 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.
// Per-attempt timeout and retry limit for batch priority transactions, e.g. expired-message trim.
private final Duration batchPriorityTransactionTimeout;
private final long batchPriorityTransactionRetryLimit;
@@ -398,6 +398,8 @@ public class FoundationDbMessageStore {
return databasesByEpoch[getConfigurationEpoch(versionstamp)][getShardId(versionstamp)].runAsync(transaction -> {
transaction.clear(messageKey);
transaction.clear(getReadsSinceLastAcknowledgedMessageKey(aci, deviceId));
return CompletableFuture.completedFuture(null);
}, FaultTolerantDatabase.Context.DELETE_MESSAGE)
.thenRun(() -> {
@@ -406,35 +408,6 @@ public class FoundationDbMessageStore {
});
}
CompletableFuture<Optional<FoundationDbMessageStreamEntry.Message>> deleteAndGet(final AciServiceIdentifier aci, final byte deviceId, final UUID messageGuid) {
return deleteAndGet(aci, deviceId, versionstampUUIDCipher.decryptVersionstamp(messageGuid, aci.uuid(), deviceId));
}
CompletableFuture<Optional<FoundationDbMessageStreamEntry.Message>> deleteAndGet(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.get(messageKey)
.thenApply(value -> {
if (value == null) {
return Optional.<byte[]>empty();
}
transaction.clear(messageKey);
return Optional.of(value);
}), FaultTolerantDatabase.Context.DELETE_MESSAGE)
.whenComplete((_, _) -> sample.stop(DELETE_MESSAGE_TIMER))
.thenApply(maybeValue -> maybeValue.map(value -> {
DELETE_MESSAGE_COUNTER.increment();
try {
return new FoundationDbMessageStreamEntry.Message(versionstamp, MessageProtos.Envelope.parseFrom(value));
} catch (final InvalidProtocolBufferException e) {
throw new UncheckedIOException(e);
}
}));
}
public void clearAll(final AciServiceIdentifier aci) {
doForAllDatabasesWithMessages(aci, database -> database.run(transaction -> {
transaction.clear(getAccountSubspace(aci).range());
@@ -461,28 +434,15 @@ public class FoundationDbMessageStore {
return getMessages(aci, deviceId, Util.NOOP);
}
FaultTolerantDatabase[] getDatabasesByEpochForAci(final AciServiceIdentifier aci) {
// For each configured database epoch, which database held (or holds) the messages for this ACI/device pair?
final FaultTolerantDatabase[] databasesForQueueByEpoch = new FaultTolerantDatabase[databasesByEpoch.length];
for (final int epoch : liveEpochs) {
databasesForQueueByEpoch[epoch] = getShardForAci(aci, epoch);
}
return databasesForQueueByEpoch;
}
@VisibleForTesting
FoundationDbMessageStream getMessages(final AciServiceIdentifier aci,
final byte deviceId,
final Runnable doAfterCleanup) {
final FaultTolerantDatabase[] databasesForQueueByEpoch = getDatabasesByEpochForAci(aci);
return new FoundationDbMessageStream(this,
aci,
deviceId,
databasesForQueueByEpoch,
getDistinctDatabasesForAci(aci),
new MessageGuidCodec(aci.uuid(), deviceId, versionstampUUIDCipher),
doAfterCleanup,
presenceRenewalExecutorService,
@@ -496,7 +456,7 @@ public class FoundationDbMessageStore {
///
/// @return a future that yields `true` if the identified queue contains any messages or `false` if the queue is empty
public CompletableFuture<Boolean> hasMessages(final AciServiceIdentifier aci, final byte deviceId) {
return getDistinctDatabasesForAci(aci)
return Flux.fromArray(getDistinctDatabasesForAci(aci))
.flatMap(database -> Mono.fromFuture(() -> database.readAsync(transaction ->
transaction.getRange(getDeviceQueueSubspace(aci, deviceId).range(), 1).asList(),
FaultTolerantDatabase.Context.GET_HAS_MESSAGES)))
@@ -514,7 +474,7 @@ public class FoundationDbMessageStore {
/// @return a future that yields `true` if the identified queue contains an urgent message within a sample or `false`
/// otherwise
public CompletableFuture<Boolean> mayHaveUrgentMessages(final AciServiceIdentifier aci, final byte deviceId) {
return getDistinctDatabasesForAci(aci)
return Flux.fromArray(getDistinctDatabasesForAci(aci))
.flatMap(database -> Mono.fromFuture(() -> database.readAsync(transaction ->
transaction.getRange(getDeviceQueueSubspace(aci, deviceId).range(), MAY_HAVE_URGENT_MESSAGES_QUERY_LIMIT).asList(),
FaultTolerantDatabase.Context.GET_HAS_URGENT_MESSAGES))
@@ -540,7 +500,7 @@ public class FoundationDbMessageStore {
public CompletableFuture<Optional<Instant>> getEarliestUndeliveredMessageTimestamp(final AciServiceIdentifier aci,
final byte deviceId) {
return getDistinctDatabasesForAci(aci)
return Flux.fromArray(getDistinctDatabasesForAci(aci))
.flatMap(database -> Mono.fromFuture(() -> database.readAsync(transaction ->
transaction.getRange(getDeviceQueueSubspace(aci, deviceId).range(), 1).asList(),
FaultTolerantDatabase.Context.GET_EARLIEST_TIMESTAMP))
@@ -684,8 +644,17 @@ public class FoundationDbMessageStore {
@VisibleForTesting
record QueueSizeAndRangeSplitPoints(long estimatedQueueSize, Map<FaultTolerantDatabase, List<byte[]>> splitPointsByDatabase) {}
private Flux<FaultTolerantDatabase> getDistinctDatabasesForAci(final AciServiceIdentifier aci) {
return Flux.fromStream(Arrays.stream(getDatabasesByEpochForAci(aci)).filter(Objects::nonNull).distinct());
private FaultTolerantDatabase[] getDistinctDatabasesForAci(final AciServiceIdentifier aci) {
// Optimization: if we only have one live epoch (true most of the time!), we can skip the overhead of working with
// a stream
if (liveEpochs.length == 1) {
return new FaultTolerantDatabase[] { getShardForAci(aci, liveEpochs[0]) };
}
return Arrays.stream(liveEpochs)
.mapToObj(epoch -> getShardForAci(aci, epoch))
.distinct()
.toArray(FaultTolerantDatabase[]::new);
}
/// Estimates the size of the provided queue in bytes.
@@ -696,7 +665,7 @@ public class FoundationDbMessageStore {
Mono<Long> estimateQueueSize(final AciServiceIdentifier aci, final byte deviceId) {
final Range deviceQueueRange = getDeviceQueueSubspace(aci, deviceId).range();
return getDistinctDatabasesForAci(aci)
return Flux.fromArray(getDistinctDatabasesForAci(aci))
.flatMap(database -> Mono.fromFuture(() -> database.runAsync(transaction -> transaction.getEstimatedRangeSizeBytes(deviceQueueRange), FaultTolerantDatabase.Context.ESTIMATE_QUEUE_SIZE)))
.reduce(0L, Long::sum);
}
@@ -712,7 +681,8 @@ public class FoundationDbMessageStore {
final AciServiceIdentifier aci,
final byte deviceId,
final long rangeSplitChunkSize) {
return getDistinctDatabasesForAci(aci)
return Flux.fromArray(getDistinctDatabasesForAci(aci))
.flatMap(database -> Mono.fromFuture(() -> estimateQueueSizeAndRangeSplitsForDatabase(database, aci, deviceId, rangeSplitChunkSize))
.map(pair -> Tuples.of(pair.first(), database, pair.second().getKeys())))
.collect(Collectors.teeing(
@@ -740,7 +710,7 @@ public class FoundationDbMessageStore {
final long maxQueueSizeBytes,
final long targetQueueSizeBytes,
final long rangeSplitChunkSizeBytes,
final UnaryOperator<Mono<Boolean>> deleteModifier) {
final Function<Mono<Boolean>, Mono<Boolean>> deleteModifier) {
final Tag platformTag = Tag.of("platform", DevicePlatformUtil.getDevicePlatform(device)
.map(platform -> platform.name().toLowerCase(Locale.ROOT))
.orElse("unknown"));
@@ -794,9 +764,9 @@ public class FoundationDbMessageStore {
remainingBytesToDelete.addAndGet(-estimatedDeletedBytes);
ESTIMATED_TRIMMED_BYTES_COUNTER.increment(estimatedDeletedBytes);
})
.flatMap(_ -> Mono.just(true));
.then(Mono.just(true));
return deleteModifier.apply(deleteMono)
return deleteMono.transform(deleteModifier)
.onErrorResume(throwable -> {
if (!ExceptionUtils.isBreakerOpen(throwable)) {
LOGGER.warn("Failed to trim message queue for {}:{}", aci, device.getId(), throwable);
@@ -828,6 +798,24 @@ public class FoundationDbMessageStore {
}, FaultTolerantDatabase.Context.TRIM_QUEUE);
}
/// Returns the number of times a subscriber has started reading a message queue since the last time any message in
/// the queue was acknowledged. In cases where a caller's messages span multiple database shards (i.e. during a
/// migration), this method returns the maximum count across all shards.
///
/// @param aci the account identifier for which to retrieve a read-without-acknowledging-head count
/// @param deviceId the device ID for which to retrieve a read-without-acknowledging-head count
///
/// @return the number of times a subscriber has started reading messages from the identified message queue since the
/// last time any message in the queue was acknowledged
public CompletableFuture<Long> getReadsSinceLastAcknowledgedMessage(final AciServiceIdentifier aci, final byte deviceId) {
return Flux.fromArray(getDistinctDatabasesForAci(aci))
.flatMap(database -> Mono.fromFuture(() -> database.readAsync(transaction ->
transaction.get(getReadsSinceLastAcknowledgedMessageKey(aci, deviceId)), FaultTolerantDatabase.Context.TEST)))
.map(countBytes -> ByteBuffer.wrap(countBytes).order(ByteOrder.LITTLE_ENDIAN).getLong())
.reduce(0L, Math::max)
.toFuture();
}
@VisibleForTesting
public static Subspace getAccountSubspace(final AciServiceIdentifier aci) {
return getAccountSubspace(MESSAGES_SUBSPACE, aci);
@@ -842,6 +830,10 @@ public class FoundationDbMessageStore {
return getAccountSubspace(aci).pack("l");
}
static byte[] getReadsSinceLastAcknowledgedMessageKey(final AciServiceIdentifier aci, final byte deviceId) {
return getDeviceSubspace(aci, deviceId).pack("r");
}
@VisibleForTesting
static byte[] getServerId() {
return SERVER_ID;
@@ -8,10 +8,7 @@ import com.apple.foundationdb.subspace.Subspace;
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.List;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
@@ -42,7 +39,7 @@ public class FoundationDbMessageStream implements MessageStream {
private final Subspace deviceQueueSubspace;
private final byte[] presenceKey;
private final byte[] messagesAvailableWatchKey;
private final FaultTolerantDatabase[] databasesByEpoch;
private final FaultTolerantDatabase[] databases;
private final MessageGuidCodec messageGuidCodec;
/// The maximum number of messages we will fetch per range query operation to avoid excessive memory consumption
private final Flow.Publisher<MessageStreamEntry> messageStreamPublisher;
@@ -71,7 +68,7 @@ public class FoundationDbMessageStream implements MessageStream {
FoundationDbMessageStream(final FoundationDbMessageStore foundationDbMessageStore,
final AciServiceIdentifier aciServiceIdentifier,
final byte deviceId,
final FaultTolerantDatabase[] databasesByEpoch,
final FaultTolerantDatabase[] databases,
final MessageGuidCodec messageGuidCodec,
final Runnable doAfterCleanup,
final ScheduledExecutorService presenceRenewalExecutorService,
@@ -82,7 +79,7 @@ public class FoundationDbMessageStream implements MessageStream {
this.deviceQueueSubspace = FoundationDbMessageStore.getDeviceQueueSubspace(aciServiceIdentifier, deviceId);
this.presenceKey = FoundationDbMessageStore.getPresenceKey(aciServiceIdentifier, deviceId);
this.messagesAvailableWatchKey = FoundationDbMessageStore.getMessagesAvailableWatchKey(aciServiceIdentifier);
this.databasesByEpoch = databasesByEpoch;
this.databases = databases;
this.messageGuidCodec = messageGuidCodec;
this.messageStreamPublisher = JdkFlowAdapter.publisherToFlowPublisher(createMessagePublisher());
this.doAfterCleanup = doAfterCleanup;
@@ -124,11 +121,7 @@ public class FoundationDbMessageStream implements MessageStream {
/// on [#messagesAvailableWatchKey] which is updated when a new message is available.
/// See [FoundationDbMessageStore] for more details on the message insert process.
private Flux<FoundationDbMessageStreamEntry> createFoundationDbMessagePublisher() {
// This may seem like an odd construction since it looks like we could also just do `Flux#fromArray`, but
// `Flux#fromArray` cannot handle `null` elements
final List<FaultTolerantDatabase> databases = Arrays.stream(databasesByEpoch).filter(Objects::nonNull).distinct().toList();
return Flux.fromIterable(databases)
return Flux.fromArray(this.databases)
.flatMap(database -> Mono.fromFuture(() -> getEndOfQueueKeyExclusive(database))
.map(maybeEndOfQueueKeyExclusive -> Tuples.of(database, maybeEndOfQueueKeyExclusive)))
.collectMap(Tuple2::getT1, Tuple2::getT2)
@@ -144,7 +137,8 @@ public class FoundationDbMessageStream implements MessageStream {
database,
clock,
KeySelector.firstGreaterOrEqual(deviceQueueSubspace.range().begin),
endOfQueueKeyExclusive)
endOfQueueKeyExclusive,
FoundationDbMessageStore.getReadsSinceLastAcknowledgedMessageKey(aciServiceIdentifier, deviceId))
.getMessages())
.orElseGet(Flux::empty)
.handle((fdbMessageStreamEntry, sink) -> {
@@ -177,6 +171,7 @@ public class FoundationDbMessageStream implements MessageStream {
infinitePublisherBeginKey,
KeySelector.firstGreaterThan(deviceQueueSubspace.range().end),
NEXT_STREAM_ID.getAndIncrement(),
FoundationDbMessageStore.getReadsSinceLastAcknowledgedMessageKey(aciServiceIdentifier, deviceId),
presenceKey,
presenceRenewalExecutorService,
messagesAvailableWatchKey).getMessages();
@@ -229,17 +224,4 @@ public class FoundationDbMessageStream implements MessageStream {
return foundationDbMessageStore.delete(aciServiceIdentifier, deviceId, messageGuid);
}
public CompletableFuture<Optional<MessageStreamEntry.Envelope>> acknowledgeAndGetMessage(final UUID messageGuid) {
messageAcknowledgedCounter.increment();
return foundationDbMessageStore.deleteAndGet(aciServiceIdentifier, deviceId, messageGuid)
.thenApply(foundationDbMessageStreamEntry -> foundationDbMessageStreamEntry.map(m -> {
final MessageStreamEntry messageStreamEntry = m.toMessageStreamEntry(messageGuidCodec);
if (!(messageStreamEntry instanceof MessageStreamEntry.Envelope)) {
throw new AssertionError("Expected MessageStreamEntry.Envelope, got " + messageStreamEntry);
}
return (MessageStreamEntry.Envelope) messageStreamEntry;
}));
}
}
@@ -23,6 +23,7 @@
/// | | device was present
/// | | + {device ID (byte)} (device subspace)
/// | | | * "p" => presence: server-id || last-seen-time
/// | | | * "r" => reads since last message acknowledgement: 64-bit integer (little-endian)
/// | | | + "Q" (device message queue subspace)
/// | | | | * versionstamp => serialized envelope
/// ```
@@ -7,9 +7,11 @@ package org.whispersystems.textsecuregcm.util;
import org.signal.libsignal.usernames.BaseUsernameException;
import org.signal.libsignal.usernames.Username;
import org.signal.libsignal.usernames.UsernameHash;
import org.signal.libsignal.zkgroup.InvalidInputException;
public class UsernameHashZkProofVerifier {
public void verifyProof(final byte[] proof, final byte[] hash) throws BaseUsernameException {
Username.verifyProof(proof, hash);
public void verifyProof(final byte[] proof, final byte[] hash) throws BaseUsernameException, InvalidInputException {
Username.verifyProof(proof, new UsernameHash(hash));
}
}
@@ -230,17 +230,6 @@ public class Util {
return workingCopy == prefix;
}
/**
* Benin changed phone number formats from +229 XXXXXXXX to +229 01XXXXXXXX on November 30, 2024
*
* @param phoneNumber the phone number to check.
* @return whether the provided phone number is an old-format Benin phone number
*/
public static boolean isOldFormatBeninPhoneNumber(final Phonenumber.PhoneNumber phoneNumber) {
return "BJ".equals(PHONE_NUMBER_UTIL.getRegionCodeForNumber(phoneNumber)) &&
PHONE_NUMBER_UTIL.getNationalSignificantNumber(phoneNumber).length() == 8;
}
/**
* @return whether the E164-formatted {@code number} is in a range that registration-service treats as fictitious
*/
@@ -257,9 +246,6 @@ public class Util {
*/
public static Phonenumber.PhoneNumber canonicalizePhoneNumber(final Phonenumber.PhoneNumber phoneNumber)
throws NumberParseException, ObsoletePhoneNumberFormatException {
if (isOldFormatBeninPhoneNumber(phoneNumber)) {
throw new ObsoletePhoneNumberFormatException("bj");
}
return phoneNumber;
}
@@ -9,14 +9,11 @@ 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() {
@@ -25,6 +22,6 @@ public final class 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);
logger.atError().addKeyValue("impossible", true).log(message, args);
}
}
@@ -19,6 +19,7 @@ import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.LongAdder;
import javax.annotation.Nullable;
@@ -141,10 +142,21 @@ public class WebSocketConnection {
final Timer.Sample queueDrainStart = Timer.start();
messageSubscription.set(JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages())
.name(SEND_MESSAGES_FLUX_NAME)
.tap(Micrometer.metrics(Metrics.globalRegistry))
.limitRate(MESSAGE_PUBLISHER_LIMIT_RATE)
final AtomicInteger maxConcurrency = new AtomicInteger(MESSAGE_SENDER_MAX_CONCURRENCY);
messageSubscription.set(Mono.fromFuture(() -> messagesManager.hasSuspectedDeliveryLoop(authenticatedAccount.getAccountIdentifier(), authenticatedDevice.getId()))
.flatMapMany(hasSuspectedDeliveryLoop -> {
if (hasSuspectedDeliveryLoop) {
maxConcurrency.set(1);
MessageMetrics.recordSuspectedDeliveryLoop(MessageMetrics.WEBSOCKET_CHANNEL, userAgent, clientReleaseManager);
}
return JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages())
.name(SEND_MESSAGES_FLUX_NAME)
.tag("hasSuspectedDeliveryLoop", String.valueOf(hasSuspectedDeliveryLoop))
.tap(Micrometer.metrics(Metrics.globalRegistry))
.limitRate(maxConcurrency.get());
})
// We want to handle conflicting connections as soon as possible, and so do this before we start processing
// messages in the `flatMapSequential` stage below. If we didn't do this first, then we'd wait for clients to
// process messages before sending the "connected elsewhere" signal, and while that's ultimately not harmful,
@@ -156,7 +168,7 @@ public class WebSocketConnection {
.flatMapSequential(entry -> switch (entry) {
case MessageStreamEntry.Envelope envelope -> Mono.fromFuture(() -> sendMessage(envelope.message())).thenReturn(entry);
case MessageStreamEntry.QueueEmpty _ -> Mono.just(entry);
}, MESSAGE_SENDER_MAX_CONCURRENCY)
}, maxConcurrency.get())
.subscribeOn(messageDeliveryScheduler)
.subscribe(
entry -> {
@@ -90,9 +90,12 @@ enum DeviceCapability {
reserved 5;
DEVICE_CAPABILITY_ATTACHMENT_BACKFILL = 6;
DEVICE_CAPABILITY_SPARSE_POST_QUANTUM_RATCHET = 7;
DEVICE_CAPABILITY_PROFILES_V2 = 8;
reserved 8;
DEVICE_CAPABILITY_USERNAME_CHANGE_SYNC_MESSAGE = 9;
DEVICE_CAPABILITY_OPTIONAL_PHONE_NUMBER = 10;
DEVICE_CAPABILITY_REPLY_PRIVATELY = 11;
DEVICE_CAPABILITY_CONTACT_DELETE = 12;
DEVICE_CAPABILITY_ADMIN_REMOVE_AND_DELETE = 13;
}
message ZkCredential {
@@ -137,7 +137,7 @@ message DevicePreKeyBundle {
// A one-time KEM pre-key (or a last-resort KEM pre-key) for the targeted
// account/device/identity.
common.KemSignedPreKey kem_one_time_pre_key = 3;
common.KemSignedPreKey kem_pre_key = 3;
// The registration ID for the targeted account/device/identity.
uint32 registration_id = 4;
@@ -230,8 +230,16 @@ message CheckIdentityKeyRequest {
}
message CheckIdentityKeyResponse {
// The service identifier of the account for which there is a mismatch between the client and server identity key fingerprints.
common.ServiceIdentifier target_identifier = 1;
// The identity key that is stored by the server for the target account/identity type.
bytes identity_key = 2;
oneof response {
// The key for the target account/identity type matched.
google.protobuf.Empty matched = 1;
// The identity key that is stored by the server for the target account/identity type.
bytes identity_key = 2;
// Either the target account was not found, or it has no identity key for
// the requested identity type.
errors.NotFound target_not_found = 3 [(tag.reason) = "not_found"];
}
}
@@ -30,8 +30,8 @@ service OneTimeDonations {
// and token.
//
// The PayPal approval page presented to the user may be localized. Callers
// should set their language preferences via an "Accept-Language" header on
// the request:
// should set their language preferences via gRPC metadata on the request with
// the key "Accept-Language" header:
// https://datatracker.ietf.org/doc/html/rfc3282#section-3
rpc CreatePayPalBoost(CreatePayPalBoostRequest) returns (CreatePayPalBoostResponse) {}
@@ -289,8 +289,8 @@ message LegacyProfileResult {
bytes about = 2;
// The ciphertext of the emoji on the profile.
bytes about_emoji = 3;
// The cdn0 path of the avatar on the profile.
string avatar = 4;
// The URL of the avatar on the profile.
string avatar_url = 4;
// The ciphertext of the phone-number sharing setting on the profile.
bytes phone_number_sharing = 5;
// The ciphertext of the MobileCoin wallet ID on the profile.
@@ -414,7 +414,7 @@ message ExtendAvatarTTLRequest {
message ExtendAvatarTTLResponse {
oneof response {
// The avatar that was extended. May be used as a check against state de-synchronization.
string path = 1;
string url = 1;
errors.FailedZkAuthentication invalid_credential_presentation = 2 [(tag.reason) = "invalid_credential_presentation"];
// the identity does not have an active avatar
errors.NotFound not_found = 3 [(tag.reason) = "no_active_avatar"];
@@ -25,8 +25,8 @@ service RemoteConfiguration {
// Returns detailed information for all configured badges, keyed by badge ID.
//
// Badge descriptions may contain localized strings. Callers should set their
// language preferences via an "Accept-Language" header on the request
// https://datatracker.ietf.org/doc/html/rfc3282#section-3
// language preferences via gRPC metadata on the request with the key
// "Accept-Language": https://datatracker.ietf.org/doc/html/rfc3282#section-3
//
// Callers may cache a badges result for up to 1 day before checking (via
// etag) if there are any new updates.
@@ -39,8 +39,8 @@ service Subscriptions {
// Returns a PayPal billing agreement approval URL and token that can be used to set up PayPal as a payment method.
//
// The presented billing agreement may be localized. Callers should set their
// language preferences via an "Accept-Language" header on the request:
// https://datatracker.ietf.org/doc/html/rfc3282#section-3
// language preferences via gRPC metadata on the request with the key
// "Accept-Language": https://datatracker.ietf.org/doc/html/rfc3282#section-3
rpc CreatePayPalPaymentMethod(CreatePayPalPaymentMethodRequest) returns (CreatePayPalPaymentMethodResponse) {}
// Sets the default payment method for a subscriber.
@@ -60,6 +60,7 @@ import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import org.signal.libsignal.usernames.BaseUsernameException;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
import org.whispersystems.textsecuregcm.auth.StoredRegistrationLock;
@@ -675,7 +676,7 @@ class AccountControllerTest {
@Test
void testConfirmUsernameHash()
throws BaseUsernameException, UsernameHashNotAvailableException, UsernameReservationNotFoundException {
throws BaseUsernameException, UsernameHashNotAvailableException, UsernameReservationNotFoundException, InvalidInputException {
Account account = mock(Account.class);
final UUID uuid = UUID.randomUUID();
when(account.getUsernameHash()).thenReturn(Optional.of(USERNAME_HASH_1));
@@ -713,7 +714,7 @@ class AccountControllerTest {
@Test
void testConfirmUsernameHashOld()
throws BaseUsernameException, UsernameHashNotAvailableException, UsernameReservationNotFoundException {
throws BaseUsernameException, UsernameHashNotAvailableException, UsernameReservationNotFoundException, InvalidInputException {
Account account = mock(Account.class);
when(account.getUsernameHash()).thenReturn(Optional.of(USERNAME_HASH_1));
when(account.getUsernameLinkHandle()).thenReturn(null);
@@ -737,7 +738,7 @@ class AccountControllerTest {
@Test
void testConfirmUnreservedUsernameHash()
throws BaseUsernameException, UsernameHashNotAvailableException, UsernameReservationNotFoundException {
throws BaseUsernameException, UsernameHashNotAvailableException, UsernameReservationNotFoundException, InvalidInputException {
when(accountsManager.confirmReservedUsernameHash(any(), eq(USERNAME_HASH_1), any()))
.thenThrow(new UsernameReservationNotFoundException());
@@ -754,7 +755,7 @@ class AccountControllerTest {
@Test
void testConfirmLapsedUsernameHash()
throws BaseUsernameException, UsernameHashNotAvailableException, UsernameReservationNotFoundException {
throws BaseUsernameException, UsernameHashNotAvailableException, UsernameReservationNotFoundException, InvalidInputException {
when(accountsManager.confirmReservedUsernameHash(any(), eq(USERNAME_HASH_1), any()))
.thenThrow(new UsernameHashNotAvailableException());
@@ -805,7 +806,7 @@ class AccountControllerTest {
}
@Test
void testCommitUsernameHashWithInvalidProof() throws BaseUsernameException {
void testCommitUsernameHashWithInvalidProof() throws BaseUsernameException, InvalidInputException {
doThrow(new BaseUsernameException("invalid username")).when(usernameZkProofVerifier).verifyProof(eq(ZK_PROOF), eq(USERNAME_HASH_1));
try (final Response response = resources.getJerseyTest()
@@ -144,22 +144,12 @@ class AttachmentControllerV4Test {
.isEqualTo(Response.Status.REQUEST_ENTITY_TOO_LARGE.getStatusCode());
}
@Test
void missingUploadLengthDoesNotRateLimit() throws RateLimitExceededException {
doThrow(RateLimitExceededException.class).when(BYTE_RATE_LIMITER).validate(AuthHelper.VALID_UUID);
assertThatNoException().isThrownBy(() -> resources.getJerseyTest()
.target("/v4/attachments/form/upload")
.request()
.header("Authorization", CDN3_ENABLED_CREDS)
.get().getStatus());
}
@Test
void countRateLimitExceeded() throws RateLimitExceededException {
doThrow(RateLimitExceededException.class).when(COUNT_RATE_LIMITER).validate(AuthHelper.VALID_UUID);
assertThat(resources.getJerseyTest()
.target("/v4/attachments/form/upload")
.queryParam("uploadLength", MAX_UPLOAD_LENGTH)
.request()
.header("Authorization", CDN3_ENABLED_CREDS)
.get().getStatus())
@@ -202,6 +192,7 @@ class AttachmentControllerV4Test {
void testV4GcsForm() throws MalformedURLException {
AttachmentDescriptorV3 descriptor = resources.getJerseyTest()
.target("/v4/attachments/form/upload")
.queryParam("uploadLength", MAX_UPLOAD_LENGTH)
.request()
.header("Authorization", CDN3_DISABLED_CREDS)
.get(AttachmentDescriptorV3.class);
@@ -209,6 +200,16 @@ class AttachmentControllerV4Test {
assertValidCdn2Response(descriptor);
}
@Test
void testV4GcsFormNoUploadLength() throws MalformedURLException {
assertThat(resources.getJerseyTest()
.target("/v4/attachments/form/upload")
.request()
.header("Authorization", CDN3_DISABLED_CREDS)
.get()
.getStatus()).isEqualTo(400);
}
private static void assertValidCdn2Response(final AttachmentDescriptorV3 descriptor) throws MalformedURLException {
assertThat(descriptor.key()).isNotBlank();
assertThat(descriptor.cdn()).isEqualTo(2);
@@ -259,25 +259,6 @@ class VerificationControllerTest {
);
}
@Test
void createBeninSessionFailure() throws RateLimitExceededException {
// libphonenumber 8.13.50 and on generate new-format numbers for Benin
final String newFormatBeninE164 = PhoneNumberUtil.getInstance()
.format(PhoneNumberUtil.getInstance().getExampleNumber("BJ"), PhoneNumberUtil.PhoneNumberFormat.E164);
final String oldFormatBeninE164 = newFormatBeninE164.replaceFirst("01", "");
when(registrationServiceClient.createRegistrationSession(any(), anyString(), anyBoolean(), any(), any(), any()))
.thenReturn(new RegistrationServiceSession(SESSION_ID, NUMBER, false, null, null, null, SESSION_EXPIRATION_SECONDS));
final Invocation.Builder request = resources.getJerseyTest()
.target("/v1/verification/session")
.request()
.header(HttpHeaders.X_FORWARDED_FOR, "127.0.0.1");
try (Response response = request.post(Entity.json(createSessionJson(oldFormatBeninE164, "token", "fcm")))) {
assertEquals(499, response.getStatus());
}
}
@ParameterizedTest
@MethodSource
void createSessionSuccess(final String pushToken, final String pushTokenType,
@@ -112,6 +112,7 @@ import org.signal.chat.errors.FailedPrecondition;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.signal.libsignal.usernames.BaseUsernameException;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.ZkCredentialKeyPair;
import org.signal.libsignal.zkgroup.ZkCredentialPublicKey;
import org.whispersystems.textsecuregcm.auth.InvalidRegistrationSessionException;
@@ -520,7 +521,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
}
@Test
void confirmUsernameHashInvalidProof() throws BaseUsernameException {
void confirmUsernameHashInvalidProof() throws BaseUsernameException, InvalidInputException {
final byte[] usernameHash = TestRandomUtil.nextBytes(AccountController.USERNAME_HASH_LENGTH);
final byte[] usernameCiphertext = TestRandomUtil.nextBytes(32);
@@ -449,7 +449,10 @@ class DevicesGrpcServiceTest extends SimpleBaseGrpcTest<DevicesGrpcService, Devi
@CartesianTest.Values(booleans = {true, false}) final boolean transfer,
@CartesianTest.Values(booleans = {true, false}) final boolean attachmentBackfill,
@CartesianTest.Values(booleans = {true, false}) final boolean spqr,
@CartesianTest.Values(booleans = {true, false}) final boolean usernameChangeSyncMessage) {
@CartesianTest.Values(booleans = {true, false}) final boolean usernameChangeSyncMessage,
@CartesianTest.Values(booleans = {true, false}) final boolean replyPrivately,
@CartesianTest.Values(booleans = {true, false}) final boolean contactDelete,
@CartesianTest.Values(booleans = {true, false}) final boolean adminRemoveAndDelete) {
mockAuthenticationInterceptor().setAuthenticatedDevice(AUTHENTICATED_ACI, deviceId);
@@ -478,6 +481,18 @@ class DevicesGrpcServiceTest extends SimpleBaseGrpcTest<DevicesGrpcService, Devi
requestBuilder.addCapabilities(org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_USERNAME_CHANGE_SYNC_MESSAGE);
}
if (replyPrivately) {
requestBuilder.addCapabilities(org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_REPLY_PRIVATELY);
}
if (contactDelete) {
requestBuilder.addCapabilities(org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_CONTACT_DELETE);
}
if (adminRemoveAndDelete) {
requestBuilder.addCapabilities(org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_ADMIN_REMOVE_AND_DELETE);
}
final SetCapabilitiesResponse ignored = authenticatedServiceStub().setCapabilities(requestBuilder.build());
final Set<DeviceCapability> expectedCapabilities = new HashSet<>();
@@ -503,6 +518,18 @@ class DevicesGrpcServiceTest extends SimpleBaseGrpcTest<DevicesGrpcService, Devi
expectedCapabilities.add(DeviceCapability.USERNAME_CHANGE_SYNC_MESSAGE);
}
if (replyPrivately) {
expectedCapabilities.add(DeviceCapability.REPLY_PRIVATELY);
}
if (contactDelete) {
expectedCapabilities.add(DeviceCapability.CONTACT_DELETE);
}
if (adminRemoveAndDelete) {
expectedCapabilities.add(DeviceCapability.ADMIN_REMOVE_AND_DELETE);
}
verify(device).setCapabilities(expectedCapabilities);
}
@@ -0,0 +1,173 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.google.protobuf.ByteString;
import io.grpc.CallOptions;
import io.grpc.Channel;
import io.grpc.ClientCall;
import io.grpc.ClientInterceptor;
import io.grpc.Codec;
import io.grpc.DecompressorRegistry;
import io.grpc.ForwardingClientCall;
import io.grpc.ForwardingClientCallListener;
import io.grpc.ManagedChannel;
import io.grpc.Metadata;
import io.grpc.MethodDescriptor;
import io.grpc.Server;
import io.grpc.inprocess.InProcessChannelBuilder;
import io.grpc.inprocess.InProcessServerBuilder;
import java.io.IOException;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.signal.chat.rpc.EchoRequest;
import org.signal.chat.rpc.EchoResponse;
import org.signal.chat.rpc.EchoServiceGrpc;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicGrpcCompressionConfiguration;
import org.whispersystems.textsecuregcm.tests.util.FakeDynamicConfigurationManager;
class GrpcCompressionInterceptorTest {
private static final String SERVER_NAME = GrpcCompressionInterceptor.class.getSimpleName();
private static final Metadata.Key<String> GRPC_ENCODING_KEY =
Metadata.Key.of("grpc-encoding", Metadata.ASCII_STRING_MARSHALLER);
private static final EchoRequest REQUEST = EchoRequest.newBuilder()
.setPayload(ByteString.copyFromUtf8("compressible ".repeat(100)))
.build();
private Server server;
private ManagedChannel channel;
private final ResponseHeaderCapturingInterceptor responseHeaderCapturingInterceptor =
new ResponseHeaderCapturingInterceptor();
@AfterEach
void tearDown() throws Exception {
server.shutdownNow();
channel.shutdownNow();
server.awaitTermination(1, TimeUnit.SECONDS);
channel.awaitTermination(1, TimeUnit.SECONDS);
}
@Test
void noCompressionByDefault() throws Exception {
final EchoServiceGrpc.EchoServiceBlockingStub client =
setup(Collections.emptySet(), Collections.emptySet(), DecompressorRegistry.getDefaultInstance());
assertThat(client.echo(REQUEST).getPayload()).isEqualTo(REQUEST.getPayload());
assertThat(responseHeaderCapturingInterceptor.responseEncoding).isEqualTo("identity");
}
@Test
void compressByMethod() throws Exception {
final EchoServiceGrpc.EchoServiceBlockingStub client =
setup(Collections.emptySet(), Set.of("org.signal.chat.rpc.EchoService/echo"),
DecompressorRegistry.getDefaultInstance());
final EchoResponse echo = client.echo(REQUEST);
assertThat(echo.getPayload()).isEqualTo(REQUEST.getPayload());
assertThat(responseHeaderCapturingInterceptor.responseEncoding).isEqualTo("gzip");
final EchoResponse echo2 = client.echo2(REQUEST);
assertThat(echo2.getPayload()).isEqualTo(REQUEST.getPayload());
assertThat(responseHeaderCapturingInterceptor.responseEncoding).isEqualTo("identity");
}
@Test
void compressByService() throws Exception {
final EchoServiceGrpc.EchoServiceBlockingStub client =
setup(Set.of("org.signal.chat.rpc.EchoService"), Collections.emptySet(),
DecompressorRegistry.getDefaultInstance());
final EchoResponse echo = client.echo(REQUEST);
assertThat(echo.getPayload()).isEqualTo(REQUEST.getPayload());
assertThat(responseHeaderCapturingInterceptor.responseEncoding).isEqualTo("gzip");
final EchoResponse echo2 = client.echo2(REQUEST);
assertThat(echo2.getPayload()).isEqualTo(REQUEST.getPayload());
assertThat(responseHeaderCapturingInterceptor.responseEncoding).isEqualTo("gzip");
}
@Test
void compressByServiceWrongService() throws Exception {
final EchoServiceGrpc.EchoServiceBlockingStub client =
setup(Set.of("org.signal.chat.rpc.NotEchoService"), Collections.emptySet(),
DecompressorRegistry.getDefaultInstance());
assertThat(client.echo(REQUEST).getPayload()).isEqualTo(REQUEST.getPayload());
assertThat(responseHeaderCapturingInterceptor.responseEncoding).isEqualTo("identity");
}
@Test
void clientDoesNotAcceptGzip() throws Exception {
final EchoServiceGrpc.EchoServiceBlockingStub client =
setup(Set.of("org.signal.chat.rpc.EchoService"), Collections.emptySet(),
DecompressorRegistry.emptyInstance().with(Codec.Identity.NONE, true));
assertThat(client.echo(REQUEST).getPayload()).isEqualTo(REQUEST.getPayload());
assertThat(responseHeaderCapturingInterceptor.responseEncoding).isEqualTo("identity");
}
private EchoServiceGrpc.EchoServiceBlockingStub setup(
final Set<String> compressedServices,
final Set<String> compressedMethods,
final DecompressorRegistry clientDecompressorRegistry) throws IOException {
final DynamicConfiguration configuration = mock(DynamicConfiguration.class);
when(configuration.getGrpcCompression())
.thenReturn(new DynamicGrpcCompressionConfiguration(compressedServices, compressedMethods));
server = InProcessServerBuilder.forName(SERVER_NAME)
.directExecutor()
.addService(new EchoServiceImpl())
.intercept(new GrpcCompressionInterceptor(new FakeDynamicConfigurationManager<>(configuration)))
.build()
.start();
channel = InProcessChannelBuilder.forName(SERVER_NAME)
.directExecutor()
.decompressorRegistry(clientDecompressorRegistry)
.intercept(responseHeaderCapturingInterceptor)
.build();
return EchoServiceGrpc.newBlockingStub(channel);
}
private static class ResponseHeaderCapturingInterceptor implements ClientInterceptor {
@Nullable
private volatile String responseEncoding;
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(final MethodDescriptor<ReqT, RespT> method,
final CallOptions callOptions, final Channel next) {
return new ForwardingClientCall.SimpleForwardingClientCall<>(next.newCall(method, callOptions)) {
@Override
public void start(final Listener<RespT> responseListener, final Metadata headers) {
responseEncoding = null;
super.start(new ForwardingClientCallListener.SimpleForwardingClientCallListener<>(responseListener) {
@Override
public void onHeaders(final Metadata responseHeaders) {
responseEncoding = responseHeaders.get(GRPC_ENCODING_KEY);
super.onHeaders(responseHeaders);
}
}, headers);
}
};
}
}
}
@@ -26,13 +26,12 @@ import java.security.NoSuchAlgorithmException;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
@@ -45,6 +44,7 @@ import org.signal.chat.common.EcPreKey;
import org.signal.chat.common.EcSignedPreKey;
import org.signal.chat.common.KemSignedPreKey;
import org.signal.chat.common.ServiceIdentifier;
import org.signal.chat.errors.NotFound;
import org.signal.chat.keys.AccountPreKeyBundles;
import org.signal.chat.keys.CheckIdentityKeyRequest;
import org.signal.chat.keys.CheckIdentityKeyResponse;
@@ -54,7 +54,6 @@ import org.signal.chat.keys.GetPreKeysAnonymousResponse;
import org.signal.chat.keys.GetPreKeysRequest;
import org.signal.chat.keys.KeysAnonymousGrpc;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.InvalidKeyException;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.signal.libsignal.zkgroup.ServerSecretParams;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessChecksum;
@@ -137,7 +136,7 @@ class KeysAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<KeysAnonymousGrpcS
.putDevicePreKeys(Device.PRIMARY_ID, DevicePreKeyBundle.newBuilder()
.setEcOneTimePreKey(toGrpcEcPreKey(ecPreKey))
.setEcSignedPreKey(toGrpcEcSignedPreKey(ecSignedPreKey))
.setKemOneTimePreKey(toGrpcKemSignedPreKey(kemSignedPreKey))
.setKemPreKey(toGrpcKemSignedPreKey(kemSignedPreKey))
.build()))
.build();
@@ -197,7 +196,7 @@ class KeysAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<KeysAnonymousGrpcS
.putDevicePreKeys(Device.PRIMARY_ID, DevicePreKeyBundle.newBuilder()
.setEcOneTimePreKey(toGrpcEcPreKey(ecPreKey))
.setEcSignedPreKey(toGrpcEcSignedPreKey(ecSignedPreKey))
.setKemOneTimePreKey(toGrpcKemSignedPreKey(kemSignedPreKey))
.setKemPreKey(toGrpcKemSignedPreKey(kemSignedPreKey))
.setRegistrationId(identityType == IdentityType.ACI ? aciRegistrationId : pniRegistrationId)
.build());
@@ -258,7 +257,7 @@ class KeysAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<KeysAnonymousGrpcS
.putDevicePreKeys(Device.PRIMARY_ID, DevicePreKeyBundle.newBuilder()
.setEcOneTimePreKey(toGrpcEcPreKey(ecPreKey))
.setEcSignedPreKey(toGrpcEcSignedPreKey(ecSignedPreKey))
.setKemOneTimePreKey(toGrpcKemSignedPreKey(kemSignedPreKey))
.setKemPreKey(toGrpcKemSignedPreKey(kemSignedPreKey))
.build()))
.build();
@@ -463,7 +462,6 @@ class KeysAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<KeysAnonymousGrpcS
final IdentityKey mismatchedPniFingerpringAccountIdentityKey = new IdentityKey(ECKeyPair.generate().getPublicKey());
// Complete futures asynchronously to catch potential async/context-propagation issues
final Duration futureDelay = Duration.ofMillis(1);
when(mismatchedAciFingerprintAccount.getAccountIdentityKey()).thenReturn(mismatchedAciFingerprintAccountIdentityKey);
when(accountsManager.getByServiceIdentifierAsync(new AciServiceIdentifier(mismatchedAciFingerprintAccountIdentifier)))
.thenReturn(delayedAccount(mismatchedAciFingerprintAccount));
@@ -476,11 +474,21 @@ class KeysAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<KeysAnonymousGrpcS
when(accountsManager.getByServiceIdentifierAsync(new PniServiceIdentifier(mismatchedPniFingerprintAccountIdentifier)))
.thenReturn(delayedAccount(mismatchedPniFingerprintAccount));
final Map<UUID, IdentityKey> expectedResponses = Map.of(
mismatchedAciFingerprintAccountIdentifier, mismatchedAciFingerprintAccountIdentityKey,
mismatchedPniFingerprintAccountIdentifier, mismatchedPniFingerpringAccountIdentityKey);
final List<CheckIdentityKeyResponse> expectedResponses = List.of(
CheckIdentityKeyResponse.newBuilder()
.setIdentityKey(ByteString.copyFrom(mismatchedAciFingerprintAccountIdentityKey.serialize()))
.build(),
CheckIdentityKeyResponse.newBuilder()
.setMatched(Empty.getDefaultInstance())
.build(),
CheckIdentityKeyResponse.newBuilder()
.setTargetNotFound(NotFound.getDefaultInstance())
.build(),
CheckIdentityKeyResponse.newBuilder()
.setIdentityKey(ByteString.copyFrom(mismatchedPniFingerpringAccountIdentityKey.serialize()))
.build());
final Map<UUID, IdentityKey> responses = new ConcurrentHashMap<>();
final List<CheckIdentityKeyResponse> responses = Collections.synchronizedList(new ArrayList<>());
final CountDownLatch completedLatch = new CountDownLatch(1);
final AtomicReference<Throwable> error = new AtomicReference<>();
@@ -488,13 +496,7 @@ class KeysAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<KeysAnonymousGrpcS
keysAnonymousStub.checkIdentityKeys(new StreamObserver<>() {
@Override
public void onNext(final CheckIdentityKeyResponse checkIdentityKeyResponse) {
try {
responses.put(
GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(checkIdentityKeyResponse.getTargetIdentifier()).uuid(),
new IdentityKey(checkIdentityKeyResponse.getIdentityKey().toByteArray()));
} catch (final InvalidKeyException e) {
throw new RuntimeException(e);
}
responses.add(checkIdentityKeyResponse);
}
@Override
@@ -597,7 +597,7 @@ class KeysGrpcServiceTest extends SimpleBaseGrpcTest<KeysGrpcService, KeysGrpc.K
.setPublicKey(ByteString.copyFrom(ecSignedPreKey.serializedPublicKey()))
.setSignature(ByteString.copyFrom(ecSignedPreKey.signature()))
.build())
.setKemOneTimePreKey(KemSignedPreKey.newBuilder()
.setKemPreKey(KemSignedPreKey.newBuilder()
.setKeyId(KeyIdUtil.toUnsignedInt(kemSignedPreKey.keyId()))
.setPublicKey(ByteString.copyFrom(kemSignedPreKey.serializedPublicKey()))
.setSignature(ByteString.copyFrom(kemSignedPreKey.signature()))
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.grpc;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyByte;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
@@ -94,6 +95,9 @@ class MessageDispatcherTest {
when(device.getId()).thenReturn(DEVICE_ID);
when(device.isPrimary()).thenReturn(true);
when(messagesManager.hasSuspectedDeliveryLoop(any(), anyByte()))
.thenReturn(CompletableFuture.completedFuture(false));
dispatcher = new MessageDispatcher(
receiptSender,
messagesManager,
@@ -140,7 +144,7 @@ class MessageDispatcherTest {
final AciServiceIdentifier sourceServiceId = new AciServiceIdentifier(UUID.randomUUID());
final List<Envelope> messages = IntStream
.range(0, MessageDispatcher.MAX_UNACKED_MESSAGES + 2)
.range(0, MessageDispatcher.DEFAULT_MAX_UNACKED_MESSAGES + 2)
.mapToObj(i -> createMessage(sourceServiceId, ACI, i, "hello"))
.toList();
final List<UUID> guids = messages.stream().map(Envelope::getServerGuid).map(UUIDUtil::fromByteString).toList();
@@ -158,18 +162,18 @@ class MessageDispatcherTest {
dispatcher.getMessages(true, TEST_UA, account, device, acks.flux());
StepVerifier.create(responses)
.expectNext(expectedMessages.subList(0, MessageDispatcher.MAX_UNACKED_MESSAGES).toArray(GetMessagesResponse[]::new))
.expectNext(expectedMessages.subList(0, MessageDispatcher.DEFAULT_MAX_UNACKED_MESSAGES).toArray(GetMessagesResponse[]::new))
.expectNoEvent(Duration.ofMillis(1))
// Sending an ack should allow another message to come back
.then(() -> acks.next(guids.get(0)))
.expectNext(expectedMessages.get(MessageDispatcher.MAX_UNACKED_MESSAGES))
.expectNext(expectedMessages.get(MessageDispatcher.DEFAULT_MAX_UNACKED_MESSAGES))
.then(() -> verify(messageStream, times(1)).acknowledgeMessage(guids.get(0), timestamps.get(0)))
.expectNoEvent(Duration.ofMillis(1))
// Send another one
.then(() -> acks.next(guids.get(1)))
.expectNext(expectedMessages.get(MessageDispatcher.MAX_UNACKED_MESSAGES + 1))
.expectNext(expectedMessages.get(MessageDispatcher.DEFAULT_MAX_UNACKED_MESSAGES + 1))
.then(() -> verify(messageStream, times(1)).acknowledgeMessage(guids.get(1), timestamps.get(1)))
.expectNoEvent(Duration.ofMillis(1))
@@ -187,7 +191,7 @@ class MessageDispatcherTest {
void maxOutstandingAllowsGaps() {
final AciServiceIdentifier sourceServiceId = new AciServiceIdentifier(UUID.randomUUID());
final int totalMessages = MessageDispatcher.MAX_UNACKED_MESSAGES * 2;
final int totalMessages = MessageDispatcher.DEFAULT_MAX_UNACKED_MESSAGES * 2;
final List<Envelope> messages = IntStream
.range(0, totalMessages)
@@ -208,22 +212,22 @@ class MessageDispatcherTest {
dispatcher.getMessages(true, TEST_UA, account, device, acks.flux());
StepVerifier.create(responses)
.expectNext(expectedMessages.subList(0, MessageDispatcher.MAX_UNACKED_MESSAGES).toArray(GetMessagesResponse[]::new))
.expectNext(expectedMessages.subList(0, MessageDispatcher.DEFAULT_MAX_UNACKED_MESSAGES).toArray(GetMessagesResponse[]::new))
.expectNoEvent(Duration.ofMillis(1))
.then(() -> {
for (int i = 0; i < MessageDispatcher.MAX_UNACKED_MESSAGES; i++) {
for (int i = 0; i < MessageDispatcher.DEFAULT_MAX_UNACKED_MESSAGES; i++) {
if (i != 2) {
acks.next(ackRequests.get(i));
}
}
})
.expectNext(expectedMessages.subList(MessageDispatcher.MAX_UNACKED_MESSAGES, totalMessages - 1).toArray(GetMessagesResponse[]::new))
.expectNext(expectedMessages.subList(MessageDispatcher.DEFAULT_MAX_UNACKED_MESSAGES, totalMessages - 1).toArray(GetMessagesResponse[]::new))
.expectNoEvent(Duration.ofMillis(1))
.then(() -> acks.next(ackRequests.get(2)))
.expectNext(expectedMessages.get(totalMessages - 1))
.expectNoEvent(Duration.ofMillis(1))
.then(() -> {
for (int i = MessageDispatcher.MAX_UNACKED_MESSAGES; i < totalMessages; i++) {
for (int i = MessageDispatcher.DEFAULT_MAX_UNACKED_MESSAGES; i < totalMessages; i++) {
acks.next(ackRequests.get(i));
}
})
@@ -236,7 +240,7 @@ class MessageDispatcherTest {
void duplicateAckIgnored() {
final AciServiceIdentifier sourceServiceId = new AciServiceIdentifier(UUID.randomUUID());
final List<Envelope> messages = IntStream
.range(0, MessageDispatcher.MAX_UNACKED_MESSAGES + 2)
.range(0, MessageDispatcher.DEFAULT_MAX_UNACKED_MESSAGES + 2)
.mapToObj(i -> createMessage(sourceServiceId, ACI, i, "hello"))
.toList();
@@ -249,7 +253,7 @@ class MessageDispatcherTest {
StepVerifier
.create(dispatcher.getMessages(true, TEST_UA, account, device, acks.flux()))
.expectNextCount(MessageDispatcher.MAX_UNACKED_MESSAGES)
.expectNextCount(MessageDispatcher.DEFAULT_MAX_UNACKED_MESSAGES)
.expectNoEvent(Duration.ofMillis(1))
// Ack a message, we should then get a new message
@@ -312,7 +316,7 @@ class MessageDispatcherTest {
void conflictingConsumerWhileWaitingForAcks() {
final AciServiceIdentifier sourceServiceId = new AciServiceIdentifier(UUID.randomUUID());
final List<MessageStreamEntry.Envelope> messages = IntStream
.range(0, MessageDispatcher.MAX_UNACKED_MESSAGES + 2)
.range(0, MessageDispatcher.DEFAULT_MAX_UNACKED_MESSAGES + 2)
.mapToObj(i -> createMessage(sourceServiceId, ACI, i, "hello"))
.map(MessageStreamEntry.Envelope::new)
.toList();
@@ -323,7 +327,7 @@ class MessageDispatcherTest {
StepVerifier
.create(dispatcher.getMessages(true, TEST_UA, account, device, Flux.never()))
.then(() -> messages.forEach(source::next))
.expectNextCount(MessageDispatcher.MAX_UNACKED_MESSAGES)
.expectNextCount(MessageDispatcher.DEFAULT_MAX_UNACKED_MESSAGES)
.expectNoEvent(Duration.ofMillis(1))
// The error should make it to us immediately even though there are max-unacked messages outstanding
.then(() -> source.error(new ConflictingMessageConsumerException()))
@@ -103,7 +103,7 @@ public class MetricServerInterceptorTest {
void unary() {
final EchoServiceGrpc.EchoServiceBlockingStub client = EchoServiceGrpc.newBlockingStub(channel);
final EchoRequest request = EchoRequest.newBuilder().setPayload(ByteString.copyFromUtf8("hello")).build();
final EchoResponse response = client.echo(request);
client.echo(request);
final Tags commonTags = Tags.of(
"platform", "android",
@@ -119,9 +119,6 @@ public class MetricServerInterceptorTest {
final Counter responseCount = find(Counter.class, MetricServerInterceptor.RESPONSE_COUNTER_NAME);
assertThat(responseCount.count()).isCloseTo(1.0, offset(0.01));
final Counter responseByteCount = find(Counter.class, MetricServerInterceptor.RESPONSE_BYTES_COUNTER_NAME);
assertThat(responseByteCount.count()).isCloseTo(response.getSerializedSize(), offset(0.01));
final Counter rpcCount = find(Counter.class, MetricServerInterceptor.RPC_COUNTER_NAME);
assertThat(rpcCount.count()).isCloseTo(1.0, offset(0.01));
@@ -170,9 +167,6 @@ public class MetricServerInterceptorTest {
final Counter responseCount = find(Counter.class, MetricServerInterceptor.RESPONSE_COUNTER_NAME);
assertThat(responseCount.count()).isCloseTo(responses.size(), offset(0.01));
final Counter responseByteCount = find(Counter.class, MetricServerInterceptor.RESPONSE_BYTES_COUNTER_NAME);
assertThat(responseByteCount.count()).isCloseTo(responses.stream().mapToInt(EchoResponse::getSerializedSize).sum(), offset(0.01));
final Counter rpcCount = find(Counter.class, MetricServerInterceptor.RPC_COUNTER_NAME);
assertThat(rpcCount.count()).isCloseTo(1.0, offset(0.01));
@@ -0,0 +1,149 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.offset;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.google.common.net.InetAddresses;
import com.google.protobuf.ByteString;
import io.grpc.ManagedChannel;
import io.grpc.Server;
import io.grpc.netty.NettyChannelBuilder;
import io.grpc.netty.NettyServerBuilder;
import io.grpc.stub.BlockingClientCall;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.signal.chat.rpc.EchoRequest;
import org.signal.chat.rpc.EchoResponse;
import org.signal.chat.rpc.EchoServiceGrpc;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicGrpcCompressionConfiguration;
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
import org.whispersystems.textsecuregcm.tests.util.FakeDynamicConfigurationManager;
class MetricServerStreamTracerTest {
private static final String USER_AGENT = "Signal-Android/12.53.7 (Android 14.1; libsignal)";
private static final EchoRequest REQUEST = EchoRequest.newBuilder()
.setPayload(ByteString.copyFromUtf8("compressible ".repeat(100)))
.build();
private Server server;
private ManagedChannel channel;
private SimpleMeterRegistry simpleMeterRegistry;
@BeforeEach
void setUp() throws Exception {
simpleMeterRegistry = new SimpleMeterRegistry();
final MockRequestAttributesInterceptor mockRequestAttributesInterceptor = new MockRequestAttributesInterceptor();
mockRequestAttributesInterceptor.setRequestAttributes(
new RequestAttributes(InetAddresses.forString("127.0.0.1"), USER_AGENT, null));
// Only compress echo
final DynamicConfiguration configuration = mock(DynamicConfiguration.class);
when(configuration.getGrpcCompression())
.thenReturn(new DynamicGrpcCompressionConfiguration(Set.of(), Set.of("org.signal.chat.rpc.EchoService/echo")));
// By default, the in-process transport doesn't report message sizes to stream tracers at all, and it never
// compresses messages; use a real transport instead
server = NettyServerBuilder.forPort(0)
.directExecutor()
.addService(new EchoServiceImpl())
.addStreamTracerFactory(new MetricServerStreamTracer.Factory())
.intercept(new GrpcCompressionInterceptor(new FakeDynamicConfigurationManager<>(configuration)))
.intercept(new MetricServerInterceptor(simpleMeterRegistry, mock(ClientReleaseManager.class)))
.intercept(mockRequestAttributesInterceptor)
.build()
.start();
channel = NettyChannelBuilder.forAddress("localhost", server.getPort())
.directExecutor()
.usePlaintext()
.build();
}
@AfterEach
void tearDown() throws Exception {
server.shutdownNow();
channel.shutdownNow();
server.awaitTermination(1, TimeUnit.SECONDS);
channel.awaitTermination(1, TimeUnit.SECONDS);
}
@Test
void uncompressed() {
final EchoResponse response = EchoServiceGrpc.newBlockingStub(channel).echo2(REQUEST);
final Counter wireBytes = find(MetricServerInterceptor.RESPONSE_BYTES_COUNTER_NAME, "echo2");
assertThat(wireBytes.count()).isCloseTo(response.getSerializedSize(), offset(0.01));
}
@Test
void streaming() throws Exception {
final EchoServiceGrpc.EchoServiceBlockingV2Stub client = EchoServiceGrpc.newBlockingV2Stub(channel);
final BlockingClientCall<EchoRequest, EchoResponse> echoStream = client.echoStream();
final List<EchoRequest> requests = IntStream.range(0, 2)
.mapToObj(i -> EchoRequest.newBuilder().setPayload(ByteString.copyFromUtf8(String.valueOf(i))).build())
.toList();
final List<EchoResponse> responses = new ArrayList<>(requests.size());
for (final EchoRequest request : requests) {
echoStream.write(request);
responses.add(echoStream.read());
}
echoStream.halfClose();
// Wait for the close to finish; metrics are reported after close
channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
final int expectedBytes = responses.stream().mapToInt(EchoResponse::getSerializedSize).sum();
assertThat(find(MetricServerInterceptor.RESPONSE_BYTES_COUNTER_NAME, "echoStream").count())
.isCloseTo(expectedBytes, offset(0.01));
}
@Test
void compressed() {
final EchoResponse response = EchoServiceGrpc.newBlockingStub(channel).echo(REQUEST);
final Counter wireBytes = find(MetricServerInterceptor.RESPONSE_BYTES_COUNTER_NAME, "echo");
assertThat(wireBytes.count()).isPositive().isLessThan(response.getSerializedSize());
// we expect >90% compression
assertThat(wireBytes.count() / response.getSerializedSize()).isLessThan(0.1);
final Tags expectedTags = Tags.of(
"platform", "android",
"grpcService", "org.signal.chat.rpc.EchoService",
"method", "echo");
for (final Tag tag : expectedTags) {
assertThat(wireBytes.getId().getTag(tag.getKey())).isEqualTo(tag.getValue());
}
}
private Counter find(final String name, final String method) {
return simpleMeterRegistry.find(name).tag("method", method).counter();
}
}
@@ -98,7 +98,6 @@ import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
import org.whispersystems.textsecuregcm.storage.VersionedProfile;
import org.whispersystems.textsecuregcm.storage.VersionedProfileV1;
@@ -111,6 +110,8 @@ import org.whispersystems.textsecuregcm.util.UUIDUtil;
public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileAnonymousGrpcService, ProfileAnonymousGrpc.ProfileAnonymousBlockingStub> {
private static final String CDN_BASE_URL = "https://cdn.example.com";
private static final ServerSecretParams SERVER_SECRET_PARAMS = ServerSecretParams.generate();
@Mock
@@ -152,6 +153,7 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
profilesManager,
profileBadgeConverter,
new PostPolicyGenerator("us-west-1", "profile-bucket", "accessKey", "accessSecret"),
CDN_BASE_URL,
genericServerSecretParams,
rateLimiters,
clock,
@@ -211,7 +213,7 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
.setName(ByteString.copyFrom(name))
.setAbout(ByteString.copyFrom(about))
.setAboutEmoji(ByteString.copyFrom(emoji))
.setAvatar(avatar)
.setAvatarUrl(CDN_BASE_URL + "/" + avatar)
.setPhoneNumberSharing(ByteString.copyFrom(phoneNumberSharing))
.setAccountInfo(AccountInfo.newBuilder()
.addAllBadgeIds(badgeIds)
@@ -261,7 +263,6 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
when(account.getCurrentProfileVersion()).thenReturn(Optional.of(version));
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(true);
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
when(account.hasCapability(DeviceCapability.PROFILES_V2)).thenReturn(true);
when(account.getAccountIdentityKey()).thenReturn(identityKey);
when(account.getBadges()).thenReturn(Collections.emptyList());
@@ -317,7 +318,6 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
when(account.getCurrentProfileVersion()).thenReturn(Optional.of(version));
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(true);
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
when(account.hasCapability(DeviceCapability.PROFILES_V2)).thenReturn(true);
when(account.getAccountIdentityKey()).thenReturn(identityKey);
when(account.getBadges()).thenReturn(Collections.emptyList());
@@ -515,7 +515,6 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
final ProfileKeyCredentialRequestContext profileKeyCredentialRequestContext =
clientZkProfile.createProfileKeyCredentialRequestContext(new ServiceId.Aci(targetUuid), profileKey);
when(account.hasCapability(DeviceCapability.PROFILES_V2)).thenReturn(hasV2Capability);
if (hasV2Capability) {
final VersionedProfile profile = mock(VersionedProfile.class);
when(profile.commitment()).thenReturn(profileKeyCommitment.serialize());
@@ -790,9 +789,9 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
final ExtendAvatarTTLResponse response = authenticatedServiceStub().extendAvatarTTL(request);
assertTrue(response.hasPath());
assertTrue(response.hasUrl());
assertEquals(path, response.getPath());
assertEquals(CDN_BASE_URL + "/" + path, response.getUrl());
}
@Test
@@ -15,9 +15,8 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.signal.chat.common.DeviceCapability;
import org.signal.chat.profile.ProfileResult;
import org.signal.chat.profile.AccountInfo;
import org.signal.chat.profile.ProfileResult;
class ProfileGrpcHelperTest {
@@ -86,6 +85,20 @@ class ProfileGrpcHelperTest {
assertArrayEquals(unset, explicitlyEmpty);
}
@ParameterizedTest
@MethodSource
void cdnUrl(final String baseUrl, final String path) {
assertEquals("https://cdn.example.com/profiles/abc", ProfileGrpcHelper.cdnUrl(baseUrl, path));
}
private static Stream<Arguments> cdnUrl() {
return Stream.of(
Arguments.of("https://cdn.example.com", "profiles/abc"),
Arguments.of("https://cdn.example.com/", "profiles/abc"),
Arguments.of("https://cdn.example.com", "/profiles/abc"),
Arguments.of("https://cdn.example.com/", "/profiles/abc"));
}
private static ProfileResult.Builder profile() {
return ProfileResult.newBuilder()
.setData(ByteString.copyFromUtf8("profile-data"))
@@ -103,7 +103,6 @@ import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountBadge;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
import org.whispersystems.textsecuregcm.storage.VersionedProfile;
@@ -118,6 +117,8 @@ import org.whispersystems.textsecuregcm.util.UUIDUtil;
public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcService, ProfileGrpc.ProfileBlockingStub> {
private static final String CDN_BASE_URL = "https://cdn.example.com";
private static final byte[] VERSION = TestRandomUtil.nextBytes(32);
private static final byte[] VALID_DATA = new byte[128];
@@ -192,7 +193,6 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
when(account.getAccountIdentifier()).thenReturn(AUTHENTICATED_ACI);
when(account.getNumber()).thenReturn(Optional.of(phoneNumber));
when(account.getBadges()).thenReturn(Collections.emptyList());
when(account.hasCapability(DeviceCapability.PROFILES_V2)).thenReturn(true);
when(profile.paymentAddress()).thenReturn(null);
when(profile.avatar()).thenReturn("");
@@ -215,6 +215,7 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
dynamicConfigurationManager,
badgesConfiguration,
policyGenerator,
CDN_BASE_URL,
genericServerSecretParams,
profileBadgeConverter,
rateLimiters
@@ -653,7 +654,7 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
.setName(ByteString.copyFrom(name))
.setAbout(ByteString.copyFrom(about))
.setAboutEmoji(ByteString.copyFrom(emoji))
.setAvatar(avatar)
.setAvatarUrl(CDN_BASE_URL + "/" + avatar)
.setPhoneNumberSharing(ByteString.copyFrom(phoneNumberSharing))
.setAccountInfo(AccountInfo.newBuilder()
.addAllBadgeIds(badgeIds)
@@ -695,7 +696,6 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
when(account.getAccountIdentifier()).thenReturn(targetAci);
when(account.getCurrentProfileVersion()).thenReturn(Optional.of(version));
when(account.hasCapability(DeviceCapability.PROFILES_V2)).thenReturn(true);
when(account.getAccountIdentityKey()).thenReturn(identityKey);
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(true);
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
@@ -747,7 +747,6 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
final UUID targetAci = UUID.randomUUID();
when(account.getAccountIdentifier()).thenReturn(targetAci);
when(account.hasCapability(DeviceCapability.PROFILES_V2)).thenReturn(true);
when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(targetAci))).thenReturn(Optional.of(account));
when(account.getAccountIdentityKey()).thenReturn(identityKey);
@@ -1,32 +0,0 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc.net;
import static org.junit.jupiter.api.Assertions.assertEquals;
import io.netty.util.test.LeakPresenceExtension;
import java.util.Optional;
import javax.annotation.Nullable;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
@ExtendWith(LeakPresenceExtension.class)
class BoringSslServerKeyManagerTest {
@ParameterizedTest
@CsvSource(nullValues = "null", value = {
"Ed25519, EdDSA",
"SHA256withECDSA, EC",
"SHA512withECDSA, EC",
"SHA256withRSA, RSA",
"SHA512withRSA, RSA",
"SHA256withRSA_PSS_PSS, null",
"Ed448, null",
})
void getJdkKeyType(final String signatureAlgorithm, @Nullable final String expectedKeyType) {
assertEquals(Optional.ofNullable(expectedKeyType), BoringSslServerKeyManager.getJdkKeyType(signatureAlgorithm));
}
}
@@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import io.dropwizard.util.DataSize;
@@ -16,12 +17,13 @@ import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.DefaultEventLoopGroup;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.MultiThreadIoEventLoopGroup;
import io.netty.channel.SimpleUserEventChannelHandler;
import io.netty.channel.local.LocalAddress;
import io.netty.channel.local.LocalIoHandler;
import io.netty.channel.local.LocalServerChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.nio.NioIoHandler;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioChannelOption;
import io.netty.channel.socket.nio.NioServerSocketChannel;
@@ -36,6 +38,8 @@ import io.netty.handler.codec.http2.DefaultHttp2GoAwayFrame;
import io.netty.handler.codec.http2.DefaultHttp2Headers;
import io.netty.handler.codec.http2.DefaultHttp2HeadersFrame;
import io.netty.handler.codec.http2.DefaultHttp2ResetFrame;
import io.netty.handler.codec.http2.DefaultHttp2WindowUpdateFrame;
import io.netty.handler.codec.http2.Http2CodecUtil;
import io.netty.handler.codec.http2.Http2DataFrame;
import io.netty.handler.codec.http2.Http2Error;
import io.netty.handler.codec.http2.Http2FrameCodecBuilder;
@@ -66,7 +70,7 @@ import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -114,8 +118,8 @@ class OmnibusH2ServerTest {
private static final String TEST_DOMAIN = "foo.example.com";
private static NioEventLoopGroup nioEventLoopGroup;
private static DefaultEventLoopGroup localEventLoopGroup;
private static EventLoopGroup nioEventLoopGroup;
private static EventLoopGroup localEventLoopGroup;
private static Mapping<String, SslContext> sniMapping;
@@ -147,8 +151,8 @@ class OmnibusH2ServerTest {
sniMapping = SniMapper.buildSniMapping(new ByteArrayInputStream(byteArrayOutputStream.toByteArray()),
new String(keyStorePassword), SslProvider.OPENSSL);
nioEventLoopGroup = new NioEventLoopGroup();
localEventLoopGroup = new DefaultEventLoopGroup();
nioEventLoopGroup = new MultiThreadIoEventLoopGroup(NioIoHandler.newFactory());
localEventLoopGroup = new MultiThreadIoEventLoopGroup(LocalIoHandler.newFactory());
}
@BeforeEach
@@ -174,12 +178,16 @@ class OmnibusH2ServerTest {
ReferenceCountUtil.release(sniMapping.map(TEST_DOMAIN));
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void defaultBackend(final boolean localChannel) throws Exception {
final OmnibusH2Server server = startOmnibusServer(
Map.of(PATH, startBackendServer(localChannel, PATH_BACKEND_IDENTITY)),
startBackendServer(localChannel, DEFAULT_BACKEND_IDENTITY));
@CartesianTest
void defaultBackend(
@CartesianTest.Values(booleans = {false, true}) final boolean localChannel,
@CartesianTest.Values(booleans = {false, true}) final boolean pooled)
throws Exception {
final OmnibusH2Server server = omnibusServer()
.addRoute(PATH, backendServer().localChannel(localChannel).identity(PATH_BACKEND_IDENTITY))
.pooled(pooled)
.addDefault(backendServer().localChannel(localChannel))
.start();
final String response = sendRequestThroughOmnibus(connectToOmnibus(server), "/a/different/path");
assertEquals(DEFAULT_BACKEND_IDENTITY, response);
}
@@ -191,7 +199,7 @@ class OmnibusH2ServerTest {
final HAProxyMessage proxyMessage = usePpv2
? new HAProxyMessage(HAProxyProtocolVersion.V2, HAProxyCommand.PROXY, HAProxyProxiedProtocol.TCP4, expectedSource, "127.0.0.2", 1234, 5678)
: null;
final OmnibusH2Server server = startOmnibusServer(startBackendServer(true, DEFAULT_BACKEND_IDENTITY));
final OmnibusH2Server server = omnibusServer().start();
final Channel h2Connection = connectToOmnibus(server, proxyMessage);
final String xForwardedFor = sendRequestThroughOmnibus(h2Connection, "/forwarded-for");
assertEquals(expectedSource, xForwardedFor);
@@ -200,10 +208,12 @@ class OmnibusH2ServerTest {
@CartesianTest
void pathBackend(
@CartesianTest.Values(booleans = {false, true}) final boolean localChannel,
@CartesianTest.Values(booleans = {false, true}) final boolean pooled,
@CartesianTest.Values(strings = {"/v1/path/", "/v1/path/?foo=bar", "/v1/path/?foo=bar&baz=quux"}) final String path) throws Exception {
final OmnibusH2Server server = startOmnibusServer(
Map.of(PATH, startBackendServer(localChannel, PATH_BACKEND_IDENTITY)),
startBackendServer(true, DEFAULT_BACKEND_IDENTITY));
final OmnibusH2Server server = omnibusServer()
.addRoute(PATH, backendServer().localChannel(localChannel).identity(PATH_BACKEND_IDENTITY))
.pooled(pooled)
.start();
final String response = sendRequestThroughOmnibus(connectToOmnibus(server), path);
assertEquals(PATH_BACKEND_IDENTITY, response);
}
@@ -212,9 +222,10 @@ class OmnibusH2ServerTest {
void multipleStreamsOnSameConnection(
@CartesianTest.Values(booleans = {true, false}) final boolean defaultLocalChannel,
@CartesianTest.Values(booleans = {true, false}) final boolean prefixLocalChannel) throws Exception {
final OmnibusH2Server server = startOmnibusServer(
Map.of(PATH, startBackendServer(prefixLocalChannel, PATH_BACKEND_IDENTITY)),
startBackendServer(defaultLocalChannel, DEFAULT_BACKEND_IDENTITY));
final OmnibusH2Server server = omnibusServer()
.addRoute(PATH, backendServer().localChannel(prefixLocalChannel).identity(PATH_BACKEND_IDENTITY))
.addDefault(backendServer().localChannel(defaultLocalChannel))
.start();
final Channel h2Connection = connectToOmnibus(server);
final int numStreams = 10;
@@ -236,14 +247,15 @@ class OmnibusH2ServerTest {
}
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void backendDownStreamReset(final boolean localChannel) throws Exception {
final Channel backend = startBackendServer(localChannel, DEFAULT_BACKEND_IDENTITY);
final OmnibusH2Server server = startOmnibusServer(backend);
@CartesianTest
void backendDownStreamReset(
@CartesianTest.Values(booleans = {true, false}) final boolean localChannel,
@CartesianTest.Values(booleans = {true, false}) final boolean pooled) throws Exception {
final BackendServerBuilder backend = backendServer().localChannel(localChannel);
final OmnibusH2Server server = omnibusServer().addDefault(backend).pooled(pooled).start();
// Kill the default backend so connection attempts from the omnibus fail
backend.close().syncUninterruptibly();
backend.channel().close().syncUninterruptibly();
final Channel h2Connection = connectToOmnibus(server);
final CompletableFuture<Http2HeadersFrame> headersFuture = new CompletableFuture<>();
@@ -274,8 +286,12 @@ class OmnibusH2ServerTest {
@CartesianTest
void backendCloseClosesClientStream(
@CartesianTest.Values(booleans = {true, false}) final boolean localChannel,
@CartesianTest.Values(booleans = {true, false}) final boolean pooled,
@CartesianTest.Values(strings = {"/goaway", "/reset"}) final String path) throws Exception {
final OmnibusH2Server server = startOmnibusServer(startBackendServer(localChannel, DEFAULT_BACKEND_IDENTITY));
final OmnibusH2Server server = omnibusServer()
.addDefault(backendServer().localChannel(localChannel))
.pooled(pooled)
.start();
final Channel h2Connection = connectToOmnibus(server);
final CompletableFuture<Http2ResetFrame> resetFuture = new CompletableFuture<>();
@@ -298,10 +314,14 @@ class OmnibusH2ServerTest {
assertTrue(h2Connection.isActive());
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void queuedDataFrames(final boolean localChannel) throws Exception {
final OmnibusH2Server server = startOmnibusServer(startBackendServer(localChannel, DEFAULT_BACKEND_IDENTITY));
@CartesianTest
void queuedDataFrames(
@CartesianTest.Values(booleans = {true, false}) final boolean localChannel,
@CartesianTest.Values(booleans = {true, false}) final boolean pooled) throws Exception {
final OmnibusH2Server server = omnibusServer()
.addDefault(backendServer().localChannel(localChannel))
.pooled(pooled)
.start();
final Channel h2Connection = connectToOmnibus(server);
final CompletableFuture<byte[]> responseFuture = new CompletableFuture<>();
final Http2StreamChannel stream = new Http2StreamChannelBootstrap(h2Connection)
@@ -337,12 +357,19 @@ class OmnibusH2ServerTest {
h2Connection.close().syncUninterruptibly();
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void clientDisconnectClosesBackendConnections(final boolean localChannel) throws Exception {
@CartesianTest
void clientDisconnectClosesBackendStreams(
@CartesianTest.Values(booleans = {true, false}) final boolean localChannel,
@CartesianTest.Values(booleans = {true, false}) final boolean pooled) throws Exception {
final CompletableFuture<Channel> backendH2Connection = new CompletableFuture<>();
final Channel backendServerChannel = startBackendServer(localChannel, DEFAULT_BACKEND_IDENTITY, backendH2Connection::complete, _ -> {});
final OmnibusH2Server server = startOmnibusServer(backendServerChannel);
final CompletableFuture<Channel> backendH2Stream = new CompletableFuture<>();
final OmnibusH2Server server = omnibusServer()
.addDefault(backendServer()
.localChannel(localChannel)
.h2ChannelInit(backendH2Connection::complete)
.h2StreamInit(backendH2Stream::complete))
.pooled(pooled)
.start();
final Channel h2Connection = connectToOmnibus(server);
final Http2StreamChannelBootstrap streamBootstrap = new Http2StreamChannelBootstrap(h2Connection);
@@ -360,25 +387,31 @@ class OmnibusH2ServerTest {
.authority("localhost");
stream.writeAndFlush(new DefaultHttp2HeadersFrame(headers, false)).syncUninterruptibly();
assertFalse(
backendH2Connection.join().closeFuture().awaitUninterruptibly(10, TimeUnit.MILLISECONDS),
"Channel should be open");
final Channel backendStream = backendH2Stream.get(5, TimeUnit.SECONDS);
assertFalse(backendStream.closeFuture().awaitUninterruptibly(10, TimeUnit.MILLISECONDS), "Stream should be open");
// All backend connections the omnibus opened on behalf of this client should close if we disconnect the client
// All backend streams the omnibus opened on behalf of this client should close if we disconnect the client
h2Connection.close().syncUninterruptibly();
assertTrue(backendH2Connection.join().closeFuture().await(5, TimeUnit.SECONDS));
assertTrue(backendStream.closeFuture().await(5, TimeUnit.SECONDS));
// Pooled connections are shared with other clients, so only unpooled connections should close
assertEquals(!pooled, backendH2Connection.join().closeFuture().await(pooled ? 100 : 5000, TimeUnit.MILLISECONDS));
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void requestBackpressure(final boolean localChannel) throws Exception {
@CartesianTest
void requestBackpressure(@CartesianTest.Values(booleans = {true, false}) final boolean localChannel,
@CartesianTest.Values(booleans = {true, false}) final boolean pooled) throws Exception {
final AtomicReference<Channel> backendStreamChannel = new AtomicReference<>();
final Channel backendServer = startBackendServer(localChannel, "request-backpressure", _ -> {
}, ch -> {
ch.config().setAutoRead(false);
backendStreamChannel.set(ch);
});
final OmnibusH2Server omnibusH2Server = startOmnibusServer(backendServer);
final OmnibusH2Server omnibusH2Server = omnibusServer()
.addDefault(backendServer()
.localChannel(localChannel)
.identity("request-backpressure")
.h2StreamInit(ch -> {
ch.config().setAutoRead(false);
backendStreamChannel.set(ch);
}))
.pooled(pooled)
.start();
final Channel h2Connection = connectToOmnibus(omnibusH2Server, null);
// We'll take the client channel becoming unwritable as backpressure signal
@@ -445,6 +478,7 @@ class OmnibusH2ServerTest {
@CartesianTest
void responseBackpressure(@CartesianTest.Values(booleans = {true, false}) final boolean localChannel,
@CartesianTest.Values(booleans = {true, false}) final boolean pooled,
@CartesianTest.Values(ints = {193, 512, 2048}) final int responseSizeKib) throws Exception {
final int responseSize = Math.toIntExact(DataSize.kibibytes(responseSizeKib).toBytes());
@@ -457,21 +491,26 @@ class OmnibusH2ServerTest {
final CountDownLatch backendStreamUnwritable = new CountDownLatch(1);
final AtomicLong pendingWhenUnwritable = new AtomicLong();
final OmnibusH2Server server = startOmnibusServer(startBackendServer(localChannel, "response-backpressure",
_ -> {}, ch -> {
ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
@Override
public void channelWritabilityChanged(final ChannelHandlerContext backendStreamCtx) {
if (!backendStreamCtx.channel().isWritable() && backendStreamUnwritable.getCount() > 0) {
// A change in writability on the backend stream means we introduced backpressure
pendingWhenUnwritable.set(backendStreamCtx.channel().bytesBeforeWritable());
backendStreamUnwritable.countDown();
}
backendStreamCtx.fireChannelWritabilityChanged();
}
});
backendStreamInitialized.countDown();
}));
final OmnibusH2Server server = omnibusServer()
.addDefault(backendServer()
.localChannel(localChannel)
.identity("response-backpressure")
.h2StreamInit(ch -> {
ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
@Override
public void channelWritabilityChanged(final ChannelHandlerContext backendStreamCtx) {
if (!backendStreamCtx.channel().isWritable() && backendStreamUnwritable.getCount() > 0) {
// A change in writability on the backend stream means we introduced backpressure
pendingWhenUnwritable.set(backendStreamCtx.channel().bytesBeforeWritable());
backendStreamUnwritable.countDown();
}
backendStreamCtx.fireChannelWritabilityChanged();
}
});
backendStreamInitialized.countDown();
}))
.pooled(pooled)
.start();
final Channel h2Connection = connectToOmnibus(server);
final AtomicReference<Http2StreamChannel> clientStream = new AtomicReference<>();
@@ -499,12 +538,57 @@ class OmnibusH2ServerTest {
h2Connection.close().syncUninterruptibly();
}
@Test
void pausedStreamDoesNotStallPooledConnection() throws Exception {
final CountDownLatch backendStreamUnwritable = new CountDownLatch(1);
final OmnibusH2Server server = omnibusServer()
.addDefault(backendServer()
.h2StreamInit(ch -> ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
@Override
public void channelWritabilityChanged(final ChannelHandlerContext ctx) {
if (!ctx.channel().isWritable()) {
backendStreamUnwritable.countDown();
}
ctx.fireChannelWritabilityChanged();
}
})))
.pooled(true)
.start();
final Channel h2Connection = connectToOmnibus(server);
// Open our own connection-level window, so the paused stream doesn't stall our connection to the omnibus
h2Connection.writeAndFlush(
new DefaultHttp2WindowUpdateFrame(Integer.MAX_VALUE - Http2CodecUtil.DEFAULT_WINDOW_SIZE)).syncUninterruptibly();
// Force one of the streams to go unwritable
final AtomicReference<Channel> pausedStream = new AtomicReference<>();
final int pausedResponseSize = Math.toIntExact(DataSize.mebibytes(1).toBytes());
final CompletableFuture<byte[]> pausedResponse = request(h2Connection, pausedResponseSize, (byte) 1, ch -> {
ch.config().setAutoRead(false);
pausedStream.set(ch);
});
assertTrue(backendStreamUnwritable.await(5, TimeUnit.SECONDS), "failed to introduce backpressure");
// A different stream should not be affected
final int responseSize = Math.toIntExact(DataSize.kibibytes(1).toBytes());
assertArrayEquals(expectedBody(responseSize, (byte) 2),
request(h2Connection, responseSize, (byte) 2, _ -> {}).get(5, TimeUnit.SECONDS));
assertFalse(pausedResponse.isDone());
pausedStream.get().eventLoop().execute(() -> pausedStream.get().config().setAutoRead(true));
assertArrayEquals(expectedBody(pausedResponseSize, (byte) 1), pausedResponse.get(5, TimeUnit.SECONDS));
h2Connection.close().syncUninterruptibly();
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void idleTest(final boolean localChannel) throws Exception {
final Duration timeout = Duration.ofMillis(500);
final OmnibusH2Server timeoutServer =
startOmnibusServer(Collections.emptyMap(), startBackendServer(localChannel, DEFAULT_BACKEND_IDENTITY), timeout);
final OmnibusH2Server timeoutServer = omnibusServer()
.addDefault(backendServer().localChannel(localChannel))
.idleTimeout(timeout)
.start();
final Channel channel = connectToOmnibus(timeoutServer, null);
// Send a request to make sure idleTimeouts work even after a stream / backend connection has been established
@@ -519,9 +603,9 @@ class OmnibusH2ServerTest {
@Test
void loadShed() throws Exception {
dynamicConfiguration.set(new DynamicOmnibusConfiguration(BigDecimal.ONE));
final OmnibusH2Server server = startOmnibusServer(
Map.of(PATH, startBackendServer(true, PATH_BACKEND_IDENTITY)),
startBackendServer(true, DEFAULT_BACKEND_IDENTITY));
final OmnibusH2Server server = omnibusServer()
.addRoute(PATH, backendServer().identity(PATH_BACKEND_IDENTITY))
.start();
final CompletableFuture<Http2GoAwayFrame> goAwayFuture = new CompletableFuture<>();
final Bootstrap clientBootstrap = new Bootstrap()
@@ -570,8 +654,8 @@ class OmnibusH2ServerTest {
@CartesianTest.Values(ints = {10}) final int repetitions) throws Exception {
// Use two threads to make sure that our connections are working concurrently
final NioEventLoopGroup nioEventLoopGroup = new NioEventLoopGroup(2);
final DefaultEventLoopGroup localEventLoopGroup = new DefaultEventLoopGroup(2);
final EventLoopGroup nioEventLoopGroup = new MultiThreadIoEventLoopGroup(2, NioIoHandler.newFactory());
final EventLoopGroup localEventLoopGroup = new MultiThreadIoEventLoopGroup(2, LocalIoHandler.newFactory());
groupsToShutDown.add(nioEventLoopGroup);
groupsToShutDown.add(localEventLoopGroup);
@@ -581,11 +665,11 @@ class OmnibusH2ServerTest {
try {
final int responseSize = Math.toIntExact(DataSize.kibibytes(responseSizeKib).toBytes());
final OmnibusH2Server server = startOmnibusServer(nioEventLoopGroup, localEventLoopGroup,
Collections.emptyMap(),
startBackendServer(localChannel ? localEventLoopGroup : nioEventLoopGroup, localChannel,
DEFAULT_BACKEND_IDENTITY, _ -> {}, _ -> {}),
Duration.ofMinutes(1));
final OmnibusH2Server server = omnibusServer()
.eventLoopGroups(nioEventLoopGroup, localEventLoopGroup)
.addDefault(backendServer().localChannel(localChannel))
.pooled(false)
.start();
for (int i = 0; i < connections; i++) {
clientConnections.add(connectToOmnibus(server));
@@ -650,85 +734,149 @@ class OmnibusH2ServerTest {
return body;
}
/// Start an OmnibusH2Server. The returned server and provided backends will be torn down in [#tearDown()]
///
/// @param routes A map of prefixes and the corresponding backend server channels the omnibus will target
/// @param defaultBackend The target backend if no prefix routes match the request path
/// @param timeout The omnibus idle timeout
private OmnibusH2Server startOmnibusServer(final Map<String, Channel> routes, final Channel defaultBackend, final Duration timeout) throws Exception {
return startOmnibusServer(nioEventLoopGroup, localEventLoopGroup, routes, defaultBackend, timeout);
/// A builder for an OmnibusH2Server. The started server and its backends will be torn down in [#tearDown()]
private OmnibusServerBuilder omnibusServer() {
return new OmnibusServerBuilder();
}
private OmnibusH2Server startOmnibusServer(
final NioEventLoopGroup nioEventLoopGroup,
final DefaultEventLoopGroup localEventLoopGroup,
final Map<String, Channel> routes,
final Channel defaultBackend,
final Duration timeout) throws Exception {
backendChannelsToShutDown.addAll(routes.values());
backendChannelsToShutDown.add(defaultBackend);
private class OmnibusServerBuilder {
final OmnibusH2Server server = new OmnibusH2Server(
sniMapping,
nioEventLoopGroup,
localEventLoopGroup,
new InetSocketAddress("127.0.0.1", 0),
new OmnibusRouter(routes.entrySet().stream().collect(Collectors.toMap(
Map.Entry::getKey,
e -> e.getValue().localAddress())),
defaultBackend.localAddress()),
dynamicConfiguration::get,
timeout);
server.start();
omnibusH2ServersToShutDown.add(server);
return server;
private final Map<String, BackendServerBuilder> routes = new HashMap<>();
private BackendServerBuilder defaultBackend = backendServer();
private Duration idleTimeout = Duration.ofMinutes(1);
private boolean pooled = true;
private EventLoopGroup nioEventLoopGroup = OmnibusH2ServerTest.nioEventLoopGroup;
private EventLoopGroup localEventLoopGroup = OmnibusH2ServerTest.localEventLoopGroup;
/// Requests with paths starting with `prefix` will go to `backend`
OmnibusServerBuilder addRoute(final String prefix, final BackendServerBuilder backend) {
routes.put(prefix, backend);
return this;
}
/// Requests that don't match any route will go to `backend`. Defaults to [#backendServer()].
OmnibusServerBuilder addDefault(final BackendServerBuilder backend) {
this.defaultBackend = backend;
return this;
}
/// Defaults to 1 minute
OmnibusServerBuilder idleTimeout(final Duration idleTimeout) {
this.idleTimeout = idleTimeout;
return this;
}
/// Whether to connect to backends via pooled h2 connections. Defaults to true.
OmnibusServerBuilder pooled(final boolean pooled) {
this.pooled = pooled;
return this;
}
/// The event loop groups used by the omnibus and its backends. Defaults to the shared event loop groups.
OmnibusServerBuilder eventLoopGroups(final EventLoopGroup nioEventLoopGroup,
final EventLoopGroup localEventLoopGroup) {
this.nioEventLoopGroup = nioEventLoopGroup;
this.localEventLoopGroup = localEventLoopGroup;
return this;
}
/// Start the backends and then the omnibus
OmnibusH2Server start() throws Exception {
final OmnibusRouter router = new OmnibusRouter(routes.entrySet().stream().collect(Collectors.toMap(
Map.Entry::getKey,
e -> startBackend(e.getValue()))),
startBackend(defaultBackend));
final OmnibusH2Server server = new OmnibusH2Server(
sniMapping,
nioEventLoopGroup,
new InetSocketAddress("127.0.0.1", 0),
router,
dynamicConfiguration::get,
idleTimeout);
server.start();
omnibusH2ServersToShutDown.add(server);
return server;
}
private H2ConnectionFactory startBackend(final BackendServerBuilder backend) {
final EventLoopGroup eventLoopGroup = backend.localChannel ? localEventLoopGroup : nioEventLoopGroup;
final Channel channel = backend.start(eventLoopGroup);
backendChannelsToShutDown.add(channel);
return pooled
? new PooledH2ConnectionFactory(channel.localAddress(), eventLoopGroup, Duration.ofDays(1))
: new UnpooledH2ConnectionFactory(channel.localAddress(), eventLoopGroup);
}
}
private OmnibusH2Server startOmnibusServer(final Channel defaultBackend) throws Exception {
return startOmnibusServer(Collections.emptyMap(), defaultBackend, Duration.ofMinutes(1));
/// A builder for a h2c server that can be used as a target of the omnibus. The server is started by
/// [OmnibusServerBuilder#start()].
private BackendServerBuilder backendServer() {
return new BackendServerBuilder();
}
private OmnibusH2Server startOmnibusServer(final Map<String, Channel> routes, final Channel defaultBackend) throws Exception {
return startOmnibusServer(routes, defaultBackend, Duration.ofMinutes(1));
}
private class BackendServerBuilder {
/// Start a h2c server that can be used as a target of the omnibus
///
/// @param localChannel whether the omnibus should target this backend via a LocalChannel or an NioChannel
/// @param identity how the backend should respond to identity requests
/// @param h2ChannelInit a Consumer that will be called every time a new HTTP/2 connection is made to this server
/// @param h2StreamInit a Consumer that will be called every time a new HTTP/2 stream is created on this server
private Channel startBackendServer(final boolean localChannel, final String identity, Consumer<Channel> h2ChannelInit, Consumer<Channel> h2StreamInit) {
return startBackendServer(localChannel ? localEventLoopGroup : nioEventLoopGroup,
localChannel, identity, h2ChannelInit, h2StreamInit);
}
private boolean localChannel = true;
private String identity = DEFAULT_BACKEND_IDENTITY;
private Consumer<Channel> h2ChannelInit = _ -> {};
private Consumer<Channel> h2StreamInit = _ -> {};
@Nullable
private Channel channel = null;
private Channel startBackendServer(final EventLoopGroup eventLoopGroup, final boolean localChannel,
final String identity, Consumer<Channel> h2ChannelInit, Consumer<Channel> h2StreamInit) {
return new ServerBootstrap()
.group(eventLoopGroup, eventLoopGroup)
.channel(localChannel ? LocalServerChannel.class : NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<>() {
@Override
protected void initChannel(final Channel ch) {
h2ChannelInit.accept(ch);
ch.pipeline().addLast(Http2FrameCodecBuilder.forServer().build());
ch.pipeline().addLast(new Http2MultiplexHandler(new ChannelInitializer<Http2StreamChannel>() {
@Override
protected void initChannel(final Http2StreamChannel ch) {
h2StreamInit.accept(ch);
ch.pipeline().addLast(new TestHandler(identity));
}
}));
}
})
.bind(localChannel ? new LocalAddress(identity) : new InetSocketAddress("127.0.0.1", 0))
.syncUninterruptibly()
.channel();
}
/// Whether the omnibus should target this backend via a LocalChannel or an NioChannel. Defaults to true.
BackendServerBuilder localChannel(final boolean localChannel) {
this.localChannel = localChannel;
return this;
}
private Channel startBackendServer(final boolean localChannel, final String identity) {
return startBackendServer(localChannel, identity, _ -> {}, _ -> {});
/// How the backend should respond to identity requests. Defaults to [#DEFAULT_BACKEND_IDENTITY].
BackendServerBuilder identity(final String identity) {
this.identity = identity;
return this;
}
/// A Consumer that will be called every time a new HTTP/2 connection is made to this server
BackendServerBuilder h2ChannelInit(final Consumer<Channel> h2ChannelInit) {
this.h2ChannelInit = h2ChannelInit;
return this;
}
/// A Consumer that will be called every time a new HTTP/2 stream is created on this server
BackendServerBuilder h2StreamInit(final Consumer<Channel> h2StreamInit) {
this.h2StreamInit = h2StreamInit;
return this;
}
/// The backend's server channel, once it has started
Channel channel() {
assertNotNull(channel, "backend has not started");
return channel;
}
private Channel start(final EventLoopGroup eventLoopGroup) {
channel = new ServerBootstrap()
.group(eventLoopGroup, eventLoopGroup)
.channel(localChannel ? LocalServerChannel.class : NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<>() {
@Override
protected void initChannel(final Channel ch) {
h2ChannelInit.accept(ch);
ch.pipeline().addLast(Http2FrameCodecBuilder.forServer().build());
ch.pipeline().addLast(new Http2MultiplexHandler(new ChannelInitializer<Http2StreamChannel>() {
@Override
protected void initChannel(final Http2StreamChannel ch) {
h2StreamInit.accept(ch);
ch.pipeline().addLast(new TestHandler(identity));
}
}));
}
})
.bind(localChannel ? new LocalAddress(identity) : new InetSocketAddress("127.0.0.1", 0))
.syncUninterruptibly()
.channel();
return channel;
}
}
/// Makes an H2 connection to the omnibus at `server` on which new H2 streams can be opened
@@ -0,0 +1,220 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc.net;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoop;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.MultiThreadIoEventLoopGroup;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.channel.local.LocalAddress;
import io.netty.channel.local.LocalIoHandler;
import io.netty.channel.local.LocalServerChannel;
import io.netty.handler.codec.http2.DefaultHttp2GoAwayFrame;
import io.netty.handler.codec.http2.Http2Error;
import io.netty.handler.codec.http2.Http2FrameCodecBuilder;
import io.netty.handler.codec.http2.Http2GoAwayFrame;
import io.netty.handler.codec.http2.Http2MultiplexHandler;
import io.netty.util.concurrent.GlobalEventExecutor;
import io.netty.util.test.LeakPresenceExtension;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@ExtendWith(LeakPresenceExtension.class)
class PooledH2ConnectionFactoryTest {
private static EventLoopGroup backendEventLoopGroup;
private static EventLoopGroup callerEventLoopGroup;
private LocalAddress backendAddress;
private Channel backendServer;
private BlockingQueue<Channel> newBackendConnections;
private ChannelGroup allBackendConnections;
private PooledH2ConnectionFactory factory;
@BeforeAll
static void setUpBeforeAll() {
backendEventLoopGroup = new MultiThreadIoEventLoopGroup(LocalIoHandler.newFactory());
callerEventLoopGroup = new MultiThreadIoEventLoopGroup(2, LocalIoHandler.newFactory());
}
@BeforeEach
void setUp() {
backendAddress = new LocalAddress(PooledH2ConnectionFactoryTest.class);
newBackendConnections = new LinkedBlockingQueue<>();
allBackendConnections = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
startBackend();
factory = new PooledH2ConnectionFactory(backendAddress, backendEventLoopGroup, Duration.ofDays(1));
}
@AfterEach
void tearDown() {
backendServer.close().syncUninterruptibly();
allBackendConnections.close().syncUninterruptibly();
}
@AfterAll
static void tearDownAfterAll() throws InterruptedException {
backendEventLoopGroup.shutdownGracefully(0, 1, TimeUnit.SECONDS).sync();
callerEventLoopGroup.shutdownGracefully(0, 1, TimeUnit.SECONDS).sync();
}
@Test
void reuseConnection() throws Exception {
final EventLoop eventLoop1 = callerEventLoopGroup.next();
final EventLoop eventLoop2 = callerEventLoopGroup.next();
final Channel connection = getConnection(eventLoop1).channel();
assertSame(connection, getConnection(eventLoop1).channel());
assertNotSame(connection, getConnection(eventLoop2).channel());
}
@Test
void shareConnectionWhileConnecting() throws Exception {
final EventLoop callerEventLoop = callerEventLoopGroup.next();
final List<ChannelFuture> connectFutures = callerEventLoop.submit(() -> List.of(
factory.getConnectionChannelFuture(callerEventLoop),
factory.getConnectionChannelFuture(callerEventLoop)))
.get();
assertSame(connectFutures.get(0), connectFutures.get(1));
}
@Test
void replaceClosedConnection() throws Exception {
final EventLoop callerEventLoop = callerEventLoopGroup.next();
final Channel connection = getConnection(callerEventLoop).channel();
backendConnection().close().syncUninterruptibly();
connection.closeFuture().syncUninterruptibly();
final Channel replacement = getConnection(callerEventLoop).channel();
assertNotSame(connection, replacement);
assertTrue(replacement.isActive());
}
@Test
void replaceFailedConnection() throws Exception {
backendServer.close().syncUninterruptibly();
final EventLoop callerEventLoop = callerEventLoopGroup.next();
assertFalse(getConnection(callerEventLoop).isSuccess());
startBackend();
assertTrue(getConnection(callerEventLoop).isSuccess());
}
@Test
void replaceConnectionAfterGoAway() throws Exception {
final EventLoop callerEventLoop = callerEventLoopGroup.next();
final Channel connection = getConnection(callerEventLoop).channel();
final CompletableFuture<Void> goAwayRead = goAwayRead(connection);
backendConnection().writeAndFlush(new DefaultHttp2GoAwayFrame(Http2Error.NO_ERROR)).syncUninterruptibly();
goAwayRead.get(5, TimeUnit.SECONDS);
assertNotSame(connection, getConnection(callerEventLoop).channel());
assertTrue(connection.isActive());
factory.release(connection);
assertTrue(connection.closeFuture().await(5, TimeUnit.SECONDS));
}
@Test
void retireConnection() throws Exception {
factory = new PooledH2ConnectionFactory(backendAddress, backendEventLoopGroup, Duration.ZERO);
final EventLoop callerEventLoop = callerEventLoopGroup.next();
final Channel connection = getConnection(callerEventLoop).channel();
assertNotSame(connection, getConnection(callerEventLoop).channel());
assertTrue(connection.isActive());
factory.release(connection);
assertTrue(connection.closeFuture().await(5, TimeUnit.SECONDS));
}
@Test
void closeUnusedConnectionWhenReplaced() throws Exception {
factory = new PooledH2ConnectionFactory(backendAddress, backendEventLoopGroup, Duration.ZERO);
final EventLoop callerEventLoop = callerEventLoopGroup.next();
final Channel connection = getConnection(callerEventLoop).channel();
factory.release(connection);
assertTrue(connection.isActive());
getConnection(callerEventLoop);
assertTrue(connection.closeFuture().await(5, TimeUnit.SECONDS));
}
private void startBackend() {
backendServer = new ServerBootstrap()
.group(backendEventLoopGroup)
.channel(LocalServerChannel.class)
.childHandler(new ChannelInitializer<>() {
@Override
protected void initChannel(final Channel ch) {
ch.pipeline().addLast(Http2FrameCodecBuilder.forServer().build());
ch.pipeline().addLast(new Http2MultiplexHandler(new ChannelInboundHandlerAdapter()));
newBackendConnections.add(ch);
allBackendConnections.add(ch);
}
})
.bind(backendAddress)
.syncUninterruptibly()
.channel();
}
/// Get a connection from the factory on `callerEventLoop`, waiting for it to finish connecting
private ChannelFuture getConnection(final EventLoop callerEventLoop) throws Exception {
return callerEventLoop.submit(() -> factory.getConnectionChannelFuture(callerEventLoop)).get().await();
}
/// The backend's side of the next connection the factory made
private Channel backendConnection() throws InterruptedException {
final Channel backendConnection = newBackendConnections.poll(5, TimeUnit.SECONDS);
assertNotNull(backendConnection);
return backendConnection;
}
/// A future that completes once the factory has seen a GOAWAY on `connection`
private static CompletableFuture<Void> goAwayRead(final Channel connection) {
final CompletableFuture<Void> goAwayRead = new CompletableFuture<>();
connection.eventLoop().submit(() -> connection.pipeline()
.addAfter(connection.pipeline().context(Http2MultiplexHandler.class).name(), null,
new ChannelInboundHandlerAdapter() {
@Override
public void channelRead(final ChannelHandlerContext ctx, final Object msg) {
ctx.fireChannelRead(msg);
if (msg instanceof Http2GoAwayFrame) {
goAwayRead.complete(null);
}
}
}))
.syncUninterruptibly();
return goAwayRead;
}
}
@@ -15,10 +15,12 @@ import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.DefaultEventLoopGroup;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.MultiThreadIoEventLoopGroup;
import io.netty.channel.SimpleUserEventChannelHandler;
import io.netty.channel.local.LocalAddress;
import io.netty.channel.local.LocalChannel;
import io.netty.channel.local.LocalIoHandler;
import io.netty.channel.local.LocalServerChannel;
import io.netty.handler.ssl.SniHandler;
import io.netty.handler.ssl.SslContext;
@@ -73,7 +75,7 @@ class SniMapperTest {
CertificateBuilder.Algorithm.rsa2048
};
private static DefaultEventLoopGroup eventLoopGroup;
private static EventLoopGroup eventLoopGroup;
private static final Map<SslProvider, Mapping<String, SslContext>> sniMappingsByProvider =
new EnumMap<>(SslProvider.class);
@@ -113,7 +115,7 @@ class SniMapperTest {
new ByteArrayInputStream(byteArrayOutputStream.toByteArray()), new String(keyStorePassword), sslProvider));
}
eventLoopGroup = new DefaultEventLoopGroup();
eventLoopGroup = new MultiThreadIoEventLoopGroup(LocalIoHandler.newFactory());
}
private void startServer(final SslProvider sslProvider) throws InterruptedException {
@@ -18,10 +18,11 @@ import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.DefaultEventLoopGroup;
import io.netty.channel.MultithreadEventLoopGroup;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.MultiThreadIoEventLoopGroup;
import io.netty.channel.local.LocalAddress;
import io.netty.channel.local.LocalChannel;
import io.netty.channel.local.LocalIoHandler;
import io.netty.channel.local.LocalServerChannel;
import io.netty.handler.ssl.SniHandler;
import io.netty.handler.ssl.SslContext;
@@ -62,7 +63,7 @@ class TlsHandshakeMetricsHandlerTest {
private static final String DOMAIN = "example.org";
private static MultithreadEventLoopGroup eventLoopGroup;
private static EventLoopGroup eventLoopGroup;
private static byte[] keyStoreBytes;
private static String keyStorePassword;
@@ -94,7 +95,7 @@ class TlsHandshakeMetricsHandlerTest {
keyStoreBytes = byteArrayOutputStream.toByteArray();
keyStorePassword = new String(password);
eventLoopGroup = new DefaultEventLoopGroup();
eventLoopGroup = new MultiThreadIoEventLoopGroup(LocalIoHandler.newFactory());
}
@BeforeEach
@@ -34,8 +34,10 @@ import java.util.stream.Collectors;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.EnumSource;
import org.junit.jupiter.params.provider.MethodSource;
import org.junitpioneer.jupiter.cartesian.CartesianTest;
import org.signal.libsignal.protocol.InvalidMessageException;
import org.signal.libsignal.protocol.InvalidVersionException;
@@ -297,4 +299,25 @@ class MessagesManagerTest {
messagesManager.getEarliestUndeliveredTimestampForDevice(accountIdentifier, device).join();
assertEquals(Optional.ofNullable(expected).map(Instant::ofEpochMilli), earliest);
}
@ParameterizedTest
@MethodSource
void hasSuspectedDeliveryLoop(final long readsSinceLastAcknowledgedMessage, final boolean expectSuspectedLoop) {
final AciServiceIdentifier aciServiceIdentifier = new AciServiceIdentifier(UUID.randomUUID());
final byte deviceId = Device.PRIMARY_ID;
when(foundationDbMessageStore.getReadsSinceLastAcknowledgedMessage(aciServiceIdentifier, deviceId))
.thenReturn(CompletableFuture.completedFuture(readsSinceLastAcknowledgedMessage));
assertEquals(expectSuspectedLoop,
messagesManager.hasSuspectedDeliveryLoop(aciServiceIdentifier.uuid(), deviceId).join());
}
private static List<Arguments> hasSuspectedDeliveryLoop() {
return List.of(
Arguments.of(MessagesManager.DELIVERY_LOOP_READ_THRESHOLD - 1, false),
Arguments.of(MessagesManager.DELIVERY_LOOP_READ_THRESHOLD, true),
Arguments.of(MessagesManager.DELIVERY_LOOP_READ_THRESHOLD + 1, true)
);
}
}
@@ -1,69 +0,0 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage.devicecheck;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import com.webauthn4j.appattest.DeviceCheckManager;
import com.webauthn4j.appattest.data.DCAssertionData;
import com.webauthn4j.appattest.data.DCAssertionRequest;
import com.webauthn4j.converter.exception.DataConversionException;
import com.webauthn4j.converter.util.ObjectConverter;
import com.webauthn4j.data.attestation.authenticator.AuthenticatorData;
import java.nio.ByteBuffer;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
class AppAttestAssertionConverterTest {
private static final ObjectConverter OBJECT_CONVERTER = DeviceCheckManager.createObjectConverter();
@ParameterizedTest
@ValueSource(bytes = {AuthenticatorData.BIT_AT, AuthenticatorData.BIT_ED, AuthenticatorData.BIT_AT | AuthenticatorData.BIT_ED})
void parseBadAssertion(byte flags) {
final DCAssertionData data = AppAttestAssertionConverter.parseAppleAssertion(
new DCAssertionRequest(new byte[32], createAssertion(flags), new byte[32]));
assertThat(data.getAuthenticatorDataBytes()).isEqualTo(createAuthenticatorData(flags));
assertThat(data.getAuthenticatorData().getFlags()).isEqualTo(flags);
assertThat(data.getAuthenticatorData().getSignCount()).isEqualTo(32);
assertThat(data.getAuthenticatorData().getAttestedCredentialData()).isNull();
assertThat(data.getAuthenticatorData().getExtensions().getKeys())
.containsExactlyInAnyOrder("apple_bundle_version_01", "apple_validation_category_01");
}
// If this test fails, we have updated to a version of webauthn4j that handles misformatted attestations, and
// the helper class can be removed.
@Test
void webauthn4jRejectsIOS27Assertion() {
final DeviceCheckManager deviceCheckManager = new DeviceCheckManager(new AppleDeviceCheckTrustAnchor());
final byte[] appAttestAssertion = createAssertion((byte) (AuthenticatorData.BIT_AT | AuthenticatorData.BIT_ED));
assertThatExceptionOfType(DataConversionException.class).isThrownBy(() ->
deviceCheckManager.parse(new DCAssertionRequest(new byte[32], appAttestAssertion, new byte[32])));
}
/// An assertion that has extensions and no attestedCredentialData but potentially with mismatched flags
private static byte[] createAssertion(final byte flags) {
return OBJECT_CONVERTER.getCborMapper().writeValueAsBytes(Map.of(
"signature", new byte[64],
"authenticatorData", createAuthenticatorData(flags)));
}
private static byte[] createAuthenticatorData(final byte flags) {
final byte[] extensions = OBJECT_CONVERTER.getCborMapper().writeValueAsBytes(Map.of(
"apple_bundle_version_01", "1",
"apple_validation_category_01", new byte[]{2, 0, 0, 0}));
return ByteBuffer.allocate(37 + extensions.length)
.put(new byte[32]) // rpIdHash
.put((byte) flags) // flags
.putInt(32) // signCount
.put(extensions)
.array();
}
}
@@ -14,7 +14,6 @@ import com.webauthn4j.appattest.data.DCAttestationParameters;
import com.webauthn4j.appattest.data.DCAttestationRequest;
import com.webauthn4j.appattest.server.DCServerProperty;
import com.webauthn4j.data.attestation.AttestationObject;
import com.webauthn4j.data.client.challenge.DefaultChallenge;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
@@ -74,7 +73,7 @@ public class DeviceCheckTestUtil {
public static DCAppleDevice sampleDevice() {
final byte[] clientDataHash = sha256(SAMPLE_CHALLENGE.getBytes(StandardCharsets.UTF_8));
return validate(SAMPLE_CHALLENGE, clientDataHash, SAMPLE_KEY_ID, SAMPLE_ATTESTATION, SAMPLE_TEAM_ID,
return validate(clientDataHash, SAMPLE_KEY_ID, SAMPLE_ATTESTATION, SAMPLE_TEAM_ID,
SAMPLE_BUNDLE_ID, SAMPLE_TIME);
}
@@ -83,11 +82,11 @@ public class DeviceCheckTestUtil {
// despite them referring to the value as a challenge
final byte[] clientDataHash = APPLE_SAMPLE_CHALLENGE.getBytes(StandardCharsets.UTF_8);
return validate(APPLE_SAMPLE_CHALLENGE, clientDataHash, APPLE_SAMPLE_KEY_ID, APPLE_SAMPLE_ATTESTATION,
return validate(clientDataHash, APPLE_SAMPLE_KEY_ID, APPLE_SAMPLE_ATTESTATION,
APPLE_SAMPLE_TEAM_ID, APPLE_SAMPLE_BUNDLE_ID, APPLE_SAMPLE_TIME);
}
private static DCAppleDevice validate(final String challengePlainText, final byte[] clientDataHash,
private static DCAppleDevice validate(final byte[] clientDataHash,
final byte[] keyId, final byte[] attestation, final String teamId, final String bundleId, final Instant now) {
final DCAttestationRequest dcAttestationRequest = new DCAttestationRequest(keyId, attestation, clientDataHash);
@@ -97,9 +96,7 @@ public class DeviceCheckTestUtil {
instantMock.when(Instant::now).thenReturn(now);
dcAttestationData = appleDeviceCheckManager().validate(dcAttestationRequest, new DCAttestationParameters(
new DCServerProperty(
teamId, bundleId,
new DefaultChallenge(challengePlainText.getBytes(StandardCharsets.UTF_8)))));
new DCServerProperty(teamId, bundleId, clientDataHash)));
}
final AttestationObject attestationObject = dcAttestationData.getAttestationObject();
@@ -130,6 +130,7 @@ class FoundationDbMessagePublisherTest {
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.begin),
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.end),
STREAM_ID,
FoundationDbMessageStore.getReadsSinceLastAcknowledgedMessageKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
null,
null,
null,
@@ -207,6 +208,7 @@ class FoundationDbMessagePublisherTest {
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.begin),
KeySelector.firstGreaterOrEqual(new byte[]{(byte) 10}),
STREAM_ID,
FoundationDbMessageStore.getReadsSinceLastAcknowledgedMessageKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
FoundationDbMessageStore.getPresenceKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
presenceRenewalExecutorService,
MESSAGES_AVAILABLE_WATCH_KEY,
@@ -297,6 +299,7 @@ class FoundationDbMessagePublisherTest {
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.begin),
KeySelector.firstGreaterOrEqual(new byte[]{(byte) 10}),
STREAM_ID,
FoundationDbMessageStore.getReadsSinceLastAcknowledgedMessageKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
FoundationDbMessageStore.getPresenceKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
presenceRenewalExecutorService,
MESSAGES_AVAILABLE_WATCH_KEY,
@@ -351,6 +354,7 @@ class FoundationDbMessagePublisherTest {
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.begin),
KeySelector.firstGreaterOrEqual(new byte[]{(byte) 10}),
STREAM_ID,
FoundationDbMessageStore.getReadsSinceLastAcknowledgedMessageKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
FoundationDbMessageStore.getPresenceKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
presenceRenewalExecutorService,
MESSAGES_AVAILABLE_WATCH_KEY,
@@ -399,6 +403,7 @@ class FoundationDbMessagePublisherTest {
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.begin),
KeySelector.firstGreaterThan(SUBSPACE_RANGE.end),
STREAM_ID,
FoundationDbMessageStore.getReadsSinceLastAcknowledgedMessageKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
FoundationDbMessageStore.getPresenceKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
presenceRenewalExecutorService,
MESSAGES_AVAILABLE_WATCH_KEY);
@@ -461,6 +466,7 @@ class FoundationDbMessagePublisherTest {
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.begin),
KeySelector.firstGreaterOrEqual(new byte[]{(byte) 10}),
STREAM_ID,
FoundationDbMessageStore.getReadsSinceLastAcknowledgedMessageKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
FoundationDbMessageStore.getPresenceKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
presenceRenewalExecutorService,
MESSAGES_AVAILABLE_WATCH_KEY,
@@ -527,6 +533,7 @@ class FoundationDbMessagePublisherTest {
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.begin),
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.end),
STREAM_ID,
FoundationDbMessageStore.getReadsSinceLastAcknowledgedMessageKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
null,
null,
null,
@@ -585,6 +592,7 @@ class FoundationDbMessagePublisherTest {
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.begin),
KeySelector.firstGreaterOrEqual(SUBSPACE_RANGE.end),
STREAM_ID,
FoundationDbMessageStore.getReadsSinceLastAcknowledgedMessageKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
FoundationDbMessageStore.getPresenceKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
presenceRenewalExecutorService,
MESSAGES_AVAILABLE_WATCH_KEY,
@@ -528,25 +528,6 @@ class FoundationDbMessageStoreTest {
getItemsInDeviceQueue(retainedMessageAci, retainedMessageDeviceId).getFirst().getValue());
}
@Test
void acknowledgeAndGetMessage() {
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
final byte deviceId = Device.PRIMARY_ID;
final UUID messageGuid =
foundationDbMessageStore.insert(aci, Map.of(deviceId, generateRandomMessage(false))).join()
.get(deviceId).messageGuid().orElseThrow();
final FoundationDbMessageStream messageStream = foundationDbMessageStore.getMessages(aci, deviceId);
final Optional<MessageStreamEntry.Envelope> acknowledgeAndGetResult =
messageStream.acknowledgeAndGetMessage(messageGuid).join();
assertTrue(acknowledgeAndGetResult.isPresent());
assertEquals(messageGuid, UUIDUtil.fromByteString(acknowledgeAndGetResult.get().message().getServerGuid()));
assertTrue(getItemsInDeviceQueue(aci, deviceId).isEmpty());
}
@Test
void clearAllForAccount() {
final AciServiceIdentifier deletedAccountIdentifier = new AciServiceIdentifier(UUID.randomUUID());
@@ -1333,6 +1314,46 @@ class FoundationDbMessageStoreTest {
foundationDbMessageStore.getEarliestUndeliveredMessageTimestamp(aci, deviceId).join());
}
@Test
void getReadsSinceLastAcknowledgedMessage() {
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
final int messageCount = 16;
final UUID[] messageGuids = new UUID[messageCount];
for (int i = 0; i < messageCount; i++) {
final Map<Byte, FoundationDbMessageStore.InsertResult> insertResults =
foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, generateRandomMessage(false))).join();
messageGuids[i] = insertResults.get(Device.PRIMARY_ID).messageGuid().orElseThrow();
}
assertEquals(0, foundationDbMessageStore.getReadsSinceLastAcknowledgedMessage(aci, Device.PRIMARY_ID).join(),
"Initial \"Reads since last acknowledged message\" count should be zero");
JdkFlowAdapter.flowPublisherToFlux(foundationDbMessageStore.getMessages(aci, Device.PRIMARY_ID).getMessages())
.take(messageCount)
.then()
.block();
assertEquals(1, foundationDbMessageStore.getReadsSinceLastAcknowledgedMessage(aci, Device.PRIMARY_ID).join(),
"\"Reads since last acknowledged message\" count should increment on first read");
final FoundationDbMessageStream messageStream = foundationDbMessageStore.getMessages(aci, Device.PRIMARY_ID);
JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages())
.take(messageCount)
.then()
.block();
assertEquals(2, foundationDbMessageStore.getReadsSinceLastAcknowledgedMessage(aci, Device.PRIMARY_ID).join(),
"\"Reads since last acknowledged message\" count should increment on subsequent reads");
messageStream.acknowledgeMessage(messageGuids[1], 0L).join();
assertEquals(0, foundationDbMessageStore.getReadsSinceLastAcknowledgedMessage(aci, Device.PRIMARY_ID).join(),
"\"Reads since last acknowledged message\" count should reset when acknowledging any message");
}
static MessageProtos.Envelope generateRandomMessage(final boolean ephemeral, final int contentSize) {
return generateRandomMessage(ephemeral, contentSize, CLOCK.millis());
}
@@ -6,17 +6,10 @@
package org.whispersystems.textsecuregcm.util;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
@@ -75,47 +68,4 @@ class UtilTest {
void startsWithDecimal(final long number, final long prefix, final boolean expectStartsWithPrefix) {
assertEquals(expectStartsWithPrefix, Util.startsWithDecimal(number, prefix));
}
@ParameterizedTest
@MethodSource
void isOldFormatBeninPhoneNumber4(final Phonenumber.PhoneNumber beninNumber, final boolean isOldFormatBeninNumber) {
if (isOldFormatBeninNumber) {
assertTrue(Util.isOldFormatBeninPhoneNumber(beninNumber));
} else {
assertFalse(Util.isOldFormatBeninPhoneNumber(beninNumber));
}
}
private static Stream<Arguments> isOldFormatBeninPhoneNumber4() throws NumberParseException {
final Phonenumber.PhoneNumber oldFormatBeninE164 = PhoneNumberUtil.getInstance().parse(OLD_FORMAT_BENIN_E164_STRING, null);
final Phonenumber.PhoneNumber newFormatBeninE164 = PhoneNumberUtil.getInstance().parse(NEW_FORMAT_BENIN_E164_STRING, null);
return Stream.of(
Arguments.of(oldFormatBeninE164, true),
Arguments.of(newFormatBeninE164, false),
Arguments.of(PhoneNumberUtil.getInstance().getExampleNumber("US"), false)
);
}
@ParameterizedTest
@MethodSource
void normalizeBeninPhoneNumber(final Phonenumber.PhoneNumber beninNumber, final Phonenumber.PhoneNumber expectedBeninNumber, @Nullable Class<? extends Throwable> exception)
throws Exception {
if (exception == null) {
assertTrue(expectedBeninNumber.exactlySameAs(Util.canonicalizePhoneNumber(beninNumber)));
} else {
assertThrows(exception, () -> Util.canonicalizePhoneNumber(beninNumber));
}
}
private static Stream<Arguments> normalizeBeninPhoneNumber() throws NumberParseException {
final Phonenumber.PhoneNumber oldFormatBeninPhoneNumber = PhoneNumberUtil.getInstance().parse(OLD_FORMAT_BENIN_E164_STRING, null);
final Phonenumber.PhoneNumber newFormatBeninPhoneNumber = PhoneNumberUtil.getInstance().parse(NEW_FORMAT_BENIN_E164_STRING, null);
final Phonenumber.PhoneNumber usPhoneNumber = PhoneNumberUtil.getInstance().getExampleNumber("US");
return Stream.of(
Arguments.of(newFormatBeninPhoneNumber, newFormatBeninPhoneNumber, null),
Arguments.of(oldFormatBeninPhoneNumber, null, ObsoletePhoneNumberFormatException.class),
Arguments.of(usPhoneNumber, usPhoneNumber, null)
);
}
}
@@ -10,6 +10,7 @@ import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyByte;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
@@ -50,7 +51,6 @@ import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestListener;
import org.whispersystems.textsecuregcm.auth.DisconnectionRequestManager;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.filters.PriorityFilter;
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
@@ -102,6 +102,7 @@ class AuthenticatedConnectListenerIntegrationTest {
void setUp() throws Exception {
reset(messagesManager, disconnectionRequestManager, accountsManager, account, device);
when(messagesManager.mayHaveMessages(any(), any())).thenReturn(CompletableFuture.completedFuture(false));
when(messagesManager.hasSuspectedDeliveryLoop(any(), anyByte())).thenReturn(CompletableFuture.completedFuture(false));
when(account.getNumber()).thenReturn(Optional.of(E164));
when(account.getAccountIdentifier()).thenReturn(ACCOUNT_UUID);
when(account.getDevice(DEVICE_ID)).thenReturn(Optional.of(device));
@@ -7,6 +7,7 @@ package org.whispersystems.textsecuregcm.websocket;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyByte;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.argThat;
@@ -43,9 +44,7 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.InOrder;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.metrics.MessageMetrics;
@@ -98,6 +97,9 @@ class WebSocketConnectionTest {
messageDeliveryScheduler = Schedulers.newBoundedElastic(10, 10_000, "messageDelivery");
clientReleaseManager = mock(ClientReleaseManager.class);
when(messagesManager.hasSuspectedDeliveryLoop(any(), anyByte()))
.thenReturn(CompletableFuture.completedFuture(false));
ON_ERROR_DROPPED_COUNTER.set(0);
}
@@ -263,6 +263,7 @@ fcm: # FCM configuration
credentials: secret://fcm.credentials
cdn:
baseUrl: https://cdn.example.com # Public base URL for objects in the bucket
bucket: cdn # S3 Bucket name
credentials:
accessKeyId: secret://cdn.accessKey