The response has been limited to 50k tokens of the smallest files in the repo. You can remove this limitation by removing the max tokens filter.
├── .github
    ├── CODEOWNERS
    ├── dependabot.yml
    └── workflows
    │   ├── maven-release.yml
    │   └── pr.yml
├── .gitignore
├── .gitmodules
├── LICENSE
├── Makefile
├── README.md
├── docker-compose.yml
├── manage.sh
├── pom.xml
└── src
    ├── main
        └── java
        │   └── com
        │       └── wire
        │           ├── blender
        │               ├── Blender.java
        │               └── BlenderListener.java
        │           └── lithium
        │               ├── API.java
        │               ├── BotClient.java
        │               ├── ClientRepo.java
        │               ├── Configuration.java
        │               ├── Server.java
        │               ├── healthchecks
        │                   ├── Alice2Bob.java
        │                   ├── CryptoHealthCheck.java
        │                   ├── Outbound.java
        │                   └── StorageHealthCheck.java
        │               ├── models
        │                   └── NewBotResponseModel.java
        │               ├── server
        │                   ├── filters
        │                   │   ├── AuthenticationFeature.java
        │                   │   └── AuthenticationFilter.java
        │                   ├── monitoring
        │                   │   ├── AbstractJsonLayout.java
        │                   │   ├── AccessEventJsonLayout.java
        │                   │   ├── LoggingEventJsonLayout.java
        │                   │   ├── MDCUtils.java
        │                   │   ├── RequestMdcFactoryFilter.java
        │                   │   ├── StatusResource.java
        │                   │   └── VersionResource.java
        │                   ├── resources
        │                   │   ├── BotsResource.java
        │                   │   └── MessageResource.java
        │                   └── tasks
        │                   │   ├── AvailablePrekeysTask.java
        │                   │   ├── ConversationTask.java
        │                   │   └── TaskBase.java
        │               └── tools
        │                   └── AuthValidator.java
    └── test
        └── java
            └── com
                └── wire
                    └── lithium
                        ├── CryptoDatabaseTest.java
                        ├── CryptoFileTest.java
                        ├── CryptoPostgresTest.java
                        ├── DatabaseTestBase.java
                        ├── MentionTest.java
                        ├── PostgresCryptoStorageTest.java
                        ├── PostgresStateTest.java
                        ├── WireBackendTest.java
                        └── helpers
                            ├── MemStorage.java
                            └── Util.java


/.github/CODEOWNERS:
--------------------------------------------------------------------------------
1 | @wireapp/integrations


--------------------------------------------------------------------------------
/.github/dependabot.yml:
--------------------------------------------------------------------------------
 1 | # To get started with Dependabot version updates, you'll need to specify which
 2 | # package ecosystems to update and where the package manifests are located.
 3 | # Please see the documentation for all configuration options:
 4 | # https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
 5 | 
 6 | version: 2
 7 | updates:
 8 |   # Maven updates
 9 |   - package-ecosystem: "maven"
10 |     directory: "/"
11 |     schedule:
12 |       interval: "weekly"
13 |     ignore:
14 |       # ignore Flyway, as we're stuck on older version because of the
15 |       # older PostgreSQL running in the production
16 |       - dependency-name: "org.flywaydb:flyway-core"
17 | 
18 |   # Maintain dependencies for GitHub Actions
19 |   - package-ecosystem: "github-actions"
20 |     directory: "/"
21 |     schedule:
22 |       interval: "weekly"
23 | 


--------------------------------------------------------------------------------
/.github/workflows/maven-release.yml:
--------------------------------------------------------------------------------
 1 | name: Release to Maven Central
 2 | 
 3 | on:
 4 |   push:
 5 |     tags:
 6 |       - '*'
 7 | 
 8 | jobs:
 9 |   tests:
10 |     runs-on: ubuntu-20.04
11 |     container: wirebot/cryptobox:1.3.0
12 |     # enable postgres
13 |     services:
14 |       postgres:
15 |         image: postgres:15
16 |         env:
17 |           POSTGRES_PASSWORD: postgres
18 |     steps:
19 |       - uses: actions/checkout@v4
20 | 
21 |       - name: Setup Environment Variables
22 |         run: |
23 |           echo "POSTGRES_USER=postgres" >> $GITHUB_ENV
24 |           echo "POSTGRES_PASSWORD=postgres" >> $GITHUB_ENV
25 |           echo "POSTGRES_URL=postgres:5432/postgres" >> $GITHUB_ENV
26 | 
27 |       - name: Execute Tests
28 |         run: |
29 |           mvn test -DargLine="-Djava.library.path=$LD_LIBRARY_PATH"
30 | 
31 |       - name: Try to create package
32 |         run: |
33 |           mvn package -DskipTests
34 | 
35 |       - name: Webhook to Wire
36 |         uses: 8398a7/action-slack@v3
37 |         with:
38 |           status: ${{ job.status }}
39 |           author_name: Lithium - Test execution before release
40 |         env:
41 |           SLACK_WEBHOOK_URL: ${{ secrets.WEBHOOK_RELEASE }}
42 |         if: failure()
43 | 
44 |   release:
45 |     needs: [ tests ]
46 |     name: Release on Sonatype Central
47 |     runs-on: ubuntu-20.04
48 |     steps:
49 |       - uses: actions/checkout@v4
50 | 
51 |       - name: Set up JDK
52 |         uses: actions/setup-java@v4
53 |         with:
54 |           distribution: 'temurin'
55 |           java-version: 11
56 | 
57 |       - name: Build with Maven
58 |         run: mvn -DskipTests package
59 | 
60 |       - name: Set up Apache Maven Central
61 |         uses: actions/setup-java@v4
62 |         with: # running setup-java again overwrites the settings.xml
63 |           distribution: 'temurin'
64 |           java-version: 11
65 |           server-id: central
66 |           server-username: CENTRAL_USERNAME
67 |           server-password: CENTRAL_PASSWORD
68 |           gpg-private-key: ${{ secrets.MAVEN_GPG_PRIVATE_KEY }}
69 |           gpg-passphrase: MAVEN_GPG_PASSPHRASE
70 | 
71 |       - name: Publish to Apache Maven Central
72 |         run: mvn -DskipTests deploy
73 |         env:
74 |           CENTRAL_USERNAME: ${{ secrets.CENTRAL_USERNAME }}
75 |           CENTRAL_PASSWORD: ${{ secrets.CENTRAL_PASSWORD }}
76 |           MAVEN_GPG_PASSPHRASE: ${{ secrets.MAVEN_GPG_PASSPHRASE }}
77 | 
78 |       # Send webhook to Wire using Slack Bot
79 |       - name: Webhook to Wire
80 |         uses: 8398a7/action-slack@v3
81 |         with:
82 |           status: ${{ job.status }}
83 |           author_name: Lithium - Release to Maven Central
84 |         env:
85 |           SLACK_WEBHOOK_URL: ${{ secrets.WEBHOOK_RELEASE }}
86 |         # Send message only if previous step failed
87 |         if: always()
88 | 


--------------------------------------------------------------------------------
/.github/workflows/pr.yml:
--------------------------------------------------------------------------------
 1 | name: Code Check
 2 | 
 3 | on:
 4 |   workflow_dispatch:
 5 |   pull_request:
 6 | 
 7 | jobs:
 8 |   tests:
 9 |     runs-on: ubuntu-latest
10 |     container: wirebot/cryptobox:1.3.0
11 |     # enable postgres
12 |     services:
13 |       postgres:
14 |         image: postgres:15
15 |         env:
16 |           POSTGRES_PASSWORD: postgres
17 |     steps:
18 |       - uses: actions/checkout@v4
19 | 
20 |       # override template environment variables
21 |       - name: Setup Environment Variables
22 |         run: |
23 |           echo "POSTGRES_USER=postgres" >> $GITHUB_ENV
24 |           echo "POSTGRES_PASSWORD=postgres" >> $GITHUB_ENV
25 |           echo "POSTGRES_URL=postgres:5432/postgres" >> $GITHUB_ENV
26 | 
27 |       - name: Execute Tests
28 |         run: |
29 |           mvn test -DargLine="-Djava.library.path=$LD_LIBRARY_PATH"
30 | 
31 |       - name: Try to create package
32 |         run: |
33 |           mvn package -DskipTests
34 | 


--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
 1 | # Created by .gitignore support plugin (hsz.mobi)
 2 | ### Java template
 3 | 
 4 | .idea/
 5 | *.iml
 6 | target/
 7 | data/
 8 | libs/
 9 | .classpath
10 | .project
11 | .settings
12 | 


--------------------------------------------------------------------------------
/.gitmodules:
--------------------------------------------------------------------------------
1 | [submodule "vendor/jmx_exporter"]
2 | 	path = vendor/jmx_exporter
3 | 	url = https://github.com/prometheus/jmx_exporter
4 | 


--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
  1 |                     GNU GENERAL PUBLIC LICENSE
  2 |                        Version 3, 29 June 2007
  3 | 
  4 |  Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
  5 |  Everyone is permitted to copy and distribute verbatim copies
  6 |  of this license document, but changing it is not allowed.
  7 | 
  8 |                             Preamble
  9 | 
 10 |   The GNU General Public License is a free, copyleft license for
 11 | software and other kinds of works.
 12 | 
 13 |   The licenses for most software and other practical works are designed
 14 | to take away your freedom to share and change the works.  By contrast,
 15 | the GNU General Public License is intended to guarantee your freedom to
 16 | share and change all versions of a program--to make sure it remains free
 17 | software for all its users.  We, the Free Software Foundation, use the
 18 | GNU General Public License for most of our software; it applies also to
 19 | any other work released this way by its authors.  You can apply it to
 20 | your programs, too.
 21 | 
 22 |   When we speak of free software, we are referring to freedom, not
 23 | price.  Our General Public Licenses are designed to make sure that you
 24 | have the freedom to distribute copies of free software (and charge for
 25 | them if you wish), that you receive source code or can get it if you
 26 | want it, that you can change the software or use pieces of it in new
 27 | free programs, and that you know you can do these things.
 28 | 
 29 |   To protect your rights, we need to prevent others from denying you
 30 | these rights or asking you to surrender the rights.  Therefore, you have
 31 | certain responsibilities if you distribute copies of the software, or if
 32 | you modify it: responsibilities to respect the freedom of others.
 33 | 
 34 |   For example, if you distribute copies of such a program, whether
 35 | gratis or for a fee, you must pass on to the recipients the same
 36 | freedoms that you received.  You must make sure that they, too, receive
 37 | or can get the source code.  And you must show them these terms so they
 38 | know their rights.
 39 | 
 40 |   Developers that use the GNU GPL protect your rights with two steps:
 41 | (1) assert copyright on the software, and (2) offer you this License
 42 | giving you legal permission to copy, distribute and/or modify it.
 43 | 
 44 |   For the developers' and authors' protection, the GPL clearly explains
 45 | that there is no warranty for this free software.  For both users' and
 46 | authors' sake, the GPL requires that modified versions be marked as
 47 | changed, so that their problems will not be attributed erroneously to
 48 | authors of previous versions.
 49 | 
 50 |   Some devices are designed to deny users access to install or run
 51 | modified versions of the software inside them, although the manufacturer
 52 | can do so.  This is fundamentally incompatible with the aim of
 53 | protecting users' freedom to change the software.  The systematic
 54 | pattern of such abuse occurs in the area of products for individuals to
 55 | use, which is precisely where it is most unacceptable.  Therefore, we
 56 | have designed this version of the GPL to prohibit the practice for those
 57 | products.  If such problems arise substantially in other domains, we
 58 | stand ready to extend this provision to those domains in future versions
 59 | of the GPL, as needed to protect the freedom of users.
 60 | 
 61 |   Finally, every program is threatened constantly by software patents.
 62 | States should not allow patents to restrict development and use of
 63 | software on general-purpose computers, but in those that do, we wish to
 64 | avoid the special danger that patents applied to a free program could
 65 | make it effectively proprietary.  To prevent this, the GPL assures that
 66 | patents cannot be used to render the program non-free.
 67 | 
 68 |   The precise terms and conditions for copying, distribution and
 69 | modification follow.
 70 | 
 71 |                        TERMS AND CONDITIONS
 72 | 
 73 |   0. Definitions.
 74 | 
 75 |   "This License" refers to version 3 of the GNU General Public License.
 76 | 
 77 |   "Copyright" also means copyright-like laws that apply to other kinds of
 78 | works, such as semiconductor masks.
 79 | 
 80 |   "The Program" refers to any copyrightable work licensed under this
 81 | License.  Each licensee is addressed as "you".  "Licensees" and
 82 | "recipients" may be individuals or organizations.
 83 | 
 84 |   To "modify" a work means to copy from or adapt all or part of the work
 85 | in a fashion requiring copyright permission, other than the making of an
 86 | exact copy.  The resulting work is called a "modified version" of the
 87 | earlier work or a work "based on" the earlier work.
 88 | 
 89 |   A "covered work" means either the unmodified Program or a work based
 90 | on the Program.
 91 | 
 92 |   To "propagate" a work means to do anything with it that, without
 93 | permission, would make you directly or secondarily liable for
 94 | infringement under applicable copyright law, except executing it on a
 95 | computer or modifying a private copy.  Propagation includes copying,
 96 | distribution (with or without modification), making available to the
 97 | public, and in some countries other activities as well.
 98 | 
 99 |   To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies.  Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 | 
103 |   An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License.  If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 | 
112 |   1. Source Code.
113 | 
114 |   The "source code" for a work means the preferred form of the work
115 | for making modifications to it.  "Object code" means any non-source
116 | form of a work.
117 | 
118 |   A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 | 
123 |   The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form.  A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 | 
134 |   The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities.  However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work.  For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 | 
147 |   The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 | 
151 |   The Corresponding Source for a work in source code form is that
152 | same work.
153 | 
154 |   2. Basic Permissions.
155 | 
156 |   All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met.  This License explicitly affirms your unlimited
159 | permission to run the unmodified Program.  The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work.  This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 | 
164 |   You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force.  You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright.  Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 | 
175 |   Conveying under any other circumstances is permitted solely under
176 | the conditions stated below.  Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 | 
179 |   3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 | 
181 |   No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 | 
187 |   When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 | 
195 |   4. Conveying Verbatim Copies.
196 | 
197 |   You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 | 
205 |   You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 | 
208 |   5. Conveying Modified Source Versions.
209 | 
210 |   You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 | 
214 |     a) The work must carry prominent notices stating that you modified
215 |     it, and giving a relevant date.
216 | 
217 |     b) The work must carry prominent notices stating that it is
218 |     released under this License and any conditions added under section
219 |     7.  This requirement modifies the requirement in section 4 to
220 |     "keep intact all notices".
221 | 
222 |     c) You must license the entire work, as a whole, under this
223 |     License to anyone who comes into possession of a copy.  This
224 |     License will therefore apply, along with any applicable section 7
225 |     additional terms, to the whole of the work, and all its parts,
226 |     regardless of how they are packaged.  This License gives no
227 |     permission to license the work in any other way, but it does not
228 |     invalidate such permission if you have separately received it.
229 | 
230 |     d) If the work has interactive user interfaces, each must display
231 |     Appropriate Legal Notices; however, if the Program has interactive
232 |     interfaces that do not display Appropriate Legal Notices, your
233 |     work need not make them do so.
234 | 
235 |   A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit.  Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 | 
245 |   6. Conveying Non-Source Forms.
246 | 
247 |   You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 | 
252 |     a) Convey the object code in, or embodied in, a physical product
253 |     (including a physical distribution medium), accompanied by the
254 |     Corresponding Source fixed on a durable physical medium
255 |     customarily used for software interchange.
256 | 
257 |     b) Convey the object code in, or embodied in, a physical product
258 |     (including a physical distribution medium), accompanied by a
259 |     written offer, valid for at least three years and valid for as
260 |     long as you offer spare parts or customer support for that product
261 |     model, to give anyone who possesses the object code either (1) a
262 |     copy of the Corresponding Source for all the software in the
263 |     product that is covered by this License, on a durable physical
264 |     medium customarily used for software interchange, for a price no
265 |     more than your reasonable cost of physically performing this
266 |     conveying of source, or (2) access to copy the
267 |     Corresponding Source from a network server at no charge.
268 | 
269 |     c) Convey individual copies of the object code with a copy of the
270 |     written offer to provide the Corresponding Source.  This
271 |     alternative is allowed only occasionally and noncommercially, and
272 |     only if you received the object code with such an offer, in accord
273 |     with subsection 6b.
274 | 
275 |     d) Convey the object code by offering access from a designated
276 |     place (gratis or for a charge), and offer equivalent access to the
277 |     Corresponding Source in the same way through the same place at no
278 |     further charge.  You need not require recipients to copy the
279 |     Corresponding Source along with the object code.  If the place to
280 |     copy the object code is a network server, the Corresponding Source
281 |     may be on a different server (operated by you or a third party)
282 |     that supports equivalent copying facilities, provided you maintain
283 |     clear directions next to the object code saying where to find the
284 |     Corresponding Source.  Regardless of what server hosts the
285 |     Corresponding Source, you remain obligated to ensure that it is
286 |     available for as long as needed to satisfy these requirements.
287 | 
288 |     e) Convey the object code using peer-to-peer transmission, provided
289 |     you inform other peers where the object code and Corresponding
290 |     Source of the work are being offered to the general public at no
291 |     charge under subsection 6d.
292 | 
293 |   A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 | 
297 |   A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling.  In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage.  For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product.  A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 | 
310 |   "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source.  The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 | 
318 |   If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information.  But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 | 
329 |   The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed.  Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 | 
337 |   Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 | 
343 |   7. Additional Terms.
344 | 
345 |   "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law.  If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 | 
354 |   When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it.  (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.)  You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 | 
361 |   Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 | 
365 |     a) Disclaiming warranty or limiting liability differently from the
366 |     terms of sections 15 and 16 of this License; or
367 | 
368 |     b) Requiring preservation of specified reasonable legal notices or
369 |     author attributions in that material or in the Appropriate Legal
370 |     Notices displayed by works containing it; or
371 | 
372 |     c) Prohibiting misrepresentation of the origin of that material, or
373 |     requiring that modified versions of such material be marked in
374 |     reasonable ways as different from the original version; or
375 | 
376 |     d) Limiting the use for publicity purposes of names of licensors or
377 |     authors of the material; or
378 | 
379 |     e) Declining to grant rights under trademark law for use of some
380 |     trade names, trademarks, or service marks; or
381 | 
382 |     f) Requiring indemnification of licensors and authors of that
383 |     material by anyone who conveys the material (or modified versions of
384 |     it) with contractual assumptions of liability to the recipient, for
385 |     any liability that these contractual assumptions directly impose on
386 |     those licensors and authors.
387 | 
388 |   All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10.  If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term.  If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 | 
398 |   If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 | 
403 |   Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 | 
407 |   8. Termination.
408 | 
409 |   You may not propagate or modify a covered work except as expressly
410 | provided under this License.  Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 | 
415 |   However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 | 
422 |   Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 | 
429 |   Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License.  If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 | 
435 |   9. Acceptance Not Required for Having Copies.
436 | 
437 |   You are not required to accept this License in order to receive or
438 | run a copy of the Program.  Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance.  However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work.  These actions infringe copyright if you do
443 | not accept this License.  Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 | 
446 |   10. Automatic Licensing of Downstream Recipients.
447 | 
448 |   Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License.  You are not responsible
451 | for enforcing compliance by third parties with this License.
452 | 
453 |   An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations.  If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 | 
463 |   You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License.  For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 | 
471 |   11. Patents.
472 | 
473 |   A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based.  The
475 | work thus licensed is called the contributor's "contributor version".
476 | 
477 |   A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version.  For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 | 
487 |   Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 | 
492 |   In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement).  To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 | 
499 |   If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients.  "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 | 
513 |   If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 | 
521 |   A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License.  You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 | 
536 |   Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 | 
540 |   12. No Surrender of Others' Freedom.
541 | 
542 |   If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License.  If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all.  For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 | 
552 |   13. Use with the GNU Affero General Public License.
553 | 
554 |   Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work.  The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 | 
563 |   14. Revised Versions of this License.
564 | 
565 |   The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time.  Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 | 
570 |   Each version is given a distinguishing version number.  If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation.  If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 | 
579 |   If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 | 
584 |   Later license versions may give you additional or different
585 | permissions.  However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 | 
589 |   15. Disclaimer of Warranty.
590 | 
591 |   THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 | 
600 |   16. Limitation of Liability.
601 | 
602 |   IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 | 
612 |   17. Interpretation of Sections 15 and 16.
613 | 
614 |   If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 | 
621 |                      END OF TERMS AND CONDITIONS
622 | 
623 |             How to Apply These Terms to Your New Programs
624 | 
625 |   If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 | 
629 |   To do so, attach the following notices to the program.  It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 | 
634 |     <one line to give the program's name and a brief idea of what it does.>
635 |     Copyright (C) <year>  <name of author>
636 | 
637 |     This program is free software: you can redistribute it and/or modify
638 |     it under the terms of the GNU General Public License as published by
639 |     the Free Software Foundation, either version 3 of the License, or
640 |     (at your option) any later version.
641 | 
642 |     This program is distributed in the hope that it will be useful,
643 |     but WITHOUT ANY WARRANTY; without even the implied warranty of
644 |     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
645 |     GNU General Public License for more details.
646 | 
647 |     You should have received a copy of the GNU General Public License
648 |     along with this program.  If not, see <http://www.gnu.org/licenses/>.
649 | 
650 | Also add information on how to contact you by electronic and paper mail.
651 | 
652 |   If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 | 
655 |     <program>  Copyright (C) <year>  <name of author>
656 |     This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 |     This is free software, and you are welcome to redistribute it
658 |     under certain conditions; type `show c' for details.
659 | 
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License.  Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 | 
664 |   You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | <http://www.gnu.org/licenses/>.
668 | 
669 |   The GNU General Public License does not permit incorporating your program
670 | into proprietary programs.  If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library.  If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License.  But first, please read
674 | <http://www.gnu.org/philosophy/why-not-lgpl.html>.
675 | 


--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
 1 | db:
 2 | 	docker-compose up -d db
 3 | 
 4 | stop-db:
 5 | 	docker-compose stop db
 6 | 
 7 | test: db
 8 | 	export POSTGRES_USER=postgres && export POSTGRES_PASSWORD=postgres && export POSTGRES_URL=localhost:5432/postgres && mvn test;
 9 | 
10 | publish:
11 | 	mvn -DskipTests clean deploy
12 | 


--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
  1 | # Wire™
  2 | 
  3 | [![Wire logo](https://github.com/wireapp/wire/blob/master/assets/header-small.png?raw=true)](https://wire.com/jobs/)
  4 | 
  5 | ## Lithium
  6 | 
  7 | [![Build Status](https://travis-ci.org/wireapp/lithium.svg?branch=master)](https://travis-ci.org/wireapp/lithium)
  8 | 
  9 | - Lithium is Wire Services SDK written in Java
 10 | 
 11 | ## How to use it to build your bots?
 12 | - In your `pom.xml`:
 13 | ```
 14 | <dependencies>
 15 |     <dependency>
 16 |         <groupId>com.wire</groupId>
 17 |         <artifactId>lithium</artifactId>
 18 |         <version>3.5.5</version>
 19 |     </dependency>
 20 | <dependencies>
 21 | ```
 22 | 
 23 | If you want to use [Version]() resource (API endpoint), you must create version file during the build.
 24 | For example, during the Docker build, one can put following code inside `Dockerfile`:
 25 | ```dockerfile
 26 | # create version file
 27 | ARG release_version=development
 28 | ENV RELEASE_FILE_PATH=/path/to/release.txt
 29 | RUN echo $release_version > $RELEASE_FILE_PATH
 30 | ```
 31 | And than add build argument ie. in the build pipeline 
 32 | [like that](https://github.com/dkovacevic/roman/blob/8d41bcba20a8f7607210263944c9ccecd757ed44/.github/workflows/release.yml#L26).
 33 | 
 34 | ### Tutorial:
 35 | - [Echo Bot](https://github.com/wireapp/echo-bot)
 36 | 
 37 | ## Bot API Documentation
 38 | 
 39 | - [API Documentation](https://github.com/wireapp/bot-sdk/wiki).
 40 | 
 41 | ## How to build the project
 42 | 
 43 | Requirements:
 44 | 
 45 | - [Java >= 11](http://www.oracle.com)
 46 | - [Maven](https://maven.apache.org)
 47 | - [Cryptobox4j](https://github.com/wireapp/cryptobox4j)
 48 | 
 49 | To build the library, run:
 50 | 
 51 | ```bash
 52 | mvn install -DskipTests
 53 | ```
 54 | 
 55 | ## How to register your service with Wire
 56 | 
 57 | The `manage.sh` script helps you register as a service provider, create a certificate, and register your service instance.
 58 | 
 59 | ### Script requirements
 60 | 
 61 | - [Bash](https://www.gnu.org/software/bash)
 62 | - [jq](https://stedolan.github.io/jq/)
 63 | - [cURL](https://curl.haxx.se/)
 64 | 
 65 | ### How to use the script
 66 | 
 67 | In order to register a service, you need to generate a certificate (or bring your own), register as a provider and then register the service.
 68 | 
 69 | Using the `manage.sh` script:
 70 | 
 71 | - Register as a provider with `manage.sh new-provider`. If everything goes well, the response will contain a password and provider ID, and you should get an email. Open the email and follow the link in the email to confirm your identity. You need to do this only once, even when developing multiple services. This will save the credentials in the local folder, for further authentication.
 72 | - If you don't have a certificate already, create a new certificate with `manage.sh new-cert` and follow the instructions. This needs to match the certificate that is used for the SSL termination on your service.
 73 | - Deploy your service and make it accessible by public IP, using HTTPS and the certificate you created at step one.
 74 | - Obtain an authentication token with `manage.sh auth-provider`. This is a temporary token to perform authenticated requests, and will need to be refreshed periodically if you don't use the script for more than 10 minutes.
 75 | - Register a new service with `manage.sh new-service` and enter the required information. Make sure the base URL is an `https` URL. You will receive an service auth token.
 76 | - Once a server is created, you can update it with `manage.sh update-service`. 
 77 | - Edit the YAML configuration file of your service and add the service token you received at the previous step.
 78 | - (Re)-start the service with the new configuration file.
 79 | - Activate the service with `manage.sh update-service-conn` to make it _enabled_
 80 | 
 81 | ## Use Hello World sample service as your first service
 82 | 
 83 | - [Hello World](https://github.com/wireapp/echo-bot)
 84 | 
 85 | ## Environment variables used:
 86 | - `WIRE_API_HOST`: Wire Backend. `https://prod-nginz-https.wire.com` by default
 87 | - `SERVICE_TOKEN`: Your service authentication token. All requests sent by the BE will have this token as Bearer Authorization HTTP header
 88 | 
 89 | ## Logging to JSON
 90 | Wire uses JSON logging in the production. To enable JSON logging one must specify `json-console` appender in the Dropwizard yaml.
 91 | ```yaml
 92 | logging:
 93 |   appenders:
 94 |     - type: json-console
 95 | ```
 96 | 
 97 | ## Other examples of Wire Services
 98 | 
 99 | - [Hello World](https://github.com/wireapp/echo-bot)
100 | - [GitHub-bot](https://github.com/wearezeta/github-bot)
101 | - [GitLab-bot](https://github.com/wireapp/gitlab)
102 | - [Alert-bot](https://github.com/wireapp/alert-bot)
103 | - [Texas Holdem](https://github.com/dkovacevic/holdem)
104 | - [Broadcast-bot](https://github.com/wireapp/broadcast-bot)
105 | - [Channel-bot](https://github.com/dkovacevic/channel-bot)
106 | - [Don](https://github.com/wireapp/don-bot)
107 | - [Recording-bot](https://github.com/wireapp/recording-bot)
108 | 
109 | ## Other implementations of Bot API
110 | 
111 | - [Node.js](https://github.com/wireapp/bot-sdk-node) Wire Services SDK in Node.js
112 | - [Beryllium](https://github.com/OmnijarBots/beryllium) Wire Services SDK in Rust
113 | 


--------------------------------------------------------------------------------
/docker-compose.yml:
--------------------------------------------------------------------------------
 1 | version: '3.8'
 2 | services:
 3 |   db:
 4 |     image: postgres:15
 5 |     environment:
 6 |       - POSTGRES_USER=postgres
 7 |       - POSTGRES_PASSWORD=postgres
 8 |       - POSTGRES_DB=postgres
 9 |     ports:
10 |       - "5432:5432"
11 | 


--------------------------------------------------------------------------------
/manage.sh:
--------------------------------------------------------------------------------
  1 | #!/bin/bash
  2 | set -e
  3 | 
  4 | PROGNAME=$(basename "$0")
  5 | REQUIRED_TOOLS="jq curl"
  6 | 
  7 | ################################################################################
  8 | # Functions
  9 | 
 10 | die() {
 11 |     echo "$PROGNAME: $*" >&2
 12 |     exit 1
 13 | }
 14 | 
 15 | usage() {
 16 |     if [ "$*" != "" ]; then
 17 |         echo "Error: $*"
 18 |     fi
 19 | 
 20 |     cat << EOF
 21 | Usage: $PROGNAME [OPTION ...] [command]
 22 | Service Provider Utility
 23 | 
 24 | Commands:
 25 | new-provider        Register a new provider.
 26 | auth-provider       Authenticate as a provider.
 27 | get-provider        Get the provider profile.
 28 | update-provider     Update the provider profile.
 29 | delete-provider     Delete the provider.
 30 | list-services       List services.
 31 | new-service         Add a new service.
 32 | get-service         Get a service.
 33 | update-service      Update a service profile.
 34 | update-service-conn Update a service connection.
 35 | delete-service      Delete a service.
 36 | new-cert            Generate a new self-signed certificate.
 37 | 
 38 | Options:
 39 | -h, --help          Display this help text and exit.
 40 | -e, --env           Environment to use [edge].
 41 | EOF
 42 | 
 43 |     exit 1
 44 | }
 45 | 
 46 | check_tools() {
 47 |     for TOOL in $REQUIRED_TOOLS; do
 48 |         if ! command -v "$TOOL" > /dev/null; then
 49 |             echo "Could not find $TOOL! Exiting."
 50 |             exit 1
 51 |         fi
 52 |     done
 53 | }
 54 | 
 55 | check_auth() {
 56 |     if [ ! -f "./.cookie" ]; then
 57 |         echo "Not authenticated. Use the 'auth-provider' command."
 58 |         exit 1
 59 |     fi
 60 | }
 61 | 
 62 | authenticate() {
 63 |     read -p "Local identifier [default: $zident]: " auth_ident
 64 |     if [ -z "$auth_ident" ]; then
 65 |         auth_ident="$zident"
 66 |     fi
 67 |     if [ ! -d "$auth_ident" ]; then
 68 |         echo "Invalid identifier. Directory not found: $auth_ident"
 69 |         exit 1
 70 |     fi
 71 |     auth_email=$(< "$auth_ident/.email")
 72 |     auth_password=$(< "$auth_ident/.password")
 73 |     curl -s -XPOST "$zapi/provider/login" \
 74 |         -H 'Content-Type: application/json' \
 75 |         -d '{"email":"'"$auth_email"'"
 76 |             ,"password":"'"$auth_password"'"}' \
 77 |         -c ./.cookie
 78 |     echo "$auth_ident" > .current
 79 |     echo "Authenticated as $auth_email"
 80 | }
 81 | 
 82 | new_provider() {
 83 |     read -p "Local identifier [default: $zident]: " provider_ident
 84 |     if [ -z "$provider_ident" ]; then
 85 |         provider_ident="$zident"
 86 |     fi
 87 |     if [ -d "$provider_ident" ]; then
 88 |         echo "Directory exists: $provider_ident"
 89 |         exit 1
 90 |     fi
 91 | 
 92 |     read -p "Provider name: " provider_name
 93 |     read -p "Provider email: " provider_email
 94 |     read -p "Provider homepage: " provider_url
 95 |     read -p "Provider description: " provider_descr
 96 | 
 97 |     echo "Creating directory $provider_ident ..."
 98 |     mkdir ${provider_ident}
 99 |     echo "Registering $provider_name ..."
100 |     resp=$(curl -s -X POST "$zapi/provider/register" \
101 |         -H 'Content-Type: application/json' \
102 |         -d '{"name": "'"$provider_name"'",
103 |              "email": "'"$provider_email"'",
104 |              "url": "'"$provider_url"'",
105 |              "description": "'"$provider_descr"'"
106 |             }')
107 |     echo "$resp"
108 |     echo "$resp" | jq -r '.password' > ${provider_ident}/.password
109 |     echo "$provider_email" > ${provider_ident}/.email
110 |     echo "Done. Please check your e-mail."
111 | }
112 | 
113 | get_provider() {
114 |     check_auth
115 |     curl -s -XGET "$zapi/provider" -b ./.cookie | jq .
116 | }
117 | 
118 | update_provider() {
119 |     check_auth
120 |     read -p "New provider name [default: no change]: " new_name
121 |     read -p "New provider URL [default: no change]: " new_url
122 |     read -p "New provider description [default: no change]: " new_descr
123 |     if [ -z "$new_name" ]; then
124 |         new_name="null"
125 |     else
126 |         new_name="\"$new_name\""
127 |     fi
128 |     if [ -z "$new_url" ]; then
129 |         new_url="null"
130 |     else
131 |         new_url="\"$new_url\""
132 |     fi
133 |     if [ -z "$new_descr" ]; then
134 |         new_descr="null"
135 |     else
136 |         new_descr="\"$new_descr\""
137 |     fi
138 |     echo "Updating provider profile ..."
139 |     curl -s -XPUT "$zapi/provider" \
140 |         -H 'Content-Type: application/json' \
141 |         -d '{"name": '"$new_name"',
142 |              "url": '"$new_url"',
143 |              "description": '"$new_descr"'
144 |             }' \
145 |         -b ./.cookie
146 |     echo "Done"
147 | }
148 | 
149 | delete_provider() {
150 |     check_auth
151 |     auth_ident=$(read_ident)
152 |     auth_password=$(read_password)
153 |     read -p "Are you sure (yN)? " yn
154 |     if [ "$yn" == "y" ] ; then
155 |         echo "Deleting provider ..."
156 |         curl -s -XDELETE "$zapi/provider" \
157 |             -H 'Content-Type: application/json' \
158 |             -d '{"password": "'"$auth_password"'"}' \
159 |             -b ./.cookie
160 |         rm -f ./.current
161 |         rm -f ./.cookie
162 |         rm -rf "$auth_ident"
163 |         echo "Done"
164 |     fi
165 | }
166 | 
167 | new_service() {
168 |     check_auth
169 |     read -p "Service name: " service_name
170 |     read -p "Service description: " service_descr
171 |     read -p "Service summary: " service_summary
172 |     read -p "Service base URL: " service_base_url
173 |     read -p "Service RSA public key file: " service_pubkey_file
174 | 
175 |     service_pubkey=$(< "$service_pubkey_file")
176 | 
177 |     echo "Registering service $service_name ..."
178 |     curl -s -XPOST "$zapi/provider/services" \
179 |         -H 'Content-Type: application/json' \
180 |         -d '{"name": "'"$service_name"'",
181 |              "description": "'"$service_descr"'",
182 |              "summary": "'"$service_summary"'",
183 |              "base_url": "'"$service_base_url"'",
184 |              "public_key": "'"$service_pubkey"'",
185 |              "tags": ["tutorial"]
186 |             }' \
187 |         -b ./.cookie \
188 |         | jq .
189 |     echo "Done"
190 | }
191 | 
192 | get_service() {
193 |     check_auth
194 |     read -p "Service ID: " service_id
195 |     curl -s -XGET "$zapi/provider/services/$service_id" -b ./.cookie | jq .
196 | }
197 | 
198 | list_services() {
199 |     check_auth
200 |     curl -s -XGET "$zapi/provider/services" -b ./.cookie | jq .
201 | }
202 | 
203 | update_service() {
204 |     check_auth
205 |     read -p "Service ID: " service_id
206 |     read -p "New service name [default: no change]: " new_name
207 |     read -p "New service description [default: no change]: " new_descr
208 |     read -p "New service summary [default: no change]: " new_summary
209 |     if [ -z "$new_name" ]; then
210 |         new_name="null"
211 |     else
212 |         new_name="\"$new_name\""
213 |     fi
214 |     if [ -z "$new_descr" ]; then
215 |         new_descr="null"
216 |     else
217 |         new_descr="\"$new_descr\""
218 |     fi
219 |     if [ -z "$new_summary" ]; then
220 |         new_summary="null"
221 |     else
222 |         new_summary="\"$new_summary\""
223 |     fi
224 |     echo "Updating service profile ..."
225 |     curl -s -XPUT "$zapi/provider/services/$service_id" \
226 |         -H 'Content-Type: application/json' \
227 |         -d '{"name": '"$new_name"',
228 |              "description": '"$new_descr"',
229 |              "summary": '"$new_summary"'
230 |             }' \
231 |         -b ./.cookie
232 |     echo "Done"
233 | }
234 | 
235 | update_service_conn() {
236 |     check_auth
237 |     read -p "Service ID: " service_id
238 |     read -p "New service base URL [default: no change]: " new_base_url
239 |     read -p "New service auth token [default: no change]: " new_auth_token
240 |     read -p "New service public key (file) [default: no change]: " new_pubkey_file
241 |     read -p "New service enabled status (true|false) [default: no change]: " new_enabled
242 |     if [ -z "$new_base_url" ]; then
243 |         new_base_url="null"
244 |     else
245 |         new_base_url="\"$new_base_url\""
246 |     fi
247 |     if [ -z "$new_auth_token" ]; then
248 |         new_auth_tokens="null"
249 |     else
250 |         new_auth_tokens="[\"$new_auth_token\"]"
251 |     fi
252 |     if [ -z "$new_pubkey_file" ]; then
253 |         new_pubkeys="null"
254 |     else
255 |         new_pubkey=$(< "$new_pubkey_file")
256 |         new_pubkeys="[\"$new_pubkey\"]"
257 |     fi
258 |     if [ -z "$new_enabled" ]; then
259 |         new_enabled="null"
260 |     fi
261 |     auth_password=$(read_password)
262 |     echo "Updating service connection data ..."
263 |     curl -s -XPUT "$zapi/provider/services/$service_id/connection" \
264 |         -H 'Content-Type: application/json' \
265 |         -d '{"base_url": '"$new_base_url"',
266 |              "auth_tokens": '"$new_auth_tokens"',
267 |              "public_keys": '"$new_pubkeys"',
268 |              "enabled": '"$new_enabled"',
269 |              "password": "'"$auth_password"'"
270 |             }' \
271 |         -b ./.cookie \
272 |         | jq .
273 |     echo "Done"
274 | }
275 | 
276 | delete_service() {
277 |     check_auth
278 |     read -p "Service ID: " service_id
279 |     auth_password=$(read_password)
280 |     echo "Deleting service $service_id ..."
281 |     curl -s -XDELETE "$zapi/provider/services/$service_id" \
282 |         -H 'Content-Type: application/json' \
283 |         -d '{"password": "'"$auth_password"'"}' \
284 |         -b ./.cookie
285 |     echo "Done"
286 | }
287 | 
288 | new_cert() {
289 |     read -p "Target directory: " cert_dir
290 |     mkdir -p "$cert_dir"
291 |     echo "Writing RSA key pair to $cert_dir/key.pem"
292 |     openssl genrsa -out "$cert_dir/key.pem" 4096
293 |     echo "Writing CSR to $cert_dir/csr.pem"
294 |     openssl req -new -key "$cert_dir/key.pem" -out "$cert_dir/csr.pem"
295 |     echo "Writing self-signed certificate to $cert_dir/cert.pem"
296 |     openssl x509 -req -days 7300 -in "$cert_dir/csr.pem" -signkey "$cert_dir/key.pem" -out "$cert_dir/cert.pem"
297 |     echo "Writing RSA public key to $cert_dir/pubkey.pem"
298 |     openssl rsa -in "$cert_dir/key.pem" -pubout -out "$cert_dir/pubkey.pem"
299 | }
300 | 
301 | read_ident() {
302 |     cat ./.current
303 | }
304 | 
305 | read_password() {
306 |     auth_ident=$(< .current)
307 |     cat "$auth_ident/.password"
308 | }
309 | 
310 | ################################################################################
311 | # Program
312 | 
313 | check_tools
314 | 
315 | zident=$(whoami)
316 | zcmd=""
317 | zenv="prod"
318 | while [ $# -gt 0 ]; do
319 |     case "$1" in
320 |     -h|--help)
321 |         usage
322 |         ;;
323 |     -e|--env)
324 |         zenv="$2"
325 |         shift
326 |         ;;
327 |     -*)
328 |         usage "Unknown option '$1'"
329 |         ;;
330 |     *)
331 |         if [ -z "$zcmd" ] ; then
332 |             zcmd="$1"
333 |         else
334 |             usage "Too many arguments"
335 |         fi
336 |         ;;
337 |     esac
338 |     shift
339 | done
340 | 
341 | if [ $zenv = prod ]; then
342 |    zdomain=wire.com
343 | else
344 |    zdomain=zinfra.io
345 | fi
346 | 
347 | if [ -z "$zcmd" ] ; then
348 |     usage "Not enough arguments"
349 | fi
350 | 
351 | zapi="https://${zenv}-nginz-https.${zdomain}"
352 | 
353 | case "$zcmd" in
354 |     "new-provider") new_provider ;;
355 |     "auth-provider") authenticate ;;
356 |     "get-provider") get_provider ;;
357 |     "update-provider") update_provider ;;
358 |     "delete-provider") delete_provider ;;
359 |     "new-service") new_service ;;
360 |     "list-services") list_services ;;
361 |     "get-service") get_service ;;
362 |     "update-service") update_service ;;
363 |     "update-service-conn") update_service_conn ;;
364 |     "delete-service") delete_service ;;
365 |     "new-cert") new_cert ;;
366 |     *) echo "Unknown command: $zcmd" ;;
367 | esac
368 | 
369 | 


--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
  1 | <?xml version="1.0" encoding="UTF-8"?>
  2 | <project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3 |          xmlns="http://maven.apache.org/POM/4.0.0"
  4 |          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5 |     <modelVersion>4.0.0</modelVersion>
  6 | 
  7 |     <groupId>com.wire</groupId>
  8 |     <artifactId>lithium</artifactId>
  9 |     <version>3.6.5</version>
 10 |     <name>Lithium</name>
 11 |     <description>Wire Bots SDK written in Java</description>
 12 |     <url>https://wire.com/</url>
 13 | 
 14 |     <licenses>
 15 |         <license>
 16 |             <name>GNU General Public License v3.0</name>
 17 |             <url>https://www.gnu.org/licenses/gpl-3.0.en.html</url>
 18 |             <distribution>repo</distribution>
 19 |         </license>
 20 |     </licenses>
 21 | 
 22 |     <developers>
 23 |         <developer>
 24 |             <name>Dejan Kovacevic</name>
 25 |             <email>dejan@wire.com</email>
 26 |             <organization>Wire Swiss GmbH</organization>
 27 |             <organizationUrl>https://wire.com</organizationUrl>
 28 |             <timezone>UTC+01:00</timezone>
 29 |         </developer>
 30 |         <developer>
 31 |             <name>Lukas Forst</name>
 32 |             <email>lukas@wire.com</email>
 33 |             <organization>Wire Swiss GmbH</organization>
 34 |             <organizationUrl>https://wire.com</organizationUrl>
 35 |             <timezone>UTC+01:00</timezone>
 36 |         </developer>
 37 |         <developer>
 38 |             <name>Yamil Medina</name>
 39 |             <email>yamil@wire.com</email>
 40 |             <organization>Wire Swiss GmbH</organization>
 41 |             <organizationUrl>https://wire.com</organizationUrl>
 42 |             <timezone>UTC+01:00</timezone>
 43 |         </developer>
 44 |     </developers>
 45 | 
 46 |     <scm>
 47 |         <url>https://github.com/wireapp/lithium</url>
 48 |     </scm>
 49 | 
 50 |     <properties>
 51 |         <maven.compiler.source>11</maven.compiler.source>
 52 |         <maven.compiler.target>11</maven.compiler.target>
 53 |         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 54 |         <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
 55 |         <maven.test.skip>true</maven.test.skip>
 56 |         <!-- BEFORE UPGRADING! VERIFY RUNTIME PG VERSION COMPATIBILITY -->
 57 |         <flyway.version>7.15.0</flyway.version>
 58 |         <dropwizard.version>4.0.0</dropwizard.version>
 59 |         <jakarta.version>2.1.1</jakarta.version>
 60 |     </properties>
 61 | 
 62 |     <repositories>
 63 |         <!-- to fetch specific version of dropwizard-swagger dependency -->
 64 |         <repository>
 65 |             <id>jitpack.io</id>
 66 |             <url>https://jitpack.io</url>
 67 |         </repository>
 68 |     </repositories>
 69 | 
 70 |     <dependencyManagement>
 71 |         <dependencies>
 72 |             <dependency>
 73 |                 <groupId>io.dropwizard</groupId>
 74 |                 <artifactId>dropwizard-bom</artifactId>
 75 |                 <version>${dropwizard.version}</version>
 76 |                 <type>pom</type>
 77 |                 <scope>import</scope>
 78 |             </dependency>
 79 |         </dependencies>
 80 |     </dependencyManagement>
 81 | 
 82 |     <dependencies>
 83 |         <dependency>
 84 |             <groupId>com.wire</groupId>
 85 |             <artifactId>xenon</artifactId>
 86 |             <version>1.5.5</version>
 87 |             <exclusions>
 88 |                 <exclusion>
 89 |                     <groupId>org.slf4j</groupId>
 90 |                     <artifactId>slf4j-log4j12</artifactId>
 91 |                 </exclusion>
 92 |                 <exclusion>
 93 |                     <groupId>log4j</groupId>
 94 |                     <artifactId>log4j</artifactId>
 95 |                 </exclusion>
 96 |             </exclusions>
 97 |         </dependency>
 98 |         <dependency>
 99 |             <groupId>io.dropwizard</groupId>
100 |             <artifactId>dropwizard-core</artifactId>
101 |             <scope>provided</scope>
102 |         </dependency>
103 |         <dependency>
104 |             <groupId>io.dropwizard</groupId>
105 |             <artifactId>dropwizard-jdbi3</artifactId>
106 |             <scope>provided</scope>
107 |         </dependency>
108 |         <dependency>
109 |             <groupId>io.dropwizard</groupId>
110 |             <artifactId>dropwizard-client</artifactId>
111 |             <scope>provided</scope>
112 |         </dependency>
113 |         <dependency>
114 |             <groupId>org.postgresql</groupId>
115 |             <artifactId>postgresql</artifactId>
116 |             <version>42.6.0</version>
117 |         </dependency>
118 |         <dependency>
119 |             <groupId>org.flywaydb</groupId>
120 |             <artifactId>flyway-core</artifactId>
121 |             <version>${flyway.version}</version>
122 |         </dependency>
123 |         <dependency>
124 |             <groupId>jakarta.annotation</groupId>
125 |             <artifactId>jakarta.annotation-api</artifactId>
126 |             <version>${jakarta.version}</version>
127 |         </dependency>
128 |         <dependency>
129 |             <groupId>jakarta.validation</groupId>
130 |             <artifactId>jakarta.validation-api</artifactId>
131 |             <version>3.0.2</version>
132 |         </dependency>
133 |         <dependency>
134 |             <groupId>com.smoketurner</groupId>
135 |             <artifactId>dropwizard-swagger</artifactId>
136 |             <version>4.0.0-1</version>
137 |         </dependency>
138 |         <dependency>
139 |             <groupId>io.swagger</groupId>
140 |             <artifactId>swagger-annotations</artifactId>
141 |             <version>1.6.13</version>
142 |         </dependency>
143 | 
144 | 
145 |         <dependency>
146 |             <groupId>io.dropwizard</groupId>
147 |             <artifactId>dropwizard-testing</artifactId>
148 |             <scope>test</scope>
149 |         </dependency>
150 |         <dependency>
151 |             <groupId>org.assertj</groupId>
152 |             <artifactId>assertj-core</artifactId>
153 |             <version>3.24.2</version>
154 |             <scope>test</scope>
155 |         </dependency>
156 |         <dependency>
157 |             <groupId>org.junit.jupiter</groupId>
158 |             <artifactId>junit-jupiter</artifactId>
159 |             <version>5.9.2</version>
160 |             <scope>test</scope>
161 |         </dependency>
162 |         <dependency>
163 |             <groupId>org.junit.jupiter</groupId>
164 |             <artifactId>junit-jupiter-engine</artifactId>
165 |             <version>5.10.1</version>
166 |             <scope>test</scope>
167 |         </dependency>
168 |     </dependencies>
169 | 
170 |     <packaging>jar</packaging>
171 |     <build>
172 |         <finalName>lithium</finalName>
173 |         <plugins>
174 |             <plugin>
175 |                 <groupId>org.sonatype.central</groupId>
176 |                 <artifactId>central-publishing-maven-plugin</artifactId>
177 |                 <version>0.7.0</version>
178 |                 <extensions>true</extensions>
179 |                 <configuration>
180 |                     <publishingServerId>central</publishingServerId>
181 |                     <autoPublish>true</autoPublish>
182 |                 </configuration>
183 |             </plugin>
184 |             <plugin>
185 |                 <groupId>org.apache.maven.plugins</groupId>
186 |                 <artifactId>maven-source-plugin</artifactId>
187 |                 <version>3.2.1</version>
188 |                 <executions>
189 |                     <execution>
190 |                         <id>attach-sources</id>
191 |                         <goals>
192 |                             <goal>jar-no-fork</goal>
193 |                         </goals>
194 |                     </execution>
195 |                 </executions>
196 |             </plugin>
197 |             <plugin>
198 |                 <groupId>org.apache.maven.plugins</groupId>
199 |                 <artifactId>maven-javadoc-plugin</artifactId>
200 |                 <version>3.6.0</version>
201 |                 <executions>
202 |                     <execution>
203 |                         <id>attach-javadocs</id>
204 |                         <goals>
205 |                             <goal>jar</goal>
206 |                         </goals>
207 |                     </execution>
208 |                 </executions>
209 |             </plugin>
210 |             <plugin>
211 |                 <groupId>org.apache.maven.plugins</groupId>
212 |                 <artifactId>maven-gpg-plugin</artifactId>
213 |                 <version>3.0.1</version>
214 |                 <configuration>
215 |                     <!-- Prevent gpg from using pinentry programs -->
216 |                     <gpgArguments>
217 |                         <arg>--pinentry-mode</arg>
218 |                         <arg>loopback</arg>
219 |                     </gpgArguments>
220 |                 </configuration>
221 |                 <executions>
222 |                     <execution>
223 |                         <id>sign-artifacts</id>
224 |                         <phase>verify</phase>
225 |                         <goals>
226 |                             <goal>sign</goal>
227 |                         </goals>
228 |                     </execution>
229 |                 </executions>
230 |             </plugin>
231 |             <!--             running the JUnit 5 tests -->
232 |             <plugin>
233 |                 <groupId>org.apache.maven.plugins</groupId>
234 |                 <artifactId>maven-surefire-plugin</artifactId>
235 |                 <version>3.1.2</version>
236 |             </plugin>
237 |         </plugins>
238 |     </build>
239 | </project>
240 | 


--------------------------------------------------------------------------------
/src/main/java/com/wire/blender/Blender.java:
--------------------------------------------------------------------------------
 1 | package com.wire.blender;
 2 | 
 3 | import java.util.ArrayList;
 4 | import java.util.List;
 5 | 
 6 | public class Blender {
 7 |     static {
 8 |         System.loadLibrary("blender"); // Load native library at runtime
 9 |     }
10 |     
11 |     private final List<BlenderListener> listeners = new ArrayList<>();
12 |     private long blenderPointer;
13 | 
14 |     public void log(String msg) {
15 |     }
16 | 
17 |     public void registerListener(BlenderListener listener) {
18 |         listeners.add(listener);
19 |     }
20 | 
21 |     private void onCallingMessage(String id,
22 |                                   String userId,
23 |                                   String clientId,
24 |                                   String peerId,
25 |                                   String peerClientId,
26 |                                   String content,
27 |                                   boolean trans) {
28 | 
29 |         for (BlenderListener listener : listeners) {
30 |             listener.onCallingMessage(id,
31 |                     userId,
32 |                     clientId,
33 |                     peerId,
34 |                     peerClientId,
35 |                     content,
36 |                     trans);
37 |         }
38 |     }
39 | 
40 |     private void onConfigRequest() {
41 |     }
42 | 
43 |     public native void recvMessage(String convId, String userId,
44 |                                    String clientId, String content);
45 | 
46 |     public native void init(String name, String userId, String clientId,
47 |                             String localAddress, int minPort, int maxPort);
48 | }
49 | 


--------------------------------------------------------------------------------
/src/main/java/com/wire/blender/BlenderListener.java:
--------------------------------------------------------------------------------
 1 | package com.wire.blender;
 2 | 
 3 | public interface BlenderListener {
 4 |     void onCallingMessage(String id,
 5 |                           String userId,
 6 |                           String clientId,
 7 |                           String peerId,
 8 |                           String peerClientId,
 9 |                           String content,
10 |                           boolean trans);
11 | }
12 | 
13 | 


--------------------------------------------------------------------------------
/src/main/java/com/wire/lithium/API.java:
--------------------------------------------------------------------------------
  1 | //
  2 | // Wire
  3 | // Copyright (C) 2016 Wire Swiss GmbH
  4 | //
  5 | // This program is free software: you can redistribute it and/or modify
  6 | // it under the terms of the GNU General Public License as published by
  7 | // the Free Software Foundation, either version 3 of the License, or
  8 | // (at your option) any later version.
  9 | //
 10 | // This program is distributed in the hope that it will be useful,
 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 13 | // GNU General Public License for more details.
 14 | //
 15 | // You should have received a copy of the GNU General Public License
 16 | // along with this program. If not, see http://www.gnu.org/licenses/.
 17 | //
 18 | 
 19 | package com.wire.lithium;
 20 | 
 21 | import com.fasterxml.jackson.annotation.JsonProperty;
 22 | import com.wire.lithium.models.NewBotResponseModel;
 23 | import com.wire.xenon.Const;
 24 | import com.wire.xenon.WireAPI;
 25 | import com.wire.xenon.assets.IAsset;
 26 | import com.wire.xenon.backend.models.Conversation;
 27 | import com.wire.xenon.backend.models.User;
 28 | import com.wire.xenon.exceptions.HttpException;
 29 | import com.wire.xenon.models.AssetKey;
 30 | import com.wire.xenon.models.otr.*;
 31 | import com.wire.xenon.tools.Logger;
 32 | import com.wire.xenon.tools.Util;
 33 | import jakarta.annotation.Nullable;
 34 | import jakarta.ws.rs.NotSupportedException;
 35 | import jakarta.ws.rs.client.Client;
 36 | import jakarta.ws.rs.client.Entity;
 37 | import jakarta.ws.rs.client.Invocation;
 38 | import jakarta.ws.rs.client.WebTarget;
 39 | import jakarta.ws.rs.core.*;
 40 | import org.glassfish.jersey.client.ClientProperties;
 41 | import org.glassfish.jersey.logging.LoggingFeature;
 42 | 
 43 | import java.io.ByteArrayOutputStream;
 44 | import java.io.IOException;
 45 | import java.net.URI;
 46 | import java.nio.charset.StandardCharsets;
 47 | import java.util.*;
 48 | import java.util.logging.Level;
 49 | 
 50 | public class API implements WireAPI {
 51 |     private final String wireHost;
 52 | 
 53 |     private final WebTarget messages;
 54 |     private final WebTarget assets;
 55 |     private final WebTarget client;
 56 |     private final WebTarget prekeys;
 57 |     private final WebTarget users;
 58 |     private final WebTarget conversation;
 59 |     private final WebTarget bot;
 60 | 
 61 |     private final Client httpClient;
 62 |     private final String token;
 63 | 
 64 |     public API(Client httpClient, String token) {
 65 |         this(httpClient, token, deriveHost());
 66 |     }
 67 | 
 68 |     public API(Client httpClient, String token, String wireHost) {
 69 |         this.httpClient = httpClient;
 70 |         this.token = token;
 71 | 
 72 |         this.wireHost = wireHost;
 73 | 
 74 |         bot = httpClient
 75 |                 .target(wireHost)
 76 |                 .path("bot");
 77 |         messages = bot
 78 |                 .path("messages");
 79 |         assets = bot
 80 |                 .path("assets");
 81 |         users = bot
 82 |                 .path("users");
 83 |         conversation = bot
 84 |                 .path("conversation");
 85 |         client = bot
 86 |                 .path("client")
 87 |                 .path("prekeys");
 88 |         prekeys = users
 89 |                 .path("prekeys");
 90 | 
 91 |         if (Logger.getLevel() == Level.FINE) {
 92 |             Feature feature = new LoggingFeature(Logger.getLOGGER(), Level.FINE, null, null);
 93 |             assets.register(feature);
 94 |             users.register(feature);
 95 |         }
 96 |     }
 97 | 
 98 |     private static String deriveHost() {
 99 |         String host = System.getProperty(Const.WIRE_BOTS_SDK_API, System.getenv("WIRE_API_HOST"));
100 |         return host != null ? host : "https://prod-nginz-https.wire.com";
101 |     }
102 | 
103 |     public Response status() {
104 |         URI uri = URI.create(wireHost);
105 |         String scheme = uri.getScheme();
106 |         String host = uri.getHost();
107 |         String target = String.format("%s://%s", scheme, host);
108 |         return httpClient.target(target)
109 |                 .path("api-version")
110 |                 .request()
111 |                 .get();
112 |     }
113 | 
114 |     public String getWireHost() {
115 |         return this.wireHost;
116 |     }
117 | 
118 |     /**
119 |      * This method sends the OtrMessage to BE. Message must contain cipher for all participants and all their clients.
120 |      *
121 |      * @param msg           OtrMessage object containing ciphers for all clients
122 |      * @param ignoreMissing If TRUE ignore missing clients and deliver the message to available clients
123 |      * @return List of missing devices in case of fail or an empty list.
124 |      * @throws HttpException Http Exception is thrown when status {@literal >}= 400
125 |      */
126 |     @Override
127 |     public Devices sendMessage(OtrMessage msg, Object... ignoreMissing) throws HttpException {
128 |         try (Response response = messages
129 |                 .queryParam("ignore_missing", ignoreMissing)
130 |                 .request(MediaType.APPLICATION_JSON)
131 |                 .header(HttpHeaders.AUTHORIZATION, bearer())
132 |                 .post(Entity.entity(msg, MediaType.APPLICATION_JSON))) {
133 | 
134 |             int statusCode = response.getStatus();
135 |             if (statusCode == 412) {
136 |                 // This message was not sent due to missing clients. Parse those missing clients so the caller can add them
137 |                 return response.readEntity(Devices.class);
138 |             }
139 | 
140 |             if (statusCode >= 400) {
141 |                 throw new HttpException(response.readEntity(String.class), statusCode);
142 |             }
143 | 
144 |             return response.readEntity(Devices.class);
145 |         }
146 |     }
147 | 
148 |     @Override
149 |     public Devices sendPartialMessage(OtrMessage msg, UUID userId) throws HttpException {
150 |         try (Response response = messages
151 |                 .queryParam("report_missing", userId)
152 |                 .request(MediaType.APPLICATION_JSON)
153 |                 .header(HttpHeaders.AUTHORIZATION, bearer())
154 |                 .post(Entity.entity(msg, MediaType.APPLICATION_JSON))) {
155 | 
156 |             int statusCode = response.getStatus();
157 |             if (statusCode == 412) {
158 |                 // This message was not sent due to missing clients. Parse those missing clients so the caller can add them
159 |                 return response.readEntity(Devices.class);
160 |             }
161 | 
162 |             if (statusCode >= 400) {
163 |                 throw new HttpException(response.readEntity(String.class), statusCode);
164 |             }
165 | 
166 |             return response.readEntity(Devices.class);
167 |         }
168 |     }
169 | 
170 |     @Override
171 |     public Collection<User> getUsers(Collection<UUID> ids) {
172 |         return users
173 |                 .queryParam("ids", ids.toArray())
174 |                 .request(MediaType.APPLICATION_JSON)
175 |                 .header(HttpHeaders.AUTHORIZATION, bearer())
176 |                 .get(new GenericType<ArrayList<User>>() {
177 |                 });
178 |     }
179 | 
180 |     @Override
181 |     public User getSelf() {
182 |         return bot
183 |                 .path("self")
184 |                 .request(MediaType.APPLICATION_JSON)
185 |                 .header(HttpHeaders.AUTHORIZATION, bearer())
186 |                 .get(User.class);
187 |     }
188 | 
189 |     @Override
190 |     public Conversation getConversation() {
191 |         return conversation
192 |                 .request()
193 |                 .header(HttpHeaders.AUTHORIZATION, bearer())
194 |                 .accept(MediaType.APPLICATION_JSON)
195 |                 .get(Conversation.class);
196 |     }
197 | 
198 |     @Override
199 |     public PreKeys getPreKeys(Missing missing) {
200 |         return prekeys
201 |                 .request(MediaType.APPLICATION_JSON)
202 |                 .header(HttpHeaders.AUTHORIZATION, bearer())
203 |                 .accept(MediaType.APPLICATION_JSON)
204 |                 .post(Entity.entity(missing, MediaType.APPLICATION_JSON), PreKeys.class);
205 |     }
206 | 
207 |     @Override
208 |     public ArrayList<Integer> getAvailablePrekeys(@Nullable String clientId) {
209 |         return client
210 |                 .request()
211 |                 .header(HttpHeaders.AUTHORIZATION, bearer())
212 |                 .accept(MediaType.APPLICATION_JSON)
213 |                 .get(new GenericType<>() {
214 |                 });
215 |     }
216 | 
217 |     @Override
218 |     public void uploadPreKeys(ArrayList<PreKey> preKeys) throws IOException {
219 |         NewBotResponseModel model = new NewBotResponseModel();
220 |         model.preKeys = preKeys;
221 | 
222 |         try (Response res = client
223 |                 .request(MediaType.APPLICATION_JSON)
224 |                 .header(HttpHeaders.AUTHORIZATION, bearer())
225 |                 .accept(MediaType.APPLICATION_JSON)
226 |                 .post(Entity.entity(model, MediaType.APPLICATION_JSON))) {
227 | 
228 |             int statusCode = res.getStatus();
229 |             if (statusCode >= 400) {
230 |                 throw new IOException(res.readEntity(String.class));
231 |             }
232 |         }
233 |     }
234 | 
235 |     @Override
236 |     public AssetKey uploadAsset(IAsset asset) throws Exception {
237 |         StringBuilder sb = new StringBuilder();
238 | 
239 |         // Part 1
240 |         String strMetadata = String.format("{\"public\": %s, \"retention\": \"%s\"}",
241 |                 asset.isPublic(),
242 |                 asset.getRetention());
243 |         sb.append("--frontier\r\n");
244 |         sb.append("Content-Type: application/json; charset=utf-8\r\n");
245 |         sb.append("Content-Length: ")
246 |                 .append(strMetadata.length())
247 |                 .append("\r\n\r\n");
248 |         sb.append(strMetadata)
249 |                 .append("\r\n");
250 | 
251 |         // Part 2
252 |         sb.append("--frontier\r\n");
253 |         sb.append("Content-Type: ")
254 |                 .append(asset.getMimeType())
255 |                 .append("\r\n");
256 |         sb.append("Content-Length: ")
257 |                 .append(asset.getEncryptedData().length)
258 |                 .append("\r\n");
259 |         sb.append("Content-MD5: ")
260 |                 .append(Util.calcMd5(asset.getEncryptedData()))
261 |                 .append("\r\n\r\n");
262 | 
263 |         // Complete
264 |         ByteArrayOutputStream os = new ByteArrayOutputStream();
265 |         os.write(sb.toString().getBytes(StandardCharsets.UTF_8));
266 |         os.write(asset.getEncryptedData());
267 |         os.write("\r\n--frontier--\r\n".getBytes(StandardCharsets.UTF_8));
268 | 
269 |         try (Response response = assets
270 |                 .request(MediaType.APPLICATION_JSON_TYPE)
271 |                 .header(HttpHeaders.AUTHORIZATION, bearer())
272 |                 .post(Entity.entity(os.toByteArray(), "multipart/mixed; boundary=frontier"))) {
273 | 
274 |             if (response.getStatus() >= 400) {
275 |                 throw new HttpException(response.readEntity(String.class), response.getStatus());
276 |             }
277 | 
278 |             return response.readEntity(AssetKey.class);
279 |         }
280 |     }
281 | 
282 |     @Override
283 |     public byte[] downloadAsset(String assetId, String assetToken) throws HttpException {
284 |         Invocation.Builder req = assets
285 |                 .path(assetId)
286 |                 .request()
287 |                 .property(ClientProperties.FOLLOW_REDIRECTS, Boolean.FALSE)
288 |                 .header(HttpHeaders.AUTHORIZATION, bearer());
289 | 
290 |         if (assetToken != null && !assetToken.isBlank())
291 |             req.header("Asset-Token", assetToken);
292 | 
293 |         Response response = req.get();
294 | 
295 |         if (response.getStatus() >= 400) {
296 |             throw new HttpException(response.readEntity(String.class), response.getStatus());
297 |         }
298 | 
299 |         final String location = response.getHeaderString(HttpHeaders.LOCATION);
300 |         response.close();
301 | 
302 |         response = httpClient
303 |                 .target(location)
304 |                 .request()
305 |                 .get();
306 | 
307 |         if (response.getStatus() >= 400) {
308 |             throw new HttpException(response.readEntity(String.class), response.getStatus());
309 |         }
310 | 
311 |         return response.readEntity(byte[].class);
312 |     }
313 | 
314 |     @Override
315 |     public boolean deleteConversation(UUID teamId) {
316 |         throw new NotSupportedException();
317 |     }
318 | 
319 |     @Override
320 |     public User addService(UUID serviceId, UUID providerId) {
321 |         throw new NotSupportedException();
322 |     }
323 | 
324 |     @Override
325 |     public User addParticipants(UUID... userIds) {
326 |         throw new NotSupportedException();
327 |     }
328 | 
329 |     @Override
330 |     public Conversation createConversation(String name, UUID teamId, List<UUID> users) {
331 |         throw new NotSupportedException();
332 |     }
333 | 
334 |     @Override
335 |     public Conversation createOne2One(UUID teamId, UUID userId) {
336 |         throw new NotSupportedException();
337 |     }
338 | 
339 |     @Override
340 |     public void leaveConversation(UUID user) {
341 |         throw new NotSupportedException();
342 |     }
343 | 
344 |     @Override
345 |     public User getUser(UUID userId) {
346 |         return getUsers(Collections.singletonList(userId))
347 |                 .stream()
348 |                 .findFirst()
349 |                 .orElse(null);
350 |     }
351 | 
352 |     @Override
353 |     public UUID getUserId(String handle) {
354 |         throw new NotSupportedException();
355 |     }
356 | 
357 |     @Override
358 |     public boolean hasDevice(UUID userId, String clientId) {
359 |         throw new NotSupportedException();
360 |     }
361 | 
362 |     @Override
363 |     public UUID getTeam() {
364 |         throw new NotSupportedException();
365 |     }
366 | 
367 |     @Override
368 |     public Collection<UUID> getTeamMembers(UUID teamId) {
369 |         throw new NotSupportedException();
370 |     }
371 | 
372 |     @Override
373 |     public void acceptConnection(UUID user) {
374 |         throw new NotSupportedException();
375 |     }
376 | 
377 |     private String bearer() {
378 |         return String.format("Bearer %s", token);
379 |     }
380 | 
381 |     public static class MetaData {
382 |         @JsonProperty("public")
383 |         public boolean scope;
384 |         @JsonProperty
385 |         public String retention;
386 |     }
387 | }
388 | 


--------------------------------------------------------------------------------
/src/main/java/com/wire/lithium/BotClient.java:
--------------------------------------------------------------------------------
 1 | //
 2 | // Wire
 3 | // Copyright (C) 2016 Wire Swiss GmbH
 4 | //
 5 | // This program is free software: you can redistribute it and/or modify
 6 | // it under the terms of the GNU General Public License as published by
 7 | // the Free Software Foundation, either version 3 of the License, or
 8 | // (at your option) any later version.
 9 | //
10 | // This program is distributed in the hope that it will be useful,
11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | // GNU General Public License for more details.
14 | //
15 | // You should have received a copy of the GNU General Public License
16 | // along with this program. If not, see http://www.gnu.org/licenses/.
17 | //
18 | 
19 | package com.wire.lithium;
20 | 
21 | import com.wire.xenon.WireAPI;
22 | import com.wire.xenon.WireClientBase;
23 | import com.wire.xenon.backend.models.NewBot;
24 | import com.wire.xenon.crypto.Crypto;
25 | 
26 | public class BotClient extends WireClientBase {
27 |     public BotClient(WireAPI api, Crypto crypto, NewBot state) {
28 |         super(api, crypto, state);
29 |     }
30 | }
31 | 


--------------------------------------------------------------------------------
/src/main/java/com/wire/lithium/ClientRepo.java:
--------------------------------------------------------------------------------
 1 | package com.wire.lithium;
 2 | 
 3 | import com.wire.bots.cryptobox.CryptoException;
 4 | import com.wire.xenon.WireAPI;
 5 | import com.wire.xenon.WireClient;
 6 | import com.wire.xenon.backend.models.NewBot;
 7 | import com.wire.xenon.crypto.Crypto;
 8 | import com.wire.xenon.factories.CryptoFactory;
 9 | import com.wire.xenon.factories.StorageFactory;
10 | import com.wire.xenon.state.State;
11 | import jakarta.ws.rs.client.Client;
12 | 
13 | import java.io.IOException;
14 | import java.util.UUID;
15 | 
16 | public class ClientRepo {
17 |     protected final Client httpClient;
18 |     protected final CryptoFactory cf;
19 |     protected final StorageFactory sf;
20 | 
21 |     public ClientRepo(Client httpClient, CryptoFactory cf, StorageFactory sf) {
22 |         this.httpClient = httpClient;
23 |         this.cf = cf;
24 |         this.sf = sf;
25 |     }
26 | 
27 |     public WireClient getClient(UUID botId) throws IOException, CryptoException {
28 |         NewBot state = sf.create(botId).getState();
29 |         Crypto crypto = cf.create(botId);
30 |         WireAPI api = new API(httpClient, state.token);
31 |         return new BotClient(api, crypto, state);
32 |     }
33 | 
34 |     public void purgeBot(UUID botId) throws IOException {
35 |         State state = sf.create(botId);
36 |         if (state == null)
37 |             return;
38 | 
39 |         boolean purged = state.removeState();
40 |         if (!purged)
41 |             throw new IOException("Failed to purge Bot: " + botId);
42 |     }
43 | 
44 |     public Client getHttpClient() {
45 |         return httpClient;
46 |     }
47 | 
48 |     public CryptoFactory getCf() {
49 |         return cf;
50 |     }
51 | 
52 |     public StorageFactory getSf() {
53 |         return sf;
54 |     }
55 | }
56 | 


--------------------------------------------------------------------------------
/src/main/java/com/wire/lithium/Configuration.java:
--------------------------------------------------------------------------------
 1 | //
 2 | // Wire
 3 | // Copyright (C) 2016 Wire Swiss GmbH
 4 | //
 5 | // This program is free software: you can redistribute it and/or modify
 6 | // it under the terms of the GNU General Public License as published by
 7 | // the Free Software Foundation, either version 3 of the License, or
 8 | // (at your option) any later version.
 9 | //
10 | // This program is distributed in the hope that it will be useful,
11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | // GNU General Public License for more details.
14 | //
15 | // You should have received a copy of the GNU General Public License
16 | // along with this program. If not, see http://www.gnu.org/licenses/.
17 | //
18 | 
19 | package com.wire.lithium;
20 | 
21 | import com.fasterxml.jackson.annotation.JsonProperty;
22 | import io.dropwizard.client.JerseyClientConfiguration;
23 | import io.dropwizard.db.DataSourceFactory;
24 | import io.federecio.dropwizard.swagger.SwaggerBundleConfiguration;
25 | import jakarta.validation.Valid;
26 | import jakarta.validation.constraints.NotNull;
27 | 
28 | 
29 | /**
30 |  * Application configuration class. Extend this class to add your custom configuration
31 |  */
32 | public class Configuration extends io.dropwizard.core.Configuration {
33 |     @JsonProperty
34 |     @Valid
35 |     public Database database = new Database();
36 | 
37 |     @JsonProperty
38 |     @NotNull
39 |     public String token;   // Service token. Obtained when the Service is registered with Wire
40 | 
41 |     @JsonProperty
42 |     public boolean healthchecks = true;
43 | 
44 |     @Valid
45 |     private _JerseyClientConfiguration jerseyClient = new _JerseyClientConfiguration();
46 | 
47 |     @JsonProperty("swagger")
48 |     public SwaggerBundleConfiguration swagger = new _SwaggerBundleConfiguration();
49 | 
50 |     @JsonProperty
51 |     public String apiHost = "https://prod-nginz-https.wire.com";
52 | 
53 |     @JsonProperty("jerseyClient")
54 |     public JerseyClientConfiguration getJerseyClient() {
55 |         return jerseyClient;
56 |     }
57 | 
58 |     @JsonProperty("jerseyClient")
59 |     public void setJerseyClient(_JerseyClientConfiguration jerseyClient) {
60 |         this.jerseyClient = jerseyClient;
61 |     }
62 | 
63 |     public static class Database extends DataSourceFactory {
64 |         @JsonProperty
65 |         public boolean baseline;
66 |     }
67 | 
68 |     public static class _JerseyClientConfiguration extends JerseyClientConfiguration {
69 |         public _JerseyClientConfiguration() {
70 |             setChunkedEncodingEnabled(false);
71 |             setGzipEnabled(false);
72 |             setGzipEnabledForRequests(false);
73 |         }
74 |     }
75 | 
76 |     private static class _SwaggerBundleConfiguration extends SwaggerBundleConfiguration {
77 |         _SwaggerBundleConfiguration() {
78 |             setResourcePackage("com.wire.lithium.server.resources");
79 |         }
80 |     }
81 | }
82 | 


--------------------------------------------------------------------------------
/src/main/java/com/wire/lithium/Server.java:
--------------------------------------------------------------------------------
  1 | //
  2 | // Wire
  3 | // Copyright (C) 2016 Wire Swiss GmbH
  4 | //
  5 | // This program is free software: you can redistribute it and/or modify
  6 | // it under the terms of the GNU General Public License as published by
  7 | // the Free Software Foundation, either version 3 of the License, or
  8 | // (at your option) any later version.
  9 | //
 10 | // This program is distributed in the hope that it will be useful,
 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 13 | // GNU General Public License for more details.
 14 | //
 15 | // You should have received a copy of the GNU General Public License
 16 | // along with this program. If not, see http://www.gnu.org/licenses/.
 17 | //
 18 | 
 19 | package com.wire.lithium;
 20 | 
 21 | import com.codahale.metrics.Gauge;
 22 | import com.codahale.metrics.health.HealthCheck;
 23 | import com.codahale.metrics.jmx.JmxReporter;
 24 | import com.fasterxml.jackson.jakarta.rs.json.JacksonJsonProvider;
 25 | import com.wire.lithium.healthchecks.Alice2Bob;
 26 | import com.wire.lithium.healthchecks.CryptoHealthCheck;
 27 | import com.wire.lithium.healthchecks.Outbound;
 28 | import com.wire.lithium.healthchecks.StorageHealthCheck;
 29 | import com.wire.lithium.server.filters.AuthenticationFeature;
 30 | import com.wire.lithium.server.monitoring.RequestMdcFactoryFilter;
 31 | import com.wire.lithium.server.monitoring.StatusResource;
 32 | import com.wire.lithium.server.monitoring.VersionResource;
 33 | import com.wire.lithium.server.resources.BotsResource;
 34 | import com.wire.lithium.server.resources.MessageResource;
 35 | import com.wire.lithium.server.tasks.AvailablePrekeysTask;
 36 | import com.wire.lithium.server.tasks.ConversationTask;
 37 | import com.wire.xenon.Const;
 38 | import com.wire.xenon.MessageHandlerBase;
 39 | import com.wire.xenon.crypto.CryptoDatabase;
 40 | import com.wire.xenon.crypto.storage.JdbiStorage;
 41 | import com.wire.xenon.factories.CryptoFactory;
 42 | import com.wire.xenon.factories.StorageFactory;
 43 | import com.wire.xenon.state.JdbiState;
 44 | import com.wire.xenon.tools.Logger;
 45 | import io.dropwizard.client.JerseyClientBuilder;
 46 | import io.dropwizard.configuration.EnvironmentVariableSubstitutor;
 47 | import io.dropwizard.configuration.SubstitutingSourceProvider;
 48 | import io.dropwizard.core.Application;
 49 | import io.dropwizard.core.setup.Bootstrap;
 50 | import io.dropwizard.core.setup.Environment;
 51 | import io.dropwizard.servlets.tasks.Task;
 52 | import jakarta.annotation.Nullable;
 53 | import jakarta.ws.rs.client.Client;
 54 | import org.flywaydb.core.Flyway;
 55 | import org.jdbi.v3.core.Jdbi;
 56 | import org.jdbi.v3.sqlobject.SqlObjectPlugin;
 57 | 
 58 | import java.util.SortedMap;
 59 | import java.util.concurrent.TimeUnit;
 60 | 
 61 | /**
 62 |  * Entry point for your Application
 63 |  *
 64 |  * @param <Config> Dropwizard configuration
 65 |  */
 66 | public abstract class Server<Config extends Configuration> extends Application<Config> {
 67 |     protected ClientRepo repo;
 68 |     protected Config config;
 69 |     protected Environment environment;
 70 |     protected Client client;
 71 |     protected MessageHandlerBase messageHandler;
 72 |     protected Jdbi jdbi;
 73 | 
 74 |     /**
 75 |      * This method is called once by the sdk in order to create the main message handler
 76 |      *
 77 |      * @param config Configuration object (yaml)
 78 |      * @param env    Environment object
 79 |      * @return Instance of your class that implements {@link MessageHandlerBase}
 80 |      * @throws Exception allowed to throw exception
 81 |      */
 82 |     protected abstract MessageHandlerBase createHandler(Config config, Environment env) throws Exception;
 83 | 
 84 |     /**
 85 |      * Override this method to put your custom initialization
 86 |      * NOTE: MessageHandler is not yet set when this method is invoked!
 87 |      *
 88 |      * @param config Configuration object (yaml)
 89 |      * @param env    Environment object
 90 |      * @throws Exception allowed to throw exception
 91 |      */
 92 |     @SuppressWarnings("RedundantThrows") // this method can be overridden
 93 |     protected void initialize(Config config, Environment env) throws Exception {
 94 | 
 95 |     }
 96 | 
 97 |     /**
 98 |      * Override this method in case you need to add custom Resource and/or Task
 99 |      * {@link #addResource(Object)}
100 |      * and {@link #addTask(io.dropwizard.servlets.tasks.Task)}
101 |      *
102 |      * @param config Configuration object (yaml)
103 |      * @param env    Environment object
104 |      * @throws Exception allowed to throw exception
105 |      */
106 |     @SuppressWarnings("RedundantThrows") // this method can be overridden
107 |     protected void onRun(Config config, Environment env) throws Exception {
108 | 
109 |     }
110 | 
111 |     @Override
112 |     public void initialize(Bootstrap<Config> bootstrap) {
113 |         bootstrap.setConfigurationSourceProvider(new SubstitutingSourceProvider(
114 |                 bootstrap.getConfigurationSourceProvider(), new EnvironmentVariableSubstitutor(false)));
115 |     }
116 | 
117 |     @Override
118 |     public void run(final Config config, Environment env) throws Exception {
119 |         this.config = config;
120 |         this.environment = env;
121 | 
122 |         System.setProperty(Const.WIRE_BOTS_SDK_TOKEN, config.token);
123 |         System.setProperty(Const.WIRE_BOTS_SDK_API, config.apiHost);
124 | 
125 |         setupDatabase(config.database);
126 | 
127 |         jdbi = buildJdbi(config.database, env);
128 | 
129 |         client = createHttpClient(config, env);
130 | 
131 |         repo = createClientRepo();
132 | 
133 |         initialize(config, env);
134 | 
135 |         messageHandler = createHandler(config, env);
136 | 
137 |         addResources();
138 | 
139 |         initTelemetry();
140 | 
141 |         if (config.healthchecks) {
142 |             runHealthChecks();
143 |         }
144 | 
145 |         onRun(config, env);
146 |     }
147 | 
148 |     private Client createHttpClient(Config config, Environment env) {
149 |         return new JerseyClientBuilder(env)
150 |                 .using(config.getJerseyClient())
151 |                 .withProvider(JacksonJsonProvider.class)
152 |                 .build(getName());
153 |     }
154 | 
155 |     protected ClientRepo createClientRepo() {
156 |         StorageFactory storageFactory = getStorageFactory();
157 |         CryptoFactory cryptoFactory = getCryptoFactory();
158 |         return new ClientRepo(getClient(), cryptoFactory, storageFactory);
159 |     }
160 | 
161 |     @Nullable
162 |     protected Jdbi buildJdbi(Configuration.Database database, Environment env) {
163 |         return Jdbi
164 |                 .create(database.build(env.metrics(), getName()))
165 |                 .installPlugin(new SqlObjectPlugin());
166 |     }
167 | 
168 |     protected void setupDatabase(Configuration.Database database) {
169 |         Flyway flyway = Flyway
170 |                 .configure()
171 |                 .dataSource(database.getUrl(), database.getUser(), database.getPassword())
172 |                 .baselineOnMigrate(database.baseline)
173 |                 .load();
174 |         flyway.migrate();
175 |     }
176 | 
177 |     public StorageFactory getStorageFactory() {
178 |         return botId -> new JdbiState(botId, getJdbi());
179 |     }
180 | 
181 |     public CryptoFactory getCryptoFactory() {
182 |         return (botId) -> new CryptoDatabase(botId, new JdbiStorage(getJdbi()));
183 |     }
184 | 
185 |     private void addResources() {
186 |         /* --- Wire Common --- */
187 |         addResource(new VersionResource()); // add version endpoint
188 |         addResource(new StatusResource()); // empty status for k8s
189 |         addResource(new RequestMdcFactoryFilter()); // MDC data
190 |         /* //- Wire Common --- */
191 | 
192 |         botResource();
193 |         messageResource();
194 | 
195 |         addTask(new ConversationTask(getRepo()));
196 |         addTask(new AvailablePrekeysTask(getRepo()));
197 |     }
198 | 
199 |     protected void messageResource() {
200 |         addResource(new MessageResource(messageHandler, getRepo()));
201 |     }
202 | 
203 |     protected void botResource() {
204 |         StorageFactory storageFactory = getStorageFactory();
205 |         CryptoFactory cryptoFactory = getCryptoFactory();
206 | 
207 |         addResource(new BotsResource(messageHandler, storageFactory, cryptoFactory));
208 |     }
209 | 
210 |     protected void addTask(Task task) {
211 |         environment.admin().addTask(task);
212 |     }
213 | 
214 |     protected void addResource(Object component) {
215 |         environment.jersey().register(component);
216 |     }
217 | 
218 |     private void initTelemetry() {
219 |         /* --- Wire Common --- */
220 |         environment.jersey().register(new RequestMdcFactoryFilter());
221 |         /* //- Wire Common --- */
222 | 
223 |         final CryptoFactory cryptoFactory = getCryptoFactory();
224 |         final StorageFactory storageFactory = getStorageFactory();
225 | 
226 |         registerFeatures();
227 | 
228 |         environment.healthChecks().register("Storage", new StorageHealthCheck(storageFactory));
229 |         environment.healthChecks().register("Crypto", new CryptoHealthCheck(cryptoFactory));
230 |         environment.healthChecks().register("Alice2Bob", new Alice2Bob(cryptoFactory));
231 |         environment.healthChecks().register("Outbound", new Outbound(getClient()));
232 | 
233 |         environment.metrics().register("logger.errors", (Gauge<Integer>) Logger::getErrorCount);
234 |         environment.metrics().register("logger.warnings", (Gauge<Integer>) Logger::getWarningCount);
235 | 
236 |         JmxReporter jmxReporter = JmxReporter.forRegistry(environment.metrics())
237 |                 .convertRatesTo(TimeUnit.SECONDS)
238 |                 .convertDurationsTo(TimeUnit.MILLISECONDS)
239 |                 .build();
240 |         jmxReporter.start();
241 |     }
242 | 
243 |     private void runHealthChecks() {
244 |         Logger.info("Running health checks...");
245 |         final SortedMap<String, HealthCheck.Result> results = environment.healthChecks().runHealthChecks();
246 |         for (String name : results.keySet()) {
247 |             final HealthCheck.Result result = results.get(name);
248 |             if (!result.isHealthy()) {
249 |                 Logger.error("%s failed with: %s", name, result.getMessage());
250 |                 throw new RuntimeException(result.getError());
251 |             }
252 |         }
253 |     }
254 | 
255 |     protected void registerFeatures() {
256 |         this.environment.jersey().register(AuthenticationFeature.class);
257 |     }
258 | 
259 |     public ClientRepo getRepo() {
260 |         return repo;
261 |     }
262 | 
263 |     public Config getConfig() {
264 |         return config;
265 |     }
266 | 
267 |     public Environment getEnvironment() {
268 |         return environment;
269 |     }
270 | 
271 |     public Client getClient() {
272 |         return client;
273 |     }
274 | 
275 |     public Jdbi getJdbi() {
276 |         return jdbi;
277 |     }
278 | }
279 | 


--------------------------------------------------------------------------------
/src/main/java/com/wire/lithium/healthchecks/Alice2Bob.java:
--------------------------------------------------------------------------------
 1 | package com.wire.lithium.healthchecks;
 2 | 
 3 | import com.codahale.metrics.health.HealthCheck;
 4 | import com.wire.lithium.server.monitoring.MDCUtils;
 5 | import com.wire.xenon.crypto.Crypto;
 6 | import com.wire.xenon.factories.CryptoFactory;
 7 | import com.wire.xenon.models.otr.PreKeys;
 8 | import com.wire.xenon.models.otr.Recipients;
 9 | import com.wire.xenon.tools.Logger;
10 | 
11 | import java.util.Arrays;
12 | import java.util.Base64;
13 | import java.util.UUID;
14 | 
15 | public class Alice2Bob extends HealthCheck {
16 |     private final CryptoFactory cryptoFactory;
17 | 
18 |     public Alice2Bob(CryptoFactory cryptoFactory) {
19 |         this.cryptoFactory = cryptoFactory;
20 |     }
21 | 
22 |     @Override
23 |     protected Result check() {
24 |         try {
25 |             MDCUtils.put("healthCheck", "Alice2Bob"); // tag the logs with health check
26 |             Logger.debug("Starting Alice2Bob healthcheck");
27 | 
28 |             UUID aliceId = UUID.randomUUID();
29 |             UUID bobId = UUID.randomUUID();
30 | 
31 |             Crypto alice = cryptoFactory.create(aliceId);
32 |             Crypto bob = cryptoFactory.create(bobId);
33 |             PreKeys bobKeys = new PreKeys(bob.newPreKeys(0, 1), "bob", bobId);
34 | 
35 |             String text = "Hello Bob, This is Alice!";
36 |             byte[] textBytes = text.getBytes();
37 | 
38 |             // Encrypt using prekeys
39 |             Recipients encrypt = alice.encrypt(bobKeys, textBytes);
40 | 
41 |             String base64Encoded = encrypt.get(bobId, "bob");
42 | 
43 |             // Decrypt using initSessionFromMessage
44 |             String decrypt = bob.decrypt(aliceId, "alice", base64Encoded);
45 |             byte[] decode = Base64.getDecoder().decode(decrypt);
46 | 
47 |             alice.close();
48 |             bob.close();
49 | 
50 |             if (!Arrays.equals(decode, textBytes))
51 |                 return Result.unhealthy("!Arrays.equals(decode, textBytes)");
52 | 
53 |             if (!text.equals(new String(decode)))
54 |                 return Result.unhealthy("!text.equals(new String(decode))");
55 | 
56 |             return Result.healthy();
57 |         } catch (Exception e) {
58 |             Logger.exception("Exception during Alice2Bob health check.", e);
59 |             return Result.unhealthy(e.getMessage());
60 |         } finally {
61 |             Logger.debug("Finished Alice2Bob healthcheck");
62 |         }
63 |     }
64 | }
65 | 


--------------------------------------------------------------------------------
/src/main/java/com/wire/lithium/healthchecks/CryptoHealthCheck.java:
--------------------------------------------------------------------------------
 1 | package com.wire.lithium.healthchecks;
 2 | 
 3 | import com.codahale.metrics.health.HealthCheck;
 4 | import com.wire.lithium.server.monitoring.MDCUtils;
 5 | import com.wire.xenon.crypto.Crypto;
 6 | import com.wire.xenon.factories.CryptoFactory;
 7 | import com.wire.xenon.tools.Logger;
 8 | 
 9 | import java.util.UUID;
10 | 
11 | public class CryptoHealthCheck extends HealthCheck {
12 |     private final CryptoFactory cryptoFactory;
13 | 
14 |     public CryptoHealthCheck(CryptoFactory cryptoFactory) {
15 |         this.cryptoFactory = cryptoFactory;
16 |     }
17 | 
18 |     @Override
19 |     protected Result check() {
20 |         try {
21 |             MDCUtils.put("healthCheck", "CryptoHealthCheck"); // tag the logs with health check
22 |             Logger.debug("Starting CryptoHealthCheck healthcheck");
23 | 
24 |             try (Crypto crypto = cryptoFactory.create(UUID.randomUUID())) {
25 |                 crypto.newLastPreKey();
26 |                 crypto.newPreKeys(0, 8);
27 |                 return Result.healthy();
28 |             }
29 |         } catch (Exception e) {
30 |             Logger.exception("Exception during CryptoHealthCheck.", e);
31 |             return Result.unhealthy(e.getMessage());
32 |         } finally {
33 |             Logger.debug("Finished CryptoHealthCheck healthcheck");
34 |         }
35 |     }
36 | }
37 | 


--------------------------------------------------------------------------------
/src/main/java/com/wire/lithium/healthchecks/Outbound.java:
--------------------------------------------------------------------------------
 1 | package com.wire.lithium.healthchecks;
 2 | 
 3 | import com.codahale.metrics.health.HealthCheck;
 4 | import com.wire.lithium.API;
 5 | import com.wire.lithium.server.monitoring.MDCUtils;
 6 | import com.wire.xenon.tools.Logger;
 7 | import jakarta.ws.rs.client.Client;
 8 | import jakarta.ws.rs.core.Response;
 9 | 
10 | public class Outbound extends HealthCheck {
11 |     private final Client client;
12 | 
13 |     public Outbound(Client client) {
14 |         this.client = client;
15 |     }
16 | 
17 |     @Override
18 |     protected Result check() {
19 |         MDCUtils.put("healthCheck", "Outbound"); // tag the logs with health check
20 |         Logger.debug("Starting Outbound healthcheck");
21 |         API api = new API(client, null);
22 | 
23 |         try (Response response = api.status()) {
24 |             String s = response.readEntity(String.class);
25 |             int status = response.getStatus();
26 |             return status == 200 ? Result.healthy() : Result.unhealthy(String.format("%s. status: %d", s, status));
27 |         } catch (Exception e) {
28 |             final String message = String.format("Unable to reach: %s, error: %s", api.getWireHost(), e.getMessage());
29 |             Logger.exception(e, message);
30 |             return Result.unhealthy(message);
31 |         } finally {
32 |             Logger.debug("Finished Outbound healthcheck");
33 |         }
34 |     }
35 | }
36 | 


--------------------------------------------------------------------------------
/src/main/java/com/wire/lithium/healthchecks/StorageHealthCheck.java:
--------------------------------------------------------------------------------
 1 | package com.wire.lithium.healthchecks;
 2 | 
 3 | import com.codahale.metrics.health.HealthCheck;
 4 | import com.wire.lithium.server.monitoring.MDCUtils;
 5 | import com.wire.xenon.backend.models.NewBot;
 6 | import com.wire.xenon.factories.StorageFactory;
 7 | import com.wire.xenon.state.State;
 8 | import com.wire.xenon.tools.Logger;
 9 | 
10 | import java.util.UUID;
11 | 
12 | public class StorageHealthCheck extends HealthCheck {
13 |     private final StorageFactory storageFactory;
14 | 
15 |     public StorageHealthCheck(StorageFactory storageFactory) {
16 |         this.storageFactory = storageFactory;
17 |     }
18 | 
19 |     @Override
20 |     protected HealthCheck.Result check() {
21 |         try {
22 |             MDCUtils.put("healthCheck", "StorageHealthCheck"); // tag the logs with health check
23 | 
24 |             Logger.debug("Starting StorageHealthCheck healthcheck");
25 |             NewBot newBot = new NewBot();
26 |             newBot.id = UUID.randomUUID();
27 |             State state = storageFactory.create(newBot.id);
28 |             return state.saveState(newBot)
29 |                     ? HealthCheck.Result.healthy()
30 |                     : HealthCheck.Result.unhealthy("Failed to save the state");
31 |         } catch (Exception e) {
32 |             Logger.exception("Exception during StorageHealthCheck.", e);
33 |             return Result.unhealthy(e.getMessage());
34 |         } finally {
35 |             Logger.debug("Finished StorageHealthCheck healthcheck");
36 |         }
37 |     }
38 | }
39 | 


--------------------------------------------------------------------------------
/src/main/java/com/wire/lithium/models/NewBotResponseModel.java:
--------------------------------------------------------------------------------
 1 | //
 2 | // Wire
 3 | // Copyright (C) 2016 Wire Swiss GmbH
 4 | //
 5 | // This program is free software: you can redistribute it and/or modify
 6 | // it under the terms of the GNU General Public License as published by
 7 | // the Free Software Foundation, either version 3 of the License, or
 8 | // (at your option) any later version.
 9 | //
10 | // This program is distributed in the hope that it will be useful,
11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | // GNU General Public License for more details.
14 | //
15 | // You should have received a copy of the GNU General Public License
16 | // along with this program. If not, see http://www.gnu.org/licenses/.
17 | //
18 | 
19 | package com.wire.lithium.models;
20 | 
21 | import com.fasterxml.jackson.annotation.JsonInclude;
22 | import com.fasterxml.jackson.annotation.JsonProperty;
23 | import com.wire.xenon.models.otr.PreKey;
24 | 
25 | import java.util.ArrayList;
26 | 
27 | @JsonInclude(JsonInclude.Include.NON_NULL)
28 | public class NewBotResponseModel {
29 |     @JsonProperty
30 |     public String name;
31 | 
32 |     @JsonProperty("accent_id")
33 |     public Integer accentId;
34 | 
35 |     @JsonProperty("last_prekey")
36 |     public PreKey lastPreKey;
37 | 
38 |     @JsonProperty("prekeys")
39 |     public ArrayList<PreKey> preKeys;
40 | 
41 |     @JsonProperty("assets")
42 |     public ArrayList<Asset> assets;
43 | 
44 |     public void addAsset(String key, String size) {
45 |         if (assets == null)
46 |             assets = new ArrayList<>();
47 | 
48 |         Asset asset = new Asset();
49 |         asset.key = key;
50 |         asset.type = "image";
51 |         asset.size = size;
52 |         assets.add(asset);
53 |     }
54 | 
55 |     public static class Asset {
56 |         @JsonProperty("type")
57 |         public String type;
58 | 
59 |         @JsonProperty("key")
60 |         public String key;
61 | 
62 |         @JsonProperty("size")
63 |         public String size;
64 |     }
65 | }
66 | 


--------------------------------------------------------------------------------
/src/main/java/com/wire/lithium/server/filters/AuthenticationFeature.java:
--------------------------------------------------------------------------------
 1 | package com.wire.lithium.server.filters;
 2 | 
 3 | import io.swagger.annotations.Authorization;
 4 | import jakarta.ws.rs.container.DynamicFeature;
 5 | import jakarta.ws.rs.container.ResourceInfo;
 6 | import jakarta.ws.rs.core.FeatureContext;
 7 | import jakarta.ws.rs.ext.Provider;
 8 | 
 9 | @Provider
10 | public class AuthenticationFeature implements DynamicFeature {
11 |     @Override
12 |     public void configure(ResourceInfo resourceInfo, FeatureContext context) {
13 |         if (resourceInfo.getResourceMethod().getAnnotation(Authorization.class) != null) {
14 |             context.register(AuthenticationFilter.class);
15 |         }
16 |     }
17 | }
18 | 


--------------------------------------------------------------------------------
/src/main/java/com/wire/lithium/server/filters/AuthenticationFilter.java:
--------------------------------------------------------------------------------
 1 | package com.wire.lithium.server.filters;
 2 | 
 3 | import com.wire.xenon.Const;
 4 | import com.wire.xenon.tools.Logger;
 5 | import com.wire.xenon.tools.Util;
 6 | import jakarta.ws.rs.WebApplicationException;
 7 | import jakarta.ws.rs.container.ContainerRequestContext;
 8 | import jakarta.ws.rs.container.ContainerRequestFilter;
 9 | import jakarta.ws.rs.core.HttpHeaders;
10 | import jakarta.ws.rs.core.Response;
11 | import jakarta.ws.rs.ext.Provider;
12 | 
13 | @Provider
14 | public class AuthenticationFilter implements ContainerRequestFilter {
15 |     @Override
16 |     public void filter(ContainerRequestContext requestContext) {
17 |         String auth = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);
18 |         if (auth == null) {
19 |             Exception cause = new IllegalArgumentException("Missing Authorization");
20 |             throw new WebApplicationException(cause, Response.Status.UNAUTHORIZED);
21 |         }
22 | 
23 |         String serviceToken = System.getProperty(Const.WIRE_BOTS_SDK_TOKEN, System.getenv("SERVICE_TOKEN"));
24 | 
25 |         if (!Util.compareAuthorizations(auth, serviceToken)) {
26 |             Logger.warning("Wrong service token");
27 |             Exception cause = new IllegalArgumentException("Wrong service token");
28 |             throw new WebApplicationException(cause, Response.Status.UNAUTHORIZED);
29 |         }
30 | 
31 |         requestContext.setProperty("wire-auth", Util.extractToken(auth));
32 |     }
33 | }


--------------------------------------------------------------------------------
/src/main/java/com/wire/lithium/server/monitoring/AbstractJsonLayout.java:
--------------------------------------------------------------------------------
 1 | package com.wire.lithium.server.monitoring;
 2 | 
 3 | import ch.qos.logback.access.spi.IAccessEvent;
 4 | import ch.qos.logback.classic.spi.ILoggingEvent;
 5 | import ch.qos.logback.core.CoreConstants;
 6 | import ch.qos.logback.core.LayoutBase;
 7 | import ch.qos.logback.core.filter.Filter;
 8 | import ch.qos.logback.core.spi.DeferredProcessingAware;
 9 | import ch.qos.logback.core.spi.FilterReply;
10 | import com.fasterxml.jackson.core.JsonProcessingException;
11 | import com.fasterxml.jackson.databind.ObjectMapper;
12 | import jakarta.annotation.Nullable;
13 | import org.jboss.logging.MDC;
14 | 
15 | import java.time.Instant;
16 | import java.time.ZoneOffset;
17 | import java.time.format.DateTimeFormatter;
18 | import java.util.List;
19 | import java.util.Map;
20 | 
21 | /**
22 |  * Layout base that can convert log map to JSON.
23 |  */
24 | abstract public class AbstractJsonLayout<T extends DeferredProcessingAware> extends LayoutBase<T> {
25 |     protected static final DateTimeFormatter dateTimeFormatter =
26 |             DateTimeFormatter.ISO_DATE_TIME.withZone(ZoneOffset.UTC);
27 | 
28 |     private static final ObjectMapper objectMapper = new ObjectMapper();
29 | 
30 |     private final List<Filter<T>> filters;
31 | 
32 |     protected AbstractJsonLayout(List<Filter<T>> filters) {
33 |         this.filters = filters;
34 |     }
35 | 
36 |     protected boolean shouldIgnoreEvent(T event) {
37 |         for (Filter<T> filter : filters) {
38 |             if (filter.decide(event) == FilterReply.DENY) {
39 |                 return true;
40 |             }
41 |         }
42 |         return false;
43 |     }
44 | 
45 |     protected String formatTimeStamp(final long timestamp) {
46 |         return dateTimeFormatter.format(Instant.ofEpochMilli(timestamp));
47 |     }
48 | 
49 |     protected String formatTime(final ILoggingEvent event) {
50 |         return formatTimeStamp(event.getTimeStamp());
51 |     }
52 | 
53 |     protected String formatTime(final IAccessEvent event) {
54 |         return formatTimeStamp(event.getTimeStamp());
55 |     }
56 | 
57 |     protected String finalizeLog(final Map<String, Object> jsonMap) {
58 |         return finalizeLog(jsonMap, null);
59 |     }
60 | 
61 |     /**
62 |      * Puts MDC to log and uses Object Mapper to create final log string.
63 |      * <p>
64 |      * Catches {@link JsonProcessingException} during processing, returns formatted string anyway.
65 |      *
66 |      * @param jsonMap    key value map of properties that will go to final log.
67 |      * @param logMessage message to log
68 |      * @return final log message
69 |      */
70 |     protected String finalizeLog(Map<String, Object> jsonMap, @Nullable final String logMessage) {
71 |         // put all MDC values to the final map
72 |         MDC.getMap().forEach(jsonMap::put);
73 | 
74 |         try {
75 |             final String json = objectMapper.writeValueAsString(jsonMap);
76 |             return json + CoreConstants.LINE_SEPARATOR;
77 |         } catch (JsonProcessingException e) {
78 |             final String message = logMessage != null ? logMessage : "http request";
79 |             // as we are serializing just maps then this should not happen...
80 |             e.printStackTrace();
81 |             return String.format(
82 |                     "It was not possible to log %s! Exception message %s, Exception %s %s",
83 |                     message,
84 |                     e.getMessage(),
85 |                     e,
86 |                     CoreConstants.LINE_SEPARATOR);
87 |         }
88 |     }
89 | }
90 | 


--------------------------------------------------------------------------------
/src/main/java/com/wire/lithium/server/monitoring/AccessEventJsonLayout.java:
--------------------------------------------------------------------------------
 1 | package com.wire.lithium.server.monitoring;
 2 | 
 3 | import ch.qos.logback.access.spi.IAccessEvent;
 4 | import ch.qos.logback.classic.Level;
 5 | import ch.qos.logback.core.filter.Filter;
 6 | import jakarta.servlet.http.HttpServletResponse;
 7 | 
 8 | import java.util.LinkedHashMap;
 9 | import java.util.List;
10 | import java.util.Map;
11 | 
12 | /**
13 |  * Layout used on Wire production services in the ELK stack - for access events - HTTP log.
14 |  */
15 | public class AccessEventJsonLayout extends AbstractJsonLayout<IAccessEvent> {
16 | 
17 | 
18 |     public AccessEventJsonLayout(List<Filter<IAccessEvent>> filters) {
19 |         super(filters);
20 |     }
21 | 
22 |     @Override
23 |     public String doLayout(IAccessEvent event) {
24 |         if (shouldIgnoreEvent(event)) {
25 |             return null;
26 |         }
27 |         final Map<String, Object> jsonMap = new LinkedHashMap<>(10);
28 | 
29 |         jsonMap.put("@timestamp", formatTime(event));
30 |         jsonMap.put("type", "http");
31 |         jsonMap.put("logger", "com.wire.HttpRequest");
32 | 
33 |         jsonMap.put("level", Level.INFO.levelStr);
34 |         jsonMap.put("requestURI", event.getRequestURI());
35 |         // put there query only if it is not empty
36 |         final String query = event.getQueryString();
37 |         if (query != null && !query.trim().isEmpty()) {
38 |             jsonMap.put("query", query);
39 |         }
40 |         jsonMap.put("remoteHost", event.getRemoteHost());
41 |         jsonMap.put("remoteAddr", event.getRemoteAddr());
42 |         jsonMap.put("method", event.getMethod());
43 |         jsonMap.put("elapsedMls", event.getElapsedTime());
44 |         // we check for null, even though there shouldn't be null, better be safe then sorry
45 |         final HttpServletResponse response = event.getResponse();
46 |         if (response != null) {
47 |             jsonMap.put("responseStatus", response.getStatus());
48 |         }
49 |         return finalizeLog(jsonMap);
50 |     }
51 | }
52 | 


--------------------------------------------------------------------------------
/src/main/java/com/wire/lithium/server/monitoring/LoggingEventJsonLayout.java:
--------------------------------------------------------------------------------
 1 | package com.wire.lithium.server.monitoring;
 2 | 
 3 | import ch.qos.logback.classic.spi.ILoggingEvent;
 4 | import ch.qos.logback.classic.spi.IThrowableProxy;
 5 | import ch.qos.logback.classic.spi.ThrowableProxyUtil;
 6 | import ch.qos.logback.core.filter.Filter;
 7 | 
 8 | import java.util.LinkedHashMap;
 9 | import java.util.List;
10 | import java.util.Map;
11 | 
12 | /**
13 |  * Layout used on Wire production services in the ELK stack.
14 |  */
15 | public class LoggingEventJsonLayout extends AbstractJsonLayout<ILoggingEvent> {
16 | 
17 |     public LoggingEventJsonLayout(List<Filter<ILoggingEvent>> filters) {
18 |         super(filters);
19 |     }
20 | 
21 |     @Override
22 |     public String doLayout(ILoggingEvent event) {
23 |         if (shouldIgnoreEvent(event)) {
24 |             return null;
25 |         }
26 | 
27 |         final Map<String, Object> jsonMap = new LinkedHashMap<>(6);
28 | 
29 |         jsonMap.put("@timestamp", formatTime(event));
30 |         jsonMap.put("type", "log");
31 |         jsonMap.put("message", event.getFormattedMessage());
32 | 
33 |         jsonMap.put("logger", event.getLoggerName());
34 |         jsonMap.put("level", event.getLevel().levelStr);
35 |         jsonMap.put("threadName", event.getThreadName());
36 | 
37 |         if (event.getThrowableProxy() != null) {
38 |             jsonMap.put("exception", exception(event.getThrowableProxy()));
39 |         }
40 | 
41 |         return finalizeLog(jsonMap, event.getFormattedMessage());
42 |     }
43 | 
44 |     private Map<String, String> exception(IThrowableProxy proxy) {
45 |         final Map<String, String> jsonMap = new LinkedHashMap<>(3);
46 |         jsonMap.put("stacktrace", ThrowableProxyUtil.asString(proxy));
47 |         jsonMap.put("message", proxy.getMessage());
48 |         jsonMap.put("class", proxy.getClassName());
49 |         return jsonMap;
50 |     }
51 | }
52 | 


--------------------------------------------------------------------------------
/src/main/java/com/wire/lithium/server/monitoring/MDCUtils.java:
--------------------------------------------------------------------------------
 1 | package com.wire.lithium.server.monitoring;
 2 | 
 3 | import jakarta.annotation.Nullable;
 4 | import jakarta.validation.constraints.NotNull;
 5 | import org.slf4j.MDC;
 6 | 
 7 | 
 8 | public class MDCUtils {
 9 | 
10 |     /**
11 |      * Put value to MDC under given key.
12 |      *
13 |      * @param key   MDC key
14 |      * @param value value to the key
15 |      */
16 |     public static void put(@NotNull final String key, @Nullable Object value) {
17 |         if (value != null) {
18 |             final String stringValue = value.toString().trim();
19 |             if (!stringValue.isEmpty()) {
20 |                 MDC.put(key, stringValue);
21 |             }
22 |         }
23 |     }
24 | 
25 |     /**
26 |      * Remove key from the MDC.
27 |      *
28 |      * @param key key to be removed
29 |      */
30 |     public static void removeKey(@NotNull final String key) {
31 |         MDC.remove(key);
32 |     }
33 | }
34 | 


--------------------------------------------------------------------------------
/src/main/java/com/wire/lithium/server/monitoring/RequestMdcFactoryFilter.java:
--------------------------------------------------------------------------------
 1 | package com.wire.lithium.server.monitoring;
 2 | 
 3 | import jakarta.annotation.Nullable;
 4 | import jakarta.ws.rs.container.ContainerRequestContext;
 5 | import jakarta.ws.rs.container.ContainerRequestFilter;
 6 | import jakarta.ws.rs.ext.Provider;
 7 | import org.slf4j.MDC;
 8 | 
 9 | import java.util.UUID;
10 | 
11 | /**
12 |  * Filter that sets MDC.
13 |  */
14 | @Provider
15 | public class RequestMdcFactoryFilter implements ContainerRequestFilter {
16 |     @Override
17 |     public void filter(ContainerRequestContext requestContext) {
18 |         // save id generated by the Nginx
19 |         addIfNotNull("forwardedFor", requestContext.getHeaderString("X-Request-Id"));
20 |         // generate unique id for each request in the application
21 |         addIfNotNull("appRequest", UUID.randomUUID().toString());
22 |         // header from proxy
23 |         addIfNotNull("forwardedFor", requestContext.getHeaderString("X-Forwarded-For"));
24 |         addIfNotNull("realIp", requestContext.getHeaderString("X-Real-IP"));
25 |     }
26 | 
27 |     private void addIfNotNull(final String key, @Nullable String value) {
28 |         if (value != null && !value.isEmpty()){
29 |             MDC.put(key, value);
30 |         }
31 |     }
32 | }
33 | 


--------------------------------------------------------------------------------
/src/main/java/com/wire/lithium/server/monitoring/StatusResource.java:
--------------------------------------------------------------------------------
 1 | //
 2 | // Wire
 3 | // Copyright (C) 2016 Wire Swiss GmbH
 4 | //
 5 | // This program is free software: you can redistribute it and/or modify
 6 | // it under the terms of the GNU General Public License as published by
 7 | // the Free Software Foundation, either version 3 of the License, or
 8 | // (at your option) any later version.
 9 | //
10 | // This program is distributed in the hope that it will be useful,
11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | // GNU General Public License for more details.
14 | //
15 | // You should have received a copy of the GNU General Public License
16 | // along with this program. If not, see http://www.gnu.org/licenses/.
17 | //
18 | 
19 | package com.wire.lithium.server.monitoring;
20 | 
21 | import io.swagger.annotations.Api;
22 | import io.swagger.annotations.ApiOperation;
23 | import jakarta.ws.rs.GET;
24 | import jakarta.ws.rs.Path;
25 | import jakarta.ws.rs.Produces;
26 | import jakarta.ws.rs.core.MediaType;
27 | import jakarta.ws.rs.core.Response;
28 | 
29 | @Api
30 | @Path("/status")
31 | @Produces(MediaType.TEXT_PLAIN)
32 | public class StatusResource {
33 |     @GET
34 |     @ApiOperation(value = "Status")
35 |     public Response statusEmpty() {
36 |         return Response
37 |                 .ok()
38 |                 .build();
39 |     }
40 | }
41 | 


--------------------------------------------------------------------------------
/src/main/java/com/wire/lithium/server/monitoring/VersionResource.java:
--------------------------------------------------------------------------------
 1 | package com.wire.lithium.server.monitoring;
 2 | 
 3 | import io.swagger.annotations.Api;
 4 | import io.swagger.annotations.ApiOperation;
 5 | import io.swagger.annotations.ApiResponse;
 6 | import io.swagger.annotations.ApiResponses;
 7 | import jakarta.validation.constraints.NotEmpty;
 8 | import jakarta.validation.constraints.NotNull;
 9 | import jakarta.ws.rs.GET;
10 | import jakarta.ws.rs.Path;
11 | import jakarta.ws.rs.Produces;
12 | import jakarta.ws.rs.core.MediaType;
13 | import jakarta.ws.rs.core.Response;
14 | 
15 | import java.io.RandomAccessFile;
16 | 
17 | @Api
18 | @Path("/version")
19 | @Produces(MediaType.APPLICATION_JSON)
20 | public class VersionResource {
21 |     @GET
22 |     @ApiOperation(value = "Returns version of the running code.")
23 |     @ApiResponses(value = {
24 |             @ApiResponse(code = 200, response = Version.class, message = "Version")
25 |     })
26 |     public Response get() {
27 |         return Response
28 |                 .ok(getVersion())
29 |                 .build();
30 |     }
31 | 
32 |     private Version getVersion() {
33 |         final String path = System.getenv("RELEASE_FILE_PATH");
34 | 
35 |         String version = null;
36 |         if (path != null) {
37 |             try (final RandomAccessFile file = new RandomAccessFile(path, "r")) {
38 |                 version = file.readLine();
39 |             } catch (Exception ignored) {
40 |             }
41 |         }
42 | 
43 |         if (version == null) {
44 |             version = "development";
45 |         }
46 |         return new Version(version);
47 |     }
48 | 
49 |     static class Version {
50 |         @NotNull
51 |         @NotEmpty
52 |         public final String version;
53 | 
54 |         public Version(String version) {
55 |             this.version = version;
56 |         }
57 |     }
58 | }
59 | 


--------------------------------------------------------------------------------
/src/main/java/com/wire/lithium/server/resources/BotsResource.java:
--------------------------------------------------------------------------------
  1 | //
  2 | // Wire
  3 | // Copyright (C) 2016 Wire Swiss GmbH
  4 | //
  5 | // This program is free software: you can redistribute it and/or modify
  6 | // it under the terms of the GNU General Public License as published by
  7 | // the Free Software Foundation, either version 3 of the License, or
  8 | // (at your option) any later version.
  9 | //
 10 | // This program is distributed in the hope that it will be useful,
 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 13 | // GNU General Public License for more details.
 14 | //
 15 | // You should have received a copy of the GNU General Public License
 16 | // along with this program. If not, see http://www.gnu.org/licenses/.
 17 | //
 18 | 
 19 | package com.wire.lithium.server.resources;
 20 | 
 21 | import com.codahale.metrics.annotation.Metered;
 22 | import com.wire.lithium.models.NewBotResponseModel;
 23 | import com.wire.lithium.server.monitoring.MDCUtils;
 24 | import com.wire.xenon.MessageHandlerBase;
 25 | import com.wire.xenon.backend.models.ErrorMessage;
 26 | import com.wire.xenon.backend.models.NewBot;
 27 | import com.wire.xenon.crypto.Crypto;
 28 | import com.wire.xenon.factories.CryptoFactory;
 29 | import com.wire.xenon.factories.StorageFactory;
 30 | import com.wire.xenon.tools.Logger;
 31 | import io.swagger.annotations.*;
 32 | import jakarta.ws.rs.Consumes;
 33 | import jakarta.ws.rs.POST;
 34 | import jakarta.ws.rs.Path;
 35 | import jakarta.ws.rs.Produces;
 36 | import jakarta.ws.rs.container.ContainerRequestContext;
 37 | import jakarta.ws.rs.core.Context;
 38 | import jakarta.ws.rs.core.MediaType;
 39 | import jakarta.ws.rs.core.Response;
 40 | 
 41 | import jakarta.validation.Valid;
 42 | import jakarta.validation.constraints.NotNull;
 43 | import java.util.UUID;
 44 | 
 45 | @Api
 46 | @Produces(MediaType.APPLICATION_JSON)
 47 | @Consumes(MediaType.APPLICATION_JSON)
 48 | @Path("/bots")
 49 | public class BotsResource {
 50 |     protected final MessageHandlerBase handler;
 51 | 
 52 |     protected final StorageFactory storageF;
 53 |     protected final CryptoFactory cryptoF;
 54 | 
 55 |     public BotsResource(MessageHandlerBase handler, StorageFactory storageF, CryptoFactory cryptoF) {
 56 |         this.handler = handler;
 57 |         this.storageF = storageF;
 58 |         this.cryptoF = cryptoF;
 59 |     }
 60 | 
 61 |     @POST
 62 |     @ApiOperation(value = "New Bot instance", response = NewBotResponseModel.class, code = 201)
 63 |     @ApiResponses(value = {
 64 |             @ApiResponse(code = 401, message = "Unauthorized", response = ErrorMessage.class),
 65 |             @ApiResponse(code = 409, message = "Bot not accepted (whitelist?)", response = ErrorMessage.class),
 66 |             @ApiResponse(code = 201, message = "Alles gute")})
 67 |     @Authorization("Bearer")
 68 |     @Metered
 69 |     public Response newBot(@Context ContainerRequestContext context,
 70 |                            @ApiParam @Valid @NotNull NewBot newBot) {
 71 | 
 72 |         NewBotResponseModel ret = new NewBotResponseModel();
 73 | 
 74 |         try {
 75 |             UUID botId = newBot.id;
 76 |             // put information to every log for more information
 77 |             MDCUtils.put("botId", botId);
 78 |             MDCUtils.put("conversationId", newBot.conversation.id);
 79 |             MDCUtils.put("userId", newBot.origin.id);
 80 | 
 81 |             String token = (String) context.getProperty("wire-auth");
 82 |             if (!onNewBot(newBot, token)) {
 83 |                 return Response
 84 |                         .status(409)
 85 |                         .entity(new ErrorMessage("User not whitelisted or service does not accept new instances atm"))
 86 |                         .build();
 87 |             }
 88 | 
 89 |             boolean saveState = storageF.create(botId).saveState(newBot);
 90 |             if (!saveState) {
 91 |                 Logger.warning("Failed to save the state. Bot: %s", botId);
 92 |             }
 93 | 
 94 |             ret.name = handler.getName(newBot);
 95 |             ret.accentId = handler.getAccentColour();
 96 |             String profilePreview = handler.getSmallProfilePicture();
 97 |             if (profilePreview != null) {
 98 |                 ret.addAsset(profilePreview, "preview");
 99 |             }
100 | 
101 |             String profileBig = handler.getBigProfilePicture();
102 |             if (profileBig != null) {
103 |                 ret.addAsset(profileBig, "complete");
104 |             }
105 | 
106 |             try (Crypto crypto = cryptoF.create(botId)) {
107 |                 ret.lastPreKey = crypto.newLastPreKey();
108 |                 ret.preKeys = crypto.newPreKeys(0, 50);
109 |             }
110 | 
111 |         } catch (Exception e) {
112 |             Logger.exception(e, "newBot: %s", e.getMessage());
113 |             return Response.
114 |                     status(500).
115 |                     entity(new ErrorMessage(e.getMessage())).
116 |                     build();
117 |         }
118 | 
119 |         return Response.
120 |                 ok(ret).
121 |                 status(201).
122 |                 build();
123 |     }
124 | 
125 |     protected boolean onNewBot(NewBot newBot, String auth) {
126 |         return handler.onNewBot(newBot, auth);
127 |     }
128 | }
129 | 


--------------------------------------------------------------------------------
/src/main/java/com/wire/lithium/server/resources/MessageResource.java:
--------------------------------------------------------------------------------
  1 | //
  2 | // Wire
  3 | // Copyright (C) 2016 Wire Swiss GmbH
  4 | //
  5 | // This program is free software: you can redistribute it and/or modify
  6 | // it under the terms of the GNU General Public License as published by
  7 | // the Free Software Foundation, either version 3 of the License, or
  8 | // (at your option) any later version.
  9 | //
 10 | // This program is distributed in the hope that it will be useful,
 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 13 | // GNU General Public License for more details.
 14 | //
 15 | // You should have received a copy of the GNU General Public License
 16 | // along with this program. If not, see http://www.gnu.org/licenses/.
 17 | //
 18 | 
 19 | package com.wire.lithium.server.resources;
 20 | 
 21 | import com.codahale.metrics.annotation.Metered;
 22 | import com.fasterxml.jackson.databind.ObjectMapper;
 23 | import com.wire.bots.cryptobox.CryptoException;
 24 | import com.wire.lithium.ClientRepo;
 25 | import com.wire.lithium.server.monitoring.MDCUtils;
 26 | import com.wire.xenon.MessageHandlerBase;
 27 | import com.wire.xenon.MessageResourceBase;
 28 | import com.wire.xenon.WireClient;
 29 | import com.wire.xenon.assets.Reaction;
 30 | import com.wire.xenon.backend.models.ErrorMessage;
 31 | import com.wire.xenon.backend.models.Payload;
 32 | import com.wire.xenon.exceptions.MissingStateException;
 33 | import com.wire.xenon.tools.Logger;
 34 | import io.swagger.annotations.*;
 35 | import jakarta.ws.rs.*;
 36 | import jakarta.ws.rs.core.MediaType;
 37 | import jakarta.ws.rs.core.Response;
 38 | import jakarta.validation.Valid;
 39 | import jakarta.validation.constraints.NotNull;
 40 | import java.io.IOException;
 41 | import java.util.UUID;
 42 | import java.util.logging.Level;
 43 | 
 44 | @Api
 45 | @Produces(MediaType.APPLICATION_JSON)
 46 | @Consumes(MediaType.APPLICATION_JSON)
 47 | @Path("/bots/{bot}/messages")
 48 | public class MessageResource extends MessageResourceBase {
 49 |     private final ObjectMapper objectMapper = new ObjectMapper();
 50 |     private final ClientRepo repo;
 51 | 
 52 |     public MessageResource(MessageHandlerBase handler, ClientRepo repo) {
 53 |         super(handler);
 54 |         this.repo = repo;
 55 |     }
 56 | 
 57 |     @POST
 58 |     @ApiOperation(value = "New OTR Message")
 59 |     @ApiResponses(value = {
 60 |             @ApiResponse(code = 403, message = "Invalid Authorization", response = ErrorMessage.class),
 61 |             @ApiResponse(code = 503, message = "Missing bot's state object", response = ErrorMessage.class),
 62 |             @ApiResponse(code = 200, message = "Alles gute")})
 63 |     @Authorization("Bearer")
 64 |     @Metered
 65 |     public Response newMessage(@ApiParam("UUID Bot instance id") @PathParam("bot") UUID botId,
 66 |                                @ApiParam("UUID Unique event id") @QueryParam("id") UUID eventId,
 67 |                                @ApiParam @Valid @NotNull Payload payload) throws IOException {
 68 | 
 69 |         if (eventId == null) {
 70 |             eventId = UUID.randomUUID(); //todo fix this once Wire BE adds eventId into payload
 71 |         }
 72 | 
 73 |         if (Logger.getLevel() == Level.FINE) {
 74 |             Logger.debug("eventId: %s, botId: %s, %s",
 75 |                     eventId,
 76 |                     botId,
 77 |                     objectMapper.writeValueAsString(payload));
 78 |         }
 79 | 
 80 |         // put tracing information to logs
 81 |         MDCUtils.put("botId", botId);
 82 |         MDCUtils.put("eventId", eventId);
 83 |         MDCUtils.put("conversationId", payload.conversation.id);
 84 | 
 85 |         try (WireClient client = getWireClient(botId, payload)) {
 86 |             handleMessage(eventId, payload, client);
 87 |         } catch (CryptoException e) {
 88 |             Logger.exception(e,"newMessage: %s", botId, e.getMessage());
 89 |             respondWithError(botId, payload);
 90 |             return Response.
 91 |                     status(503).
 92 |                     entity(new ErrorMessage(e.getMessage())).
 93 |                     build();
 94 |         } catch (MissingStateException e) {
 95 |             Logger.exception(e,"newMessage: %s", botId, e.getMessage());
 96 |             return Response.
 97 |                     status(410).
 98 |                     entity(new ErrorMessage(e.getMessage())).
 99 |                     build();
100 |         } catch (Exception e) {
101 |             Logger.exception(e,"newMessage: %s", botId, e.getMessage());
102 |             return Response.
103 |                     status(400).
104 |                     entity(new ErrorMessage(e.getMessage())).
105 |                     build();
106 |         }
107 | 
108 |         return Response.
109 |                 ok().
110 |                 status(200).
111 |                 build();
112 |     }
113 | 
114 |     private void respondWithError(UUID botId, Payload payload) {
115 |         try (WireClient client = getWireClient(botId, payload)) {
116 |             client.send(new Reaction(UUID.randomUUID(), ""));
117 |         } catch (Exception e) {
118 |             Logger.exception(e,"respondWithError: bot: %s", botId, e.getMessage());
119 |         }
120 |     }
121 | 
122 |     protected WireClient getWireClient(UUID botId, Payload payload) throws IOException, CryptoException {
123 |         return repo.getClient(botId);
124 |     }
125 | }
126 | 


--------------------------------------------------------------------------------
/src/main/java/com/wire/lithium/server/tasks/AvailablePrekeysTask.java:
--------------------------------------------------------------------------------
 1 | package com.wire.lithium.server.tasks;
 2 | 
 3 | import com.fasterxml.jackson.databind.ObjectMapper;
 4 | import com.fasterxml.jackson.databind.SerializationFeature;
 5 | import com.wire.lithium.ClientRepo;
 6 | import com.wire.xenon.WireClient;
 7 | import com.wire.xenon.tools.Logger;
 8 | 
 9 | import java.io.PrintWriter;
10 | import java.util.ArrayList;
11 | import java.util.List;
12 | import java.util.Map;
13 | import java.util.UUID;
14 | 
15 | public class AvailablePrekeysTask extends TaskBase {
16 |     private final ClientRepo repo;
17 | 
18 |     public AvailablePrekeysTask(ClientRepo repo) {
19 |         super("prekeys");
20 |         this.repo = repo;
21 |     }
22 | 
23 |     @Override
24 |     public void execute(Map<String, List<String>> parameters, PrintWriter output) {
25 |         UUID botId = UUID.fromString(extractString(parameters, "bot"));
26 | 
27 |         try {
28 |             WireClient client = repo.getClient(botId);
29 |             ArrayList<Integer> availablePrekeys = client.getAvailablePrekeys();
30 |             ObjectMapper mapper = new ObjectMapper();
31 |             mapper.enable(SerializationFeature.INDENT_OUTPUT);
32 | 
33 |             output.println(mapper.writeValueAsString(availablePrekeys));
34 |         } catch (Exception e) {
35 |             Logger.exception("Exception during AvailablePrekeysTask", e);
36 |             output.println(e.getMessage());
37 |         }
38 |     }
39 | }
40 | 


--------------------------------------------------------------------------------
/src/main/java/com/wire/lithium/server/tasks/ConversationTask.java:
--------------------------------------------------------------------------------
 1 | package com.wire.lithium.server.tasks;
 2 | 
 3 | import com.fasterxml.jackson.databind.ObjectMapper;
 4 | import com.fasterxml.jackson.databind.SerializationFeature;
 5 | import com.wire.lithium.ClientRepo;
 6 | import com.wire.xenon.WireClient;
 7 | import com.wire.xenon.backend.models.Conversation;
 8 | import com.wire.xenon.tools.Logger;
 9 | 
10 | import java.io.PrintWriter;
11 | import java.util.List;
12 | import java.util.Map;
13 | import java.util.UUID;
14 | 
15 | public class ConversationTask extends TaskBase {
16 |     private final ClientRepo repo;
17 | 
18 |     public ConversationTask(ClientRepo repo) {
19 |         super("conversation");
20 |         this.repo = repo;
21 |     }
22 | 
23 |     @Override
24 |     public void execute(Map<String, List<String>> parameters, PrintWriter output) {
25 |         UUID botId = UUID.fromString(extractString(parameters, "bot"));
26 | 
27 |         try {
28 |             WireClient client = repo.getClient(botId);
29 |             Conversation conversation = client.getConversation();
30 |             ObjectMapper mapper = new ObjectMapper();
31 |             mapper.enable(SerializationFeature.INDENT_OUTPUT);
32 | 
33 |             output.println(mapper.writeValueAsString(conversation));
34 |         } catch (Exception e) {
35 |             Logger.exception("Exception during ConversationTask.", e);
36 |             output.println(e.getMessage());
37 |         }
38 |     }
39 | }
40 | 


--------------------------------------------------------------------------------
/src/main/java/com/wire/lithium/server/tasks/TaskBase.java:
--------------------------------------------------------------------------------
 1 | package com.wire.lithium.server.tasks;
 2 | 
 3 | import io.dropwizard.servlets.tasks.Task;
 4 | 
 5 | import java.util.List;
 6 | import java.util.Map;
 7 | 
 8 | public abstract class TaskBase extends Task {
 9 | 
10 |     public TaskBase(String name) {
11 |         super(name);
12 |     }
13 | 
14 |     protected static int extract(Map<String, List<String>> parameters, String name) {
15 |         return extract(parameters, name, 0);
16 |     }
17 | 
18 |     protected static int extract(Map<String, List<String>> parameters, String name, int def) {
19 |         int val = def;
20 |         final List<String> usr = parameters.get(name);
21 |         if (!usr.isEmpty()) {
22 |             String id = usr.get(0);
23 |             val = Integer.parseInt(id);
24 |         }
25 | 
26 |         return val;
27 |     }
28 | 
29 |     protected static String extractString(Map<String, List<String>> parameters, String name, String def) {
30 |         final List<String> usr = parameters.get(name);
31 |         if (!usr.isEmpty()) {
32 |             return usr.get(0);
33 |         }
34 | 
35 |         return def;
36 |     }
37 | 
38 |     protected static String extractString(Map<String, List<String>> parameters, String name) {
39 |         return extractString(parameters, name, "");
40 |     }
41 | }
42 | 


--------------------------------------------------------------------------------
/src/main/java/com/wire/lithium/tools/AuthValidator.java:
--------------------------------------------------------------------------------
 1 | package com.wire.lithium.tools;
 2 | 
 3 | import com.wire.xenon.tools.Util;
 4 | 
 5 | public class AuthValidator {
 6 |     private final String auth;
 7 | 
 8 |     public AuthValidator(String auth) {
 9 |         this.auth = auth;
10 |     }
11 | 
12 |     public boolean validate(String auth) {
13 |         return Util.compareAuthorizations(this.auth, auth);
14 |     }
15 | 
16 |     public String getAuth() {
17 |         return auth;
18 |     }
19 | }
20 | 


--------------------------------------------------------------------------------
/src/test/java/com/wire/lithium/CryptoDatabaseTest.java:
--------------------------------------------------------------------------------
  1 | package com.wire.lithium;//
  2 | // Wire
  3 | // Copyright (C) 2016 Wire Swiss GmbH
  4 | //
  5 | // This program is free software: you can redistribute it and/or modify
  6 | // it under the terms of the GNU General Public License as published by
  7 | // the Free Software Foundation, either version 3 of the License, or
  8 | // (at your option) any later version.
  9 | //
 10 | // This program is distributed in the hope that it will be useful,
 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 13 | // GNU General Public License for more details.
 14 | //
 15 | // You should have received a copy of the GNU General Public License
 16 | // along with this program. If not, see http://www.gnu.org/licenses/.
 17 | //
 18 | 
 19 | import com.wire.lithium.helpers.MemStorage;
 20 | import com.wire.lithium.helpers.Util;
 21 | import com.wire.xenon.crypto.CryptoDatabase;
 22 | import com.wire.xenon.models.otr.Missing;
 23 | import com.wire.xenon.models.otr.PreKey;
 24 | import com.wire.xenon.models.otr.PreKeys;
 25 | import com.wire.xenon.models.otr.Recipients;
 26 | import org.junit.jupiter.api.AfterEach;
 27 | import org.junit.jupiter.api.Assertions;
 28 | import org.junit.jupiter.api.BeforeEach;
 29 | import org.junit.jupiter.api.Test;
 30 | 
 31 | import java.io.IOException;
 32 | import java.util.ArrayList;
 33 | import java.util.Base64;
 34 | import java.util.UUID;
 35 | 
 36 | public class CryptoDatabaseTest {
 37 |     private String rootFolder;
 38 | 
 39 |     private UUID bobId;
 40 |     private String bobClientId;
 41 |     private UUID aliceId;
 42 |     private String aliceClientId;
 43 | 
 44 |     private CryptoDatabase alice;
 45 |     private CryptoDatabase bob;
 46 |     private PreKeys bobKeys;
 47 |     private PreKeys aliceKeys;
 48 | 
 49 |     @BeforeEach
 50 |     public void setUp() throws Exception {
 51 |         rootFolder = "lithium-test-data-" + UUID.randomUUID();
 52 | 
 53 |         aliceId = UUID.randomUUID();
 54 |         aliceClientId = aliceClientId + "-client";
 55 |         bobId = UUID.randomUUID();
 56 |         bobClientId = bobId + "-client";
 57 | 
 58 |         MemStorage storage = new MemStorage();
 59 |         alice = new CryptoDatabase(aliceId, storage, rootFolder);
 60 |         bob = new CryptoDatabase(bobId, storage, rootFolder);
 61 | 
 62 |         ArrayList<PreKey> preKeys = bob.newPreKeys(0, 10);
 63 |         bobKeys = new PreKeys(preKeys, bobClientId, bobId);
 64 | 
 65 |         preKeys = alice.newPreKeys(0, 10);
 66 |         aliceKeys = new PreKeys(preKeys, aliceClientId, aliceId);
 67 |     }
 68 | 
 69 |     @AfterEach
 70 |     public void clean() throws IOException {
 71 |         alice.close();
 72 |         bob.close();
 73 |         Util.deleteDir(rootFolder);
 74 |     }
 75 | 
 76 |     @Test
 77 |     public void testAliceToBob() throws Exception {
 78 |         String text = "Hello Bob, This is Alice!";
 79 |         byte[] textBytes = text.getBytes();
 80 | 
 81 |         // Encrypt using prekeys
 82 |         Recipients encrypt = alice.encrypt(bobKeys, textBytes);
 83 | 
 84 |         String base64Encoded = encrypt.get(bobId, bobClientId);
 85 | 
 86 |         // Decrypt using initSessionFromMessage
 87 |         String decrypt = bob.decrypt(aliceId, aliceClientId, base64Encoded);
 88 |         byte[] decode = Base64.getDecoder().decode(decrypt);
 89 | 
 90 |         Assertions.assertArrayEquals(decode, textBytes);
 91 |         Assertions.assertEquals(text, new String(decode));
 92 |     }
 93 | 
 94 |     @Test
 95 |     public void testBobToAlice() throws Exception {
 96 |         String text = "Hello Alice, This is Bob!";
 97 |         byte[] textBytes = text.getBytes();
 98 | 
 99 |         Recipients encrypt = bob.encrypt(aliceKeys, textBytes);
100 | 
101 |         String base64Encoded = encrypt.get(aliceId, aliceClientId);
102 | 
103 |         // Decrypt using initSessionFromMessage
104 |         String decrypt = alice.decrypt(bobId, bobClientId, base64Encoded);
105 |         byte[] decode = Base64.getDecoder().decode(decrypt);
106 | 
107 |         Assertions.assertArrayEquals(decode, textBytes);
108 |         Assertions.assertEquals(text, new String(decode));
109 |     }
110 | 
111 |     @Test
112 |     public void testSessions() throws Exception {
113 |         String text = "Hello Alice, This is Bob, again!";
114 |         byte[] textBytes = text.getBytes();
115 | 
116 |         Missing devices = new Missing();
117 |         devices.add(aliceId, aliceClientId);
118 | 
119 |         Recipients encrypt = bob.encrypt(aliceKeys, textBytes);
120 | 
121 |         String base64Encoded = encrypt.get(aliceId, aliceClientId);
122 | 
123 |         // Decrypt using initSessionFromMessage
124 |         String decrypt = alice.decrypt(bobId, bobClientId, base64Encoded);
125 |         byte[] decode = Base64.getDecoder().decode(decrypt);
126 | 
127 |         Assertions.assertArrayEquals(decode, textBytes);
128 |         Assertions.assertEquals(text, new String(decode));
129 | 
130 |         // from session this time
131 |         text += " from session this time!";
132 |         textBytes = text.getBytes();
133 | 
134 |         encrypt = bob.encrypt(devices, textBytes);
135 | 
136 |         base64Encoded = encrypt.get(aliceId, aliceClientId);
137 | 
138 |         // Decrypt using session
139 |         decrypt = alice.decrypt(bobId, bobClientId, base64Encoded);
140 |         decode = Base64.getDecoder().decode(decrypt);
141 | 
142 |         Assertions.assertArrayEquals(decode, textBytes);
143 |         Assertions.assertEquals(text, new String(decode));
144 |     }
145 | }
146 | 


--------------------------------------------------------------------------------
/src/test/java/com/wire/lithium/CryptoFileTest.java:
--------------------------------------------------------------------------------
  1 | package com.wire.lithium;
  2 | //
  3 | // Wire
  4 | // Copyright (C) 2016 Wire Swiss GmbH
  5 | //
  6 | // This program is free software: you can redistribute it and/or modify
  7 | // it under the terms of the GNU General Public License as published by
  8 | // the Free Software Foundation, either version 3 of the License, or
  9 | // (at your option) any later version.
 10 | //
 11 | // This program is distributed in the hope that it will be useful,
 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 14 | // GNU General Public License for more details.
 15 | //
 16 | // You should have received a copy of the GNU General Public License
 17 | // along with this program. If not, see http://www.gnu.org/licenses/.
 18 | //
 19 | 
 20 | import com.wire.lithium.helpers.Util;
 21 | import com.wire.xenon.crypto.CryptoFile;
 22 | import com.wire.xenon.models.otr.Missing;
 23 | import com.wire.xenon.models.otr.PreKey;
 24 | import com.wire.xenon.models.otr.PreKeys;
 25 | import com.wire.xenon.models.otr.Recipients;
 26 | import org.junit.jupiter.api.AfterEach;
 27 | import org.junit.jupiter.api.Assertions;
 28 | import org.junit.jupiter.api.BeforeEach;
 29 | import org.junit.jupiter.api.Test;
 30 | 
 31 | import java.io.IOException;
 32 | import java.util.ArrayList;
 33 | import java.util.Base64;
 34 | import java.util.UUID;
 35 | 
 36 | public class CryptoFileTest {
 37 | 
 38 |     private UUID bobId;
 39 |     private String bobClientId;
 40 |     private UUID aliceId;
 41 |     private String aliceClientId;
 42 | 
 43 |     private String rootFolder;
 44 |     private CryptoFile alice;
 45 |     private CryptoFile bob;
 46 |     private PreKeys bobKeys;
 47 |     private PreKeys aliceKeys;
 48 | 
 49 |     @BeforeEach
 50 |     public void setUp() throws Exception {
 51 |         rootFolder = "lithium-test-data-" + UUID.randomUUID();
 52 | 
 53 |         aliceId = UUID.randomUUID();
 54 |         aliceClientId = aliceClientId + "-client";
 55 |         bobId = UUID.randomUUID();
 56 |         bobClientId = bobId + "-client";
 57 | 
 58 |         alice = new CryptoFile(rootFolder, aliceId);
 59 |         bob = new CryptoFile(rootFolder, bobId);
 60 | 
 61 |         ArrayList<PreKey> preKeys = bob.newPreKeys(0, 1);
 62 |         bobKeys = new PreKeys(preKeys, bobClientId, bobId);
 63 | 
 64 |         preKeys = alice.newPreKeys(0, 1);
 65 |         aliceKeys = new PreKeys(preKeys, aliceClientId, aliceId);
 66 |     }
 67 | 
 68 |     @AfterEach
 69 |     public void clean() throws IOException {
 70 |         alice.close();
 71 |         bob.close();
 72 |         Util.deleteDir(rootFolder);
 73 |     }
 74 | 
 75 |     @Test
 76 |     public void testAliceToBob() throws Exception {
 77 |         String text = "Hello Bob, This is Alice!";
 78 |         byte[] textBytes = text.getBytes();
 79 | 
 80 |         // Encrypt using prekeys
 81 |         Recipients encrypt = alice.encrypt(bobKeys, textBytes);
 82 | 
 83 |         String base64Encoded = encrypt.get(bobId, bobClientId);
 84 | 
 85 |         // Decrypt using initSessionFromMessage
 86 |         String decrypt = bob.decrypt(aliceId, aliceClientId, base64Encoded);
 87 |         byte[] decode = Base64.getDecoder().decode(decrypt);
 88 | 
 89 |         Assertions.assertArrayEquals(decode, textBytes);
 90 |         Assertions.assertEquals(text, new String(decode));
 91 |     }
 92 | 
 93 |     @Test
 94 |     public void testBobToAlice() throws Exception {
 95 |         String text = "Hello Alice, This is Bob!";
 96 |         byte[] textBytes = text.getBytes();
 97 | 
 98 |         Recipients encrypt = bob.encrypt(aliceKeys, textBytes);
 99 | 
100 |         String base64Encoded = encrypt.get(aliceId, aliceClientId);
101 | 
102 |         // Decrypt using initSessionFromMessage
103 |         String decrypt = alice.decrypt(bobId, bobClientId, base64Encoded);
104 |         byte[] decode = Base64.getDecoder().decode(decrypt);
105 | 
106 |         Assertions.assertArrayEquals(decode, textBytes);
107 |         Assertions.assertEquals(text, new String(decode));
108 |     }
109 | 
110 |     @Test
111 |     public void testSessions() throws Exception {
112 |         String text = "Hello Alice, This is Bob, again!";
113 |         byte[] textBytes = text.getBytes();
114 | 
115 |         Missing devices = new Missing();
116 |         devices.add(aliceId, aliceClientId);
117 | 
118 |         // use keys first
119 |         Recipients encrypt = bob.encrypt(aliceKeys, textBytes);
120 | 
121 |         String base64Encoded = encrypt.get(aliceId, aliceClientId);
122 | 
123 |         // Decrypt using initSessionFromMessage
124 |         String decrypt = alice.decrypt(bobId, bobClientId, base64Encoded);
125 |         byte[] decode = Base64.getDecoder().decode(decrypt);
126 | 
127 |         Assertions.assertArrayEquals(decode, textBytes);
128 |         Assertions.assertEquals(text, new String(decode));
129 | 
130 |         // and then session
131 |         text += " from session this time!";
132 |         textBytes = text.getBytes();
133 |         encrypt = bob.encrypt(devices, textBytes);
134 | 
135 |         base64Encoded = encrypt.get(aliceId, aliceClientId);
136 | 
137 |         // Decrypt using session
138 |         decrypt = alice.decrypt(bobId, bobClientId, base64Encoded);
139 |         decode = Base64.getDecoder().decode(decrypt);
140 | 
141 |         Assertions.assertArrayEquals(decode, textBytes);
142 |         Assertions.assertEquals(text, new String(decode));
143 |     }
144 | }
145 | 


--------------------------------------------------------------------------------
/src/test/java/com/wire/lithium/CryptoPostgresTest.java:
--------------------------------------------------------------------------------
  1 | package com.wire.lithium;
  2 | 
  3 | import com.wire.bots.cryptobox.CryptoBox;
  4 | import com.wire.bots.cryptobox.CryptoDb;
  5 | import com.wire.bots.cryptobox.IStorage;
  6 | import com.wire.bots.cryptobox.PreKey;
  7 | import com.wire.lithium.helpers.Util;
  8 | import com.wire.xenon.crypto.storage.JdbiStorage;
  9 | import org.junit.jupiter.api.*;
 10 | 
 11 | import java.io.IOException;
 12 | import java.util.ArrayList;
 13 | import java.util.Date;
 14 | import java.util.UUID;
 15 | import java.util.concurrent.ScheduledExecutorService;
 16 | import java.util.concurrent.ScheduledThreadPoolExecutor;
 17 | import java.util.concurrent.TimeUnit;
 18 | import java.util.concurrent.atomic.AtomicBoolean;
 19 | import java.util.concurrent.atomic.AtomicInteger;
 20 | 
 21 | public class CryptoPostgresTest extends DatabaseTestBase {
 22 |     private String rootFolder;
 23 |     private String bobId;
 24 |     private String aliceId;
 25 |     private CryptoDb alice;
 26 |     private CryptoDb bob;
 27 |     private PreKey[] bobKeys;
 28 |     private PreKey[] aliceKeys;
 29 |     private IStorage storage;
 30 | 
 31 |     @BeforeEach
 32 |     public void setUp() throws Exception {
 33 |         rootFolder = "lithium-crypto-test-" + UUID.randomUUID();
 34 |         flyway.migrate();
 35 |         storage = new JdbiStorage(jdbi);
 36 | 
 37 |         aliceId = UUID.randomUUID().toString();
 38 |         bobId = UUID.randomUUID().toString();
 39 | 
 40 |         alice = new CryptoDb(aliceId, storage, rootFolder);
 41 |         bob = new CryptoDb(bobId, storage, rootFolder);
 42 | 
 43 |         bobKeys = bob.newPreKeys(0, 1);
 44 |         aliceKeys = alice.newPreKeys(0, 1);
 45 |     }
 46 | 
 47 |     @AfterEach
 48 |     public void clean() throws IOException {
 49 |         alice.close();
 50 |         bob.close();
 51 |         Util.deleteDir(rootFolder);
 52 |         flyway.clean();
 53 |     }
 54 | 
 55 |     @Test
 56 |     public void testAliceToBob() throws Exception {
 57 |         String text = "Hello Bob, This is Alice!";
 58 | 
 59 |         // Encrypt using prekeys
 60 |         byte[] cipher = alice.encryptFromPreKeys(bobId, bobKeys[0], text.getBytes());
 61 | 
 62 |         // Decrypt using initSessionFromMessage
 63 |         byte[] decrypt = bob.decrypt(aliceId, cipher);
 64 | 
 65 |         Assertions.assertArrayEquals(decrypt, text.getBytes());
 66 |         Assertions.assertEquals(text, new String(decrypt));
 67 |     }
 68 | 
 69 |     @Test
 70 |     public void testBobToAlice() throws Exception {
 71 |         String text = "Hello Alice, This is Bob!";
 72 | 
 73 |         byte[] cipher = bob.encryptFromPreKeys(aliceId, aliceKeys[0], text.getBytes());
 74 | 
 75 |         // Decrypt using initSessionFromMessage
 76 |         byte[] decrypt = alice.decrypt(bobId, cipher);
 77 | 
 78 |         Assertions.assertArrayEquals(decrypt, text.getBytes());
 79 |         Assertions.assertEquals(text, new String(decrypt));
 80 |     }
 81 | 
 82 |     @Test
 83 |     public void testSessions() throws Exception {
 84 |         String text = "Hello Alice, This is Bob!";
 85 | 
 86 |         byte[] cipher = bob.encryptFromPreKeys(aliceId, aliceKeys[0], text.getBytes());
 87 | 
 88 |         // Decrypt using initSessionFromMessage
 89 |         byte[] decrypt = alice.decrypt(bobId, cipher);
 90 | 
 91 |         Assertions.assertArrayEquals(decrypt, text.getBytes());
 92 |         Assertions.assertEquals(text, new String(decrypt));
 93 | 
 94 |         // and then from session
 95 |         text += " From session this time!";
 96 | 
 97 |         cipher = bob.encryptFromSession(aliceId, text.getBytes());
 98 | 
 99 |         // Decrypt using session
100 |         decrypt = alice.decrypt(bobId, cipher);
101 | 
102 |         Assertions.assertArrayEquals(decrypt, text.getBytes());
103 |         Assertions.assertEquals(text, new String(decrypt));
104 |     }
105 | 
106 |     @Test
107 |     public void testIdentity() throws Exception {
108 |         final String carlId = UUID.randomUUID().toString();
109 |         final String dir = rootFolder + "/" + carlId;
110 | 
111 |         CryptoDb carl = new CryptoDb(carlId, storage);
112 |         PreKey[] carlPrekeys = carl.newPreKeys(0, 8);
113 | 
114 |         var daveId = UUID.randomUUID().toString();
115 |         var davePath = String.format("%s/%s", rootFolder, daveId);
116 |         var dave = CryptoBox.open(davePath);
117 |         var davePrekeys = dave.newPreKeys(0, 8);
118 | 
119 |         String text = "Hello Bob, This is Carl!";
120 | 
121 |         // Encrypt using prekeys
122 |         byte[] cipher = dave.encryptFromPreKeys(carlId, carlPrekeys[0], text.getBytes());
123 |         byte[] decrypt = carl.decrypt(daveId, cipher);
124 |         Assertions.assertArrayEquals(decrypt, text.getBytes());
125 |         Assertions.assertEquals(text, new String(decrypt));
126 | 
127 |         carl.close();
128 |         Util.deleteDir(dir);
129 | 
130 |         cipher = dave.encryptFromSession(carlId, text.getBytes());
131 |         carl = new CryptoDb(carlId, storage);
132 |         decrypt = carl.decrypt(daveId, cipher);
133 | 
134 |         Assertions.assertArrayEquals(decrypt, text.getBytes());
135 |         Assertions.assertEquals(text, new String(decrypt));
136 | 
137 |         carl.close();
138 |         Util.deleteDir(dir);
139 | 
140 |         carl = new CryptoDb(carlId, storage);
141 | 
142 |         cipher = carl.encryptFromPreKeys(daveId, davePrekeys[0], text.getBytes());
143 |         decrypt = dave.decrypt(carlId, cipher);
144 |         Assertions.assertArrayEquals(decrypt, text.getBytes());
145 |         Assertions.assertEquals(text, new String(decrypt));
146 | 
147 |         carl.close();
148 |     }
149 | 
150 |     @Test
151 |     public void testSynchronousSingleSession() throws Exception {
152 |         // initialize test with first prekeys
153 |         String text = "Hello Alice, This is Bob!";
154 | 
155 |         byte[] cipher = bob.encryptFromPreKeys(aliceId, aliceKeys[0], text.getBytes());
156 | 
157 |         // Decrypt using initSessionFromMessage
158 |         byte[] decrypt = alice.decrypt(bobId, cipher);
159 | 
160 |         Assertions.assertArrayEquals(decrypt, text.getBytes());
161 |         Assertions.assertEquals(text, new String(decrypt));
162 | 
163 |         // and then run sessions tests
164 |         Date s = new Date();
165 |         for (int i = 0; i < 100; i++) {
166 |             text = "Hello Alice, This is Bob, again! " + i;
167 | 
168 |             cipher = bob.encryptFromSession(aliceId, text.getBytes());
169 | 
170 |             // Decrypt using session
171 |             decrypt = alice.decrypt(bobId, cipher);
172 | 
173 |             Assertions.assertArrayEquals(decrypt, text.getBytes());
174 |             Assertions.assertEquals(text, new String(decrypt));
175 | 
176 |             text = "Hey Bob, How's life? " + i;
177 | 
178 |             cipher = alice.encryptFromSession(bobId, text.getBytes());
179 | 
180 |             // Decrypt using session
181 |             decrypt = bob.decrypt(aliceId, cipher);
182 | 
183 |             Assertions.assertArrayEquals(decrypt, text.getBytes());
184 |             Assertions.assertEquals(text, new String(decrypt));
185 |         }
186 |         Date e = new Date();
187 |         long delta = e.getTime() - s.getTime();
188 | 
189 |         System.out.printf("Count: %,d,  Elapsed: %,d ms\n", 100, delta);
190 |     }
191 | 
192 |     @Test
193 |     // TODO fix me
194 |     @Disabled("This test fails with more executors then 1")
195 |     public void testConcurrentSingleSession() throws Exception {
196 |         final String text = "Hello Alice, This is Bob, again! ";
197 | 
198 |         var cipher = bob.encryptFromPreKeys(aliceId, aliceKeys[0], text.getBytes());
199 |         var decrypt = alice.decrypt(bobId, cipher);
200 |         Assertions.assertArrayEquals(text.getBytes(), decrypt);
201 | 
202 |         ScheduledExecutorService executor = new ScheduledThreadPoolExecutor(4);
203 |         final AtomicInteger counter = new AtomicInteger(0);
204 | 
205 |         var testFailed = new AtomicBoolean(false);
206 |         for (int i = 0; i < 100; i++) {
207 |             executor.execute(() -> {
208 |                 try {
209 |                     bob.encryptFromSession(aliceId, text.getBytes());
210 |                     counter.getAndIncrement();
211 |                 } catch (Exception e) {
212 |                     System.out.println("testConcurrentSessions: " + e);
213 |                     e.printStackTrace();
214 |                     testFailed.set(true);
215 |                 }
216 |             });
217 |         }
218 |         Date s = new Date();
219 |         executor.shutdown();
220 |         // we don't care if it has to shut it down or not
221 |         //noinspection ResultOfMethodCallIgnored
222 |         executor.awaitTermination(60, TimeUnit.SECONDS);
223 |         Date e = new Date();
224 |         long delta = e.getTime() - s.getTime();
225 | 
226 |         System.out.printf("Count: %,d,  Elapsed: %,d ms\n", counter.get(), delta);
227 |         if (testFailed.get()) {
228 |             Assertions.fail("See logs");
229 |         }
230 |     }
231 | 
232 |     @Test
233 |     public void testConcurrentMultipleSessions() throws Exception {
234 |         final var count = 100;
235 |         var aliceId = UUID.randomUUID().toString();
236 |         CryptoDb alice = new CryptoDb(aliceId, storage);
237 |         PreKey[] aliceKeys = alice.newPreKeys(0, count);
238 | 
239 |         final AtomicInteger counter = new AtomicInteger(0);
240 |         byte[] bytes = ("Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello " +
241 |                 "Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello " +
242 |                 "Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello " +
243 |                 "Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello ").getBytes();
244 | 
245 | 
246 |         var boxes = new ArrayList<CryptoDb>();
247 | 
248 |         for (int i = 0; i < count; i++) {
249 |             String bobId = UUID.randomUUID().toString();
250 |             CryptoDb bob = new CryptoDb(bobId, storage);
251 |             bob.encryptFromPreKeys(aliceId, aliceKeys[i], bytes);
252 |             boxes.add(bob);
253 |         }
254 | 
255 |         ScheduledExecutorService executor = new ScheduledThreadPoolExecutor(24);
256 |         Date s = new Date();
257 |         var testFailed = new AtomicBoolean(false);
258 |         for (CryptoDb bob : boxes) {
259 |             executor.execute(() -> {
260 |                 try {
261 |                     bob.encryptFromSession(aliceId, bytes);
262 |                     counter.getAndIncrement();
263 |                 } catch (Exception e) {
264 |                     System.out.println("testConcurrentDifferentCBSessions: " + e);
265 |                     e.printStackTrace();
266 |                     testFailed.set(true);
267 |                 }
268 |             });
269 |         }
270 | 
271 |         executor.shutdown();
272 |         // we don't care if it has to shut it down or not
273 |         //noinspection ResultOfMethodCallIgnored
274 |         executor.awaitTermination(60, TimeUnit.SECONDS);
275 | 
276 |         Date e = new Date();
277 |         long delta = e.getTime() - s.getTime();
278 | 
279 |         System.out.printf("testConcurrentMultipleSessions: Count: %,d,  Elapsed: %,d ms, avg: %.1f/sec\n",
280 |                 counter.get(), delta, (count * 1000f) / delta);
281 | 
282 |         for (CryptoDb bob : boxes) {
283 |             bob.close();
284 |         }
285 |         alice.close();
286 |         if (testFailed.get()) {
287 |             Assertions.fail("See logs");
288 |         }
289 |     }
290 | }
291 | 


--------------------------------------------------------------------------------
/src/test/java/com/wire/lithium/DatabaseTestBase.java:
--------------------------------------------------------------------------------
 1 | package com.wire.lithium;
 2 | 
 3 | import com.codahale.metrics.MetricRegistry;
 4 | import io.dropwizard.db.DataSourceFactory;
 5 | import io.dropwizard.db.ManagedDataSource;
 6 | import org.flywaydb.core.Flyway;
 7 | import org.jdbi.v3.core.Jdbi;
 8 | import org.jdbi.v3.sqlobject.SqlObjectPlugin;
 9 | import org.junit.jupiter.api.AfterAll;
10 | import org.junit.jupiter.api.BeforeAll;
11 | 
12 | abstract public class DatabaseTestBase {
13 |     protected static Flyway flyway;
14 |     protected static Jdbi jdbi;
15 | 
16 |     @BeforeAll
17 |     public static void initiate() {
18 |         DataSourceFactory dataSourceFactory = new DataSourceFactory();
19 |         dataSourceFactory.setDriverClass("org.postgresql.Driver");
20 | 
21 |         String envUrl = System.getenv("POSTGRES_URL");
22 |         dataSourceFactory.setUrl("jdbc:postgresql://" + (envUrl != null ? envUrl : "localhost/lithium"));
23 |         String envUser = System.getenv("POSTGRES_USER");
24 |         if (envUser != null) dataSourceFactory.setUser(envUser);
25 |         String envPassword = System.getenv("POSTGRES_PASSWORD");
26 |         if (envPassword != null) dataSourceFactory.setPassword(envPassword);
27 | 
28 |         // Migrate DB if needed
29 |         flyway = Flyway
30 |                 .configure()
31 |                 .cleanDisabled(false)
32 |                 .dataSource(dataSourceFactory.getUrl(), dataSourceFactory.getUser(), dataSourceFactory.getPassword())
33 |                 .baselineOnMigrate(true)
34 |                 .load();
35 | 
36 |         ManagedDataSource dataSource = dataSourceFactory.build(new MetricRegistry(), "CryptoPostgresTest");
37 | 
38 |         jdbi = Jdbi.create(dataSource).installPlugin(new SqlObjectPlugin());
39 |     }
40 | 
41 |     @AfterAll
42 |     public static void classCleanup() {
43 |         flyway.clean();
44 |     }
45 | }
46 | 


--------------------------------------------------------------------------------
/src/test/java/com/wire/lithium/MentionTest.java:
--------------------------------------------------------------------------------
 1 | package com.wire.lithium;
 2 | 
 3 | 
 4 | import org.junit.jupiter.api.Test;
 5 | 
 6 | import static com.wire.xenon.tools.Util.mentionLen;
 7 | import static com.wire.xenon.tools.Util.mentionStart;
 8 | 
 9 | public class MentionTest {
10 |     @Test
11 |     public void beginExtractMentionTest() {
12 |         String txt = "@dejan This is a mention";
13 |         int offset = mentionStart(txt);
14 |         int len = mentionLen(txt);
15 |         String mention = txt.substring(offset, offset + len);
16 | 
17 |         assert offset == 0;
18 |         assert len == 6;
19 |         assert mention.equals("@dejan");
20 |     }
21 | 
22 |     @Test
23 |     public void middleExtractMentionTest() {
24 |         String txt = "Hey @dejan_wire This is a mention";
25 |         int offset = mentionStart(txt);
26 |         int len = mentionLen(txt);
27 |         String mention = txt.substring(offset, offset + len);
28 | 
29 |         assert offset == 4;
30 |         assert len == 11;
31 |         assert mention.equals("@dejan_wire");
32 |     }
33 | 
34 |     @Test
35 |     public void endExtractMentionTest() {
36 |         String txt = "This is a mention @dejan";
37 |         int offset = mentionStart(txt);
38 |         int len = mentionLen(txt);
39 |         String mention = txt.substring(offset, offset + len);
40 | 
41 |         assert offset == 18;
42 |         assert len == 6;
43 | 
44 |         assert mention.equals("@dejan");
45 |     }
46 | 
47 |     @Test
48 |     public void specialExtractMentionTest() {
49 |         String txt = "@ This is @dejan: A mention ";
50 |         int offset = mentionStart(txt);
51 |         int len = mentionLen(txt);
52 |         String mention = txt.substring(offset, offset + len);
53 | 
54 |         assert mention.equals("@dejan");
55 |     }
56 | }
57 | 


--------------------------------------------------------------------------------
/src/test/java/com/wire/lithium/PostgresCryptoStorageTest.java:
--------------------------------------------------------------------------------
  1 | package com.wire.lithium;
  2 | 
  3 | import com.wire.bots.cryptobox.IRecord;
  4 | import com.wire.bots.cryptobox.PreKey;
  5 | import com.wire.xenon.crypto.storage.JdbiStorage;
  6 | import org.junit.jupiter.api.AfterEach;
  7 | import org.junit.jupiter.api.Assertions;
  8 | import org.junit.jupiter.api.BeforeEach;
  9 | import org.junit.jupiter.api.Test;
 10 | 
 11 | import java.util.ArrayList;
 12 | import java.util.Random;
 13 | 
 14 | public class PostgresCryptoStorageTest extends DatabaseTestBase {
 15 | 
 16 |     private JdbiStorage storage;
 17 | 
 18 |     @BeforeEach
 19 |     public void setUp() {
 20 |         flyway.migrate();
 21 |         storage = new JdbiStorage(jdbi);
 22 |     }
 23 | 
 24 |     @AfterEach
 25 |     public void clean() {
 26 |         flyway.clean();
 27 |     }
 28 | 
 29 |     @Test
 30 |     public void testFetchSession() {
 31 |         Random random = new Random();
 32 |         String id = "" + random.nextInt();
 33 |         String sid = "" + random.nextInt();
 34 | 
 35 |         IRecord record = storage.fetchSession(id, sid);
 36 |         Assertions.assertNull(record.getData());
 37 | 
 38 |         byte[] data = new byte[1024];
 39 |         random.nextBytes(data);
 40 | 
 41 |         record.persist(data);
 42 | 
 43 |         record = storage.fetchSession(id, sid);
 44 |         Assertions.assertNotNull(record.getData());
 45 |         Assertions.assertArrayEquals(data, record.getData());
 46 | 
 47 |         record.persist(data);
 48 |     }
 49 | 
 50 |     @Test
 51 |     public void testFetchIdentity() {
 52 |         Random random = new Random();
 53 |         String id = "" + random.nextInt();
 54 | 
 55 |         byte[] identity = storage.fetchIdentity(id);
 56 |         Assertions.assertNull(identity);
 57 | 
 58 |         identity = new byte[1024];
 59 |         random.nextBytes(identity);
 60 | 
 61 |         storage.insertIdentity(id, identity);
 62 | 
 63 |         byte[] control = storage.fetchIdentity(id);
 64 |         Assertions.assertNotNull(control);
 65 |         Assertions.assertArrayEquals(identity, control);
 66 |     }
 67 | 
 68 |     @Test
 69 |     public void testFetchLastPrekey() {
 70 |         Random random = new Random();
 71 |         String id = "" + random.nextInt();
 72 | 
 73 |         PreKey[] preKeys = storage.fetchPrekeys(id);
 74 |         Assertions.assertNull(preKeys);
 75 | 
 76 |         byte[] data = new byte[1024];
 77 |         random.nextBytes(data);
 78 |         PreKey preKey = new PreKey(0xFFFF, data);
 79 | 
 80 |         storage.insertPrekey(id, preKey.id, preKey.data);
 81 | 
 82 |         PreKey[] control = storage.fetchPrekeys(id);
 83 | 
 84 |         Assertions.assertNotNull(control);
 85 |         Assertions.assertEquals(1, control.length);
 86 | 
 87 |         PreKey controlKey = control[0];
 88 | 
 89 |         Assertions.assertEquals(preKey.id, controlKey.id);
 90 |         Assertions.assertArrayEquals(preKey.data, controlKey.data);
 91 |     }
 92 | 
 93 |     @Test
 94 |     public void testFetchPrekeys() {
 95 |         int SIZE = 10;
 96 |         Random random = new Random();
 97 |         String id = "" + random.nextInt();
 98 | 
 99 |         PreKey[] preKeys = storage.fetchPrekeys(id);
100 |         Assertions.assertNull(preKeys);
101 | 
102 |         ArrayList<PreKey> prekeys = new ArrayList<>();
103 |         for (int i = 0; i < SIZE; i++) {
104 |             byte[] data = new byte[1024];
105 |             random.nextBytes(data);
106 |             PreKey preKey = new PreKey(i, data);
107 |             prekeys.add(preKey);
108 | 
109 |             storage.insertPrekey(id, preKey.id, preKey.data);
110 |         }
111 | 
112 |         PreKey[] control = storage.fetchPrekeys(id);
113 | 
114 |         Assertions.assertNotNull(control);
115 |         Assertions.assertEquals(SIZE, control.length);
116 |         for (int i = 0; i < SIZE; i++) {
117 |             PreKey preKey = prekeys.get(i);
118 |             PreKey controlKey = control[i];
119 | 
120 |             Assertions.assertEquals(preKey.id, controlKey.id);
121 |             Assertions.assertArrayEquals(preKey.data, controlKey.data);
122 |         }
123 |     }
124 | 
125 |     @Test
126 |     public void testPurge() {
127 |         Random random = new Random();
128 |         String id = "" + random.nextInt();
129 | 
130 |         //Identity
131 |         byte[] data = new byte[1024];
132 |         random.nextBytes(data);
133 |         storage.insertIdentity(id, data);
134 | 
135 |         //Prekeys
136 |         random.nextBytes(data);
137 |         PreKey preKey = new PreKey(0xFFFF, data);
138 |         storage.insertPrekey(id, preKey.id, preKey.data);
139 | 
140 |         //Session
141 |         String sid = "" + random.nextInt();
142 |         IRecord record = storage.fetchSession(id, sid);
143 |         random.nextBytes(data);
144 |         record.persist(data);
145 | 
146 |         storage.purge(id);
147 | 
148 |         byte[] identity = storage.fetchIdentity(id);
149 |         Assertions.assertNull(identity);
150 | 
151 |         PreKey[] preKeys = storage.fetchPrekeys(id);
152 |         Assertions.assertNull(preKeys);
153 | 
154 |         record = storage.fetchSession(id, sid);
155 |         Assertions.assertNull(record.getData());
156 |     }
157 | }
158 | 


--------------------------------------------------------------------------------
/src/test/java/com/wire/lithium/PostgresStateTest.java:
--------------------------------------------------------------------------------
 1 | package com.wire.lithium;
 2 | 
 3 | import com.wire.xenon.backend.models.Conversation;
 4 | import com.wire.xenon.backend.models.NewBot;
 5 | import com.wire.xenon.state.JdbiState;
 6 | import org.junit.jupiter.api.AfterEach;
 7 | import org.junit.jupiter.api.Assertions;
 8 | import org.junit.jupiter.api.BeforeEach;
 9 | import org.junit.jupiter.api.Test;
10 | 
11 | import java.util.UUID;
12 | 
13 | public class PostgresStateTest extends DatabaseTestBase {
14 | 
15 |     private JdbiState storage;
16 |     private UUID botId;
17 | 
18 |     @BeforeEach
19 |     public void setup() {
20 |         flyway.migrate();
21 |         botId = UUID.randomUUID();
22 |         storage = new JdbiState(botId, jdbi);
23 |     }
24 | 
25 |     @AfterEach
26 |     public void teardown() {
27 |         flyway.clean();
28 |     }
29 | 
30 |     @Test
31 |     public void test() throws Exception {
32 |         NewBot bot = new NewBot();
33 |         bot.id = botId;
34 |         bot.client = "client";
35 |         bot.locale = "en";
36 |         bot.token = "token";
37 |         bot.conversation = new Conversation();
38 |         bot.conversation.id = UUID.randomUUID();
39 |         bot.conversation.name = "conv";
40 | 
41 |         boolean b = storage.saveState(bot);
42 |         Assertions.assertTrue(b);
43 | 
44 |         NewBot state = storage.getState();
45 |         Assertions.assertNotNull(state);
46 |         Assertions.assertEquals(bot.id, state.id);
47 |         Assertions.assertEquals(bot.conversation.name, state.conversation.name);
48 | 
49 |         boolean removeState = storage.removeState();
50 |         Assertions.assertTrue(removeState);
51 |     }
52 | }
53 | 


--------------------------------------------------------------------------------
/src/test/java/com/wire/lithium/WireBackendTest.java:
--------------------------------------------------------------------------------
  1 | package com.wire.lithium;
  2 | 
  3 | import com.waz.model.Messages;
  4 | import com.wire.bots.cryptobox.CryptoException;
  5 | import com.wire.lithium.models.NewBotResponseModel;
  6 | import com.wire.xenon.MessageHandlerBase;
  7 | import com.wire.xenon.WireClient;
  8 | import com.wire.xenon.backend.models.Conversation;
  9 | import com.wire.xenon.backend.models.NewBot;
 10 | import com.wire.xenon.backend.models.Payload;
 11 | import com.wire.xenon.backend.models.User;
 12 | import com.wire.xenon.crypto.Crypto;
 13 | import com.wire.xenon.factories.CryptoFactory;
 14 | import com.wire.xenon.models.PingMessage;
 15 | import com.wire.xenon.models.otr.PreKeys;
 16 | import com.wire.xenon.models.otr.Recipients;
 17 | import com.wire.xenon.tools.Logger;
 18 | import io.dropwizard.core.setup.Environment;
 19 | import io.dropwizard.testing.ConfigOverride;
 20 | import io.dropwizard.testing.DropwizardTestSupport;
 21 | import jakarta.ws.rs.client.Entity;
 22 | import jakarta.ws.rs.client.WebTarget;
 23 | import jakarta.ws.rs.core.MediaType;
 24 | import jakarta.ws.rs.core.Response;
 25 | import org.junit.jupiter.api.AfterEach;
 26 | import org.junit.jupiter.api.BeforeEach;
 27 | import org.junit.jupiter.api.Test;
 28 | 
 29 | import java.io.IOException;
 30 | import java.util.ArrayList;
 31 | import java.util.Date;
 32 | import java.util.LinkedList;
 33 | import java.util.UUID;
 34 | 
 35 | import static org.assertj.core.api.Assertions.assertThat;
 36 | 
 37 | public class WireBackendTest extends DatabaseTestBase {
 38 |     private String serviceAuth;
 39 |     private String BOT_CLIENT_DUMMY;
 40 |     private String USER_CLIENT_DUMMY;
 41 |     private DropwizardTestSupport<Configuration> support;
 42 | 
 43 |     private WebTarget target;
 44 |     private CryptoFactory cryptoFactory;
 45 | 
 46 |     @BeforeEach
 47 |     public void setup() throws Exception {
 48 |         serviceAuth = UUID.randomUUID().toString();
 49 |         BOT_CLIENT_DUMMY = UUID.randomUUID().toString();
 50 |         USER_CLIENT_DUMMY = UUID.randomUUID().toString();
 51 | 
 52 |         String envUrl = System.getenv("POSTGRES_URL");
 53 |         var databaseUrl = "jdbc:postgresql://" + (envUrl != null ? envUrl : "localhost/lithium");
 54 |         var envUser = System.getenv("POSTGRES_USER");
 55 |         var envPassword = System.getenv("POSTGRES_PASSWORD");
 56 |         var overrides = new LinkedList<ConfigOverride>();
 57 |         overrides.push(ConfigOverride.config("token", serviceAuth));
 58 |         overrides.push(ConfigOverride.config("database.driverClass", "org.postgresql.Driver"));
 59 |         overrides.push(ConfigOverride.config("database.url", databaseUrl));
 60 | 
 61 |         overrides.push(ConfigOverride.config("jerseyClient.timeout", "40s"));
 62 |         overrides.push(ConfigOverride.config("jerseyClient.connectionTimeout", "40s"));
 63 |         overrides.push(ConfigOverride.config("jerseyClient.connectionRequestTimeout", "40s"));
 64 |         overrides.push(ConfigOverride.config("jerseyClient.retries", "3"));
 65 | 
 66 |         if (envUser != null) {
 67 |             overrides.push(ConfigOverride.config("database.user", envUser));
 68 |         }
 69 |         if (envPassword != null) {
 70 |             overrides.push(ConfigOverride.config("database.password", envPassword));
 71 |         }
 72 | 
 73 |         // sad java noises..
 74 |         ConfigOverride[] arrs = new ConfigOverride[overrides.size()];
 75 |         for (int i = 0; i < overrides.size(); i++) {
 76 |             arrs[i] = overrides.get(i);
 77 |         }
 78 | 
 79 |         flyway.migrate();
 80 | 
 81 |         support = new DropwizardTestSupport<>(
 82 |                 TestServer.class,
 83 |                 null,
 84 |                 arrs
 85 |         );
 86 | 
 87 |         support.before();
 88 | 
 89 |         final TestServer server = support.getApplication();
 90 | 
 91 |         cryptoFactory = server.getCryptoFactory();
 92 |         target = server.getClient().target("http://localhost:" + support.getLocalPort());
 93 |     }
 94 | 
 95 |     @AfterEach
 96 |     public void cleanup() {
 97 |         support.after();
 98 |         flyway.clean();
 99 |     }
100 | 
101 |     @Test
102 |     public void incomingMessageFromBackendTest() throws CryptoException, IOException {
103 |         final UUID botId = UUID.randomUUID();
104 |         final UUID userId = UUID.randomUUID();
105 |         final UUID convId = UUID.randomUUID();
106 | 
107 |         // Test GET /status
108 |         final int status = target
109 |                 .path("status")
110 |                 .request()
111 |                 .get()
112 |                 .getStatus();
113 |         assertThat(status).isEqualTo(200);
114 | 
115 |         // Test Bot added into conv. BE calls POST /bots with NewBot object
116 |         NewBotResponseModel newBotResponseModel = newBotFromBE(botId, userId, convId);
117 |         assertThat(newBotResponseModel.lastPreKey).isNotNull();
118 |         assertThat(newBotResponseModel.preKeys).isNotNull();
119 | 
120 |         final Crypto crypto = cryptoFactory.create(botId);
121 |         PreKeys preKeys = new PreKeys(newBotResponseModel.preKeys, USER_CLIENT_DUMMY, userId);
122 | 
123 |         // Test Ping message is sent to Echo by the BE. BE calls POST /bots/{botId}/messages with Payload obj
124 |         Recipients encrypt = crypto.encrypt(preKeys, generatePingMessage());
125 |         String cypher = encrypt.get(userId, USER_CLIENT_DUMMY);
126 |         Response res = newOtrMessageFromBackend(botId, userId, convId, cypher);
127 |         assertThat(res.getStatus()).isEqualTo(200);
128 | 
129 |         crypto.close();
130 |     }
131 | 
132 |     private NewBotResponseModel newBotFromBE(UUID botId, UUID userId, UUID convId) {
133 |         NewBot newBot = new NewBot();
134 |         newBot.id = botId;
135 |         newBot.locale = "en";
136 |         newBot.token = "token_dummy";
137 |         newBot.client = BOT_CLIENT_DUMMY;
138 |         newBot.origin = new User();
139 |         newBot.origin.id = userId;
140 |         newBot.origin.name = "user_name";
141 |         newBot.origin.handle = "user_handle";
142 |         newBot.conversation = new Conversation();
143 |         newBot.conversation.id = convId;
144 |         newBot.conversation.name = "conv_name";
145 |         newBot.conversation.creator = userId;
146 |         newBot.conversation.members = new ArrayList<>();
147 | 
148 |         try (Response res = target
149 |                 .path("bots")
150 |                 .request()
151 |                 .header("Authorization", "Bearer " + serviceAuth)
152 |                 .post(Entity.entity(newBot, MediaType.APPLICATION_JSON_TYPE))) {
153 | 
154 |             assertThat(res.getStatus()).isEqualTo(201);
155 | 
156 |             return res.readEntity(NewBotResponseModel.class);
157 |         }
158 |     }
159 | 
160 |     private Response newOtrMessageFromBackend(UUID botId, UUID userId, UUID convId, String cypher) {
161 |         Payload payload = new Payload();
162 |         payload.type = "conversation.otr-message-add";
163 |         payload.from = new Payload.Qualified(userId, "");
164 |         payload.conversation = new Payload.Qualified(convId, "");
165 |         payload.time = new Date().toString();
166 |         payload.data = new Payload.Data();
167 |         payload.data.sender = USER_CLIENT_DUMMY;
168 |         payload.data.recipient = BOT_CLIENT_DUMMY;
169 |         payload.data.text = cypher;
170 | 
171 |         return target
172 |                 .path("bots")
173 |                 .path(botId.toString())
174 |                 .path("messages")
175 |                 .request()
176 |                 .header("Authorization", "Bearer " + serviceAuth)
177 |                 .post(Entity.entity(payload, MediaType.APPLICATION_JSON_TYPE));
178 |     }
179 | 
180 |     private byte[] generatePingMessage() {
181 |         return Messages.GenericMessage.newBuilder()
182 |                 .setMessageId(UUID.randomUUID().toString())
183 |                 .setKnock(Messages.Knock.newBuilder().setHotKnock(false))
184 |                 .build()
185 |                 .toByteArray();
186 |     }
187 | 
188 |     public static class TestServer extends Server<Configuration> {
189 |         @Override
190 |         protected MessageHandlerBase createHandler(Configuration configuration, Environment env) {
191 |             return new MessageHandlerBase() {
192 |                 @Override
193 |                 public void onPing(WireClient client, PingMessage msg) {
194 |                     Logger.info("onPing: %s user: %s", client.getId(), msg.getUserId());
195 |                 }
196 |             };
197 |         }
198 |     }
199 | }
200 | 


--------------------------------------------------------------------------------
/src/test/java/com/wire/lithium/helpers/MemStorage.java:
--------------------------------------------------------------------------------
 1 | package com.wire.lithium.helpers;
 2 | 
 3 | import com.wire.bots.cryptobox.IRecord;
 4 | import com.wire.bots.cryptobox.IStorage;
 5 | import com.wire.bots.cryptobox.PreKey;
 6 | 
 7 | import java.util.ArrayList;
 8 | import java.util.concurrent.ConcurrentHashMap;
 9 | 
10 | public class MemStorage implements IStorage {
11 |     private final ConcurrentHashMap<String, Record> sessions = new ConcurrentHashMap<>();
12 |     private final ConcurrentHashMap<String, byte[]> identities = new ConcurrentHashMap<>();
13 |     private final ConcurrentHashMap<String, ArrayList<PreKey>> prekeys = new ConcurrentHashMap<>();
14 | 
15 |     @Override
16 |     public IRecord fetchSession(String id, String sid) {
17 |         String key = key(id, sid);
18 |         Record record = sessions.computeIfAbsent(key, k -> null);
19 |         if (record == null)
20 |             return new Record(key, null);
21 | 
22 |         for (int i = 0; i < 1000 && record.locked; i++) {
23 |             sleep(1);
24 |             record = sessions.get(key);
25 |         }
26 |         record.locked = true;
27 |         //sessions.put(key, record);
28 |         return new Record(key, record.data);
29 |     }
30 | 
31 |     @Override
32 |     public byte[] fetchIdentity(String id) {
33 |         return identities.get(id);
34 |     }
35 | 
36 |     @Override
37 |     public void insertIdentity(String id, byte[] data) {
38 |         identities.put(id, data);
39 |     }
40 | 
41 |     @Override
42 |     public PreKey[] fetchPrekeys(String id) {
43 |         ArrayList<PreKey> ret = prekeys.get(id);
44 |         return ret == null ? null : ret.toArray(new PreKey[0]);
45 |     }
46 | 
47 |     @Override
48 |     public void insertPrekey(String id, int kid, byte[] data) {
49 |         PreKey preKey = new PreKey(kid, data);
50 |         ArrayList<PreKey> list = prekeys.computeIfAbsent(id, k -> new ArrayList<>());
51 |         list.add(preKey);
52 |     }
53 | 
54 |     @Override
55 |     public void purge(String id) {
56 |         sessions.remove(id);
57 |         prekeys.remove(id);
58 |         identities.remove(id);
59 |     }
60 | 
61 |     private void sleep(int millis) {
62 |         try {
63 |             Thread.sleep(millis);
64 |         } catch (InterruptedException ignored) {
65 |         }
66 |     }
67 | 
68 |     private String key(String id, String sid) {
69 |         return String.format("%s-%s", id, sid);
70 |     }
71 | 
72 |     private static class Record implements IRecord {
73 |         boolean locked;
74 |         //private final String key;
75 |         private byte[] data;
76 | 
77 |         Record(String key, byte[] data) {
78 |             //this.key = key;
79 |             this.data = data;
80 |         }
81 | 
82 |         @Override
83 |         public byte[] getData() {
84 |             return data;
85 |         }
86 | 
87 |         @Override
88 |         public void persist(byte[] data) {
89 |             this.data = data;
90 |             //sessions.put(key, this);
91 |         }
92 |     }
93 | }
94 | 


--------------------------------------------------------------------------------
/src/test/java/com/wire/lithium/helpers/Util.java:
--------------------------------------------------------------------------------
 1 | package com.wire.lithium.helpers;
 2 | 
 3 | import java.io.File;
 4 | import java.io.IOException;
 5 | import java.nio.file.FileVisitOption;
 6 | import java.nio.file.Files;
 7 | import java.nio.file.Path;
 8 | import java.nio.file.Paths;
 9 | import java.util.Comparator;
10 | 
11 | public class Util {
12 |     public static void deleteDir(String dir) throws IOException {
13 |         Path rootPath = Paths.get(dir);
14 |         if (!rootPath.toFile().exists()) return;
15 |         //noinspection ResultOfMethodCallIgnored
16 |         Files.walk(rootPath, FileVisitOption.FOLLOW_LINKS)
17 |                 .sorted(Comparator.reverseOrder())
18 |                 .map(Path::toFile)
19 |                 .forEach(File::delete);
20 |     }
21 | }
22 | 


--------------------------------------------------------------------------------